hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40e372b192499940daa402e5a935df39436e443e
| 575
|
cpp
|
C++
|
BZOJ/4269/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/4269/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/4269/brute.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#define rg register
#define rep(i,x,y) for(rg int i=(x);i<=(y);++i)
#define per(i,x,y) for(rg int i=(x);i>=(y);--i)
using namespace std;
namespace brute{
const int N=1e5+10;
int n,a[N],fir,sec;
void dfs(int k,int d){
if(k==n+1){
if(d>fir)sec=fir,fir=d;
if(d<fir&&d>sec)sec=d;
return;
}
dfs(k+1,d);dfs(k+1,d^a[k]);
}
int main(){
scanf("%d",&n);
rep(i,1,n)scanf("%d",&a[i]);
dfs(1,0);
printf("%d %d",fir,sec);
return 0;
}
}
int main(){
freopen("code.in","r",stdin);freopen("brute.out","w",stdout);
return brute::main();
}
| 17.96875
| 62
| 0.587826
|
sjj118
|
40e70b7bfb7c911e8a4e27976c29302e33c5e6b5
| 5,166
|
cc
|
C++
|
google/cloud/storage/examples/storage_bucket_cors_samples.cc
|
tritone/google-cloud-cpp
|
fac45971f70205dfeebe88c472c2da1ed4eb8ce5
|
[
"Apache-2.0"
] | 3
|
2020-05-27T23:21:23.000Z
|
2020-05-31T22:31:53.000Z
|
google/cloud/storage/examples/storage_bucket_cors_samples.cc
|
cjrolo/google-cloud-cpp
|
bf7a432146952c5f3e8f29b84f5bf85eff69d327
|
[
"Apache-2.0"
] | 2
|
2020-05-31T22:26:57.000Z
|
2020-06-19T00:14:10.000Z
|
google/cloud/storage/examples/storage_bucket_cors_samples.cc
|
cjrolo/google-cloud-cpp
|
bf7a432146952c5f3e8f29b84f5bf85eff69d327
|
[
"Apache-2.0"
] | 1
|
2020-05-09T20:12:05.000Z
|
2020-05-09T20:12:05.000Z
|
// Copyright 2020 Google LLC
//
// 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 "google/cloud/storage/client.h"
#include "google/cloud/storage/examples/storage_examples_common.h"
#include "google/cloud/internal/getenv.h"
#include <functional>
#include <iostream>
#include <map>
namespace {
void SetCorsConfiguration(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
//! [cors configuration] [START storage_cors_configuration]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& origin) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
std::vector<gcs::CorsEntry> cors_configuration;
cors_configuration.emplace_back(
gcs::CorsEntry{3600, {"GET"}, {origin}, {"Content-Type"}});
StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetCors(cors_configuration),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.status().message());
}
if (patched_metadata->cors().empty()) {
std::cout << "Cors configuration is not set for bucket "
<< patched_metadata->name() << "\n";
return;
}
std::cout << "Cors configuration successfully set for bucket "
<< patched_metadata->name() << "\nNew cors configuration: ";
for (auto const& cors_entry : patched_metadata->cors()) {
std::cout << "\n " << cors_entry << "\n";
}
}
//! [cors configuration] [END storage_cors_configuration]
(std::move(client), argv.at(0), argv.at(1));
}
void RemoveCorsConfiguration(google::cloud::storage::Client client,
std::vector<std::string> const& argv) {
// [START storage_remove_cors_configuration]
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
bucket_name, gcs::BucketMetadataPatchBuilder().ResetCors(),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched) throw std::runtime_error(patched.status().message());
std::cout << "Cors configuration successfully removed for bucket "
<< patched->name() << "\n";
}
// [END storage_remove_cors_configuration]
(std::move(client), argv.at(0));
}
void RunAll(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::storage::examples;
namespace gcs = ::google::cloud::storage;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
});
auto const project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto generator = google::cloud::internal::DefaultPRNG(std::random_device{}());
auto const bucket_name =
examples::MakeRandomBucketName(generator, "cloud-cpp-test-examples-");
auto client = gcs::Client::CreateDefaultClient().value();
std::cout << "\nCreating bucket to run the example (" << bucket_name << ")"
<< std::endl;
auto bucket_metadata = client
.CreateBucketForProject(bucket_name, project_id,
gcs::BucketMetadata{})
.value();
std::cout << "\nRunning the SetCorsConfiguration() example" << std::endl;
SetCorsConfiguration(client, {bucket_name, "http://origin1.example.com"});
std::cout << "\nRunning the RemoveCorsConfiguration() example" << std::endl;
RemoveCorsConfiguration(client, {bucket_name});
(void)client.DeleteBucket(bucket_name);
}
} // namespace
int main(int argc, char* argv[]) {
namespace examples = ::google::cloud::storage::examples;
examples::Example example({
examples::CreateCommandEntry("set-cors-configuration",
{"<bucket-name>", "<config>"},
SetCorsConfiguration),
examples::CreateCommandEntry("remove-cors-configuration",
{"<bucket-name>"}, RemoveCorsConfiguration),
{"auto", RunAll},
});
return example.Run(argc, argv);
}
| 39.435115
| 80
| 0.659892
|
tritone
|
40ea82e41ebbe80c9c8ab3aa1d7dc78bde1528aa
| 37,648
|
cpp
|
C++
|
modules/humanStructure/main.cpp
|
robotology/assistive-rehab
|
7c148385010483202d91b92d6b20c09996d6452e
|
[
"BSD-3-Clause"
] | 17
|
2019-01-28T08:38:42.000Z
|
2022-03-25T13:23:08.000Z
|
modules/humanStructure/main.cpp
|
robotology/assistive-rehab
|
7c148385010483202d91b92d6b20c09996d6452e
|
[
"BSD-3-Clause"
] | 120
|
2019-01-29T10:54:53.000Z
|
2022-03-30T13:18:37.000Z
|
modules/humanStructure/main.cpp
|
robotology/assistive-rehab
|
7c148385010483202d91b92d6b20c09996d6452e
|
[
"BSD-3-Clause"
] | 5
|
2019-04-29T14:30:40.000Z
|
2020-09-10T06:29:48.000Z
|
/*
* Copyright (C) 2019 iCub Facility - Istituto Italiano di Tecnologia
* Author: Vadim Tikhanoff
* email: vadim.tikhanoff@iit.it
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* http://www.robotcub.org/icub/license/gpl.txt
*
* 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
*/
#include <yarp/os/BufferedPort.h>
#include <yarp/os/ResourceFinder.h>
#include <yarp/os/RFModule.h>
#include <yarp/os/Network.h>
#include <yarp/os/Log.h>
#include <yarp/os/LogStream.h>
#include <yarp/os/Semaphore.h>
#include <yarp/sig/Image.h>
#include <yarp/sig/Vector.h>
#include <yarp/cv/Cv.h>
#include <yarp/os/Stamp.h>
#include <yarp/os/RpcClient.h>
#include <yarp/math/Math.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <cstring>
#include <vector>
#include <iostream>
#include <utility>
#include <cmath>
#include "humanStructure_IDLServer.h"
using namespace yarp::math;
/********************************************************/
class Processing : public yarp::os::BufferedPort<yarp::os::Bottle>
{
std::string moduleName;
yarp::os::RpcServer handlerPort;
yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > imageInPort;
yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > imageOutPort;
yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelMono> > imageOutDepthPort;
yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelMono> > imageOutSegmentPort;
yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelFloat>> imageInFloat;
yarp::os::BufferedPort<yarp::os::Bottle > targetPort;
yarp::os::BufferedPort<yarp::os::Bottle > blobPort;
yarp::os::RpcClient camPort;
yarp::os::RpcClient armPort;
int followSkeletonIndex;
cv::Mat overlayFrame;
cv::Mat overlayObject;
bool camera_configured;
double fov_h;
double fov_v;
double minVal;
double maxVal;
bool isArmLifted;
yarp::sig::ImageOf<yarp::sig::PixelFloat> depth;
public:
int armthresh;
/********************************************************/
Processing( const std::string &moduleName )
{
this->moduleName = moduleName;
}
/********************************************************/
~Processing()
{
};
/********************************************************/
bool setDepthValues(const double min, const double max ){
minVal = min;
maxVal = max;
yDebug() << "setting Min val to " << minVal << "setting max val to " << maxVal;
return true;
}
/********************************************************/
bool open()
{
this->useCallback();
BufferedPort<yarp::os::Bottle >::open( "/" + moduleName + "/skeleton:i" );
imageInPort.open("/" + moduleName + "/image:i");
imageOutPort.open("/" + moduleName + "/image:o");
imageOutDepthPort.open("/" + moduleName + "/depth:o");
imageOutSegmentPort.open("/" + moduleName + "/segmented:o");
targetPort.open("/" + moduleName + "/target:o");
blobPort.open("/" + moduleName + "/blobs:o");
armPort.open("/" + moduleName + "/trigger:o");
imageInFloat.open("/" + moduleName + "/float:i");
camPort.open("/" + moduleName + "/cam:rpc");
followSkeletonIndex = -1;
isArmLifted = false;
armthresh = 20;
return true;
}
/********************************************************/
void close()
{
imageInFloat.close();
imageOutPort.close();
imageInPort.close();
BufferedPort<yarp::os::Bottle >::close();
targetPort.close();
blobPort.close();
camPort.close();
imageOutDepthPort.close();
imageOutSegmentPort.close();
armPort.close();
}
/********************************************************/
void interrupt()
{
BufferedPort<yarp::os::Bottle >::interrupt();
}
/**********************************************************/
int findArmLift( const yarp::os::Bottle &blobs,
const yarp::os::Bottle &skeletons)
{
int index = -1;
if (skeletons.size() > 0)
{
size_t skeletonSize = skeletons.get(0).asList()->size();
size_t internalElements = 0;
yDebug() << "skeleton " << skeletonSize;
std::vector<cv::Point> relbow;
std::vector<cv::Point> rwrist;
std::vector<cv::Point> lelbow;
std::vector<cv::Point> lwrist;
std::vector<cv::Point> neck;
std::vector<cv::Point> midHip;
cv::Point point;
if (skeletonSize>0)
internalElements = skeletons.get(0).asList()->get(0).asList()->size();
for (size_t i = 0; i < skeletonSize; i++)
{
if (yarp::os::Bottle *propField = skeletons.get(0).asList()->get(i).asList())
{
for (int ii = 0; ii < internalElements; ii++)
{
if (yarp::os::Bottle *propFieldPos = propField->get(ii).asList())
{
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RElbow") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
relbow.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RWrist") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rwrist.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LElbow") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
lelbow.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LWrist") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
lwrist.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"Neck") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
neck.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"MidHip") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
midHip.push_back(point);
}
}
}
}
}
int getIndex = -1;
if (neck.size() > 0)
{
for (int i = 0; i < skeletonSize; i++)
{
if ( relbow[i].y - rwrist[i].y > armthresh && relbow[i].y > 0 && rwrist[i].y > 0 )
{
getIndex = i;
}
else if( lelbow[i].y - lwrist[i].y > armthresh && lelbow[i].y > 0 && lwrist[i].y > 0 )
{
getIndex = i;
}
}
if (getIndex > -1)
{
yError() << "************************" << blobs.size();
for (int i=0;i<blobs.size(); i++)
{
yarp::os::Bottle *item=blobs.get(i).asList();
int cog = item->get(0).asInt32();//item->get(2).asInt32() - ( (item->get(2).asInt32() -item->get(0).asInt32()) / 2);
if ( abs(cog - neck[getIndex].x) < armthresh)
index = i;
}
}
}
}
return index;
}
/********************************************************/
bool getCameraOptions()
{ fov_h = 55;
fov_v = 42;
/*if (camPort.getOutputCount()>0)
{
yarp::os::Bottle cmd,rep;
cmd.addVocab32("visr");
cmd.addVocab32("get");
cmd.addVocab32("fov");
if (camPort.write(cmd,rep))
{
if (rep.size()>=5)
{
fov_h=rep.get(3).asFloat64();
fov_v=rep.get(4).asFloat64();
yInfo()<<"camera fov_h (from sensor) ="<<fov_h;
yInfo()<<"camera fov_v (from sensor) ="<<fov_v;
return true;
}
}
}*/
return true;
}
/********************************************************/
bool getPoint3D(const int u, const int v, yarp::sig::Vector &p) const
{
if ((u>=0) && (u<depth.width()) && (v>=0) && (v<depth.height()))
{
double f=depth.width()/(2.0*tan(fov_h*(M_PI/180.0)/2.0));
double d=depth(u,v);
if ((d>0.0) && (f>0.0))
{
double x=u-0.5*(depth.width()-1);
double y=v-0.5*(depth.height()-1);
p=d*ones(3);
p[0]*=x/f;
p[1]*=y/f;
return true;
}
}
return false;
}
/********************************************************/
void onRead( yarp::os::Bottle &data )
{
if (!camera_configured)
camera_configured=getCameraOptions();
yarp::sig::ImageOf<yarp::sig::PixelRgb> &outImage = imageOutPort.prepare();
yarp::sig::ImageOf<yarp::sig::PixelMono> &outDepth = imageOutDepthPort.prepare();
yarp::sig::ImageOf<yarp::sig::PixelMono> &outSegment = imageOutSegmentPort.prepare();
while (imageInPort.getInputCount() < 1 || imageInFloat.getInputCount() < 1 )
{
yError() << "waiting for connections";
yarp::os::Time::delay(0.1);
}
yDebug()<< "setting up system";
yarp::sig::ImageOf<yarp::sig::PixelRgb> *inImage = imageInPort.read();
yDebug()<< __LINE__;
yarp::sig::ImageOf<yarp::sig::PixelFloat> *float_yarp = imageInFloat.read();
yDebug()<< __LINE__;
depth = *float_yarp;
cv::Mat float_cv = yarp::cv::toCvMat(*float_yarp);
cv::Mat mono_cv = cv::Mat::ones(float_yarp->height(), float_yarp->width(), CV_8UC1);
float_cv -= minVal;
float_cv.convertTo(mono_cv, CV_8U, 255.0/(maxVal-minVal) );
cv::Mat depth_cv(float_yarp->height(), float_yarp->width(), CV_8UC1, cv::Scalar(255));
cv::Mat segment_cv(inImage->height(), inImage->width(), CV_8UC1, cv::Scalar(0));
depth_cv = depth_cv - mono_cv;
cv::Mat mask;
inRange(depth_cv, cv::Scalar(255), cv::Scalar(255), mask);
cv::Mat black_image(depth_cv.size(), CV_8U, cv::Scalar(0));
black_image.copyTo(depth_cv, mask);
yarp::os::Stamp stamp;
imageInPort.getEnvelope(stamp);
yarp::os::Bottle &target = targetPort.prepare();
size_t skeletonSize = data.get(0).asList()->size();
size_t internalElements = 0;
if (skeletonSize>0)
{
target = data;
internalElements = data.get(0).asList()->get(0).asList()->size();
}
outImage = *inImage;
outImage.resize(inImage->width(), inImage->height());
std::vector<cv::Point> rightEye2D;
std::vector<cv::Point> leftEye2D;
std::vector<cv::Point> neck2D;
std::vector<cv::Point> nose2D;
std::vector<cv::Point> rightEar2D;
std::vector<cv::Point> leftEar2D;
std::vector<cv::Point> leftShoulder2D;
std::vector<cv::Point> rightShoulder2D;
std::vector<cv::Point> rightWrist2D;
std::vector<cv::Point> leftWrist2D;
std::vector<cv::Point> rightElbow2D;
std::vector<cv::Point> leftElbow2D;
std::vector<cv::Point> MidHip2D;
std::vector<cv::Point> LHip2D;
std::vector<cv::Point> RHip2D;
cv::Point point;
std::vector<yarp::os::Bottle> shapes;
shapes.clear();
std::vector<std::pair <int,int> > elements;
elements.clear();
yDebug() << "skeletonSize" << skeletonSize;
for (int i = 0; i < skeletonSize; i++)
{
if (yarp::os::Bottle *propField = data.get(0).asList()->get(i).asList())
{
for (int ii = 0; ii < internalElements; ii++)
{
if (yarp::os::Bottle *propFieldPos = propField->get(ii).asList())
{
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"REye") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rightEye2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LEye") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
leftEye2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"REar") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rightEar2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LEar") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
leftEar2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"Neck") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
neck2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"Nose") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
nose2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LShoulder") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
leftShoulder2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RShoulder") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rightShoulder2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RWrist") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rightWrist2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LWrist") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
leftWrist2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RElbow") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
rightElbow2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LElbow") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
leftElbow2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"MidHip") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
MidHip2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"LHip") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
LHip2D.push_back(point);
}
if ( std::strcmp (propFieldPos->get(0).asString().c_str(),"RHip") == 0)
{
point.x = (int)propFieldPos->get(1).asFloat64();
point.y = (int)propFieldPos->get(2).asFloat64();
RHip2D.push_back(point);
}
}
}
}
}
cv::Mat out_cv = yarp::cv::toCvMat(outImage);
//need this increment as case might be that skeleton does not
//satisfy conditions to fill in bottle
int increment = 0;
for (size_t i = 0; i < skeletonSize; i++)
{
cv::Point topLeft;
cv::Point bottomRight;
yInfo() << "###########";
yInfo() << "MidHip2D " << MidHip2D[i].x << MidHip2D[i].y << "NecK2D " << neck2D[i].x << neck2D[i].y;
yarp::os::Bottle tmp;
tmp.clear();
if (MidHip2D[i].x > 0)
{
yInfo() << "in midHip";
tmp.addInt32(MidHip2D[i].x);
tmp.addInt32(MidHip2D[i].y);
elements.push_back(std::make_pair(MidHip2D[i].x,increment));
shapes.push_back(tmp);
increment++;
}
else if (neck2D[i].x > 0)
{
yInfo() << "in neck";
tmp.addInt32(neck2D[i].x);
tmp.addInt32(neck2D[i].y);
elements.push_back(std::make_pair(neck2D[i].x,increment));
shapes.push_back(tmp);
increment++;
}
else
{
yError() << "Cannot compute...cannot detect anything";
}
}
yarp::os::Bottle list;
yInfo() << "**************** Skeleton Size" << skeletonSize << "Element SIZE " << elements.size() << "shape SIZE" << shapes.size() ;
if (elements.size()>0)
{
for (int i=0; i<elements.size(); i++)
yInfo() << "Testing elements " << i << elements[i].first << elements[i].second;
std::sort(elements.begin(), elements.end());
for (int i=0; i<elements.size(); i++)
yInfo() << "Sorted elements " << i << elements[i].first << elements[i].second;
if ( shapes.size() > 0)
{
yarp::os::Bottle blobs;
blobs.clear();
for (int i=0; i<shapes.size(); i++)
{
yInfo() << "**************** shapes elements" << shapes[elements[i].second].toString();
yarp::os::Bottle &tmp = blobs.addList();
tmp.addInt32(shapes[elements[i].second].get(0).asInt32());
tmp.addInt32(shapes[elements[i].second].get(1).asInt32());
}
list = blobs;
targetPort.setEnvelope(stamp);
targetPort.write();
}
}
if ( shapes.size() > 0)
{
int index = findArmLift(list, data);
out_cv.copyTo(overlayFrame);
out_cv.copyTo(overlayObject);
if (index > -1 )
followSkeletonIndex = index;
yDebug() << " Looking at skeleton " << followSkeletonIndex;
int finalIndex = -1;
for (int i=0;i<list.size(); i++)
{
yarp::os::Bottle *item=list.get(i).asList();
int cog = item->get(0).asInt32(); //item->get(2).asInt32() - ( (item->get(2).asInt32() -item->get(0).asInt32()) / 2);
if ( abs(cog - neck2D[followSkeletonIndex].x) < 30)
finalIndex = i;
}
if (followSkeletonIndex > -1 && finalIndex > -1)
{
yDebug() << "Final index is " << finalIndex;
if (leftEye2D[finalIndex].x > 0 && leftEye2D[finalIndex].y > 0 && leftEye2D[finalIndex].x > 0 && leftEye2D[finalIndex].y > 0)
line(overlayFrame, leftEye2D[finalIndex], nose2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (rightEye2D[finalIndex].x > 0 && rightEye2D[finalIndex].y > 0 && nose2D[finalIndex].x > 0 && nose2D[finalIndex].y > 0)
line(overlayFrame, rightEye2D[finalIndex], nose2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (leftEar2D[finalIndex].x > 0 && leftEar2D[finalIndex].y > 0 && leftEye2D[finalIndex].x > 0 && leftEye2D[finalIndex].y > 0)
line(overlayFrame, leftEye2D[finalIndex], leftEar2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (rightEar2D[finalIndex].x > 0 && rightEar2D[finalIndex].y > 0 && rightEye2D[finalIndex].x > 0 && rightEye2D[finalIndex].y > 0)
line(overlayFrame, rightEye2D[finalIndex], rightEar2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (nose2D[finalIndex].x > 0 && nose2D[finalIndex].y > 0 && neck2D[finalIndex].x > 0 && neck2D[finalIndex].y > 0)
line(overlayFrame, nose2D[finalIndex], neck2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (neck2D[finalIndex].x > 0 && neck2D[finalIndex].y > 0 && leftShoulder2D[finalIndex].x > 0 && leftShoulder2D[finalIndex].y > 0)
line(overlayFrame, neck2D[finalIndex], leftShoulder2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (leftElbow2D[finalIndex].x > 0 && leftElbow2D[finalIndex].y > 0 && leftShoulder2D[finalIndex].x > 0 && leftShoulder2D[finalIndex].y > 0)
line(overlayFrame, leftShoulder2D[finalIndex], leftElbow2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (leftWrist2D[finalIndex].x > 0 && leftWrist2D[finalIndex].y > 0 && leftElbow2D[finalIndex].x > 0 && leftElbow2D[finalIndex].y > 0)
line(overlayFrame, leftElbow2D[finalIndex], leftWrist2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (neck2D[finalIndex].x > 0 && neck2D[finalIndex].y > 0 && rightShoulder2D[finalIndex].x > 0 && rightShoulder2D[finalIndex].y > 0)
line(overlayFrame, neck2D[finalIndex], rightShoulder2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (rightElbow2D[finalIndex].x > 0 && rightElbow2D[finalIndex].y > 0 && rightShoulder2D[finalIndex].x > 0 && rightShoulder2D[finalIndex].y > 0)
line(overlayFrame, rightShoulder2D[finalIndex], rightElbow2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (rightWrist2D[finalIndex].x > 0 && rightWrist2D[finalIndex].y > 0 && rightElbow2D[finalIndex].x > 0 && rightElbow2D[finalIndex].y > 0)
line(overlayFrame, rightElbow2D[finalIndex], rightWrist2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
if (RHip2D[finalIndex].x > 0 && LHip2D[finalIndex].x > 0 && neck2D[finalIndex].x > 0 && neck2D[finalIndex].y > 0)
{
line(overlayFrame, neck2D[finalIndex], LHip2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
line(overlayFrame, neck2D[finalIndex], RHip2D[finalIndex], cv::Scalar(118, 185 , 0), 4, 8);
}
double opacity = 0.4;
cv::addWeighted(overlayFrame, opacity, out_cv, 1 - opacity, 0, out_cv);
yDebug() << "neck 2D " << neck2D[finalIndex].x << neck2D[finalIndex].y;
yDebug() << "left wrist 2D " << leftWrist2D[finalIndex].x << leftWrist2D[finalIndex].y;
yDebug() << "right wrist 2D " << rightWrist2D[finalIndex].x << rightWrist2D[finalIndex].y;
yDebug() << "left elbow 2D " << leftElbow2D[finalIndex].x << leftElbow2D[finalIndex].y;
yDebug() << "right elbow 2D " << rightElbow2D[finalIndex].x << rightElbow2D[finalIndex].y;
yDebug() << "right hip 2D " << RHip2D[finalIndex].x << RHip2D[finalIndex].y;
yDebug() << "left hip 2D " << LHip2D[finalIndex].x << LHip2D[finalIndex].y;
//yDebug() << "mid hip 2D " << MidHip2D[finalIndex].x << MidHip2D[finalIndex].y;
std::map< double, cv::Point> valueVector;
double noseValue = depth_cv.at<uchar>(nose2D[finalIndex]);
double neckValue = depth_cv.at<uchar>(neck2D[finalIndex]);
double leftWristValue = depth_cv.at<uchar>(leftWrist2D[finalIndex]);
double rightWristValue = depth_cv.at<uchar>(rightWrist2D[finalIndex]);
double leftElbowValue = depth_cv.at<uchar>(leftElbow2D[finalIndex]);
double rightElbowValue = depth_cv.at<uchar>(rightElbow2D[finalIndex]);
//double midHipValue = depth_cv.at<uchar>(MidHip2D[finalIndex]);
double rightHipValue = depth_cv.at<uchar>(RHip2D[finalIndex]);
double leftHipValue = depth_cv.at<uchar>(LHip2D[finalIndex]);
valueVector.insert(std::make_pair(neckValue, neck2D[finalIndex]));
valueVector.insert(std::make_pair(leftWristValue, leftWrist2D[finalIndex]));
valueVector.insert(std::make_pair(rightWristValue, rightWrist2D[finalIndex]));
valueVector.insert(std::make_pair(leftElbowValue, leftElbow2D[finalIndex]));
valueVector.insert(std::make_pair(rightElbowValue, rightElbow2D[finalIndex]));
//valueVector.insert(std::make_pair(midHipValue, MidHip2D[finalIndex]));
valueVector.insert(std::make_pair(rightHipValue, RHip2D[finalIndex]));
valueVector.insert(std::make_pair(leftHipValue, LHip2D[finalIndex]));
double minLocVal, maxLocVal;
cv::Point minLoc, maxLoc;
cv::minMaxLoc( depth_cv, &minLocVal, &maxLocVal, &minLoc, &maxLoc );
//yDebug() << midHipValue << rightHipValue << leftHipValue << neckValue << leftWristValue << rightWristValue << leftElbowValue << rightElbowValue;
yDebug() << "Values " << neckValue << noseValue << leftWristValue << rightWristValue << leftElbowValue << rightElbowValue << rightHipValue << leftHipValue;
std::map<double, cv::Point>::iterator it = valueVector.begin();
double max = 0.0;
cv::Point maxPoint;
while(it != valueVector.end())
{
if (it->first>max)
{
max = it->first;
maxPoint = it->second;
}
it++;
}
yDebug() << "Max value: " << max << " max Point " << maxPoint.x << maxPoint.y;
double maxValThreshed = (max - 3);
cv::Mat cleanedImg;
cv::threshold(depth_cv, cleanedImg, maxValThreshed, 255, cv::THRESH_BINARY);
cv::Mat kernel1 = cv::Mat::ones(3, 3, CV_8UC1);
dilate(cleanedImg, cleanedImg, kernel1);
std::vector<std::vector<cv::Point> > cnt;
findContours(cleanedImg, cnt, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
std::vector<cv::Moments> mu( cnt.size() );
std::vector<cv::Point2f> mc( cnt.size() );
std::vector<std::vector<cv::Point> > contours_poly( cnt.size() );
std::vector<cv::Rect> boundRect( cnt.size() );
yarp::os::Bottle &blobs = blobPort.prepare();
blobs.clear();
double minValue = 1000;
int minValueIndex = -1;
for( size_t i = 0; i< cnt.size(); i++ )
{
mu[i] = moments( cnt[i], false );
mc[i] = cv::Point2f( (float)(mu[i].m10/mu[i].m00), (float)(mu[i].m01/mu[i].m00) );
double res = cv::norm(cv::Point((int)(mc[i].x), (int)(mc[i].y)) - maxPoint);
yDebug() << "res" << res;
if (res<minValue)
{
minValue = res;
minValueIndex = i;
}
}
yDebug() << "res minValue " << minValue << "index" << minValueIndex;
double checkValueOne = 0.0;
double checkValueTwo = 0.0;
if (neckValue > 0 && noseValue > 0)
{
yError() << "USING NECK";
checkValueOne = fabs(max-neckValue);
checkValueTwo = fabs(max-noseValue);
}
else
{
yError() << "USING HIP ";
checkValueOne = fabs(max-rightHipValue);
checkValueTwo = fabs(max-leftHipValue);
}
yError() << mc[minValueIndex].x << mc[minValueIndex].y;
yError() << maxPoint.x << maxPoint.y;
yError() << "Distance from " << minValueIndex << " is " << minValue;
yError() << "checkValueOne vs max " << checkValueOne;
yError() << "checkvalueTwo vs max " << checkValueTwo;
if ( checkValueOne >= 15 || checkValueTwo >= 15 )
{
approxPolyDP( cv::Mat(cnt[minValueIndex]), contours_poly[minValueIndex], 3, true );
boundRect[minValueIndex] = boundingRect( cv::Mat(contours_poly[minValueIndex]) );
drawContours(depth_cv, cnt, minValueIndex, cv::Scalar(255), 8);
drawContours(overlayObject, cnt, minValueIndex, cv::Scalar(216, 102 , 44), -1);
drawContours(segment_cv, cnt, minValueIndex, cv::Scalar(255), -1);
rectangle( out_cv, boundRect[minValueIndex].tl(), boundRect[minValueIndex].br(), cv::Scalar(216, 102 , 44), 2, 8, 0 );
yarp::os::Bottle &tmp = blobs.addList();
tmp.addInt32( boundRect[minValueIndex].tl().x );
tmp.addInt32( boundRect[minValueIndex].tl().y );
tmp.addInt32( boundRect[minValueIndex].br().x );
tmp.addInt32( boundRect[minValueIndex].br().y );
blobPort.setEnvelope(stamp);
blobPort.write();
double opacity = 0.4;
cv::addWeighted(overlayObject, opacity, out_cv, 1 - opacity, 0, out_cv);
}
//send arm trigger
if (index > -1 && isArmLifted==false)
{
if (armPort.getOutputCount() > 0)
{
yarp::os::Bottle cmd,rep;
cmd.addString("start");
isArmLifted = true;
armPort.write(cmd,rep);
}
}
else if (isArmLifted==true && index < 0)
{
if (armPort.getOutputCount() > 0)
{
yarp::os::Bottle cmd,rep;
cmd.addString("stop");
isArmLifted = false;
armPort.write(cmd,rep);
}
}
}
else
followSkeletonIndex = -1;
}
yDebug() << "sending images";
outImage = yarp::cv::fromCvMat<yarp::sig::PixelRgb>(out_cv);
outDepth = yarp::cv::fromCvMat<yarp::sig::PixelMono>(depth_cv);
outSegment = yarp::cv::fromCvMat<yarp::sig::PixelMono>(segment_cv);
imageOutPort.setEnvelope(stamp);
imageOutPort.write();
imageOutDepthPort.setEnvelope(stamp);
imageOutDepthPort.write();
imageOutSegmentPort.setEnvelope(stamp);
imageOutSegmentPort.write();
yDebug() << "done loop";
}
};
/********************************************************/
class Module : public yarp::os::RFModule, public humanStructure_IDLServer
{
yarp::os::ResourceFinder *rf;
yarp::os::RpcServer rpcPort;
Processing *processing;
friend class processing;
bool closing;
double minVal;
double maxVal;
/********************************************************/
bool attach(yarp::os::RpcServer &source)
{
return this->yarp().attachAsServer(source);
}
public:
/********************************************************/
Module() : closing(false) { }
/********************************************************/
bool configure(yarp::os::ResourceFinder &rf)
{
this->rf=&rf;
std::string moduleName = rf.check("name", yarp::os::Value("humanStructure"), "module name (string)").asString();
minVal = rf.check("minVal", yarp::os::Value(0.5), "minimum value for depth (double)").asFloat64();
maxVal = rf.check("maxVal", yarp::os::Value(3.5), "maximum value for depth (double)").asFloat64();
setName(moduleName.c_str());
rpcPort.open(("/"+getName("/rpc")).c_str());
processing = new Processing( moduleName );
/* now start the thread to do the work */
processing->open();
processing->setDepthValues(minVal, maxVal);
attach(rpcPort);
return true;
}
/********************************************************/
int getArmThresh()
{
return processing->armthresh;
}
/********************************************************/
bool setArmThresh(const int32_t threshold)
{
bool val = true;
if (threshold > 0)
processing->armthresh = threshold;
else
val = false;
return true;
}
/**********************************************************/
bool close()
{
processing->interrupt();
processing->close();
delete processing;
return true;
}
/**********************************************************/
bool quit(){
closing = true;
return true;
}
/********************************************************/
double getPeriod()
{
return 0.1;
}
/********************************************************/
bool updateModule()
{
return !closing;
}
};
/********************************************************/
int main(int argc, char *argv[])
{
yarp::os::Network::init();
yarp::os::Network yarp;
if (!yarp.checkNetwork())
{
yError("YARP server not available!");
return 1;
}
Module module;
yarp::os::ResourceFinder rf;
rf.setDefaultContext("humanStructure");
rf.setDefaultConfigFile("config.ini");
rf.configure(argc,argv);
return module.runModule(rf);
}
| 40.877307
| 171
| 0.472376
|
robotology
|
40eb446c05a02e67af4adcba57f35c035efec6f8
| 2,383
|
cpp
|
C++
|
firmware/main/DeviceStorage/DeviceStorage.cpp
|
ARQMS/arqms-device
|
8278c693d91b8973997a16e4f72b75e7e9a5fb26
|
[
"MIT"
] | 2
|
2022-02-01T18:04:32.000Z
|
2022-02-15T08:25:42.000Z
|
firmware/main/DeviceStorage/DeviceStorage.cpp
|
ARQMS/arqms-device
|
8278c693d91b8973997a16e4f72b75e7e9a5fb26
|
[
"MIT"
] | null | null | null |
firmware/main/DeviceStorage/DeviceStorage.cpp
|
ARQMS/arqms-device
|
8278c693d91b8973997a16e4f72b75e7e9a5fb26
|
[
"MIT"
] | null | null | null |
#include "DeviceStorage.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "nvs.h"
// Maximal 15 characters inkl zero-terminator
#define STORAGE_NAMESPACE "HumiConfStore"
#define DEVICE_CONFIG "DeviceConfig"
DeviceStorage::DeviceStorage() :
initialized(false) {
}
DeviceStorage::~DeviceStorage() {
}
void DeviceStorage::initialize() {
auto error = nvs_flash_init();
if (error == ESP_ERR_NVS_NO_FREE_PAGES || error == ESP_ERR_NVS_NEW_VERSION_FOUND) {
// NVS parition was truncated and needs to be erased
nvs_flash_erase_partition(STORAGE_NAMESPACE);
// try again to init nvs
error = nvs_flash_init();
}
ESP_ERROR_CHECK(error);
initialized = true;
}
bool DeviceStorage::isInitialized() {
return initialized;
}
DeviceParameters DeviceStorage::getDeviceParameters(void) {
NvsLayoutV1 nvsValues;
// TODO: not generic enough for other configuration parts!
// understand how NVS is organized to create maching configuration structure
// with versioning
nvs_handle* pHandler = nullptr;
nvs_open(STORAGE_NAMESPACE, NVS_READONLY, pHandler);
size_t size;
nvs_get_blob(*pHandler, DEVICE_CONFIG, &nvsValues, &size);
nvs_close(*pHandler);
return nvsValues.deviceParameters;
}
void DeviceStorage::setDeviceParameters(const DeviceParameters& param) {
NvsLayoutV1 nvsValues;
nvsValues.deviceParameters = param;
// TODO see getDeviceParameters
nvs_handle* pHandler = nullptr;
nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, pHandler);
nvs_set_blob(*pHandler, DEVICE_CONFIG, &nvsValues, CURRENT_LAYOUT_SIZE_BYTES);
nvs_commit(*pHandler);
nvs_close(*pHandler);
}
WifiParameters DeviceStorage::getWifiParameters() {
// IDF already supports wifi NVS storage
WifiParameters wifiConfig;
esp_wifi_get_config(wifi_interface_t::WIFI_IF_STA, &wifiConfig.config);
return wifiConfig;
}
void DeviceStorage::setWifiParameters(const WifiParameters& param) {
// IDF already supports wifi NVS storage
wifi_config_t config = static_cast<wifi_config_t>(param.config);
esp_wifi_set_config(wifi_interface_t::WIFI_IF_STA, &config);
}
void DeviceStorage::factoryDefault() {
// TODO preserve DeviceParameter
// nvs_flash_erase();
// Write CURRENT_LAYOUT_VERSION
// Write DeviceParameter
// Write default values.
}
| 26.775281
| 87
| 0.73311
|
ARQMS
|
40ec0170e297b0bdb99c51fc482814537a0aa0eb
| 861
|
cpp
|
C++
|
src/SineGenerator.cpp
|
Silexars/VeritasAudio
|
2e55914ad040b057fb9ebf7590d7f0b9731e8606
|
[
"Apache-2.0"
] | null | null | null |
src/SineGenerator.cpp
|
Silexars/VeritasAudio
|
2e55914ad040b057fb9ebf7590d7f0b9731e8606
|
[
"Apache-2.0"
] | null | null | null |
src/SineGenerator.cpp
|
Silexars/VeritasAudio
|
2e55914ad040b057fb9ebf7590d7f0b9731e8606
|
[
"Apache-2.0"
] | null | null | null |
#include <Veritas/Audio/SineGenerator.h>
#include <Veritas/Math/Math.h>
#include <Veritas/Audio/ValueNode.h>
using namespace Veritas;
using namespace Audio;
using namespace Math;
SineGenerator::SineGenerator(uint32 framerate, FORMAT format, float32 timespan)
: AudioNode(framerate, format, 1, timespan)
, AudioSource(framerate, format, 1, timespan)
, AudioSink(framerate, format, 1, timespan)
, time(0)
{
connect(ValueNode(440.0));
}
void SineGenerator::read(uint8 *data, uint32 bytes) {
float32 *floats = (float32*) data;
uint32 frames = bytes / sizeof(float32);
float32 frequency[frames];
getSource().read((uint8*) &frequency, sizeof(frequency));
float32 framerate = getFramerate();
for (uint32 i = 0; i < frames; i++) {
floats[i] = sin(frequency[i] * TAU * time / framerate);
time++;
}
}
| 26.90625
| 79
| 0.67712
|
Silexars
|
40f0c02b3b5cfa0a3c0a34bc5bfc2078e2644089
| 3,096
|
hpp
|
C++
|
Sources/Sampler/py_metropolis_local.hpp
|
tvieijra/netket
|
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
|
[
"Apache-2.0"
] | 10
|
2019-11-29T02:51:53.000Z
|
2021-08-14T18:52:33.000Z
|
Sources/Sampler/py_metropolis_local.hpp
|
tvieijra/netket
|
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
|
[
"Apache-2.0"
] | 2
|
2018-11-04T14:38:01.000Z
|
2018-11-08T16:56:10.000Z
|
Sources/Sampler/py_metropolis_local.hpp
|
tvieijra/netket
|
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
|
[
"Apache-2.0"
] | 6
|
2019-12-02T07:29:01.000Z
|
2021-04-04T21:55:21.000Z
|
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef NETKET_PY_METROPOLISLOCAL_HPP
#define NETKET_PY_METROPOLISLOCAL_HPP
#include <pybind11/pybind11.h>
#include "metropolis_local.hpp"
namespace py = pybind11;
namespace netket {
void AddMetropolisLocal(py::module &subm) {
py::class_<MetropolisLocal, AbstractSampler>(subm, "MetropolisLocal", R"EOF(
This sampler acts locally only on one local degree of freedom $$s_i$$,
and proposes a new state: $$ s_1 \dots s^\prime_i \dots s_N $$,
where $$ s^\prime_i \neq s_i $$.
The transition probability associated to this
sampler can be decomposed into two steps:
1. One of the site indices $$ i = 1\dots N $$ is chosen
with uniform probability.
2. Among all the possible ($$m$$) values that $$s_i$$ can take,
one of them is chosen with uniform probability.
For example, in the case of spin $$1/2$$ particles, $$m=2$$
and the possible local values are $$s_i = -1,+1$$.
In this case then `MetropolisLocal` is equivalent to flipping a random spin.
In the case of bosons, with occupation numbers
$$s_i = 0, 1, \dots n_{\mathrm{max}}$$, `MetropolisLocal`
would pick a random local occupation number uniformly between $$0$$
and $$n_{\mathrm{max}}$$.
)EOF")
.def(py::init<AbstractMachine &>(), py::keep_alive<1, 2>(),
py::arg("machine"), R"EOF(
Constructs a new ``MetropolisLocal`` sampler given a machine.
Args:
machine: A machine $$\Psi(s)$$ used for the sampling.
The probability distribution being sampled
from is $$F(\Psi(s))$$, where the function
$$F(X)$$, is arbitrary, by default $$F(X)=|X|^2$$.
Examples:
Sampling from a RBM machine in a 1D lattice of spin 1/2
```python
>>> import netket as nk
>>>
>>> g=nk.graph.Hypercube(length=10,n_dim=2,pbc=True)
>>> hi=nk.hilbert.Spin(s=0.5,graph=g)
>>>
>>> # RBM Spin Machine
>>> ma = nk.machine.RbmSpin(alpha=1, hilbert=hi)
>>>
>>> # Construct a MetropolisLocal Sampler
>>> sa = nk.sampler.MetropolisLocal(machine=ma)
>>> print(sa.hilbert.size)
100
```
)EOF");
}
} // namespace netket
#endif
| 38.7
| 82
| 0.596899
|
tvieijra
|
40f468bf26b85dff12d48bc48200ed2651464e1e
| 6,277
|
cpp
|
C++
|
debugger/src/common/generic/bus_generic.cpp
|
hossameldin1995/riscv_vhdl
|
aab7196a6b9962626ed7314b7c86b93760e76f83
|
[
"Apache-2.0"
] | 1
|
2020-07-19T19:24:36.000Z
|
2020-07-19T19:24:36.000Z
|
debugger/src/common/generic/bus_generic.cpp
|
hossameldin1995/riscv_vhdl
|
aab7196a6b9962626ed7314b7c86b93760e76f83
|
[
"Apache-2.0"
] | null | null | null |
debugger/src/common/generic/bus_generic.cpp
|
hossameldin1995/riscv_vhdl
|
aab7196a6b9962626ed7314b7c86b93760e76f83
|
[
"Apache-2.0"
] | 1
|
2021-11-18T17:40:35.000Z
|
2021-11-18T17:40:35.000Z
|
/*
* Copyright 2018 Sergey Khabarov, sergeykhbr@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <api_core.h>
#include "bus_generic.h"
#include "coreservices/icpugen.h"
#include "debug/dsumap.h"
namespace debugger {
BusGeneric::BusGeneric(const char *name) : IService(name),
IHap(HAP_ConfigDone),
busUtil_(static_cast<IService *>(this), "bus_util",
DSUREG(ulocal.v.bus_util[0]),
sizeof(DsuMapType::local_regs_type::\
local_region_type::mst_bus_util_type)) {
registerInterface(static_cast<IMemoryOperation *>(this));
registerAttribute("UseHash", &useHash_);
RISCV_mutex_init(&mutexBAccess_);
RISCV_mutex_init(&mutexNBAccess_);
RISCV_register_hap(static_cast<IHap *>(this));
busUtil_.setPriority(10); // Overmap DSU registers
imaphash_ = 0;
}
BusGeneric::~BusGeneric() {
RISCV_mutex_destroy(&mutexBAccess_);
RISCV_mutex_destroy(&mutexNBAccess_);
}
void BusGeneric::postinitService() {
IMemoryOperation *imem;
for (unsigned i = 0; i < listMap_.size(); i++) {
const AttributeType &dev = listMap_[i];
if (dev.is_string()) {
imem = static_cast<IMemoryOperation *>(RISCV_get_service_iface(
dev.to_string(), IFACE_MEMORY_OPERATION));
if (imem == 0) {
RISCV_error("Can't find slave device %s", dev.to_string());
continue;
}
map(imem);
} else if (dev.is_list() && dev.size() == 2) {
const AttributeType &devname = dev[0u];
const AttributeType &portname = dev[1];
imem = static_cast<IMemoryOperation *>(
RISCV_get_service_port_iface(devname.to_string(),
portname.to_string(),
IFACE_MEMORY_OPERATION));
if (imem == 0) {
RISCV_error("Can't find slave device %s:%s",
devname.to_string(), portname.to_string());
continue;
}
map(imem);
}
}
}
/** We need correctly mapped device list to compute hash, postinit
doesn't allow to guarantee order of initialization. */
void BusGeneric::hapTriggered(IFace *isrc,
EHapType type,
const char *descr) {
if (!useHash_.to_bool()) {
return;
}
IMemoryOperation *imem;
for (unsigned i = 0; i < imap_.size(); i++) {
imem = static_cast<IMemoryOperation *>(imap_[i].to_iface());
maphash(imem);
}
}
ETransStatus BusGeneric::b_transport(Axi4TransactionType *trans) {
ETransStatus ret = TRANS_OK;
uint32_t sz;
IMemoryOperation *memdev = 0;
RISCV_mutex_lock(&mutexBAccess_);
if (itranslator_) {
itranslator_->translate(trans);
}
getMapedDevice(trans, &memdev, &sz);
if (memdev == 0) {
RISCV_error("Blocking request to unmapped address "
"%08" RV_PRI64 "x", trans->addr);
memset(trans->rpayload.b8, 0xFF, trans->xsize);
ret = TRANS_ERROR;
} else {
memdev->b_transport(trans);
RISCV_debug("[%08" RV_PRI64 "x] => [%08x %08x]",
trans->addr,
trans->rpayload.b32[1], trans->rpayload.b32[0]);
}
// Update Bus utilization counters:
if (trans->source_idx >= 0 && trans->source_idx < 8) {
if (trans->action == MemAction_Read) {
busUtil_.getpR64()[2*trans->source_idx + 1]++;
} else if (trans->action == MemAction_Write) {
busUtil_.getpR64()[2*trans->source_idx]++;
}
}
RISCV_mutex_unlock(&mutexBAccess_);
return ret;
}
ETransStatus BusGeneric::nb_transport(Axi4TransactionType *trans,
IAxi4NbResponse *cb) {
ETransStatus ret = TRANS_OK;
IMemoryOperation *memdev = 0;
uint32_t sz;
RISCV_mutex_lock(&mutexNBAccess_);
if (itranslator_) {
itranslator_->translate(trans);
}
getMapedDevice(trans, &memdev, &sz);
if (memdev == 0) {
RISCV_error("Non-blocking request from %d to unmapped address "
"%08" RV_PRI64 "x", trans->source_idx, trans->addr);
memset(trans->rpayload.b8, 0xFF, trans->xsize);
trans->response = MemResp_Error;
cb->nb_response(trans);
ret = TRANS_ERROR;
} else {
memdev->nb_transport(trans, cb);
RISCV_debug("Non-blocking request to [%08" RV_PRI64 "x]",
trans->addr);
}
// Update Bus utilization counters:
if (trans->source_idx >= 0 && trans->source_idx < 8) {
if (trans->action == MemAction_Read) {
busUtil_.getpR64()[2*trans->source_idx + 1]++;
} else if (trans->action == MemAction_Write) {
busUtil_.getpR64()[2*trans->source_idx]++;
}
}
RISCV_mutex_unlock(&mutexNBAccess_);
return ret;
}
void BusGeneric::getMapedDevice(Axi4TransactionType *trans,
IMemoryOperation **pdev, uint32_t *sz) {
IMemoryOperation *imem;
*pdev = 0;
*sz = 0;
if (useHash_.to_bool()) {
imem = getHashedDevice(trans->addr);
if (imem) {
*pdev = imem;
return;
}
}
uint64_t bar, barsz;
for (unsigned i = 0; i < imap_.size(); i++) {
imem = static_cast<IMemoryOperation *>(imap_[i].to_iface());
bar = imem->getBaseAddress();
barsz = imem->getLength();
if (bar <= trans->addr && trans->addr < (bar + barsz)) {
if (!(*pdev) || imem->getPriority() > (*pdev)->getPriority()) {
*pdev = imem;
}
}
}
}
} // namespace debugger
| 32.863874
| 76
| 0.582922
|
hossameldin1995
|
40f4f6279abf44999120f22b799aa2ad5f52a6d6
| 537
|
hpp
|
C++
|
goop/generic/draw_state.hpp
|
johannes-braun/goop-gfx
|
f2a5dbac3d18299efdffe900e0e1d615c0c3c98d
|
[
"MIT"
] | null | null | null |
goop/generic/draw_state.hpp
|
johannes-braun/goop-gfx
|
f2a5dbac3d18299efdffe900e0e1d615c0c3c98d
|
[
"MIT"
] | null | null | null |
goop/generic/draw_state.hpp
|
johannes-braun/goop-gfx
|
f2a5dbac3d18299efdffe900e0e1d615c0c3c98d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <memory>
#include <utility>
#include <GLFW/glfw3.h>
namespace goop
{
class render_target_base;
class draw_state_base
{
public:
virtual void from_window(GLFWwindow* window) = 0;
virtual std::pair<int, int> current_surface_size() const = 0;
virtual int display(render_target_base const& source, int source_width, int source_height) = 0;
virtual void set_viewport(float x, float y, float width, float height) = 0;
virtual void set_depth_test(bool enabled) = 0;
};
}
| 26.85
| 100
| 0.6946
|
johannes-braun
|
40f744d6941bd04d69979915814845b6739623d0
| 355
|
cpp
|
C++
|
src/platform/other/OutputColorizer.cpp
|
MaxMutantMayer/wolfram_r184
|
3ba55e4c10f071384dc174d348d0556c4f462688
|
[
"MIT"
] | null | null | null |
src/platform/other/OutputColorizer.cpp
|
MaxMutantMayer/wolfram_r184
|
3ba55e4c10f071384dc174d348d0556c4f462688
|
[
"MIT"
] | null | null | null |
src/platform/other/OutputColorizer.cpp
|
MaxMutantMayer/wolfram_r184
|
3ba55e4c10f071384dc174d348d0556c4f462688
|
[
"MIT"
] | null | null | null |
#include "OutputColorizer.hpp"
#include <stdio.h>
#define YELBG "\x1B[103m"
#define RESET "\x1B[0m"
namespace wolfram_r184
{
namespace colorizer
{
void Init(void)
{
ResetOutputColor();
}
void ChangeToYellowBackground(void)
{
printf(YELBG);
}
void ResetOutputColor(void)
{
printf(RESET);
}
} // namespace colorizer
} // namespace wolfram_r184
| 11.833333
| 35
| 0.721127
|
MaxMutantMayer
|
40f8802d49a8f9bff95435c94bdd67a1a09b7d86
| 13,637
|
cpp
|
C++
|
ams/src/v20201229/model/AudioResult.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
ams/src/v20201229/model/AudioResult.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
ams/src/v20201229/model/AudioResult.cpp
|
sinjoywong/tencentcloud-sdk-cpp
|
1b931d20956a90b15a6720f924e5c69f8786f9f4
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ams/v20201229/model/AudioResult.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ams::V20201229::Model;
using namespace std;
AudioResult::AudioResult() :
m_hitFlagHasBeenSet(false),
m_labelHasBeenSet(false),
m_suggestionHasBeenSet(false),
m_scoreHasBeenSet(false),
m_textHasBeenSet(false),
m_urlHasBeenSet(false),
m_durationHasBeenSet(false),
m_extraHasBeenSet(false),
m_textResultsHasBeenSet(false),
m_moanResultsHasBeenSet(false),
m_languageResultsHasBeenSet(false)
{
}
CoreInternalOutcome AudioResult::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("HitFlag") && !value["HitFlag"].IsNull())
{
if (!value["HitFlag"].IsInt64())
{
return CoreInternalOutcome(Error("response `AudioResult.HitFlag` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_hitFlag = value["HitFlag"].GetInt64();
m_hitFlagHasBeenSet = true;
}
if (value.HasMember("Label") && !value["Label"].IsNull())
{
if (!value["Label"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Label` IsString=false incorrectly").SetRequestId(requestId));
}
m_label = string(value["Label"].GetString());
m_labelHasBeenSet = true;
}
if (value.HasMember("Suggestion") && !value["Suggestion"].IsNull())
{
if (!value["Suggestion"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Suggestion` IsString=false incorrectly").SetRequestId(requestId));
}
m_suggestion = string(value["Suggestion"].GetString());
m_suggestionHasBeenSet = true;
}
if (value.HasMember("Score") && !value["Score"].IsNull())
{
if (!value["Score"].IsInt64())
{
return CoreInternalOutcome(Error("response `AudioResult.Score` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_score = value["Score"].GetInt64();
m_scoreHasBeenSet = true;
}
if (value.HasMember("Text") && !value["Text"].IsNull())
{
if (!value["Text"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Text` IsString=false incorrectly").SetRequestId(requestId));
}
m_text = string(value["Text"].GetString());
m_textHasBeenSet = true;
}
if (value.HasMember("Url") && !value["Url"].IsNull())
{
if (!value["Url"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Url` IsString=false incorrectly").SetRequestId(requestId));
}
m_url = string(value["Url"].GetString());
m_urlHasBeenSet = true;
}
if (value.HasMember("Duration") && !value["Duration"].IsNull())
{
if (!value["Duration"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Duration` IsString=false incorrectly").SetRequestId(requestId));
}
m_duration = string(value["Duration"].GetString());
m_durationHasBeenSet = true;
}
if (value.HasMember("Extra") && !value["Extra"].IsNull())
{
if (!value["Extra"].IsString())
{
return CoreInternalOutcome(Error("response `AudioResult.Extra` IsString=false incorrectly").SetRequestId(requestId));
}
m_extra = string(value["Extra"].GetString());
m_extraHasBeenSet = true;
}
if (value.HasMember("TextResults") && !value["TextResults"].IsNull())
{
if (!value["TextResults"].IsArray())
return CoreInternalOutcome(Error("response `AudioResult.TextResults` is not array type"));
const rapidjson::Value &tmpValue = value["TextResults"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
AudioResultDetailTextResult item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_textResults.push_back(item);
}
m_textResultsHasBeenSet = true;
}
if (value.HasMember("MoanResults") && !value["MoanResults"].IsNull())
{
if (!value["MoanResults"].IsArray())
return CoreInternalOutcome(Error("response `AudioResult.MoanResults` is not array type"));
const rapidjson::Value &tmpValue = value["MoanResults"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
AudioResultDetailMoanResult item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_moanResults.push_back(item);
}
m_moanResultsHasBeenSet = true;
}
if (value.HasMember("LanguageResults") && !value["LanguageResults"].IsNull())
{
if (!value["LanguageResults"].IsArray())
return CoreInternalOutcome(Error("response `AudioResult.LanguageResults` is not array type"));
const rapidjson::Value &tmpValue = value["LanguageResults"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
AudioResultDetailLanguageResult item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_languageResults.push_back(item);
}
m_languageResultsHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AudioResult::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_hitFlagHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HitFlag";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_hitFlag, allocator);
}
if (m_labelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Label";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_label.c_str(), allocator).Move(), allocator);
}
if (m_suggestionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Suggestion";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_suggestion.c_str(), allocator).Move(), allocator);
}
if (m_scoreHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Score";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_score, allocator);
}
if (m_textHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Text";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_text.c_str(), allocator).Move(), allocator);
}
if (m_urlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Url";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_url.c_str(), allocator).Move(), allocator);
}
if (m_durationHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Duration";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_duration.c_str(), allocator).Move(), allocator);
}
if (m_extraHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Extra";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_extra.c_str(), allocator).Move(), allocator);
}
if (m_textResultsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TextResults";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_textResults.begin(); itr != m_textResults.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_moanResultsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MoanResults";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_moanResults.begin(); itr != m_moanResults.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_languageResultsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LanguageResults";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_languageResults.begin(); itr != m_languageResults.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
int64_t AudioResult::GetHitFlag() const
{
return m_hitFlag;
}
void AudioResult::SetHitFlag(const int64_t& _hitFlag)
{
m_hitFlag = _hitFlag;
m_hitFlagHasBeenSet = true;
}
bool AudioResult::HitFlagHasBeenSet() const
{
return m_hitFlagHasBeenSet;
}
string AudioResult::GetLabel() const
{
return m_label;
}
void AudioResult::SetLabel(const string& _label)
{
m_label = _label;
m_labelHasBeenSet = true;
}
bool AudioResult::LabelHasBeenSet() const
{
return m_labelHasBeenSet;
}
string AudioResult::GetSuggestion() const
{
return m_suggestion;
}
void AudioResult::SetSuggestion(const string& _suggestion)
{
m_suggestion = _suggestion;
m_suggestionHasBeenSet = true;
}
bool AudioResult::SuggestionHasBeenSet() const
{
return m_suggestionHasBeenSet;
}
int64_t AudioResult::GetScore() const
{
return m_score;
}
void AudioResult::SetScore(const int64_t& _score)
{
m_score = _score;
m_scoreHasBeenSet = true;
}
bool AudioResult::ScoreHasBeenSet() const
{
return m_scoreHasBeenSet;
}
string AudioResult::GetText() const
{
return m_text;
}
void AudioResult::SetText(const string& _text)
{
m_text = _text;
m_textHasBeenSet = true;
}
bool AudioResult::TextHasBeenSet() const
{
return m_textHasBeenSet;
}
string AudioResult::GetUrl() const
{
return m_url;
}
void AudioResult::SetUrl(const string& _url)
{
m_url = _url;
m_urlHasBeenSet = true;
}
bool AudioResult::UrlHasBeenSet() const
{
return m_urlHasBeenSet;
}
string AudioResult::GetDuration() const
{
return m_duration;
}
void AudioResult::SetDuration(const string& _duration)
{
m_duration = _duration;
m_durationHasBeenSet = true;
}
bool AudioResult::DurationHasBeenSet() const
{
return m_durationHasBeenSet;
}
string AudioResult::GetExtra() const
{
return m_extra;
}
void AudioResult::SetExtra(const string& _extra)
{
m_extra = _extra;
m_extraHasBeenSet = true;
}
bool AudioResult::ExtraHasBeenSet() const
{
return m_extraHasBeenSet;
}
vector<AudioResultDetailTextResult> AudioResult::GetTextResults() const
{
return m_textResults;
}
void AudioResult::SetTextResults(const vector<AudioResultDetailTextResult>& _textResults)
{
m_textResults = _textResults;
m_textResultsHasBeenSet = true;
}
bool AudioResult::TextResultsHasBeenSet() const
{
return m_textResultsHasBeenSet;
}
vector<AudioResultDetailMoanResult> AudioResult::GetMoanResults() const
{
return m_moanResults;
}
void AudioResult::SetMoanResults(const vector<AudioResultDetailMoanResult>& _moanResults)
{
m_moanResults = _moanResults;
m_moanResultsHasBeenSet = true;
}
bool AudioResult::MoanResultsHasBeenSet() const
{
return m_moanResultsHasBeenSet;
}
vector<AudioResultDetailLanguageResult> AudioResult::GetLanguageResults() const
{
return m_languageResults;
}
void AudioResult::SetLanguageResults(const vector<AudioResultDetailLanguageResult>& _languageResults)
{
m_languageResults = _languageResults;
m_languageResultsHasBeenSet = true;
}
bool AudioResult::LanguageResultsHasBeenSet() const
{
return m_languageResultsHasBeenSet;
}
| 28.529289
| 134
| 0.65249
|
sinjoywong
|
40fc554c6d22824884cb719b18bfaf3083014fb0
| 15,838
|
hh
|
C++
|
Async/Locks/range_lock.hh
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 2
|
2021-06-09T00:38:46.000Z
|
2021-09-04T21:55:33.000Z
|
Async/Locks/range_lock.hh
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | null | null | null |
Async/Locks/range_lock.hh
|
jlandess/LandessDevCore
|
3319c36c3232415d6bdba7da8b4896c0638badf2
|
[
"BSD-3-Clause"
] | 1
|
2021-08-30T00:46:12.000Z
|
2021-08-30T00:46:12.000Z
|
/*
* Copyright (C) 2016 Raphael S. Carvalho
*
* This program can be distributed under the terms of the GNU GPL.
* See the file COPYING.
*/
#pragma once
#if __cplusplus < 201103L
#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.
#endif
#include <unordered_map>
#include <memory>
#include <algorithm>
#include <cmath>
#include <assert.h>
#if (__cplusplus >= 201402L)
#include <shared_mutex>
#else
#include <mutex>
#endif
/// \brief Range lock class
///
/// Utility created to control access to specific regions of a shared resource,
/// such as a buffer or a file. Think of it as byte-range locking mechanism.
///
/// This implementation works by virtually dividing the shared resource into N
/// regions of the same size, and associating an id with each region.
/// A region is the unit to be individually protected from concurrent access.
///
/// Choosing an optimal region size:
/// The smaller the region size, the more regions exists.
/// The more regions exists, the finer grained the locking is.
/// If in doubt, use range_lock::create_range_lock(). It will choose a region
/// size for you.
///
/// How locking does work with range_lock?
/// A lock request may cover more than one region, so there is a need to wait
/// for each covered region to be available. Deadlock is avoided by always
/// locking regions in sequential order.
///
/// This implementation is resource efficient because it will only keep alive
/// data for the regions being used at the moment. That's done with a simple
/// reference count management.
#include "RWLock.h"
namespace LD
{
struct RangedLock
{
private:
struct region
{
uint64_t refcount = 0;
#if (__cplusplus >= 201402L)
std::shared_timed_mutex mutex;
#else
std::mutex mutex;
#endif
};
std::unordered_map<uint64_t, std::unique_ptr<region>> _regions;
std::mutex _regions_lock;
const uint64_t _region_size;
public:
RangedLock() = delete;
RangedLock& operator=(const RangedLock&) = delete;
RangedLock(const RangedLock&) = delete;
RangedLock(RangedLock&&) = default;
// NOTE: Please make sure that region_size is greater than zero and power
// of two. Use std::pow(2, exp) to generate a proper region size.
RangedLock(uint64_t region_size) : _region_size(region_size)
{
assert(region_size > 0);
assert((region_size & (region_size - 1)) == 0);
}
// Create a range_lock with a region size, which is calculated based on the
// size of resource to be protected.
// For example, if you want to protect a file, call create_range_lock()
// with the size of that file.
static std::unique_ptr<RangedLock> create_range_lock(uint64_t resource_size)
{
auto res = std::ceil(std::log2(resource_size) * 0.5);
auto exp = std::max(uint64_t(res), uint64_t(10));
uint64_t region_size = uint64_t(std::pow(2, exp));
return static_cast<std::unique_ptr<RangedLock>>(new RangedLock(region_size));
}
private:
region& get_locked_region(uint64_t region_id)
{
std::lock_guard<std::mutex> lock(_regions_lock);
auto it = _regions.find(region_id);
assert(it != _regions.end()); // assert region exists
region& r = *(it->second);
assert(r.refcount > 0); // assert region is locked
return r;
}
region& get_and_lock_region(uint64_t region_id)
{
std::lock_guard<std::mutex> lock(_regions_lock);
auto it = _regions.find(region_id);
if (it == _regions.end())
{
std::unique_ptr<region> r(new region);
auto ret = _regions.insert(std::make_pair(region_id, std::move(r)));
it = ret.first;
}
region& r = *(it->second);
r.refcount++;
return r;
}
void unlock_region(uint64_t region_id)
{
std::lock_guard<std::mutex> lock(_regions_lock);
auto it = _regions.find(region_id);
assert(it != _regions.end());
region& r = *(it->second);
if (--r.refcount == 0)
{
_regions.erase(it);
}
}
inline uint64_t get_region_id(uint64_t offset) const
{
return offset / _region_size;
}
enum class stop_iteration { no, yes };
inline void do_for_each_region(uint64_t offset, uint64_t length, std::function<stop_iteration(uint64_t)> f)
{
auto assert_alignment = [] (uint64_t v, uint64_t alignment)
{
assert((v & (alignment - 1)) == 0);
};
assert_alignment(offset, _region_size);
assert_alignment(length, _region_size);
auto regions = length / _region_size;
assert(length % _region_size == 0);
for (auto i = 0; i < regions; i++)
{
auto current_offset = offset + (i * _region_size);
stop_iteration stop = f(get_region_id(current_offset));
if (stop == stop_iteration::yes)
{
return;
}
}
}
void for_each_region(uint64_t offset, uint64_t length, std::function<stop_iteration(uint64_t)> f)
{
uint64_t aligned_down_offset = offset & ~(_region_size - 1);
uint64_t aligned_up_length = (length + _region_size - 1) & ~(_region_size - 1);
do_for_each_region(aligned_down_offset, aligned_up_length, std::move(f));
}
static inline void validate_parameters(uint64_t offset, uint64_t length)
{
assert(length > 0);
assert(offset < (offset + length)); // check for overflow
}
bool generic_try_lock(uint64_t offset, uint64_t length,
std::function<bool(uint64_t)> try_lock, std::function<void(uint64_t)> unlock)
{
std::vector<uint64_t> locked_region_ids;
bool failed_to_lock_region = false;
validate_parameters(offset, length);
for_each_region(offset, length, [&] (uint64_t region_id)
{
bool acquired = try_lock(region_id);
if (acquired)
{
locked_region_ids.push_back(region_id);
} else
{
failed_to_lock_region = true;
return stop_iteration::yes;
}
return stop_iteration::no;
});
if (failed_to_lock_region)
{
for (auto region_id : locked_region_ids)
{
unlock(region_id);
}
}
return !failed_to_lock_region;
}
public:
uint64_t region_size() const { return _region_size; }
// Lock range [offset, offset+length) for exclusive ownership.
void lock(uint64_t offset, uint64_t length)
{
validate_parameters(offset, length);
for_each_region(offset, length, [this] (uint64_t region_id)
{
region& r = this->get_and_lock_region(region_id);
r.mutex.lock();
return stop_iteration::no;
});
}
// Tries to lock the range [offset, offset+length) for exclusive ownership.
// This function returns immediately.
// On successful range acquisition returns true, otherwise returns false.
bool try_lock(uint64_t offset, uint64_t length)
{
auto try_lock_f = [this] (uint64_t region_id)
{
region& r = this->get_and_lock_region(region_id);
return r.mutex.try_lock();
};
auto unlock_f = [this] (uint64_t region_id)
{
region& r = this->get_locked_region(region_id);
r.mutex.unlock();
this->unlock_region(region_id);
};
return generic_try_lock(offset, length, try_lock_f, unlock_f);
}
// Unlock range [offset, offset+length) from exclusive ownership.
void unlock(uint64_t offset, uint64_t length) {
validate_parameters(offset, length);
for_each_region(offset, length, [this] (uint64_t region_id) {
region& r = this->get_locked_region(region_id);
r.mutex.unlock();
this->unlock_region(region_id);
return stop_iteration::no;
});
}
// Execute an operation with range [offset, offset+length) locked for exclusive ownership.
template <typename Func>
void with_lock(uint64_t offset, uint64_t length, Func&& func)
{
lock(offset, length);
func();
unlock(offset, length);
}
#if (__cplusplus >= 201402L)
// Lock range [offset, offset+length) for shared ownership.
void lock_shared(uint64_t offset, uint64_t length)
{
validate_parameters(offset, length);
for_each_region(offset, length, [this] (uint64_t region_id)
{
region& r = this->get_and_lock_region(region_id);
r.mutex.lock_shared();
return stop_iteration::no;
});
}
// Tries to lock the range [offset, offset+length) for shared ownership.
// This function returns immediately.
// On successful range acquisition returns true, otherwise returns false.
bool try_lock_shared(uint64_t offset, uint64_t length)
{
auto try_lock_f = [this] (uint64_t region_id)
{
region& r = this->get_and_lock_region(region_id);
return r.mutex.try_lock_shared();
};
auto unlock_f = [this] (uint64_t region_id)
{
region& r = this->get_locked_region(region_id);
r.mutex.unlock_shared();
this->unlock_region(region_id);
};
return generic_try_lock(offset, length, try_lock_f, unlock_f);
}
// Unlock range [offset, offset+length) from shared ownership.
void unlock_shared(uint64_t offset, uint64_t length)
{
validate_parameters(offset, length);
for_each_region(offset, length, [this] (uint64_t region_id)
{
region& r = this->get_locked_region(region_id);
r.mutex.unlock_shared();
this->unlock_region(region_id);
return stop_iteration::no;
});
}
// Execute an operation with range [offset, offset+length) locked for shared ownership.
template <typename Func>
void with_lock_shared(uint64_t offset, uint64_t length, Func&& func)
{
lock_shared(offset, length);
func();
unlock_shared(offset, length);
}
#else
/// If __cplusplus < 201402L, lock functions for shared ownership will call
/// corresponding lock functions for exclusive ownership.
/// That's because std::shared_timed_mutex is only available from C++14 on.
/// This decision is also important to not break compilation of programs (when
/// __cplusplus < 201402L) that use these functions.
#warning __cplusplus < 201402L, so lock for shared ownership will lock a range \
for exclusive ownership instead. That can be changed by using the -std=c++14 \
or -std=gnu++14 compiler options.
void lock_shared(uint64_t offset, uint64_t length)
{
lock(offset, length);
}
bool try_lock_shared(uint64_t offset, uint64_t length)
{
return try_lock(offset, length);
}
void unlock_shared(uint64_t offset, uint64_t length)
{
unlock(offset, length);
}
template <typename Func>
void with_lock_shared(uint64_t offset, uint64_t length, Func&& func)
{
with_lock(offset, length, std::move(func));
}
#endif
};
}
/*
///
/// Purpose of this program is to test range_lock implementation.
///
/// Sincerely,
/// Raphael Carvalho
///
#include "range_lock.hh"
#include <iostream>
#include <thread>
#include <assert.h>
#define print_test_name() \
std::cout << "\nRunning " << __FUNCTION__ << "...\n";
static void basic_range_lock_test(range_lock& range_lock) {
print_test_name();
auto t = std::thread([&range_lock] {
std::cout << "Trying to lock [0, 1024)\n";
range_lock.with_lock(0, 1024, [] {
std::cout << "Locked [0, 1024) properly, sleeping for 2 seconds...\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
});
std::cout << "Unlocked [0, 1024) properly\n";
});
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Trying to lock [0, 1024*1024)\n";
range_lock.with_lock(0, 1024*1024, [] {
std::cout << "Locked [0, 1024*1024) properly\n";
});
std::cout << "Unlocked [0, 1024*1024) properly\n";
t.join();
}
static void basic_range_lock_shared_test(range_lock& range_lock) {
#if (__cplusplus >= 201402L)
print_test_name();
auto print_message = [] (auto thread_id, auto message) {
std::cout << "[thread " << thread_id << "] " << message << std::endl;
};
std::vector<std::thread> ts;
for (auto i = 0; i < 5; i++) {
auto t = std::thread([&range_lock, &print_message, i] {
print_message(i, "Requiring immediate shared ownership from [0, 1024)");
bool acquired = range_lock.try_lock_shared(0, 1024);
assert(acquired);
print_message(i, "Succeeded");
std::this_thread::sleep_for(std::chrono::seconds(2));
range_lock.unlock_shared(0, 1024);
});
ts.push_back(std::move(t));
}
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Checking that [0, 8192) cannot be acquired for exclusive ownership\n";
bool acquired = range_lock.try_lock(0, 8192);
assert(!acquired);
std::cout << "Succeeded\n";
for (auto& t : ts) {
t.join();
}
std::cout << "All threads released their lock for shared ownership\n";
std::cout << "Checking that [0, 8192) can be acquired for exclusive ownership\n";
acquired = range_lock.try_lock(0, 8192);
assert(acquired);
range_lock.unlock(0, 8192);
std::cout << "Succeeded\n";
#endif
}
static void try_lock_test(range_lock& range_lock) {
print_test_name();
auto t = std::thread([&range_lock] {
std::cout << "Trying to lock [4096, 8192)\n";
range_lock.with_lock(4096, 8192, [] {
std::cout << "Locked [4096, 8192) properly, sleeping for 2 second...\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
});
std::cout << "Unlocked [4096, 8192) properly\n";
});
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Checking that [0, 8192) cannot be immediately acquired\n";
bool acquired = range_lock.try_lock(0, 8192);
assert(!acquired);
std::cout << "Succeeded\n";
t.join();
std::cout << "Checking that [0, 8192) can be immediately acquired\n";
acquired = range_lock.try_lock(0, 8192);
assert(acquired);
range_lock.unlock(0, 8192);
std::cout << "Succeeded\n";
}
int main(void) {
auto range_lock = range_lock::create_range_lock(pow(2, 30));
std::cout << "Range lock granularity (a.k.a. region size): " << range_lock->region_size() << std::endl;
basic_range_lock_test(*range_lock);
basic_range_lock_shared_test(*range_lock);
try_lock_test(*range_lock);
return 0;
}
*/
| 28.588448
| 115
| 0.599508
|
jlandess
|
40fd0a8609b02bb65ea7a39246ba53b7c63bdf92
| 3,453
|
cc
|
C++
|
cartographer/mapping_3d/local_trajectory_builder_options.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 36
|
2017-01-17T10:19:30.000Z
|
2022-02-13T09:11:51.000Z
|
cartographer/mapping_3d/local_trajectory_builder_options.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | null | null | null |
cartographer/mapping_3d/local_trajectory_builder_options.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 37
|
2016-10-09T01:52:45.000Z
|
2022-01-22T10:51:54.000Z
|
/*
* Copyright 2016 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cartographer/mapping_3d/local_trajectory_builder_options.h"
#include "cartographer/mapping_3d/kalman_local_trajectory_builder_options.h"
#include "cartographer/mapping_3d/motion_filter.h"
#include "cartographer/mapping_3d/optimizing_local_trajectory_builder_options.h"
#include "cartographer/mapping_3d/scan_matching/ceres_scan_matcher.h"
#include "cartographer/mapping_3d/submaps.h"
#include "cartographer/sensor/voxel_filter.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping_3d {
proto::LocalTrajectoryBuilderOptions CreateLocalTrajectoryBuilderOptions(
common::LuaParameterDictionary* const parameter_dictionary) {
proto::LocalTrajectoryBuilderOptions options;
options.set_laser_min_range(
parameter_dictionary->GetDouble("laser_min_range"));
options.set_laser_max_range(
parameter_dictionary->GetDouble("laser_max_range"));
options.set_scans_per_accumulation(
parameter_dictionary->GetInt("scans_per_accumulation"));
options.set_laser_voxel_filter_size(
parameter_dictionary->GetDouble("laser_voxel_filter_size"));
*options.mutable_high_resolution_adaptive_voxel_filter_options() =
sensor::CreateAdaptiveVoxelFilterOptions(
parameter_dictionary
->GetDictionary("high_resolution_adaptive_voxel_filter")
.get());
*options.mutable_low_resolution_adaptive_voxel_filter_options() =
sensor::CreateAdaptiveVoxelFilterOptions(
parameter_dictionary
->GetDictionary("low_resolution_adaptive_voxel_filter")
.get());
*options.mutable_ceres_scan_matcher_options() =
scan_matching::CreateCeresScanMatcherOptions(
parameter_dictionary->GetDictionary("ceres_scan_matcher").get());
*options.mutable_motion_filter_options() = CreateMotionFilterOptions(
parameter_dictionary->GetDictionary("motion_filter").get());
*options.mutable_submaps_options() = mapping_3d::CreateSubmapsOptions(
parameter_dictionary->GetDictionary("submaps").get());
*options.mutable_kalman_local_trajectory_builder_options() =
CreateKalmanLocalTrajectoryBuilderOptions(
parameter_dictionary->GetDictionary("kalman_local_trajectory_builder")
.get());
*options.mutable_optimizing_local_trajectory_builder_options() =
CreateOptimizingLocalTrajectoryBuilderOptions(
parameter_dictionary
->GetDictionary("optimizing_local_trajectory_builder")
.get());
const string use_string = parameter_dictionary->GetString("use");
proto::LocalTrajectoryBuilderOptions::Use use;
CHECK(proto::LocalTrajectoryBuilderOptions::Use_Parse(use_string, &use))
<< "Unknown local_trajectory_builder kind: " << use_string;
options.set_use(use);
return options;
}
} // namespace mapping_3d
} // namespace cartographer
| 44.844156
| 80
| 0.769765
|
linghusmile
|
40fdbab2f79cfb42656c4ffef34768559455a270
| 7,958
|
cpp
|
C++
|
third_party/subzero/crosstest/test_fcmp_main.cpp
|
sunnycase/swiftshader
|
592bce0dc7daaa8d2c7ee4b94bec98e0e7beeacc
|
[
"Apache-2.0"
] | 1,570
|
2016-06-30T10:40:04.000Z
|
2022-03-31T01:47:33.000Z
|
third_party/subzero/crosstest/test_fcmp_main.cpp
|
sunnycase/swiftshader
|
592bce0dc7daaa8d2c7ee4b94bec98e0e7beeacc
|
[
"Apache-2.0"
] | 9
|
2017-01-16T07:09:08.000Z
|
2020-08-25T18:28:59.000Z
|
third_party/subzero/crosstest/test_fcmp_main.cpp
|
sunnycase/swiftshader
|
592bce0dc7daaa8d2c7ee4b94bec98e0e7beeacc
|
[
"Apache-2.0"
] | 253
|
2016-06-30T18:57:10.000Z
|
2022-03-25T03:57:40.000Z
|
//===- subzero/crosstest/test_fcmp_main.cpp - Driver for tests ------------===//
//
// The Subzero Code Generator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Driver for cross testing the fcmp bitcode instruction
//
//===----------------------------------------------------------------------===//
/* crosstest.py --test=test_fcmp.pnacl.ll --driver=test_fcmp_main.cpp \
--prefix=Subzero_ --output=test_fcmp */
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstring>
#include <iostream>
#include "test_arith.def"
#include "test_fcmp.def"
#include "vectors.h"
#define X(cmp) \
extern "C" bool fcmp##cmp##Float(float a, float b); \
extern "C" bool fcmp##cmp##Double(double a, double b); \
extern "C" int fcmpSelect##cmp##Float(float a, float b, int c, int d); \
extern "C" int fcmpSelect##cmp##Double(double a, double b, int c, int d); \
extern "C" v4si32 fcmp##cmp##Vector(v4f32 a, v4f32 b); \
extern "C" bool Subzero_fcmp##cmp##Float(float a, float b); \
extern "C" bool Subzero_fcmp##cmp##Double(double a, double b); \
extern "C" int Subzero_fcmpSelect##cmp##Float(float a, float b, int c, \
int d); \
extern "C" int Subzero_fcmpSelect##cmp##Double(double a, double b, int c, \
int d); \
extern "C" v4si32 Subzero_fcmp##cmp##Vector(v4f32 a, v4f32 b);
FCMP_TABLE;
#undef X
volatile double *Values;
size_t NumValues;
void initializeValues() {
static const double NegInf = -1.0 / 0.0;
static const double Zero = 0.0;
static const double PosInf = 1.0 / 0.0;
static const double Nan = 0.0 / 0.0;
static const double NegNan = -0.0 / 0.0;
assert(std::fpclassify(NegInf) == FP_INFINITE);
assert(std::fpclassify(PosInf) == FP_INFINITE);
assert(std::fpclassify(Nan) == FP_NAN);
assert(std::fpclassify(NegNan) == FP_NAN);
assert(NegInf < Zero);
assert(NegInf < PosInf);
assert(Zero < PosInf);
static volatile double InitValues[] =
FP_VALUE_ARRAY(NegInf, PosInf, NegNan, Nan);
NumValues = sizeof(InitValues) / sizeof(*InitValues);
Values = InitValues;
}
void testsScalar(size_t &TotalTests, size_t &Passes, size_t &Failures) {
typedef bool (*FuncTypeFloat)(float, float);
typedef bool (*FuncTypeDouble)(double, double);
typedef int (*FuncTypeFloatSelect)(float, float, int, int);
typedef int (*FuncTypeDoubleSelect)(double, double, int, int);
static struct {
const char *Name;
FuncTypeFloat FuncFloatSz;
FuncTypeFloat FuncFloatLlc;
FuncTypeDouble FuncDoubleSz;
FuncTypeDouble FuncDoubleLlc;
FuncTypeFloatSelect FuncFloatSelectSz;
FuncTypeFloatSelect FuncFloatSelectLlc;
FuncTypeDoubleSelect FuncDoubleSelectSz;
FuncTypeDoubleSelect FuncDoubleSelectLlc;
} Funcs[] = {
#define X(cmp) \
{"fcmp" STR(cmp), Subzero_fcmp##cmp##Float, \
fcmp##cmp##Float, Subzero_fcmp##cmp##Double, \
fcmp##cmp##Double, Subzero_fcmpSelect##cmp##Float, \
fcmpSelect##cmp##Float, Subzero_fcmpSelect##cmp##Double, \
fcmpSelect##cmp##Double},
FCMP_TABLE
#undef X
};
const static size_t NumFuncs = sizeof(Funcs) / sizeof(*Funcs);
bool ResultSz, ResultLlc;
assert(Values && NumValues);
for (size_t f = 0; f < NumFuncs; ++f) {
for (size_t i = 0; i < NumValues; ++i) {
for (size_t j = 0; j < NumValues; ++j) {
++TotalTests;
float Value1Float = Values[i];
float Value2Float = Values[j];
ResultSz = Funcs[f].FuncFloatSz(Value1Float, Value2Float);
ResultLlc = Funcs[f].FuncFloatLlc(Value1Float, Value2Float);
if (ResultSz == ResultLlc) {
++Passes;
} else {
++Failures;
std::cout << Funcs[f].Name << "Float(" << Value1Float << ", "
<< Value2Float << "): sz=" << ResultSz
<< " llc=" << ResultLlc << "\n";
}
++TotalTests;
double Value1Double = Values[i];
double Value2Double = Values[j];
ResultSz = Funcs[f].FuncDoubleSz(Value1Double, Value2Double);
ResultLlc = Funcs[f].FuncDoubleLlc(Value1Double, Value2Double);
if (ResultSz == ResultLlc) {
++Passes;
} else {
++Failures;
std::cout << Funcs[f].Name << "Double(" << Value1Double << ", "
<< Value2Double << "): sz=" << ResultSz
<< " llc=" << ResultLlc << "\n";
}
++TotalTests;
float Value1SelectFloat = Values[i];
float Value2SelectFloat = Values[j];
ResultSz = Funcs[f].FuncFloatSelectSz(Value1Float, Value2Float, 1, 2);
ResultLlc = Funcs[f].FuncFloatSelectLlc(Value1Float, Value2Float, 1, 2);
if (ResultSz == ResultLlc) {
++Passes;
} else {
++Failures;
std::cout << Funcs[f].Name << "SelectFloat(" << Value1Float << ", "
<< Value2Float << "): sz=" << ResultSz
<< " llc=" << ResultLlc << "\n";
}
++TotalTests;
double Value1SelectDouble = Values[i];
double Value2SelectDouble = Values[j];
ResultSz =
Funcs[f].FuncDoubleSelectSz(Value1Double, Value2Double, 1, 2);
ResultLlc =
Funcs[f].FuncDoubleSelectLlc(Value1Double, Value2Double, 1, 2);
if (ResultSz == ResultLlc) {
++Passes;
} else {
++Failures;
std::cout << Funcs[f].Name << "SelectDouble(" << Value1Double << ", "
<< Value2Double << "): sz=" << ResultSz
<< " llc=" << ResultLlc << "\n";
}
}
}
}
}
void testsVector(size_t &TotalTests, size_t &Passes, size_t &Failures) {
typedef v4si32 (*FuncTypeVector)(v4f32, v4f32);
static struct {
const char *Name;
FuncTypeVector FuncVectorSz;
FuncTypeVector FuncVectorLlc;
} Funcs[] = {
#define X(cmp) {"fcmp" STR(cmp), Subzero_fcmp##cmp##Vector, fcmp##cmp##Vector},
FCMP_TABLE
#undef X
};
const static size_t NumFuncs = sizeof(Funcs) / sizeof(*Funcs);
const static size_t NumElementsInType = 4;
const static size_t MaxTestsPerFunc = 100000;
assert(Values && NumValues);
for (size_t f = 0; f < NumFuncs; ++f) {
PRNG Index;
for (size_t i = 0; i < MaxTestsPerFunc; ++i) {
v4f32 Value1, Value2;
for (size_t j = 0; j < NumElementsInType; ++j) {
Value1[j] = Values[Index() % NumValues];
Value2[j] = Values[Index() % NumValues];
}
++TotalTests;
v4si32 ResultSz, ResultLlc;
ResultSz = Funcs[f].FuncVectorSz(Value1, Value2);
ResultLlc = Funcs[f].FuncVectorLlc(Value1, Value2);
if (!memcmp(&ResultSz, &ResultLlc, sizeof(ResultSz))) {
++Passes;
} else {
++Failures;
std::cout << Funcs[f].Name << "Vector(" << vectAsString<v4f32>(Value1)
<< ", " << vectAsString<v4f32>(Value2)
<< "): sz=" << vectAsString<v4si32>(ResultSz)
<< " llc=" << vectAsString<v4si32>(ResultLlc) << "\n";
}
}
}
}
int main(int argc, char *argv[]) {
size_t TotalTests = 0;
size_t Passes = 0;
size_t Failures = 0;
initializeValues();
testsScalar(TotalTests, Passes, Failures);
testsVector(TotalTests, Passes, Failures);
std::cout << "TotalTests=" << TotalTests << " Passes=" << Passes
<< " Failures=" << Failures << "\n";
return Failures;
}
| 37.186916
| 80
| 0.554788
|
sunnycase
|
40fea15f64ce7f4eb436e57ebc018d3c7561b382
| 912
|
cpp
|
C++
|
CppPool/cpp_d14a/ex02/CommunicationDevice.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 40
|
2018-01-28T14:23:27.000Z
|
2022-03-05T15:57:47.000Z
|
CppPool/cpp_d14a/ex02/CommunicationDevice.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 1
|
2021-10-05T09:03:51.000Z
|
2021-10-05T09:03:51.000Z
|
CppPool/cpp_d14a/ex02/CommunicationDevice.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 73
|
2019-01-07T18:47:00.000Z
|
2022-03-31T08:48:38.000Z
|
#include <iostream>
#include <stdexcept>
#include "Errors.hpp"
#include "CommunicationDevice.hpp"
CommunicationDevice::CommunicationDevice(std::istream &input,
std::ostream &output)
: _api(input, output)
{
}
CommunicationDevice::~CommunicationDevice()
{
}
void
CommunicationDevice::startMission(std::string const &missionName,
std::string *users,
size_t nbUsers)
{
for (size_t i = 0; i < nbUsers; ++i)
_api.addUser(users[i]);
_api.startMission(missionName);
}
void
CommunicationDevice::send(std::string const &user,
std::string const &message) const
{
_api.sendMessage(user, message);
}
void
CommunicationDevice::receive(std::string const &user,
std::string &message) const
{
_api.receiveMessage(user, message);
}
| 22.8
| 65
| 0.596491
|
667MARTIN
|
dc0030e5d338de53e6a2df695a2c5b427c808c4e
| 4,710
|
cpp
|
C++
|
gecode/search/meta/rbs.cpp
|
zoomer/gecode
|
b16d00b209bba8602233a087be50d2d11ddba5fa
|
[
"MIT-feh"
] | 1
|
2017-05-10T05:42:43.000Z
|
2017-05-10T05:42:43.000Z
|
gecode/search/meta/rbs.cpp
|
eatstreet/gecode
|
b16d00b209bba8602233a087be50d2d11ddba5fa
|
[
"MIT-feh"
] | null | null | null |
gecode/search/meta/rbs.cpp
|
eatstreet/gecode
|
b16d00b209bba8602233a087be50d2d11ddba5fa
|
[
"MIT-feh"
] | 1
|
2017-01-27T14:52:22.000Z
|
2017-01-27T14:52:22.000Z
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2012
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 <gecode/search/meta/rbs.hh>
namespace Gecode { namespace Search { namespace Meta {
bool
RestartStop::stop(const Statistics& s, const Options& o) {
// Stop if the fail limit for the engine says so
if (s.fail > l) {
e_stopped = true;
m_stat.restart++;
return true;
}
// Stop if the stop object for the meta engine says so
if ((m_stop != NULL) && m_stop->stop(m_stat+s,o)) {
e_stopped = false;
return true;
}
return false;
}
Space*
RBS::next(void) {
if (restart) {
restart = false;
sslr++;
NoGoods& ng = e->nogoods();
// Reset number of no-goods found
ng.ng(0);
MetaInfo mi(stop->m_stat.restart,sslr,e->statistics().fail,last,ng);
bool r = master->master(mi);
stop->m_stat.nogood += ng.ng();
if (master->status(stop->m_stat) == SS_FAILED) {
stop->update(e->statistics());
delete master;
master = NULL;
e->reset(NULL);
return NULL;
} else if (r) {
stop->update(e->statistics());
Space* slave = master;
master = master->clone(shared_data,shared_info);
complete = slave->slave(mi);
e->reset(slave);
sslr = 0;
stop->m_stat.restart++;
}
}
while (true) {
Space* n = e->next();
if (n != NULL) {
// The engine found a solution
restart = true;
delete last;
last = n->clone();
return n;
} else if ( (!complete && !e->stopped()) ||
(e->stopped() && stop->enginestopped()) ) {
// The engine must perform a true restart
// The number of the restart has been incremented in the stop object
sslr = 0;
NoGoods& ng = e->nogoods();
ng.ng(0);
MetaInfo mi(stop->m_stat.restart,sslr,e->statistics().fail,last,ng);
(void) master->master(mi);
stop->m_stat.nogood += ng.ng();
long unsigned int nl = ++(*co);
stop->limit(e->statistics(),nl);
if (master->status(stop->m_stat) == SS_FAILED)
return NULL;
Space* slave = master;
master = master->clone(shared_data,shared_info);
complete = slave->slave(mi);
e->reset(slave);
} else {
return NULL;
}
}
GECODE_NEVER;
return NULL;
}
Search::Statistics
RBS::statistics(void) const {
return stop->metastatistics()+e->statistics();
}
void
RBS::constrain(const Space& b) {
if (!best)
throw NoBest("RBS::constrain");
if (last != NULL) {
last->constrain(b);
if (last->status() == SS_FAILED) {
delete last;
} else {
return;
}
}
last = b.clone();
master->constrain(b);
e->constrain(b);
}
bool
RBS::stopped(void) const {
/*
* What might happen during parallel search is that the
* engine has been stopped but the meta engine has not, so
* the meta engine does not perform a restart. However the
* invocation of next will do so and no restart will be
* missed.
*/
return e->stopped();
}
RBS::~RBS(void) {
delete e;
delete master;
delete last;
delete co;
delete stop;
}
}}}
// STATISTICS: search-meta
| 28.373494
| 76
| 0.597452
|
zoomer
|
dc07f13d82d176b096db17e55847fc38ec06d610
| 882
|
cc
|
C++
|
tests/fullscreen_test.cc
|
ogukei/cinderella-screen
|
f3fb188e521cd2d0f960b1ec19d8a28c014d7c53
|
[
"MIT"
] | null | null | null |
tests/fullscreen_test.cc
|
ogukei/cinderella-screen
|
f3fb188e521cd2d0f960b1ec19d8a28c014d7c53
|
[
"MIT"
] | null | null | null |
tests/fullscreen_test.cc
|
ogukei/cinderella-screen
|
f3fb188e521cd2d0f960b1ec19d8a28c014d7c53
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include "fullscreen.h"
TEST(FullscreenTest, FullHD) {
SIZE frame_size = {1920, 1080};
SIZE aspect_ratio = {16, 9};
imascs::WindowResizeConstraint constraint(frame_size, aspect_ratio);
imascs::WindowResizeConfiguration configuration(constraint);
EXPECT_EQ(configuration.Offset().x, 0);
EXPECT_EQ(configuration.Offset().y, 0);
EXPECT_EQ(configuration.Size().cx, 1920);
EXPECT_EQ(configuration.Size().cy, 1080);
}
TEST(FullscreenTest, _4K) {
SIZE frame_size = {3840, 2160};
SIZE aspect_ratio = {16, 9};
imascs::WindowResizeConstraint constraint(frame_size, aspect_ratio);
imascs::WindowResizeConfiguration configuration(constraint);
EXPECT_EQ(configuration.Offset().x, 0);
EXPECT_EQ(configuration.Offset().y, 0);
EXPECT_EQ(configuration.Size().cx, 3840);
EXPECT_EQ(configuration.Size().cy, 2160);
}
| 33.923077
| 71
| 0.72449
|
ogukei
|
dc0a7b06811f3c617fe87767b087a9dd48f0fd95
| 4,015
|
cpp
|
C++
|
ndn-cxx/security/pib/impl/key-impl.cpp
|
Pesa/ndn-cxx
|
0249d71d97b2f1f5313f24cec7c84450a795f2ca
|
[
"OpenSSL"
] | null | null | null |
ndn-cxx/security/pib/impl/key-impl.cpp
|
Pesa/ndn-cxx
|
0249d71d97b2f1f5313f24cec7c84450a795f2ca
|
[
"OpenSSL"
] | null | null | null |
ndn-cxx/security/pib/impl/key-impl.cpp
|
Pesa/ndn-cxx
|
0249d71d97b2f1f5313f24cec7c84450a795f2ca
|
[
"OpenSSL"
] | null | null | null |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2021 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx 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 3 of the License, or (at your option) any later version.
*
* ndn-cxx 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 copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#include "ndn-cxx/security/pib/impl/key-impl.hpp"
#include "ndn-cxx/security/pib/pib-impl.hpp"
#include "ndn-cxx/security/pib/pib.hpp"
#include "ndn-cxx/security/transform/public-key.hpp"
namespace ndn {
namespace security {
namespace pib {
namespace detail {
KeyImpl::KeyImpl(const Name& keyName, span<const uint8_t> key, shared_ptr<PibImpl> pibImpl)
: m_identity(extractIdentityFromKeyName(keyName))
, m_keyName(keyName)
, m_key(key.begin(), key.end())
, m_pib(std::move(pibImpl))
, m_certificates(keyName, m_pib)
, m_isDefaultCertificateLoaded(false)
{
BOOST_ASSERT(m_pib != nullptr);
transform::PublicKey publicKey;
try {
publicKey.loadPkcs8(key);
}
catch (const transform::PublicKey::Error&) {
NDN_THROW_NESTED(std::invalid_argument("Invalid key bits"));
}
m_keyType = publicKey.getKeyType();
m_pib->addKey(m_identity, m_keyName, key);
}
KeyImpl::KeyImpl(const Name& keyName, shared_ptr<PibImpl> pibImpl)
: m_identity(extractIdentityFromKeyName(keyName))
, m_keyName(keyName)
, m_pib(std::move(pibImpl))
, m_certificates(keyName, m_pib)
, m_isDefaultCertificateLoaded(false)
{
BOOST_ASSERT(m_pib != nullptr);
m_key = m_pib->getKeyBits(m_keyName);
transform::PublicKey key;
key.loadPkcs8(m_key);
m_keyType = key.getKeyType();
}
void
KeyImpl::addCertificate(const Certificate& certificate)
{
BOOST_ASSERT(m_certificates.isConsistent());
m_certificates.add(certificate);
}
void
KeyImpl::removeCertificate(const Name& certName)
{
BOOST_ASSERT(m_certificates.isConsistent());
if (m_isDefaultCertificateLoaded && m_defaultCertificate.getName() == certName)
m_isDefaultCertificateLoaded = false;
m_certificates.remove(certName);
}
Certificate
KeyImpl::getCertificate(const Name& certName) const
{
BOOST_ASSERT(m_certificates.isConsistent());
return m_certificates.get(certName);
}
const CertificateContainer&
KeyImpl::getCertificates() const
{
BOOST_ASSERT(m_certificates.isConsistent());
return m_certificates;
}
const Certificate&
KeyImpl::setDefaultCertificate(const Name& certName)
{
BOOST_ASSERT(m_certificates.isConsistent());
m_defaultCertificate = m_certificates.get(certName);
m_pib->setDefaultCertificateOfKey(m_keyName, certName);
m_isDefaultCertificateLoaded = true;
return m_defaultCertificate;
}
const Certificate&
KeyImpl::setDefaultCertificate(const Certificate& certificate)
{
addCertificate(certificate);
return setDefaultCertificate(certificate.getName());
}
const Certificate&
KeyImpl::getDefaultCertificate() const
{
BOOST_ASSERT(m_certificates.isConsistent());
if (!m_isDefaultCertificateLoaded) {
m_defaultCertificate = m_pib->getDefaultCertificateOfKey(m_keyName);
m_isDefaultCertificateLoaded = true;
}
BOOST_ASSERT(m_pib->getDefaultCertificateOfKey(m_keyName).wireEncode() == m_defaultCertificate.wireEncode());
return m_defaultCertificate;
}
} // namespace detail
} // namespace pib
} // namespace security
} // namespace ndn
| 29.094203
| 111
| 0.757659
|
Pesa
|
dc122bc17a5aa63495182c8d7ffaf007e36e886a
| 22,940
|
cpp
|
C++
|
MSVC/14.24.28314/atlmfc/src/mfc/afxribbonconstructor.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 2
|
2021-01-27T10:19:30.000Z
|
2021-02-09T06:24:30.000Z
|
MSVC/14.24.28314/atlmfc/src/mfc/afxribbonconstructor.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | null | null | null |
MSVC/14.24.28314/atlmfc/src/mfc/afxribbonconstructor.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 1
|
2021-01-27T10:19:36.000Z
|
2021-01-27T10:19:36.000Z
|
// This MFC Library source code supports the Microsoft Office Fluent User Interface
// (the "Fluent UI") and is provided only as referential material to supplement the
// Microsoft Foundation Classes Reference and related electronic documentation
// included with the MFC C++ library software.
// License terms to copy, use or distribute the Fluent UI are available separately.
// To learn more about our Fluent UI licensing program, please visit
// http://go.microsoft.com/fwlink/?LinkId=238214.
//
// Copyright (C) Microsoft Corporation
// All rights reserved.
#include "stdafx.h"
#include "afxribbonconstructor.h"
#include "afxribboncategory.h"
#include "afxribboncombobox.h"
#include "afxribbonpalettegallery.h"
#include "afxribbonlabel.h"
#include "afxribbonundobutton.h"
#include "afxribboncolorbutton.h"
#include "afxribbonlinkctrl.h"
#include "afxribboncheckbox.h"
#include "afxribbonslider.h"
#include "afxribbonprogressbar.h"
#include "afxribbonmainpanel.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMFCRibbonConstructor::CMFCRibbonConstructor(const CMFCRibbonInfo& info) : m_Info(info)
{
}
CMFCRibbonConstructor::~CMFCRibbonConstructor()
{
}
CMFCRibbonPanel* CMFCRibbonConstructor::CreatePanel(CMFCRibbonCategory& category, const CMFCRibbonInfo::XPanel& info) const
{
HICON hIcon = NULL;
if (info.m_nImageIndex != -1)
{
hIcon = const_cast<CMFCToolBarImages&>(GetInfo().GetRibbonBar().m_Images.m_Image).ExtractIcon(info.m_nImageIndex);
}
return category.AddPanel(info.m_strName, hIcon);
}
CMFCRibbonCategory* CMFCRibbonConstructor::CreateCategory(CMFCRibbonBar& bar, const CMFCRibbonInfo::XCategory& info) const
{
return bar.AddCategory(info.m_strName, 0, 0, GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesSmall), GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesLarge));
}
CMFCRibbonCategory* CMFCRibbonConstructor::CreateCategoryContext(CMFCRibbonBar& bar, const CMFCRibbonInfo::XContext& infoContext, const CMFCRibbonInfo::XCategory& info) const
{
return bar.AddContextCategory(info.m_strName, infoContext.m_strText, infoContext.m_ID.m_Value, infoContext.m_Color, 0, 0, GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesSmall), GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesLarge));
}
CMFCRibbonMainPanel* CMFCRibbonConstructor::CreateCategoryMain(CMFCRibbonBar& bar, const CMFCRibbonInfo::XCategoryMain& info) const
{
return bar.AddMainCategory(info.m_strName, 0, 0, GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesSmall), GetInfo().GetImageSize(CMFCRibbonInfo::e_ImagesLarge));
}
CMFCRibbonApplicationButton* CMFCRibbonConstructor::CreateApplicationButton(CMFCRibbonBar& bar) const
{
bar.m_bAutoDestroyMainButton = TRUE;
bar.SetApplicationButton(new CMFCRibbonApplicationButton, CSize(45, 45));
return bar.GetApplicationButton();
}
void CMFCRibbonConstructor::ConstructRibbonBar(CMFCRibbonBar& bar) const
{
const CMFCRibbonInfo::XRibbonBar& infoBar = GetInfo().GetRibbonBar();
CMFCRibbonPanel::m_nNextPanelID = (UINT)-10;
bar.EnableToolTips (infoBar.m_bToolTip, infoBar.m_bToolTipDescr);
bar.EnableKeyTips (infoBar.m_bKeyTips);
bar.EnablePrintPreview(infoBar.m_bPrintPreview);
CMFCRibbonFontComboBox::m_bDrawUsingFont = infoBar.m_bDrawUsingFont;
if (infoBar.m_btnMain != NULL)
{
CMFCRibbonApplicationButton* btnMain = bar.GetApplicationButton();
if (btnMain == NULL)
{
btnMain = CreateApplicationButton(bar);
}
if (btnMain != NULL)
{
ConstructElement(*btnMain, *infoBar.m_btnMain);
}
}
if (infoBar.m_MainCategory != NULL)
{
ConstructCategoryMain(bar, *infoBar.m_MainCategory);
}
ConstructTabElements(bar, infoBar);
int i = 0;
for(i = 0; i < infoBar.m_arCategories.GetSize(); i++)
{
const CMFCRibbonInfo::XCategory& infoCategory = *(const CMFCRibbonInfo::XCategory*)infoBar.m_arCategories[i];
CMFCRibbonCategory* pCategory = CreateCategory(bar, infoCategory);
if (pCategory != NULL)
{
ASSERT_VALID(pCategory);
ConstructCategory(*pCategory, infoCategory);
}
}
for(i = 0; i < infoBar.m_arContexts.GetSize(); i++)
{
const CMFCRibbonInfo::XContext* context = infoBar.m_arContexts[i];
for(int j = 0; j < context->m_arCategories.GetSize(); j++)
{
const CMFCRibbonInfo::XCategory& infoCategory = *(const CMFCRibbonInfo::XCategory*)context->m_arCategories[j];
CMFCRibbonCategory* pCategory = CreateCategoryContext(bar, *context, infoCategory);
if (pCategory != NULL)
{
ASSERT_VALID(pCategory);
ConstructCategory(*pCategory, infoCategory);
}
}
}
ConstructQATElements(bar, infoBar);
}
void CMFCRibbonConstructor::ConstructCategoryMain(CMFCRibbonBar& bar, const CMFCRibbonInfo::XCategoryMain& info) const
{
CMFCRibbonMainPanel* pPanel = CreateCategoryMain(bar, info);
ASSERT_VALID(pPanel);
CMFCRibbonCategory* pCategory = bar.GetMainCategory();
ASSERT_VALID(pCategory);
const_cast<CMFCToolBarImages&>(info.m_SmallImages.m_Image).CopyTo(pCategory->GetSmallImages());
const_cast<CMFCToolBarImages&>(info.m_LargeImages.m_Image).CopyTo(pCategory->GetLargeImages());
int i = 0;
for(i = 0; i < info.m_arElements.GetSize(); i++)
{
CMFCRibbonBaseElement* pElement = CreateElement(*(const CMFCRibbonInfo::XElement*)info.m_arElements[i]);
if (pElement != NULL)
{
ASSERT_VALID(pElement);
if (info.m_arElements[i]->GetElementType() == CMFCRibbonInfo::e_TypeButton_MainPanel)
{
pPanel->AddToBottom((CMFCRibbonMainPanelButton*)pElement);
}
else
{
pPanel->Add(pElement);
}
}
}
if (info.m_bRecentListEnable)
{
pPanel->AddRecentFilesList(info.m_strRecentListLabel, info.m_nRecentListWidth);
}
}
void CMFCRibbonConstructor::ConstructCategory(CMFCRibbonCategory& category, const CMFCRibbonInfo::XCategory& info) const
{
const_cast<CMFCToolBarImages&>(info.m_SmallImages.m_Image).CopyTo(category.GetSmallImages());
const_cast<CMFCToolBarImages&>(info.m_LargeImages.m_Image).CopyTo(category.GetLargeImages());
category.SetKeys(info.m_strKeys);
int i = 0;
for(i = 0; i < info.m_arPanels.GetSize(); i++)
{
const CMFCRibbonInfo::XPanel& infoPanel = *(const CMFCRibbonInfo::XPanel*)info.m_arPanels[i];
CMFCRibbonPanel* pPanel = CreatePanel(category, infoPanel);
if (pPanel != NULL)
{
ASSERT_VALID(pPanel);
ConstructPanel(*pPanel, infoPanel);
}
}
for(i = 0; i < info.m_arElements.GetSize(); i++)
{
CMFCRibbonBaseElement* pElement = CreateElement(*(const CMFCRibbonInfo::XElement*)info.m_arElements[i]);
if (pElement != NULL)
{
ASSERT_VALID(pElement);
category.AddHidden(pElement);
}
}
}
void CMFCRibbonConstructor::ConstructPanel(CMFCRibbonPanel& panel, const CMFCRibbonInfo::XPanel& info) const
{
panel.SetKeys(info.m_strKeys);
panel.SetJustifyColumns(info.m_bJustifyColumns);
panel.SetCenterColumnVert(info.m_bCenterColumnVert);
ConstructElement(panel.GetLaunchButton(), info.m_btnLaunch);
int i = 0;
for(i = 0; i < info.m_arElements.GetSize(); i++)
{
CMFCRibbonBaseElement* pElement = CreateElement(*(const CMFCRibbonInfo::XElement*)info.m_arElements[i]);
if (pElement != NULL)
{
ASSERT_VALID(pElement);
CMFCRibbonSeparator* pSeparator = DYNAMIC_DOWNCAST(CMFCRibbonSeparator, pElement);
if (pSeparator)
{
panel.AddSeparator();
delete pSeparator;
}
else
{
panel.Add(pElement);
}
}
}
}
void CMFCRibbonConstructor::ConstructQATElements(CMFCRibbonBar& bar, const CMFCRibbonInfo::XRibbonBar& info) const
{
const CMFCRibbonInfo::XQAT::XArrayQATItem& items = info.m_QAT.m_arItems;
CMFCRibbonQuickAccessToolBarDefaultState qatState;
int count = (int)items.GetSize();
for(int i = 0; i < count; i++)
{
qatState.AddCommand(items[i].m_ID.m_Value, items[i].m_bVisible);
}
bar.SetQuickAccessDefaultState(qatState);
bar.SetQuickAccessToolbarOnTop(info.m_QAT.m_bOnTop);
}
void CMFCRibbonConstructor::ConstructTabElements(CMFCRibbonBar& bar, const CMFCRibbonInfo::XRibbonBar& info) const
{
int i = 0;
for(i = 0; i < info.m_TabElements.m_arButtons.GetSize(); i++)
{
CMFCRibbonBaseElement* pElement = CreateElement(*(const CMFCRibbonInfo::XElement*)info.m_TabElements.m_arButtons[i]);
if (pElement != NULL)
{
CMFCRibbonButton* pButton = DYNAMIC_DOWNCAST(CMFCRibbonButton, pElement);
if (pButton != NULL && pButton->GetImageIndex(FALSE) != -1)
{
SetIcon(*pButton, CMFCRibbonBaseElement::RibbonImageLarge, GetInfo().GetRibbonBar().m_Images.m_Image, FALSE);
}
ASSERT_VALID(pElement);
bar.AddToTabs(pElement);
}
}
}
void CMFCRibbonConstructor::ConstructElement(CMFCRibbonBaseElement& element, const CMFCRibbonInfo::XElement& info) const
{
if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Application && element.IsKindOf(RUNTIME_CLASS(CMFCRibbonApplicationButton)))
{
ConstructBaseElement(element, info);
const CMFCRibbonInfo::XElementButtonApplication& infoElement = (const CMFCRibbonInfo::XElementButtonApplication&)info;
CMFCRibbonApplicationButton* pElement = (CMFCRibbonApplicationButton*)&element;
ASSERT_VALID(pElement);
const_cast<CMFCToolBarImages&>(infoElement.m_Image.m_Image).CopyTo(pElement->m_Image);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Launch && element.IsKindOf(RUNTIME_CLASS(CMFCRibbonLaunchButton)))
{
ConstructBaseElement(element, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeGroup && element.IsKindOf(RUNTIME_CLASS(CMFCRibbonButtonsGroup)))
{
const CMFCRibbonInfo::XElementGroup& infoElement = (const CMFCRibbonInfo::XElementGroup&)info;
CMFCRibbonButtonsGroup* pElement = (CMFCRibbonButtonsGroup*)&element;
ASSERT_VALID(pElement);
const_cast<CMFCToolBarImages&>(infoElement.m_Images.m_Image).CopyTo(pElement->m_Images);
for(int i = 0; i < infoElement.m_arButtons.GetSize(); i++)
{
CMFCRibbonBaseElement* pButton = CreateElement(*(const CMFCRibbonInfo::XElement*)infoElement.m_arButtons[i]);
if (pButton != NULL)
{
ASSERT_VALID(pButton);
pElement->AddButton(pButton);
}
}
}
else
{
ASSERT(FALSE);
}
}
void CMFCRibbonConstructor::SetID(CMFCRibbonBaseElement& element, const CMFCRibbonInfo::XID& info) const
{
element.SetID(info.m_Value);
}
void CMFCRibbonConstructor::SetIcon(CMFCRibbonButton& element, CMFCRibbonBaseElement::RibbonImageType type, const CMFCToolBarImages& images, BOOL bLargeIcon/* = FALSE*/) const
{
CMFCRibbonButton* pButton = (CMFCRibbonButton*)&element;
HICON* pIcon = &pButton->m_hIconSmall;
if (type == CMFCRibbonBaseElement::RibbonImageLarge)
{
pIcon = &pButton->m_hIcon;
}
if (*pIcon != NULL && pButton->m_bAutoDestroyIcon)
{
::DestroyIcon(*pIcon);
*pIcon = NULL;
}
*pIcon = const_cast<CMFCToolBarImages&>(images).ExtractIcon(pButton->GetImageIndex(bLargeIcon));
pButton->m_bAutoDestroyIcon = TRUE;
pButton->m_bAlphaBlendIcon = TRUE;
pButton->SetImageIndex(-1, bLargeIcon);
}
void CMFCRibbonConstructor::ConstructBaseElement(CMFCRibbonBaseElement& element, const CMFCRibbonInfo::XElement& info) const
{
element.SetText(info.m_strText);
element.SetToolTipText(info.m_strToolTip);
element.SetDescription(info.m_strDescription);
element.SetKeys(info.m_strKeys, info.m_strMenuKeys);
SetID(element, info.m_ID);
CMFCRibbonButton* pButton = DYNAMIC_DOWNCAST(CMFCRibbonButton, &element);
if (pButton != NULL)
{
const CMFCRibbonInfo::XElementButton& infoElement = (const CMFCRibbonInfo::XElementButton&)info;
if (pButton->GetIcon(FALSE) == NULL && pButton->GetIcon(TRUE) == NULL)
{
pButton->SetImageIndex(infoElement.m_nSmallImageIndex, FALSE);
pButton->SetImageIndex(infoElement.m_nLargeImageIndex, TRUE);
}
pButton->SetAlwaysLargeImage(info.m_bIsAlwaysLarge);
pButton->SetDefaultCommand(infoElement.m_bIsDefaultCommand);
CMFCRibbonGallery* pButtonGallery = DYNAMIC_DOWNCAST(CMFCRibbonGallery, pButton);
if (pButtonGallery != NULL)
{
for(int i = 0; i < infoElement.m_arSubItems.GetSize(); i++)
{
CMFCRibbonBaseElement* pSubItem = CreateElement(*(const CMFCRibbonInfo::XElement*)infoElement.m_arSubItems[i]);
if (pSubItem != NULL)
{
pButtonGallery->AddSubItem(pSubItem, -1, infoElement.m_bIsOnPaletteTop);
}
}
}
else
{
for(int i = 0; i < infoElement.m_arSubItems.GetSize(); i++)
{
CMFCRibbonBaseElement* pSubItem = CreateElement(*(const CMFCRibbonInfo::XElement*)infoElement.m_arSubItems[i]);
if (pSubItem != NULL)
{
pButton->AddSubItem(pSubItem);
if (pSubItem->GetID() >= AFX_IDM_WINDOW_FIRST && pSubItem->GetID() <= AFX_IDM_WINDOW_LAST)
{
pButton->m_bIsWindowsMenu = TRUE;
}
}
}
}
}
}
CMFCRibbonBaseElement* CMFCRibbonConstructor::CreateElement(const CMFCRibbonInfo::XElement& info) const
{
CMFCRibbonBaseElement* pElement = NULL;
int i = 0;
if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Application)
{
const CMFCRibbonInfo::XElementButtonApplication& infoElement = (const CMFCRibbonInfo::XElementButtonApplication&)info;
CMFCRibbonApplicationButton* pNewElement = new CMFCRibbonApplicationButton(infoElement.m_Image.m_Image.GetImageWell());
pElement = pNewElement;
ConstructElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Launch)
{
CMFCRibbonLaunchButton* pNewElement = new CMFCRibbonLaunchButton;
pElement = pNewElement;
ConstructElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeGroup)
{
CMFCRibbonButtonsGroup* pNewElement = new CMFCRibbonButtonsGroup;
pElement = pNewElement;
ConstructElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeLabel)
{
const CMFCRibbonInfo::XElementLabel& infoElement = (const CMFCRibbonInfo::XElementLabel&)info;
CMFCRibbonLabel* pNewElement = new CMFCRibbonLabel(infoElement.m_strText, infoElement.m_bIsAlwaysLarge);
pElement = pNewElement;
SetID(*pElement, info.m_ID);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeComboBox_Font)
{
const CMFCRibbonInfo::XElementFontComboBox& infoElement = (const CMFCRibbonInfo::XElementFontComboBox&)info;
CMFCRibbonFontComboBox* pNewElement = new CMFCRibbonFontComboBox(infoElement.m_ID.m_Value, infoElement.m_nFontType, infoElement.m_nCharSet, infoElement.m_nPitchAndFamily, infoElement.m_nWidth);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
if (infoElement.m_nWidthFloaty > 0)
{
pNewElement->SetWidth(infoElement.m_nWidthFloaty, TRUE);
}
((CMFCRibbonFontComboBox*)pNewElement)->m_bHasEditBox = infoElement.m_bHasEditBox;
pNewElement->EnableDropDownListResize(infoElement.m_bResizeDropDownList);
BOOL bDontNotify = ((CMFCRibbonEdit*)pNewElement)->m_bDontNotify;
((CMFCRibbonEdit*)pNewElement)->m_bDontNotify = TRUE;
if (!infoElement.m_strValue.IsEmpty())
{
if (!pNewElement->SelectItem(infoElement.m_strValue) && infoElement.m_bHasEditBox)
{
pNewElement->SetEditText(infoElement.m_strValue);
}
}
((CMFCRibbonEdit*)pNewElement)->m_bDontNotify = bDontNotify;
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeComboBox)
{
const CMFCRibbonInfo::XElementComboBox& infoElement = (const CMFCRibbonInfo::XElementComboBox&)info;
CMFCRibbonComboBox* pNewElement = new CMFCRibbonComboBox(infoElement.m_ID.m_Value, infoElement.m_bHasEditBox, infoElement.m_nWidth, infoElement.m_strText, infoElement.m_nSmallImageIndex);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
if (infoElement.m_nWidthFloaty > 0)
{
pNewElement->SetWidth(infoElement.m_nWidthFloaty, TRUE);
}
pNewElement->EnableDropDownListResize(infoElement.m_bResizeDropDownList);
for(i = 0; i < infoElement.m_arItems.GetSize(); i++)
{
pNewElement->AddItem(infoElement.m_arItems[i]);
}
BOOL bDontNotify = ((CMFCRibbonEdit*)pNewElement)->m_bDontNotify;
((CMFCRibbonEdit*)pNewElement)->m_bDontNotify = TRUE;
if (!infoElement.m_strValue.IsEmpty())
{
if (!pNewElement->SelectItem(infoElement.m_strValue) && infoElement.m_bHasEditBox)
{
pNewElement->SetEditText(infoElement.m_strValue);
}
}
((CMFCRibbonEdit*)pNewElement)->m_bDontNotify = bDontNotify;
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeEdit)
{
const CMFCRibbonInfo::XElementEdit& infoElement = (const CMFCRibbonInfo::XElementEdit&)info;
CMFCRibbonEdit* pNewElement = new CMFCRibbonEdit(infoElement.m_ID.m_Value, infoElement.m_nWidth, infoElement.m_strText, infoElement.m_nSmallImageIndex);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
if (infoElement.m_nWidthFloaty > 0)
{
pNewElement->SetWidth(infoElement.m_nWidthFloaty, TRUE);
}
if (infoElement.m_bHasSpinButtons)
{
pNewElement->EnableSpinButtons(infoElement.m_nMin, infoElement.m_nMax);
}
BOOL bDontNotify = pNewElement->m_bDontNotify;
pNewElement->m_bDontNotify = TRUE;
pNewElement->SetEditText(infoElement.m_strValue);
pNewElement->m_bDontNotify = bDontNotify;
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Undo)
{
const CMFCRibbonInfo::XElementButtonUndo& infoElement = (const CMFCRibbonInfo::XElementButtonUndo&)info;
CMFCRibbonUndoButton* pNewElement = new CMFCRibbonUndoButton(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_nSmallImageIndex, infoElement.m_nLargeImageIndex);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
pNewElement->SetButtonMode(infoElement.m_bIsButtonMode);
pNewElement->EnableMenuResize(infoElement.m_bEnableMenuResize, infoElement.m_bMenuResizeVertical);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Color)
{
const CMFCRibbonInfo::XElementButtonColor& infoElement = (const CMFCRibbonInfo::XElementButtonColor&)info;
CMFCRibbonColorButton* pNewElement = new CMFCRibbonColorButton(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_bSimpleButtonLook, infoElement.m_nSmallImageIndex, infoElement.m_nLargeImageIndex, infoElement.m_clrColor);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
pNewElement->EnableAutomaticButton(infoElement.m_strAutomaticBtnLabel.IsEmpty() ? NULL : (LPCTSTR)infoElement.m_strAutomaticBtnLabel, infoElement.m_clrAutomaticBtnColor, !infoElement.m_strAutomaticBtnLabel.IsEmpty(), infoElement.m_strAutomaticBtnToolTip, infoElement.m_bAutomaticBtnOnTop, infoElement.m_bAutomaticBtnBorder);
pNewElement->EnableOtherButton(infoElement.m_strOtherBtnLabel.IsEmpty() ? NULL : (LPCTSTR)infoElement.m_strOtherBtnLabel, infoElement.m_strOtherBtnToolTip);
pNewElement->SetColorBoxSize(infoElement.m_sizeIcon);
pNewElement->SetButtonMode(infoElement.m_bIsButtonMode);
pNewElement->EnableMenuResize(infoElement.m_bEnableMenuResize, infoElement.m_bMenuResizeVertical);
pNewElement->SetIconsInRow (infoElement.m_nIconsInRow);
if (infoElement.m_arGroups.GetSize() == 0)
{
if (!infoElement.m_bIsButtonMode)
{
pNewElement->AddGroup(_T(""), (int)pNewElement->m_Colors.GetSize());
pNewElement->m_bHasGroups = TRUE;
}
}
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Gallery)
{
const CMFCRibbonInfo::XElementButtonGallery& infoElement = (const CMFCRibbonInfo::XElementButtonGallery&)info;
CMFCRibbonGallery* pNewElement = new CMFCRibbonGallery(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_nSmallImageIndex, infoElement.m_nLargeImageIndex);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
pNewElement->SetButtonMode(infoElement.m_bIsButtonMode);
pNewElement->EnableMenuResize(infoElement.m_bEnableMenuResize, infoElement.m_bMenuResizeVertical);
pNewElement->SetIconsInRow (infoElement.m_nIconsInRow);
pNewElement->Clear();
const_cast<CMFCToolBarImages&>(infoElement.m_Images.m_Image).CopyTo(pNewElement->m_imagesPalette);
pNewElement->m_nIcons = pNewElement->m_imagesPalette.GetCount();
pNewElement->CreateIcons();
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_LinkCtrl)
{
const CMFCRibbonInfo::XElementButtonLinkCtrl& infoElement = (const CMFCRibbonInfo::XElementButtonLinkCtrl&)info;
CMFCRibbonLinkCtrl* pNewElement = new CMFCRibbonLinkCtrl(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_strLink);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_Check)
{
const CMFCRibbonInfo::XElementButtonCheck& infoElement = (const CMFCRibbonInfo::XElementButtonCheck&)info;
CMFCRibbonCheckBox* pNewElement = new CMFCRibbonCheckBox(infoElement.m_ID.m_Value, infoElement.m_strText);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton_MainPanel)
{
const CMFCRibbonInfo::XElementButtonMainPanel& infoElement = (const CMFCRibbonInfo::XElementButtonMainPanel&)info;
CMFCRibbonMainPanelButton* pNewElement = new CMFCRibbonMainPanelButton(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_nSmallImageIndex);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeButton)
{
const CMFCRibbonInfo::XElementButton& infoElement = (const CMFCRibbonInfo::XElementButton&)info;
CMFCRibbonButton* pNewElement = new CMFCRibbonButton(infoElement.m_ID.m_Value, infoElement.m_strText, infoElement.m_nSmallImageIndex, infoElement.m_nLargeImageIndex, infoElement.m_bIsAlwaysShowDescription);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeSlider)
{
const CMFCRibbonInfo::XElementSlider& infoElement = (const CMFCRibbonInfo::XElementSlider&)info;
CMFCRibbonSlider* pNewElement = new CMFCRibbonSlider(infoElement.m_ID.m_Value, infoElement.m_nWidth);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
pNewElement->SetZoomButtons(infoElement.m_bZoomButtons);
pNewElement->SetRange(infoElement.m_nMin, infoElement.m_nMax);
pNewElement->SetPos(infoElement.m_nPos, FALSE);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeProgress)
{
const CMFCRibbonInfo::XElementProgressBar& infoElement = (const CMFCRibbonInfo::XElementProgressBar&)info;
CMFCRibbonProgressBar* pNewElement = new CMFCRibbonProgressBar(infoElement.m_ID.m_Value, infoElement.m_nWidth, infoElement.m_nHeight);
pElement = pNewElement;
ConstructBaseElement(*pElement, info);
pNewElement->SetRange(infoElement.m_nMin, infoElement.m_nMax);
pNewElement->SetPos(infoElement.m_nPos, FALSE);
pNewElement->SetInfiniteMode(infoElement.m_bInfinite);
}
else if (info.GetElementType() == CMFCRibbonInfo::e_TypeSeparator)
{
const CMFCRibbonInfo::XElementSeparator& infoElement = (const CMFCRibbonInfo::XElementSeparator&)info;
CMFCRibbonSeparator* pSeparator = new CMFCRibbonSeparator(infoElement.m_bIsHoriz);
pElement = pSeparator;
}
return pElement;
}
| 35.455951
| 326
| 0.770052
|
825126369
|
dc12a18b70aa99687230978c7c5db0a42fbaeec2
| 1,738
|
hpp
|
C++
|
lib/wal/sources/Models/Callback.hpp
|
EternalRat/Bomberman
|
d4d0c6dea61f7de1e71c6f182a6bf27407092356
|
[
"MIT"
] | 6
|
2021-05-27T13:31:37.000Z
|
2021-11-21T17:35:08.000Z
|
lib/wal/sources/Models/Callback.hpp
|
EternalRat/Bomberman
|
d4d0c6dea61f7de1e71c6f182a6bf27407092356
|
[
"MIT"
] | 174
|
2021-05-12T14:10:04.000Z
|
2021-06-26T11:29:39.000Z
|
lib/wal/sources/Models/Callback.hpp
|
EternalRat/Bomberman
|
d4d0c6dea61f7de1e71c6f182a6bf27407092356
|
[
"MIT"
] | 2
|
2021-05-27T13:28:46.000Z
|
2021-06-21T12:25:27.000Z
|
//
// Created by Zoe Roux on 5/21/21.
//
#pragma once
#include <functional>
#include <utility>
#include <unordered_map>
namespace WAL
{
//! @brief A callback where you can subscribe to and emit it.
template<typename ...Types>
class Callback
{
private:
int _nextID = 0;
//! @brief The list of functions to call.
std::unordered_map<int, std::function<void (Types...)>> _functions = {};
public:
//! @brief Add a method to be called when this callback is invoked.
//! @param callback The list of arguments of the callback method
//! @return A unique ID for this callback. That can be used to remove the callback later.
template<typename Func>
int addCallback(Func callback)
{
int id = this->_nextID++;
if constexpr(std::is_same_v<Func, std::function<void (Types...)>>)
this->_functions[id] = std::move(callback);
else
this->_functions[id] = std::function<void (Types...)>(callback);
return id;
}
//! @brief Remove a function from this callback.
//! @param id The ID of the function.
void removeCallback(int id)
{
this->_functions.erase(id);
}
void operator()(Types ...args) const
{
for (const auto &[_, callback] : this->_functions)
callback(args...);
}
//! @brief A default constructor
Callback() = default;
//! @brief A default copy constructor
Callback(const Callback &) = default;
//! @brief A default destructor
~Callback() = default;
//! @brief A default assignment operator
Callback &operator=(const Callback &) = default;
//! @brief Implicitly transform a callable into a callback.
template<typename Func>
Callback(Func callback) // NOLINT(google-explicit-constructor)
{
this->addCallback(callback);
}
};
} // namespace WAL
| 25.940299
| 91
| 0.673188
|
EternalRat
|
dc17db0822f6b4a5eacbf109af86da9077db8598
| 318
|
hpp
|
C++
|
sdk/template/azure-template/inc/azure/template/template_client.hpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | 1
|
2022-01-19T22:54:41.000Z
|
2022-01-19T22:54:41.000Z
|
sdk/template/azure-template/inc/azure/template/template_client.hpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | null | null | null |
sdk/template/azure-template/inc/azure/template/template_client.hpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#pragma once
#include <string>
namespace Azure { namespace Template {
class TemplateClient final {
public:
std::string ClientVersion() const;
int GetValue(int key) const;
};
}} // namespace Azure::Template
| 18.705882
| 60
| 0.710692
|
RickWinter
|
dc181ff10fbe87cd636b95185e5da62160f77321
| 1,045
|
cpp
|
C++
|
common/netdispatcher.cpp
|
andriymoroz-mlnx/sonic-swss-common
|
e06988dd2c44f6c5200f16c765a0e9a64a0ce274
|
[
"Apache-2.0"
] | null | null | null |
common/netdispatcher.cpp
|
andriymoroz-mlnx/sonic-swss-common
|
e06988dd2c44f6c5200f16c765a0e9a64a0ce274
|
[
"Apache-2.0"
] | null | null | null |
common/netdispatcher.cpp
|
andriymoroz-mlnx/sonic-swss-common
|
e06988dd2c44f6c5200f16c765a0e9a64a0ce274
|
[
"Apache-2.0"
] | null | null | null |
#include <map>
#include "common/netdispatcher.h"
#include "common/netmsg.h"
using namespace swss;
NetDispatcher::NetDispatcher()
{
}
NetDispatcher::~NetDispatcher()
{
}
NetDispatcher& NetDispatcher::getInstance()
{
static NetDispatcher gInstance;
return gInstance;
}
void NetDispatcher::registerMessageHandler(int nlmsg_type, NetMsg *callback)
{
if (m_handlers.find(nlmsg_type) != m_handlers.end())
throw "Trying to registered on already registerd netlink message";
m_handlers[nlmsg_type] = callback;
}
void NetDispatcher::nlCallback(struct nl_object *obj, void *context)
{
NetMsg *callback = (NetMsg *)context;
callback->onMsg(nl_object_get_msgtype(obj), obj);
}
void NetDispatcher::onNetlinkMessage(struct nl_msg *msg)
{
struct nlmsghdr *nlmsghdr = nlmsg_hdr(msg);
auto callback = m_handlers.find(nlmsghdr->nlmsg_type);
/* Drop not registered messages */
if (callback == m_handlers.end())
return;
nl_msg_parse(msg, NetDispatcher::nlCallback, (void *)(callback->second));
}
| 22.717391
| 77
| 0.721531
|
andriymoroz-mlnx
|
dc197f99abb5d8dc7de1ad5d680d36777adb7e85
| 7,228
|
cpp
|
C++
|
src/brpc/nshead_message.cpp
|
PeterRK/brpc
|
55c3177f53adac1bd149c5e80a7609b758ca7492
|
[
"Apache-2.0"
] | 27
|
2019-04-11T07:57:29.000Z
|
2022-03-26T11:34:22.000Z
|
src/brpc/nshead_message.cpp
|
ww5365/brpc
|
33538c6bb69f3151863707b2ebdeff74f93e4b65
|
[
"Apache-2.0"
] | 1
|
2019-08-05T13:29:01.000Z
|
2019-08-05T13:29:01.000Z
|
src/brpc/nshead_message.cpp
|
ww5365/brpc
|
33538c6bb69f3151863707b2ebdeff74f93e4b65
|
[
"Apache-2.0"
] | 11
|
2017-12-28T03:22:45.000Z
|
2022-02-09T09:19:48.000Z
|
// Copyright (c) 2014 Baidu, 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.
// Authors: Ge,Jun (gejun@baidu.com)
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "brpc/nshead_message.h"
#include <algorithm>
#include "butil/logging.h"
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
namespace brpc {
namespace {
const ::google::protobuf::Descriptor* NsheadMessage_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_baidu_2frpc_2fnshead_5fmessage_2eproto() {
protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"baidu/rpc/nshead_message.proto");
GOOGLE_CHECK(file != NULL);
NsheadMessage_descriptor_ = file->message_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_baidu_2frpc_2fnshead_5fmessage_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
NsheadMessage_descriptor_, &NsheadMessage::default_instance());
}
} // namespace
void protobuf_ShutdownFile_baidu_2frpc_2fnshead_5fmessage_2eproto() {
delete NsheadMessage::default_instance_;
}
void protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#if GOOGLE_PROTOBUF_VERSION >= 3002000
::google::protobuf::internal::InitProtobufDefaults();
#else
::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
#endif
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\036baidu/rpc/nshead_message.proto\022\tbaidu."
"rpc\032 google/protobuf/descriptor.proto\"\017\n"
"\rNsheadMessageB\003\200\001\001", 99);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"baidu/rpc/nshead_message.proto", &protobuf_RegisterTypes);
NsheadMessage::default_instance_ = new NsheadMessage();
NsheadMessage::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(
&protobuf_ShutdownFile_baidu_2frpc_2fnshead_5fmessage_2eproto);
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto_once);
void protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto() {
::google::protobuf::GoogleOnceInit(
&protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto_once,
&protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto_impl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_baidu_2frpc_2fnshead_5fmessage_2eproto {
StaticDescriptorInitializer_baidu_2frpc_2fnshead_5fmessage_2eproto() {
protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto();
}
} static_descriptor_initializer_baidu_2frpc_2fnshead_5fmessage_2eproto_;
// ===================================================================
#ifndef _MSC_VER
#endif // !_MSC_VER
NsheadMessage::NsheadMessage()
: ::google::protobuf::Message() {
SharedCtor();
}
void NsheadMessage::InitAsDefaultInstance() {
}
NsheadMessage::NsheadMessage(const NsheadMessage& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
}
void NsheadMessage::SharedCtor() {
memset(&head, 0, sizeof(head));
}
NsheadMessage::~NsheadMessage() {
SharedDtor();
}
void NsheadMessage::SharedDtor() {
if (this != default_instance_) {
}
}
const ::google::protobuf::Descriptor* NsheadMessage::descriptor() {
protobuf_AssignDescriptorsOnce();
return NsheadMessage_descriptor_;
}
const NsheadMessage& NsheadMessage::default_instance() {
if (default_instance_ == NULL)
protobuf_AddDesc_baidu_2frpc_2fnshead_5fmessage_2eproto();
return *default_instance_;
}
NsheadMessage* NsheadMessage::default_instance_ = NULL;
NsheadMessage* NsheadMessage::New() const {
return new NsheadMessage;
}
void NsheadMessage::Clear() {
memset(&head, 0, sizeof(head));
body.clear();
}
bool NsheadMessage::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
}
return true;
#undef DO_
}
void NsheadMessage::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream*) const {
}
::google::protobuf::uint8* NsheadMessage::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
return target;
}
int NsheadMessage::ByteSize() const {
return sizeof(nshead_t) + body.size();
}
void NsheadMessage::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const NsheadMessage* source =
::google::protobuf::internal::dynamic_cast_if_available<const NsheadMessage*>(
&from);
if (source == NULL) {
LOG(ERROR) << "Can only merge from NsheadMessage";
return;
} else {
MergeFrom(*source);
}
}
void NsheadMessage::MergeFrom(const NsheadMessage& from) {
GOOGLE_CHECK_NE(&from, this);
// No way to merge two nshead messages, just overwrite.
head = from.head;
body = from.body;
}
void NsheadMessage::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void NsheadMessage::CopyFrom(const NsheadMessage& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool NsheadMessage::IsInitialized() const {
return true;
}
void NsheadMessage::Swap(NsheadMessage* other) {
if (other != this) {
const nshead_t tmp = other->head;
other->head = head;
head = tmp;
body.swap(other->body);
}
}
::google::protobuf::Metadata NsheadMessage::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = NsheadMessage_descriptor_;
metadata.reflection = NULL;
return metadata;
}
} // namespace brpc
| 30.49789
| 100
| 0.723298
|
PeterRK
|
dc1c59ee5b72b36b13574ac2d51a97bd5c8f25d0
| 3,848
|
cc
|
C++
|
tests/catch/unit/streamperthread/hipStreamPerThread_DeviceReset.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
tests/catch/unit/streamperthread/hipStreamPerThread_DeviceReset.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
tests/catch/unit/streamperthread/hipStreamPerThread_DeviceReset.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hip_test_common.hh>
#include <vector>
#include <thread>
/*
hipDeviceReset deletes all active streams including hipStreamPerThread.
Scenario: App calls hipDeviceReset while in other thread some Async operation is in
progress on hipStreamPerThread.
Watch out: hipDeviceRest should be successfull without any crash
*/
static void Copy_to_device() {
unsigned int ele_size = (32 * 1024); // 32KB
int* A_h = nullptr;
int* A_d = nullptr;
hipError_t status = hipHostMalloc(&A_h, ele_size*sizeof(int));
if (status != hipSuccess) return;
status = hipMalloc(&A_d, ele_size * sizeof(int));
if (status != hipSuccess) return;
for(unsigned int i = 0; i < ele_size; ++i) {
A_h[i] = 123;
}
hipMemcpyAsync(A_d, A_h, ele_size * sizeof(int), hipMemcpyHostToDevice,
hipStreamPerThread);
}
TEST_CASE("Unit_hipStreamPerThread_DeviceReset_1") {
constexpr unsigned int MAX_THREAD_CNT = 10;
std::vector<std::thread> threads(MAX_THREAD_CNT);
for (auto &th : threads) {
th = std::thread(Copy_to_device);
th.detach();
}
HIP_CHECK(hipDeviceReset());
}
/*
hipDeviceReset deletes all active streams including hipStreamPerThread.
Scenario: i) Launch Async task on hipStreamPerThread and waits for it to complete.
ii) Call hipDeviceReset to delete all active stream
iii) Again try to launch Async task on hipStreamPerThread
Watch out: Since hipStreamPerThread is an implicit stream hence even after device reset
it should available to use.
*/
TEST_CASE("Unit_hipStreamPerThread_DeviceReset_2") {
unsigned int ele_size = (32 * 1024); // 32KB
int* A_h = nullptr;
int* A_d = nullptr;
hipError_t status = hipHostMalloc(&A_h, ele_size*sizeof(int));
if (status != hipSuccess) return;
status = hipMalloc(&A_d, ele_size * sizeof(int));
if (status != hipSuccess) return;
for (unsigned int i = 0; i < ele_size; ++i) {
A_h[i] = 123;
}
status = hipMemcpyAsync(A_d, A_h, ele_size * sizeof(int), hipMemcpyHostToDevice,
hipStreamPerThread);
if (status != hipSuccess) return;
hipStreamSynchronize(hipStreamPerThread);
hipDeviceReset();
// After reset all memory objects will be destroyed hence allocating them again
// Intension is to use hipStreamPerThread successfully after reset hence not validating
// values after copy
status = hipHostMalloc(&A_h, ele_size*sizeof(int));
if (status != hipSuccess) return;
status = hipMalloc(&A_d, ele_size * sizeof(int));
if (status != hipSuccess) return;
status = hipMemcpyAsync(A_d, A_h, ele_size * sizeof(int), hipMemcpyHostToDevice,
hipStreamPerThread);
if (status != hipSuccess) return;
hipStreamSynchronize(hipStreamPerThread);
}
| 38.48
| 89
| 0.734927
|
FMarno
|
dc1fdf8ec44ed66dff452f71f4d58dce7372021a
| 21,576
|
cpp
|
C++
|
src/OpenSpaceToolkit/Physics/Coordinate/Frame.cpp
|
robinpdm/open-space-toolkit-physics
|
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
|
[
"Apache-2.0"
] | 5
|
2018-08-20T06:47:42.000Z
|
2019-07-15T03:36:52.000Z
|
src/OpenSpaceToolkit/Physics/Coordinate/Frame.cpp
|
robinpdm/open-space-toolkit-physics
|
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
|
[
"Apache-2.0"
] | 24
|
2018-06-25T08:06:39.000Z
|
2020-01-05T20:34:02.000Z
|
src/OpenSpaceToolkit/Physics/Coordinate/Frame.cpp
|
robinpdm/open-space-toolkit-physics
|
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
|
[
"Apache-2.0"
] | 1
|
2019-09-19T22:44:23.000Z
|
2019-09-19T22:44:23.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Open Space Toolkit ▸ Physics
/// @file OpenSpaceToolkit/Physics/Coordinate/Frame.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/ITRF.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/TIRF.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/CIRF.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/TEME.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/TOD.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/MOD.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/GCRF.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/Static.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Manager.hpp>
#include <OpenSpaceToolkit/Physics/Coordinate/Frame.hpp>
#include <OpenSpaceToolkit/Core/Error.hpp>
#include <OpenSpaceToolkit/Core/Utilities.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ostk
{
namespace physics
{
namespace coord
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using FrameManager = ostk::physics::coord::frame::Manager ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// https://stackoverflow.com/questions/8147027/how-do-i-call-stdmake-shared-on-a-class-with-only-protected-or-private-const
struct SharedFrameEnabler : public Frame
{
SharedFrameEnabler ( const String& aName,
bool isQuasiInertial,
const Shared<const Frame>& aParentFrame,
const Shared<const Provider>& aProvider )
: Frame(aName, isQuasiInertial, aParentFrame, aProvider)
{
}
} ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Frame::~Frame ( )
{
}
bool Frame::operator == ( const Frame& aFrame ) const
{
if ((!this->isDefined()) || (!aFrame.isDefined()))
{
return false ;
}
return (name_ == aFrame.name_)
&& (quasiInertial_ == aFrame.quasiInertial_)
&& (((parentFrameSPtr_ == nullptr) && (aFrame.parentFrameSPtr_ == nullptr)) || ((parentFrameSPtr_ != nullptr) && (aFrame.parentFrameSPtr_ != nullptr) && ((*parentFrameSPtr_) == (*aFrame.parentFrameSPtr_))))
&& ((providerSPtr_ != nullptr) && (aFrame.providerSPtr_ != nullptr) && (providerSPtr_.get() == aFrame.providerSPtr_.get())) ;
}
bool Frame::operator != ( const Frame& aFrame ) const
{
return !((*this) == aFrame) ;
}
std::ostream& operator << ( std::ostream& anOutputStream,
const Frame& aFrame )
{
ostk::core::utils::Print::Header(anOutputStream, "Frame") ;
ostk::core::utils::Print::Line(anOutputStream) << "Name:" << (aFrame.isDefined() ? aFrame.getName() : "Undefined") ;
ostk::core::utils::Print::Line(anOutputStream) << "Quasi-inertial:" << (aFrame.isDefined() ? String::Format("{}", aFrame.isQuasiInertial()) : "Undefined") ;
ostk::core::utils::Print::Line(anOutputStream) << "Parent frame:" << (((aFrame.parentFrameSPtr_ != nullptr) && (aFrame.parentFrameSPtr_->isDefined())) ? aFrame.parentFrameSPtr_->getName() : "None") ;
ostk::core::utils::Print::Footer(anOutputStream) ;
return anOutputStream ;
}
bool Frame::isDefined ( ) const
{
return (!name_.isEmpty()) && (providerSPtr_ != nullptr) ;
}
bool Frame::isQuasiInertial ( ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
return quasiInertial_ ;
}
bool Frame::hasParent ( ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
return parentFrameSPtr_ != nullptr ;
}
Shared<const Frame> Frame::accessParent ( ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
if (parentFrameSPtr_ == nullptr)
{
throw ostk::core::error::runtime::Undefined("Parent") ;
}
return parentFrameSPtr_ ;
}
Shared<const Frame> Frame::accessAncestor ( const Uint8 anAncestorDegree ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
if (anAncestorDegree == 0)
{
return this->shared_from_this() ;
}
if (anAncestorDegree > this->getDepth())
{
throw ostk::core::error::RuntimeError("Ancestor degree [{}] is greater than depth [{}].", anAncestorDegree, this->getDepth()) ;
}
Shared<const Frame> frameSPtr = this->shared_from_this() ;
for (Uint8 degree = 0; degree < anAncestorDegree; ++degree)
{
frameSPtr = frameSPtr->accessParent() ;
}
return frameSPtr ;
}
Shared<const Provider> Frame::accessProvider ( ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
return providerSPtr_ ;
}
String Frame::getName ( ) const
{
if (!this->isDefined())
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
return name_ ;
}
Position Frame::getOriginIn ( const Shared<const Frame>& aFrameSPtr,
const Instant& anInstant ) const
{
if (!anInstant.isDefined())
{
throw ostk::core::error::runtime::Undefined("Instant") ;
}
if ((!this->isDefined()) || (aFrameSPtr == nullptr) || (!aFrameSPtr->isDefined()))
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
const Transform transform = this->getTransformTo(aFrameSPtr, anInstant) ;
return { transform.applyToPosition(Vector3d::Zero()), Position::Unit::Meter, aFrameSPtr } ;
}
Velocity Frame::getVelocityIn ( const Shared<const Frame>& aFrameSPtr,
const Instant& anInstant ) const
{
if (!anInstant.isDefined())
{
throw ostk::core::error::runtime::Undefined("Instant") ;
}
if ((!this->isDefined()) || (aFrameSPtr == nullptr) || (!aFrameSPtr->isDefined()))
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
return { this->getTransformTo(aFrameSPtr, anInstant).applyToVelocity(Vector3d::Zero(), Vector3d::Zero()), Velocity::Unit::MeterPerSecond, aFrameSPtr } ;
}
Axes Frame::getAxesIn ( const Shared<const Frame>& aFrameSPtr,
const Instant& anInstant ) const
{
if (!anInstant.isDefined())
{
throw ostk::core::error::runtime::Undefined("Instant") ;
}
if ((!this->isDefined()) || (aFrameSPtr == nullptr) || (!aFrameSPtr->isDefined()))
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
const Transform transform = this->getTransformTo(aFrameSPtr, anInstant) ;
const Vector3d xAxis = transform.applyToVector(Vector3d::X()).normalized() ;
const Vector3d yAxis = transform.applyToVector(Vector3d::Y()).normalized() ;
const Vector3d zAxis = xAxis.cross(yAxis) ;
return { xAxis, yAxis, zAxis, aFrameSPtr } ;
}
Transform Frame::getTransformTo ( const Shared<const Frame>& aFrameSPtr,
const Instant& anInstant ) const
{
if (!anInstant.isDefined())
{
throw ostk::core::error::runtime::Undefined("Instant") ;
}
if ((!this->isDefined()) || (aFrameSPtr == nullptr) || (!aFrameSPtr->isDefined()))
{
throw ostk::core::error::runtime::Undefined("Frame") ;
}
if ((*this) == (*aFrameSPtr))
{
return Transform::Identity(anInstant) ;
}
// std::cout << "From: " << std::endl << (*this) << std::endl ;
// std::cout << "To: " << std::endl << (*aFrameSPtr) << std::endl ;
const Shared<const Frame> thisSPtr = this->shared_from_this() ;
if (auto transformPtr = FrameManager::Get().accessCachedTransform(thisSPtr, aFrameSPtr, anInstant))
{
return *transformPtr ;
}
// Find common ancestor
const Shared<const Frame> commonAncestorSPtr = Frame::FindCommonAncestor(thisSPtr, aFrameSPtr) ;
if ((commonAncestorSPtr == nullptr) || (!commonAncestorSPtr->isDefined()))
{
throw ostk::core::error::RuntimeError("No common ancestor between [{}] and [{}].", this->getName(), aFrameSPtr->getName()) ;
}
// std::cout << "Common ancestor:" << std::endl << (*commonAncestorSPtr) << std::endl ;
// Compute transform from common ancestor to origin
Transform transform_origin_common = Transform::Identity(anInstant) ;
for (auto framePtr = this; framePtr != commonAncestorSPtr.get(); framePtr = framePtr->accessParent().get())
{
transform_origin_common *= framePtr->accessProvider()->getTransformAt(anInstant) ;
}
// std::cout << String::Format("{} → {}:", commonAncestorSPtr->getName(), this->getName()) << std::endl << transform_origin_common << std::endl ;
// Compute transform from destination to common ancestor
Transform transform_destination_common = Transform::Identity(anInstant) ;
for (auto framePtr = aFrameSPtr.get(); framePtr != commonAncestorSPtr.get(); framePtr = framePtr->accessParent().get())
{
transform_destination_common *= framePtr->accessProvider()->getTransformAt(anInstant) ;
}
// std::cout << String::Format("{} → {}:", commonAncestorSPtr->getName(), aFrameSPtr->getName()) << std::endl << transform_destination_common << std::endl ;
// Compute transform from origin to destination
const Transform transform_destination_origin = transform_destination_common * transform_origin_common.getInverse() ;
// std::cout << String::Format("{} → {}:", this->getName(), aFrameSPtr->getName()) << std::endl << transform_destination_origin << std::endl ;
FrameManager::Get().addCachedTransform(thisSPtr, aFrameSPtr, anInstant, transform_destination_origin) ;
return transform_destination_origin ;
}
Shared<const Frame> Frame::Undefined ( )
{
return std::make_shared<const SharedFrameEnabler>(String::Empty(), false, nullptr, nullptr) ;
}
Shared<const Frame> Frame::GCRF ( )
{
using GCRFProvider = ostk::physics::coord::frame::provider::GCRF ;
static const Shared<const Provider> providerSPtr = std::make_shared<const GCRFProvider>() ;
return Frame::Emplace("GCRF", true, nullptr, providerSPtr) ;
}
Shared<const Frame> Frame::MOD ( const Instant& anEpoch )
{
using Scale = ostk::physics::time::Scale ;
const String frameName = String::Format("MOD @ {}", anEpoch.toString(Scale::TT)) ;
using MODProvider = ostk::physics::coord::frame::provider::MOD ;
static const Shared<const Provider> providerSPtr = std::make_shared<const MODProvider>(anEpoch) ;
return Frame::Emplace(frameName, true, Frame::GCRF(), providerSPtr) ;
}
Shared<const Frame> Frame::TOD ( const Instant& anEpoch )
{
using Scale = ostk::physics::time::Scale ;
const String frameName = String::Format("TOD @ {}", anEpoch.toString(Scale::TT)) ;
using TODProvider = ostk::physics::coord::frame::provider::TOD ;
static const Shared<const Provider> providerSPtr = std::make_shared<const TODProvider>(anEpoch) ;
return Frame::Emplace(frameName, true, Frame::MOD(anEpoch), providerSPtr) ;
}
Shared<const Frame> Frame::TEME ( )
{
using TEMEProvider = ostk::physics::coord::frame::provider::TEME ;
static const Shared<const Provider> providerSPtr = std::make_shared<const TEMEProvider>() ;
return Frame::Emplace("TEME", true, Frame::ITRF(), providerSPtr) ;
}
Shared<const Frame> Frame::TEMEOfEpoch ( const Instant& anEpoch )
{
using Scale = ostk::physics::time::Scale ;
using StaticProvider = ostk::physics::coord::frame::provider::Static ;
const String temeOfEpochFrameName = String::Format("TEMEOfEpoch @ {}", anEpoch.toString(Scale::TT)) ;
const Shared<const Provider> providerSPtr = std::make_shared<const StaticProvider>(Frame::GCRF()->getTransformTo(Frame::TEME(), anEpoch)) ;
return Frame::Emplace(temeOfEpochFrameName, true, Frame::GCRF(), providerSPtr) ;
}
Shared<const Frame> Frame::CIRF ( )
{
using CIRFProvider = ostk::physics::coord::frame::provider::CIRF ;
static const Shared<const Provider> providerSPtr = std::make_shared<const CIRFProvider>() ;
return Frame::Emplace("CIRF", false, Frame::GCRF(), providerSPtr) ;
}
Shared<const Frame> Frame::TIRF ( )
{
using TIRFProvider = ostk::physics::coord::frame::provider::TIRF ;
static const Shared<const Provider> providerSPtr = std::make_shared<const TIRFProvider>() ;
return Frame::Emplace("TIRF", false, Frame::CIRF(), providerSPtr) ;
}
Shared<const Frame> Frame::ITRF ( )
{
using ITRFProvider = ostk::physics::coord::frame::provider::ITRF ;
static const Shared<const Provider> providerSPtr = std::make_shared<const ITRFProvider>() ;
return Frame::Emplace("ITRF", false, Frame::TIRF(), providerSPtr) ;
}
Shared<const Frame> Frame::WithName ( const String& aName )
{
if (aName.isEmpty())
{
throw ostk::core::error::runtime::Undefined("Name") ;
}
if (const auto frameSPtr = FrameManager::Get().accessFrameWithName(aName))
{
return frameSPtr ;
}
return nullptr ;
}
bool Frame::Exists ( const String& aName )
{
if (aName.isEmpty())
{
throw ostk::core::error::runtime::Undefined("Name") ;
}
return FrameManager::Get().hasFrameWithName(aName) ;
}
Shared<const Frame> Frame::Construct ( const String& aName,
bool isQuasiInertial,
const Shared<const Frame>& aParentFrame,
const Shared<const Provider>& aProvider )
{
if (FrameManager::Get().hasFrameWithName(aName))
{
throw ostk::core::error::RuntimeError("Frame with name [{}] already exist.", aName) ;
}
return Frame::Emplace(aName, isQuasiInertial, aParentFrame, aProvider) ;
}
void Frame::Destruct ( const String& aName )
{
if (FrameManager::Get().hasFrameWithName(aName))
{
FrameManager::Get().removeFrameWithName(aName) ;
}
else
{
throw ostk::core::error::RuntimeError("No frame with name [{}].", aName) ;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Frame::Frame ( const String& aName,
bool isQuasiInertial,
const Shared<const Frame>& aParentFrame,
const Shared<const Provider>& aProvider )
: std::enable_shared_from_this<ostk::physics::coord::Frame>(),
name_(aName),
quasiInertial_(isQuasiInertial),
parentFrameSPtr_(aParentFrame),
providerSPtr_(aProvider)
{
}
Uint8 Frame::getDepth ( ) const
{
Uint8 depth = 0 ;
Shared<const Frame> frameSPtr = this->shared_from_this() ;
while (frameSPtr->hasParent())
{
if (depth == 255)
{
throw ostk::core::error::RuntimeError("Depth overflow.") ;
}
depth++ ;
frameSPtr = frameSPtr->accessParent() ;
}
return depth ;
}
Shared<const Frame> Frame::Emplace ( const String& aName,
bool isQuasiInertial,
const Shared<const Frame>& aParentFrame,
const Shared<const Provider>& aProvider )
{
if (const auto frameSPtr = FrameManager::Get().accessFrameWithName(aName))
{
return frameSPtr ;
}
const Shared<const Frame> frameSPtr = std::make_shared<const SharedFrameEnabler>(aName, isQuasiInertial, aParentFrame, aProvider) ;
FrameManager::Get().addFrame(frameSPtr) ;
return frameSPtr ;
}
Shared<const Frame> Frame::FindCommonAncestor ( const Shared<const Frame>& aFirstFrameSPtr,
const Shared<const Frame>& aSecondFrameSPtr )
{
const Uint8 firstFrameDepth = aFirstFrameSPtr->getDepth() ;
const Uint8 secondFrameDepth = aSecondFrameSPtr->getDepth() ;
Shared<const Frame> currentFSPtr = (firstFrameDepth > secondFrameDepth) ? aFirstFrameSPtr->accessAncestor(firstFrameDepth - secondFrameDepth) : aFirstFrameSPtr ;
Shared<const Frame> currentTSPtr = (firstFrameDepth > secondFrameDepth) ? aSecondFrameSPtr : aSecondFrameSPtr->accessAncestor(secondFrameDepth - firstFrameDepth) ;
while ((*currentFSPtr) != (*currentTSPtr))
{
currentFSPtr = currentFSPtr->accessParent() ;
currentTSPtr = currentTSPtr->accessParent() ;
}
return currentFSPtr ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 37.135972
| 214
| 0.484103
|
robinpdm
|
dc2dd0f71d21cdacce63ad78eca9c7f0fea41e2d
| 16,807
|
hpp
|
C++
|
Engine/Include/Sapphire/Maths/Space/Vector3.hpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | 2
|
2020-03-18T09:06:21.000Z
|
2020-04-09T00:07:56.000Z
|
Engine/Include/Sapphire/Maths/Space/Vector3.hpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | null | null | null |
Engine/Include/Sapphire/Maths/Space/Vector3.hpp
|
SapphireSuite/Sapphire
|
f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Sapphire development team. All Rights Reserved.
#pragma once
#ifndef SAPPHIRE_MATHS_VECTOR3_GUARD
#define SAPPHIRE_MATHS_VECTOR3_GUARD
#include <Maths/Misc/Maths.hpp>
namespace Sa
{
template <typename T>
struct Vec2;
/**
* \file Vector3.hpp
*
* \brief \b Definition of Sapphire's \b Vector 3 type.
*
* \ingroup Maths
* \{
*/
/**
* \brief \e Vector 3 Sapphire's class.
*
* \tparam T Type of the vector.
*/
template <typename T>
struct Vec3
{
/// Type of the Vector.
using Type = T;
/// Vector's X component (axis value).
T x = T();
/// Vector's Y component (axis value).
T y = T();
/// Vector's Z component (axis value).
T z = T();
/// Zero vector constant {0, 0, 0}.
static const Vec3 Zero;
/// One vector constant {1, 1, 1}.
static const Vec3 One;
/// Right vector constant {1, 0, 0}.
static const Vec3 Right;
/// Left vector constant {-1, 0, 0}.
static const Vec3 Left;
/// Up vector constant {0, 1, 0}.
static const Vec3 Up;
/// Down vector constant {0, -1, 0}.
static const Vec3 Down;
/// Down vector constant {0, 0, 1}.
static const Vec3 Forward;
/// Down vector constant {0, 0, -1}.
static const Vec3 Backward;
/**
* \brief \e Default constructor.
*/
Vec3() = default;
/**
* \brief \e Default move constructor.
*/
Vec3(Vec3&&) = default;
/**
* \brief \e Default copy constructor.
*/
Vec3(const Vec3&) = default;
/**
* \brief \e Value constructor.
*
* \param[in] _x X axis value.
* \param[in] _y Y axis value.
* \param[in] _z Z axis value.
*/
constexpr Vec3(T _x, T _y, T _z) noexcept;
/**
* \brief \b Scale \e Value constructor.
*
* \param[in] _scale Axis value to apply on all axis.
*/
constexpr Vec3(T _scale) noexcept;
///**
//* \brief \e Move constructor from same Vec3 type.
//*
//* \param[in] _other Vec3 to construct from.
//*/
//Vec3(Vec3&&) = default;
///**
//* \brief \e Value constructor from same Vec3 type.
//*
//* \param[in] _other Vec3 to construct from.
//*/
//Vec3(const Vec3&) = default;
/**
* \brief \e Value constructor from another Vec3 type.
*
* \tparam TIn Type of the input Vec3.
*
* \param[in] _other Vec3 to construct from.
*/
template <typename TIn>
constexpr explicit Vec3(const Vec3<TIn>& _other) noexcept;
/**
* \brief \e Value constructor from Vec2.
*
* \tparam TIn Type of the in Vec3.
*
* \param[in] _other Vec2 to construct from.
* \param[in] _z Z axis value.
*/
template <typename TIn>
constexpr explicit Vec3(const Vec2<TIn>& _other, T _z = T(0)) noexcept;
/**
* \brief Whether this vector is a zero vector.
*
* \return True if this is a zero vector.
*/
constexpr bool IsZero() const noexcept;
/**
* \brief \e Compare 2 vector.
*
* \param[in] _other Other vector to compare to.
* \param[in] _threshold Allowed threshold to accept equality.
*
* \return Whether this and _other are equal.
*/
constexpr bool Equals(const Vec3& _other, T _threshold = Limits<T>::epsilon) const noexcept;
/**
* \brief \e Getter of the \b length of this vector.
*
* \return Length of this vector.
*/
constexpr T Length() const noexcept;
/**
* \brief \e Getter of the <b> Squared Length </b> of this vector.
*
* \return Squared Length of this vector.
*/
constexpr T SqrLength() const noexcept;
/**
* \brief \e Getter of vector data
*
* \return this vector as a T*.
*/
T* Data() noexcept;
/**
* \brief <em> Const Getter </em> of vector data
*
* \return this vector as a const T*.
*/
const T* Data() const noexcept;
/**
* \brief \b Scale (multiply) each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return self vector scaled.
*/
Vec3& Scale(T _scale) noexcept;
/**
* \brief \b Scale (multiply) each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return new scaled vector.
*/
constexpr Vec3 GetScaled(T _scale) const noexcept;
/**
* \brief <b> Un-Scale </b> (divide) each vector axis by _scale.
*
* \param[in] _scale Unscale value to apply on all axis.
*
* \return self vector unscaled.
*/
Vec3& UnScale(T _scale);
/**
* \brief <b> Un-Scale </b> (divide) each vector axis by _scale.
*
* \param[in] _scale Unscale value to apply on all axis.
*
* \return new unscaled vector.
*/
constexpr Vec3 GetUnScaled(T _scale) const;
/**
* \brief \b Normalize this vector.
*
* \return self vector normalized.
*/
Vec3& Normalize();
/**
* \brief \b Normalize this vector.
*
* \return new normalized vector.
*/
constexpr Vec3 GetNormalized() const;
/**
* \brief Whether this vector is normalized.
*
* \return True if this vector is normalized, otherwise false.
*/
constexpr bool IsNormalized() const noexcept;
/**
* \brief \b Reflect this vector over the normal.
*
* \param[in] _normal Normal used for reflection.
* \param[in] _elasticity Elasticity reflection coefficient (use 1.0f for full reflection).
*
* \return new vector reflected.
*/
Vec3 Reflect(const Vec3& _normal, float _elasticity = 1.0f) const noexcept;
/**
* \brief \b Project this vector onto an other vector.
*
* Reference: https://en.wikipedia.org/wiki/Vector_projection
*
* \param[in] _other Vector used for projection.
*
* \return new vector projected.
*/
Vec3 ProjectOnTo(const Vec3& _other) const noexcept;
/**
* \brief \b Project this vector onto s normal.
*
* Assume _normal is normalized.
* Use GetProjectOnTo() for non normalized vector.
* Reference: https://en.wikipedia.org/wiki/Vector_projection
*
* \param[in] _normal Normal used for projection.
*
* \return new vector projected.
*/
Vec3 ProjectOnToNormal(const Vec3& _normal) const noexcept;
/**
* \brief \e Compute the <b> Dot product </b> between _lhs and _rhs.
*
* \param[in] _lhs Left hand side operand to compute dot product with.
* \param[in] _rhs Right hand side operand to compute dot product with.
*
* \return <b> Dot product </b> between _lhs and _rhs.
*/
static constexpr T Dot(const Vec3& _lhs, const Vec3& _rhs) noexcept;
/**
* \brief \e Compute the <b> Cross product </b> between _lhs and _rhs.
*
* \param[in] _lhs Left hand side operand to compute cross product with.
* \param[in] _rhs Right hand side operand to compute cross product with.
*
* \return <b> Cross product </b> between _lhs and _rhs.
*/
static constexpr Vec3<T> Cross(const Vec3& _lhs, const Vec3& _rhs) noexcept;
/**
* \brief \e Compute the <b> Signed Angle </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute angle with.
* \param[in] _end Right hand side operand to compute angle with.
* \param[in] _normal Normal of the plan between _lhs and _rhs, used to determine angle's sign.
*
* \return <b> Signed Angle </b> between _lhs and _rhs.
*/
static Deg<T> Angle(const Vec3& _start, const Vec3& _end, const Vec3& _normal = Vec3::Up) noexcept;
/**
* \brief \e Compute the <b> Unsigned Angle </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute angle with.
* \param[in] _end Right hand side operand to compute angle with.
*
* \return <b> Unsigned Angle </b> between _lhs and _rhs.
*/
static Deg<T> AngleUnsigned(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Distance </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute distance with.
* \param[in] _end Right hand side operand to compute distance with.
*
* \return <b> Distance </b> between _lhs and _rhs.
*/
static constexpr T Dist(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Squared Distance </b> between _lhs and _rhs.
*
* \param[in] _start Left hand side operand to compute squared distance with.
* \param[in] _end Right hand side operand to compute squared distance with.
*
* \return <b> Squared Distance </b> between _lhs and _rhs.
*/
static constexpr T SqrDist(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Non-Normalized Direction </b> from _lhs and _rhs.
*
* Direction get not normalized. Use DirN instead.
*
* \param[in] _start Left hand side operand to compute direction from.
* \param[in] _end Right hand side operand to compute direction to
*
* \return <b> Non-Normalized Direction </b> from _lhs and _rhs.
*/
static constexpr Vec3 Dir(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief \e Compute the <b> Normalized Direction </b> from _start to _end.
*
* \param[in] _start Starting point to compute direction from.
* \param[in] _end ending point to compute direction to.
*
* \return <b> Normalized Direction </b> from _start to _end.
*/
static constexpr Vec3 DirN(const Vec3& _start, const Vec3& _end) noexcept;
/**
* \brief <b> Clamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 Lerp(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Unclamped Lerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Linear_interpolation
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 LerpUnclamped(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Clamped SLerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Slerp
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 SLerp(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief <b> Unclamped SLerp </b> from _start to _end at _alpha.
*
* Reference: https://en.wikipedia.org/wiki/Slerp
*
* \param _start Starting point of the lerp.
* \param _end Ending point of the lerp.
* \param _alpha Alpha of the lerp.
*
* \return interpolation between _start and _end. return _start when _alpha == 0.0f and _end when _alpha == 1.0f.
*/
static Vec3 SLerpUnclamped(const Vec3& _start, const Vec3& _end, float _alpha) noexcept;
/**
* \brief \e Default move assignement.
*
* \return self vector assigned.
*/
Vec3& operator=(Vec3&&) = default;
/**
* \brief \e Default copy assignement.
*
* \return self vector assigned.
*/
Vec3& operator=(const Vec3&) = default;
/**
* \brief \e Getter of the opposite signed vector.
*
* \return new opposite signed vector.
*/
constexpr Vec3 operator-() const noexcept;
/**
* \brief \b Scale each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return new vector scaled.
*/
constexpr Vec3 operator*(T _scale) const noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _scale.
*
* \param[in] _scale Inverse scale value to apply on all axis.
*
* \return new vector inverse-scaled.
*/
constexpr Vec3 operator/(T _scale) const;
/**
* \brief \b Add term by term vector values.
*
* \param[in] _rhs Vector to add.
*
* \return new vector result.
*/
constexpr Vec3 operator+(const Vec3& _rhs) const noexcept;
/**
* \brief \b Subtract term by term vector values.
*
* \param[in] _rhs Vector to substract.
*
* \return new vector result.
*/
constexpr Vec3 operator-(const Vec3& _rhs) const noexcept;
/**
* \brief \b Multiply term by term vector values.
*
* \param[in] _rhs Vector to multiply.
*
* \return new vector result.
*/
constexpr Vec3 operator*(const Vec3& _rhs) const noexcept;
/**
* \brief \b Divide term by term vector values.
*
* \param[in] _rhs Vector to divide.
*
* \return new vector result.
*/
constexpr Vec3 operator/(const Vec3& _rhs) const;
/**
* \brief \e Compute the <b> Dot product </b> between this and _rhs.
*
* \param[in] _rhs Right hand side operand vector to compute dot product with.
*
* \return <b> Dot product </b> between this vector and _other.
*/
constexpr T operator|(const Vec3& _rhs) const noexcept;
/**
* \brief \e Compute the <b> Cross product </b> between this and _rhs.
*
* \param[in] _rhs Right hand side operand vector to compute cross product with.
*
* \return <b> Cross product </b> between this vector and _other.
*/
constexpr Vec3 operator^(const Vec3& _rhs) const noexcept;
/**
* \brief \b Scale each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return self vector scaled.
*/
Vec3& operator*=(T _scale) noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _scale.
*
* \param[in] _scale Scale value to apply on all axis.
*
* \return self vector inverse-scaled.
*/
Vec3& operator/=(T _scale);
/**
* \brief \b Add term by term vector values.
*
* \param[in] _rhs Vector to add.
*
* \return self vector result.
*/
Vec3& operator+=(const Vec3& _rhs) noexcept;
/**
* \brief \b Substract term by term vector values.
*
* \param[in] _rhs Vector to substract.
*
* \return self vector result.
*/
Vec3& operator-=(const Vec3& _rhs) noexcept;
/**
* \brief \b Multiply term by term vector values.
*
* \param[in] _rhs Vector to multiply.
*
* \return self vector result.
*/
Vec3 operator*=(const Vec3& _rhs) noexcept;
/**
* \brief \b Divide term by term vector values.
*
* \param[in] _rhs Vector to divide.
*
* \return self vector result.
*/
Vec3 operator/=(const Vec3& _rhs);
/**
* \brief \e Compare 2 vector equality.
*
* \param[in] _rhs Other vector to compare to.
*
* \return Whether this and _rhs are equal.
*/
constexpr bool operator==(const Vec3& _rhs) const noexcept;
/**
* \brief \e Compare 2 vector inequality.
*
* \param[in] _rhs Other vector to compare to.
*
* \return Whether this and _rhs are non-equal.
*/
constexpr bool operator!=(const Vec3& _rhs) const noexcept;
/**
* \brief \e Access operator by index.
*
* \param[in] _index Index to access: 0 == x, 1 == y, 2 == z.
*
* \return T value at index.
*/
T& operator[](uint32 _index);
/**
* \brief <em> Const Access </em> operator by index.
*
* \param[in] _index Index to access: 0 == x, 1 == y, 2 == z.
*
* \return T value at index.
*/
const T& operator[](uint32 _index) const;
/**
* \brief \e Cast operator into other Vec3 type.
*
* \tparam TIn Type of the casted vector.
*
* \return \e Casted result.
*/
template <typename TIn>
constexpr operator Vec3<TIn>() const noexcept;
/**
* \brief \e Cast operator into Vec2.
*
* \tparam TIn Type of the casted vector.
*
* \return \e Casted result.
*/
template <typename TIn>
constexpr operator Vec2<TIn>() const noexcept;
};
/**
* \brief \b Scale each vector axis by _lhs.
*
* \param[in] _lhs Scale value to apply on all axis.
* \param[in] _rhs Vector to scale.
*
* \return new vector scaled.
*/
template <typename T>
constexpr Vec3<T> operator*(T _lhs, const Vec3<T>& _rhs) noexcept;
/**
* \brief <b> Inverse Scale </b> each vector axis by _lhs.
*
* \param[in] _lhs Inverse scale value to apply on all axis.
* \param[in] _rhs Vector to scale.
*
* \return new vector inverse-scaled.
*/
template <typename T>
constexpr Vec3<T> operator/(T _lhs, const Vec3<T>& _rhs);
/// Alias for int32 Vec3.
using Vec3i = Vec3<int32>;
/// Alias for uint32 Vec3.
using Vec3ui = Vec3<uint32>;
/// Alias for float Vec3.
using Vec3f = Vec3<float>;
/// Alias for double Vec3.
using Vec3d = Vec3<double>;
/// Template alias of Vec3
template <typename T>
using Vector3 = Vec3<T>;
/// Alias for int32 Vector3.
using Vector3i = Vector3<int32>;
/// Alias for uint32 Vector3.
using Vector3ui = Vector3<uint32>;
/// Alias for float Vector3.
using Vector3f = Vector3<float>;
/// Alias for double Vector3.
using Vector3d = Vector3<double>;
/** \} */
}
#include <Maths/Space/Vector3.inl>
#endif // GUARD
| 24.716176
| 114
| 0.646516
|
SapphireSuite
|
dc3183454af39084355539b98e411ef20c085ac2
| 5,694
|
cpp
|
C++
|
brsdk/process/process_info.cpp
|
JerryYu512/arss
|
bd113d7f1ff2f09d210103cd5cc3dcc7c82f99dc
|
[
"MIT"
] | null | null | null |
brsdk/process/process_info.cpp
|
JerryYu512/arss
|
bd113d7f1ff2f09d210103cd5cc3dcc7c82f99dc
|
[
"MIT"
] | null | null | null |
brsdk/process/process_info.cpp
|
JerryYu512/arss
|
bd113d7f1ff2f09d210103cd5cc3dcc7c82f99dc
|
[
"MIT"
] | null | null | null |
/**
* MIT License
*
* Copyright © 2021 <wotsen>.
*
* 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
*
* 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 process_info.cpp
* @brief
* @author wotsen (astralrovers@outlook.com)
* @version 1.0.0
* @date 2021-07-11
*
* @copyright MIT License
*
*/
#include "process_info.hpp"
#include "brsdk/thread/current_thread.hpp"
#include "brsdk/fs/file.hpp"
#include <algorithm>
#include <assert.h>
#include <dirent.h>
#include <pwd.h>
#include <stdio.h> // snprintf
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/times.h>
#include <unistd.h>
namespace brsdk {
namespace ProcessInfo {
namespace detail {
__thread int t_numOpenedFiles = 0;
int fdDirFilter(const struct dirent* d) {
if (::isdigit(d->d_name[0])) {
++t_numOpenedFiles;
}
return 0;
}
__thread std::vector<pid_t>* t_pids = NULL;
int taskDirFilter(const struct dirent* d) {
if (::isdigit(d->d_name[0])) {
t_pids->push_back(atoi(d->d_name));
}
return 0;
}
int scanDir(const char* dirpath, int (*filter)(const struct dirent*)) {
struct dirent** namelist = NULL;
int result = ::scandir(dirpath, &namelist, filter, alphasort);
assert(namelist == NULL);
return result;
}
Timestamp g_startTime = Timestamp::now();
// assume those won't change during the life time of a process.
int g_clockTicks = static_cast<int>(::sysconf(_SC_CLK_TCK));
int g_pageSize = static_cast<int>(::sysconf(_SC_PAGE_SIZE));
} // namespace detail
using namespace detail;
pid_t pid() { return ::getpid(); }
std::string pidString() {
char buf[32];
snprintf(buf, sizeof buf, "%d", pid());
return buf;
}
uid_t uid() { return ::getuid(); }
std::string username() {
struct passwd pwd;
struct passwd* result = NULL;
char buf[8192];
const char* name = "unknownuser";
getpwuid_r(uid(), &pwd, buf, sizeof buf, &result);
if (result) {
name = pwd.pw_name;
}
return name;
}
uid_t euid() { return ::geteuid(); }
Timestamp startTime() { return g_startTime; }
int clockTicksPerSecond() { return g_clockTicks; }
int pageSize() { return g_pageSize; }
std::string hostname() {
// HOST_NAME_MAX 64
// _POSIX_HOST_NAME_MAX 255
char buf[256];
if (::gethostname(buf, sizeof buf) == 0) {
buf[sizeof(buf) - 1] = '\0';
return buf;
} else {
return "unknownhost";
}
}
std::string procname() { return procname(procStat()).as_string(); }
brsdk::str::StringPiece procname(const std::string& stat) {
brsdk::str::StringPiece name;
size_t lp = stat.find('(');
size_t rp = stat.rfind(')');
if (lp != std::string::npos && rp != std::string::npos && lp < rp) {
name.set(stat.data() + lp + 1, static_cast<int>(rp - lp - 1));
}
return name;
}
std::string procStatus() {
std::string result;
fs::readFile("/proc/self/status", 65536, &result);
return result;
}
std::string procStat() {
std::string result;
fs::readFile("/proc/self/stat", 65536, &result);
return result;
}
std::string threadStat() {
char buf[64];
snprintf(buf, sizeof buf, "/proc/self/task/%d/stat", thread::tid());
std::string result;
fs::readFile(buf, 65536, &result);
return result;
}
std::string exePath() {
std::string result;
char buf[1024];
ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf);
if (n > 0) {
result.assign(buf, n);
}
return result;
}
int openedFiles() {
t_numOpenedFiles = 0;
scanDir("/proc/self/fd", fdDirFilter);
return t_numOpenedFiles;
}
int maxOpenFiles() {
struct rlimit rl;
if (::getrlimit(RLIMIT_NOFILE, &rl)) {
return openedFiles();
} else {
return static_cast<int>(rl.rlim_cur);
}
}
CpuTime cpuTime() {
CpuTime t;
struct tms tms;
if (::times(&tms) >= 0) {
const double hz = static_cast<double>(clockTicksPerSecond());
t.userSeconds = static_cast<double>(tms.tms_utime) / hz;
t.systemSeconds = static_cast<double>(tms.tms_stime) / hz;
}
return t;
}
int numThreads() {
int result = 0;
std::string status = procStatus();
size_t pos = status.find("Threads:");
if (pos != std::string::npos) {
result = ::atoi(status.c_str() + pos + 8);
}
return result;
}
std::vector<pid_t> threads() {
std::vector<pid_t> result;
t_pids = &result;
scanDir("/proc/self/task", taskDirFilter);
t_pids = NULL;
std::sort(result.begin(), result.end());
return result;
}
} // namespace ProcessInfo
} // namespace brsdk
| 26.858491
| 97
| 0.624517
|
JerryYu512
|
dc3a4310e351c1e2960f88604cd61a26dfaf1f29
| 449
|
cpp
|
C++
|
array/equilibrium-point.cpp
|
Nilesh-Das/mustdogfg
|
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
|
[
"MIT"
] | null | null | null |
array/equilibrium-point.cpp
|
Nilesh-Das/mustdogfg
|
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
|
[
"MIT"
] | null | null | null |
array/equilibrium-point.cpp
|
Nilesh-Das/mustdogfg
|
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int equilibrium(vector<int> arr)
{
int n = arr.size();
int right = 0;
int left = 0;
for (int i = 0; i < n; ++i)
right += arr[i];
for (int i = 0; i < n; ++i)
{
right -= arr[i];
if (left == right) return i;
left += arr[i];
}
return -1;
}
int main() {
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++) cin >> a[i];
}
return 0;
}
| 12.828571
| 41
| 0.496659
|
Nilesh-Das
|
dc3d5b62b1f93388bad07ae50183481c5e7382ef
| 5,837
|
cpp
|
C++
|
CH02/PhilosophersDinner/PhilosophersDinner.cpp
|
pitaga/CppMultiThread
|
a103833743aa52e08783fc319c58de1d47b0750f
|
[
"MIT"
] | null | null | null |
CH02/PhilosophersDinner/PhilosophersDinner.cpp
|
pitaga/CppMultiThread
|
a103833743aa52e08783fc319c58de1d47b0750f
|
[
"MIT"
] | null | null | null |
CH02/PhilosophersDinner/PhilosophersDinner.cpp
|
pitaga/CppMultiThread
|
a103833743aa52e08783fc319c58de1d47b0750f
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#define BUTTON_CLOSE 100
#define PHILOSOPHER_COUNT 5
#define WM_INVALIDATE WM_USER + 1
typedef struct _tagCOMMUNICATIONOBJECT
{
HWND hWnd;
bool bExitApplication;
int iPhilosopherArray[PHILOSOPHER_COUNT];
int PhilosopherCount;
} COMMUNICATIONOBJECT, * PCOMMUNICATIONOBJECT;
HWND InitInstance(HINSTANCE hInstance, int nCmdShow);
ATOM MyRegisterClass(HINSTANCE hInstance);
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam);
int PhilosopherPass(int iPhilosopher);
void FillEllipse(HWND hWnd, HDC hDC, int iLeft, int iTop, int
iRight, int iBottom, int iPass);
TCHAR szTitle[] = TEXT("Philosophers Dinner Demo");
TCHAR szWindowClass[] = TEXT("__PD_WND_CLASS__");
TCHAR szSemaphoreName[] = TEXT("__PD_SEMAPHORE__");
TCHAR szMappingName[] = TEXT("__SHARED_FILE_MAPPING__");
PCOMMUNICATIONOBJECT pCommObject = NULL;
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE
hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
HANDLE hMapping = CreateFileMapping((HANDLE)-1, NULL,
PAGE_READWRITE, 0, sizeof(COMMUNICATIONOBJECT), szMappingName);
if (!hMapping)
{
MessageBox(NULL, TEXT("Cannot open file mapping"),
TEXT("Error!"), MB_OK);
return 1;
}
pCommObject = (PCOMMUNICATIONOBJECT)MapViewOfFile(hMapping,
FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (!pCommObject)
{
MessageBox(NULL, TEXT("Cannot get access to file mapping! "),
TEXT("Error!"), MB_OK);
CloseHandle(hMapping);
return 1;
}
InitCommonControls();
MyRegisterClass(hInstance);
HWND hWnd = NULL;
if (!(hWnd = InitInstance(hInstance, nCmdShow)))
{
return FALSE;
}
pCommObject->bExitApplication = false;
pCommObject->hWnd = hWnd;
memset(pCommObject->iPhilosopherArray, 0,
sizeof(*pCommObject->iPhilosopherArray));
pCommObject->PhilosopherCount = PHILOSOPHER_COUNT;
HANDLE hSemaphore = CreateSemaphore(NULL,
int(PHILOSOPHER_COUNT / 2), int(PHILOSOPHER_COUNT / 2),
szSemaphoreName);
STARTUPINFO startupInfo[PHILOSOPHER_COUNT] =
{ { 0 }, { 0 }, { 0 }, { 0 }, { 0 } };
PROCESS_INFORMATION processInformation[PHILOSOPHER_COUNT] =
{ { 0 }, { 0 }, { 0 }, { 0 }, { 0 } };
HANDLE hProcesses[PHILOSOPHER_COUNT];
TCHAR szBuffer[8];
for (int iIndex = 0; iIndex < PHILOSOPHER_COUNT; iIndex++)
{
#ifdef UNICODE
wsprintf(szBuffer, L"%d", iIndex);
#else
sprintf(szBuffer, "%d", iIndex);
#endif
if (CreateProcess(TEXT("..\\Debug\\Philosopher.exe"),
szBuffer, NULL, NULL,
FALSE, 0, NULL, NULL, &startupInfo[iIndex],
&processInformation[iIndex]))
{
hProcesses[iIndex] = processInformation[iIndex].hProcess;
}
}
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
pCommObject->bExitApplication = true;
UnmapViewOfFile(pCommObject);
WaitForMultipleObjects(PHILOSOPHER_COUNT, hProcesses, TRUE, INFINITE);
for (int iIndex = 0; iIndex < PHILOSOPHER_COUNT; iIndex++)
{
CloseHandle(hProcesses[iIndex]);
}
CloseHandle(hSemaphore);
CloseHandle(hMapping);
return (int)msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wndEx;
wndEx.cbSize = sizeof(WNDCLASSEX);
wndEx.style = CS_HREDRAW | CS_VREDRAW;
wndEx.lpfnWndProc = WndProc;
wndEx.cbClsExtra = 0;
wndEx.cbWndExtra = 0;
wndEx.hInstance = hInstance;
wndEx.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
wndEx.hCursor = LoadCursor(NULL, IDC_ARROW);
wndEx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wndEx.lpszMenuName = NULL;
wndEx.lpszClassName = szWindowClass;
wndEx.hIconSm = LoadIcon(wndEx.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
return RegisterClassEx(&wndEx);
}
HWND InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPED
| WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 200, 200, 540, 590,
NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return NULL;
}
HFONT hFont = CreateFont(14, 0, 0, 0, FW_NORMAL, FALSE, FALSE,
FALSE, BALTIC_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH |
FF_MODERN, TEXT("Microsoft Sans Serif"));
HWND hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 410, 520, 100,
25, hWnd, (HMENU)BUTTON_CLOSE, hInstance, NULL);
SendMessage(hButton, WM_SETFONT, (WPARAM)hFont, TRUE);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return hWnd;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case BUTTON_CLOSE:
{
DestroyWindow(hWnd);
break;
}
}
break;
}
case WM_INVALIDATE:
{
InvalidateRect(hWnd, NULL, TRUE);
break;
}
case WM_PAINT:
{
PAINTSTRUCT paintStruct;
HDC hDC = BeginPaint(hWnd, &paintStruct);
FillEllipse(hWnd, hDC, 210, 10, 310, 110,
PhilosopherPass(1));
FillEllipse(hWnd, hDC, 410, 170, 510, 270,
PhilosopherPass(2));
FillEllipse(hWnd, hDC, 335, 400, 435, 500,
PhilosopherPass(3));
FillEllipse(hWnd, hDC, 80, 400, 180, 500,
PhilosopherPass(4));
FillEllipse(hWnd, hDC, 10, 170, 110, 270,
PhilosopherPass(5));
EndPaint(hWnd, &paintStruct);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
default:
{
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
return 0;
}
int PhilosopherPass(int iPhilosopher)
{
return pCommObject->iPhilosopherArray[iPhilosopher - 1];
}
void FillEllipse(HWND hWnd, HDC hDC, int iLeft, int iTop, int
iRight, int iBottom, int iPass)
{
HBRUSH hBrush = NULL;
if (iPass)
{
hBrush = CreateSolidBrush(RGB(255, 0, 0));
}
else
{
hBrush = CreateSolidBrush(RGB(255, 255, 255));
}
HBRUSH hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);
Ellipse(hDC, iLeft, iTop, iRight, iBottom);
SelectObject(hDC, hOldBrush);
DeleteObject(hBrush);
}
| 27.533019
| 77
| 0.726743
|
pitaga
|
dc3ddee1b4973703946839d088d2b3c338c2717c
| 12,246
|
cpp
|
C++
|
pass/compiler/lcompiler.cpp
|
jesec/livehd
|
1a82dbea1d86dbd1511de588609de320aa4ef6ed
|
[
"BSD-3-Clause"
] | null | null | null |
pass/compiler/lcompiler.cpp
|
jesec/livehd
|
1a82dbea1d86dbd1511de588609de320aa4ef6ed
|
[
"BSD-3-Clause"
] | null | null | null |
pass/compiler/lcompiler.cpp
|
jesec/livehd
|
1a82dbea1d86dbd1511de588609de320aa4ef6ed
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include "lcompiler.hpp"
#include <bits/stdint-uintn.h>
Lcompiler::Lcompiler(std::string_view _path, std::string_view _odir, std::string_view _top, bool _gviz)
: path(_path), odir(_odir), top(_top), gviz(_gviz), gv(true, false, _odir) {}
void Lcompiler::do_prp_lnast2lgraph(std::vector<std::shared_ptr<Lnast>> lnasts) {
for (const auto &ln : lnasts) {
thread_pool.add(&Lcompiler::prp_thread_ln2lg, this, ln);
}
thread_pool.wait_all();
}
void Lcompiler::prp_thread_ln2lg(std::shared_ptr<Lnast> ln) {
gviz ? gv.do_from_lnast(ln, "raw") : void();
fmt::print("------------------------ Pyrope -> LNAST-SSA ({})------------------------ \n", ln->get_top_module_name());
ln->ssa_trans();
gviz ? gv.do_from_lnast(ln) : void();
fmt::print("------------------------ LNAST-> Lgraph ({})----------------------------- \n", ln->get_top_module_name());
auto module_name = ln->get_top_module_name();
Lnast_tolg ln2lg(module_name, path);
const auto top_stmts = ln->get_first_child(mmap_lib::Tree_index::root());
auto local_lgs = ln2lg.do_tolg(ln, top_stmts);
if (gviz) {
for (const auto &lg : local_lgs) gv.do_from_lgraph(lg, "local.raw");
}
// FIXME->sh: DEBUG: cannot separate to do_local_cprop_bitwidth(), why?
Cprop cp(false); // hier = false, gioc = false
Bitwidth bw(false, 10, global_flat_bwmap, global_hier_bwmap); // hier = false, max_iters = 10
for (const auto &lg : local_lgs) {
thread_pool.add(&Lcompiler::prp_thread_local_cprop_bitwidth, this, lg, cp, bw);
}
thread_pool.wait_all();
std::lock_guard<std::mutex>guard(lgs_mutex); // guarding Lcompiler::lgs
for (auto *lg : local_lgs) lgs.emplace_back(lg);
}
// TODO: try to make it work
void Lcompiler::do_local_cprop_bitwidth() {
Cprop cp(false); // hier = false, gioc = false
Bitwidth bw(false, 10, global_flat_bwmap, global_hier_bwmap); // hier = false, max_iters = 10
for (const auto &lg : lgs) {
thread_pool.add(&Lcompiler::prp_thread_local_cprop_bitwidth, this, lg, cp, bw);
}
thread_pool.wait_all();
}
void Lcompiler::prp_thread_local_cprop_bitwidth(Lgraph *lg, Cprop &cp, Bitwidth &bw) {
fmt::print("------------------------ Local Copy-Propagation ({})---------------------- (C-0)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed") : void();
fmt::print("------------------------ Local Bitwidth-Inference ({})-------------------- (B-0)\n", lg->get_name());
bw.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.bitwidth-ed-0") : void();
#if 0
fmt::print("------------------------ Local Bitwidth-Inference ({})-------------------- (B-1)\n", lg->get_name());
bw.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.bitwidth-ed-1") : void();
#endif
#if 0
fmt::print("------------------------ Local Copy-Prop ({})-------------------- (C-1)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed-1") : void();
#endif
}
void Lcompiler::add_pyrope_thread(std::shared_ptr<Lnast> ln) {
gviz ? gv.do_from_lnast(ln, "raw") : void();
fmt::print("------------------------ Pyrope -> LNAST-SSA ({})------------------------ \n", ln->get_top_module_name());
ln->ssa_trans();
gviz ? gv.do_from_lnast(ln) : void();
fmt::print("------------------------ LNAST-> Lgraph ({})----------------------------- \n", ln->get_top_module_name());
auto module_name = ln->get_top_module_name();
Lnast_tolg ln2lg(module_name, path);
const auto top_stmts = ln->get_first_child(mmap_lib::Tree_index::root());
auto local_lgs = ln2lg.do_tolg(ln, top_stmts);
if (gviz) {
for (const auto &lg : local_lgs) gv.do_from_lgraph(lg, "local.raw");
}
Cprop cp(false); // hier = false, gioc = false
Bitwidth bw(false, 10, global_flat_bwmap, global_hier_bwmap); // hier = false, max_iters = 10
for (const auto &lg : local_lgs) {
fmt::print("------------------------ Local Copy-Propagation ({})---------------------- (C-0)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed") : void();
fmt::print("------------------------ Local Bitwidth-Inference ({})-------------------- (B-0)\n", lg->get_name());
bw.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.bitwidth-ed-0") : void();
#if 0
fmt::print("------------------------ Local Bitwidth-Inference ({})-------------------- (B-1)\n", lg->get_name());
bw.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.bitwidth-ed-1") : void();
#endif
#if 0
fmt::print("------------------------ Local Copy-Propagation ({})-------------------- (C-1)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed-1") : void();
#endif
}
std::lock_guard<std::mutex>guard(lgs_mutex);
for (auto *lg : local_lgs) lgs.emplace_back(lg);
}
void Lcompiler::do_fir_lnast2lgraph(std::vector<std::shared_ptr<Lnast>> lnasts) {
for (const auto &ln : lnasts) {
thread_pool.add(&Lcompiler::fir_thread_ln2lg, this, ln);
}
thread_pool.wait_all();
// Graph_library::sync_all();
}
void Lcompiler::fir_thread_ln2lg(std::shared_ptr<Lnast> ln) {
gviz ? gv.do_from_lnast(ln, "raw") : void();
fmt::print("---------------- Firrtl_Protobuf -> LNAST-SSA ({}) ------- (LN-0)\n",
absl::StrCat("__firrtl_", ln->get_top_module_name()));
ln->ssa_trans();
gviz ? gv.do_from_lnast(ln) : void();
// note: since the first generated lgraphs are firrtl_op_lgs, they will be removed in the end,
// we should keep the original module_name for the firrtl_op mapped lgraph, so here I attached
// "__firrtl_" prefix for the firrtl_op_lgs
fmt::print("---------------- LNAST-> Lgraph ({}) --------------------- (LN-1)\n",
absl::StrCat("__firrtl_", ln->get_top_module_name()));
auto module_name = absl::StrCat("__firrtl_", ln->get_top_module_name());
Lnast_tolg ln2lg(module_name, path);
auto top_stmts = ln->get_first_child(mmap_lib::Tree_index::root());
auto local_lgs = ln2lg.do_tolg(ln, top_stmts);
if (gviz) {
for (const auto &lg : local_lgs) gv.do_from_lgraph(lg, "local.raw");
}
std::lock_guard<std::mutex>guard(lgs_mutex); // guarding Lcompiler::lgs
for (auto *lg : local_lgs) {
lgs.emplace_back(lg);
}
}
void Lcompiler::do_cprop() {
Cprop cp(false); // hier = false, gioc = false
auto lgcnt = 0;
auto hit = false;
auto top_name_before_mapping = absl::StrCat("__firrtl_", top);
// hierarchical traversal
for (auto &lg : lgs) {
++lgcnt;
// bottom up approach to parallelly do cprop
if (lg->get_name() == top_name_before_mapping) {
hit = true;
lg->each_hier_unique_sub_bottom_up_parallel([this, &cp](Lgraph *lg_sub) {
fmt::print("---------------- Copy-Propagation ({}) ------------------- (C-0)\n", lg_sub->get_name());
cp.do_trans(lg_sub);
// fmt::print("---------------- Copy-Propagation ({}) ------------------- (C-1)\n", lg_sub->get_name());
// cp.do_trans(lg_sub);
gviz ? gv.do_from_lgraph(lg_sub, "local.cprop-ed") : void();
});
// for top lgraph
fmt::print("---------------- Copy-Propagation ({}) ------------------- (C-0)\n", lg->get_name());
cp.do_trans(lg);
// fmt::print("---------------- Copy-Propagation ({}) ------------------- (C-1)\n", lg->get_name());
// cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed") : void();
}
}
if (lgcnt > 1 && hit == false)
Pass::error("Top module not specified for firrtl codes!\n");
// for (const auto &lg : lgs) {
// thread_pool.add(&Lcompiler::fir_thread_cprop, this, lg, cp);
// }
// thread_pool.wait_all();
}
// FIXME->sh: to be deprecated by bottom-up paralellism
void Lcompiler::fir_thread_cprop(Lgraph *lg, Cprop &cp) {
fmt::print("---------------- Copy-Propagation ({}) ------------------- (C-0)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "local.cprop-ed") : void();
}
void Lcompiler::do_firmap_bitwidth() {
// map __firrtl_foo.lg to foo.lg
std::vector<Lgraph *> mapped_lgs;
Bitwidth bw(false, 10, global_flat_bwmap, global_hier_bwmap); // hier = false, max_iters = 10
for (auto &lg : lgs) {
thread_pool.add(&Lcompiler::fir_thread_firmap_bw, this, lg, bw, mapped_lgs);
}
lgs = mapped_lgs;
}
void Lcompiler::fir_thread_firmap_bw(Lgraph *lg, Bitwidth &bw, std::vector<Lgraph *> &mapped_lgs) {
Firmap fm(fbmaps, pinmaps, spinmaps_xorr);
fmt::print("---------------- Firrtl Op Mapping ({}) --------------- (F-2)\n", lg->get_name());
auto new_lg = fm.do_firrtl_mapping(lg);
gviz ? gv.do_from_lgraph(new_lg, "gioc.firmap-ed") : void();
fmt::print("---------------- Local Bitwidth-Inference ({}) ----------- (B-0)\n", new_lg->get_name());
bw.do_trans(new_lg);
#if 0
fmt::print("---------------- Local Bitwidth-Inference ({}) ----------- (B-1)\n", new_lg->get_name());
bw.do_trans(new_lg);
#endif
#if 0
// FIXME: Why doing a cprop makes the code fail?
fmt::print("---------------- Local Cprop-Inference ({}) ----------- (C-1)\n", new_lg->get_name());
Cprop cp(false);
cp.do_trans(new_lg);
#endif
gviz ? gv.do_from_lgraph(new_lg, "") : void();
mapped_lgs.emplace_back(new_lg);
}
// TODO: move to multithreaded later
void Lcompiler::do_firbits() {
auto lgcnt = 0;
auto hit = false;
auto top_name_before_mapping = absl::StrCat("__firrtl_", top);
// hierarchical traversal
for (auto &lg : lgs) {
++lgcnt;
// bottom up approach to parallelly analyze the firbits
if (lg->get_name() == top_name_before_mapping) {
hit = true;
lg->each_hier_unique_sub_bottom_up_parallel([this](Lgraph *lg_sub) {
Firmap fm(fbmaps, pinmaps, spinmaps_xorr);
fmt::print("visiting lgraph name:{}\n", lg_sub->get_name());
fmt::print("---------------- Firrtl Bits Analysis ({}) --------------- (F-0)\n", lg_sub->get_name());
fm.do_firbits_analysis(lg_sub);
fmt::print("---------------- Firrtl Bits Analysis ({}) --------------- (F-1)\n", lg_sub->get_name());
fm.do_firbits_analysis(lg_sub);
gviz ? gv.do_from_lgraph(lg_sub, "firbits-ed") : void();
});
// for top lgraph
Firmap fm(fbmaps, pinmaps, spinmaps_xorr);
fmt::print("---------------- Firrtl Bits Analysis ({}) --------------- (F-0)\n", lg->get_name());
fm.do_firbits_analysis(lg);
fmt::print("---------------- Firrtl Bits Analysis ({}) --------------- (F-1)\n", lg->get_name());
fm.do_firbits_analysis(lg);
gviz ? gv.do_from_lgraph(lg, "firbits-ed") : void();
}
}
if (lgcnt > 1 && hit == false)
Pass::error("Top module not specified for firrtl codes!\n");
}
void Lcompiler::global_io_connection() {
Cprop cp(false); // hier = false, at_gioc = true
// Bitwidth bw(true, 10, global_flat_bwmap, global_hier_bwmap); // hier = true, max_iters = 10
// Gioc gioc(path); FIXME? Do we need this steps? (gioc is broken. It still uses the old TupGet
for (auto &lg : lgs) {
//fmt::print("---------------- Global IO Connection ({}) --------------- (GIOC)\n", lg->get_name());
//gioc.do_trans(lg);
//gviz ? gv.do_from_lgraph(lg, "gioc.raw") : void();
fmt::print("---------------- Global Copy-Propagation ({}) ------------ (GC)\n", lg->get_name());
cp.do_trans(lg);
gviz ? gv.do_from_lgraph(lg, "gioc.cprop-ed") : void();
}
}
void Lcompiler::global_bitwidth_inference() {
Bitwidth bw(true, 10, global_flat_bwmap, global_hier_bwmap); // hier = true, max_iters = 10
auto lgcnt = 0;
auto hit = false;
for (auto &lg : lgs) {
++lgcnt;
if (lg->get_name() == top) {
hit = true;
fmt::print("---------------- Global Bitwidth-Inference ({}) ----------------- (GB)\n", lg->get_name());
bw.do_trans(lg);
}
gviz ? gv.do_from_lgraph(lg, "") : void();
}
if (lgcnt > 1 && hit == false)
Pass::error("Top module not specified from multiple Pyrope source codes!\n");
}
| 37.913313
| 120
| 0.572105
|
jesec
|
dc41a44e4dddc2b92afe8bfaf7e3a052d2c4d91e
| 556
|
cpp
|
C++
|
src/Geometry.cpp
|
savageking-io/evelengine
|
f4f31419077e3467db271e82b05164eafa521eb7
|
[
"Apache-2.0"
] | null | null | null |
src/Geometry.cpp
|
savageking-io/evelengine
|
f4f31419077e3467db271e82b05164eafa521eb7
|
[
"Apache-2.0"
] | null | null | null |
src/Geometry.cpp
|
savageking-io/evelengine
|
f4f31419077e3467db271e82b05164eafa521eb7
|
[
"Apache-2.0"
] | null | null | null |
#include "Geometry.hpp"
namespace EvelEngine
{
Vector2D::Vector2D(int x, int y) : x(x), y(y)
{
}
void Vector2D::normalize()
{
int magnitude = this->magnitude();
x /= magnitude;
y /= magnitude;
}
Rect2D::Rect2D(Vector2D position, Vector2D size) : position(position), size(size)
{
}
Rect2D::Rect2D(int x, int y, int w, int h) : position(x ,y), size(w, h)
{
}
const SDL_Rect Rect2D::rect() const
{
return SDL_Rect{position.x, position.y, size.x, size.y};
}
}
| 17.935484
| 85
| 0.555755
|
savageking-io
|
dc41a645ac289afd7d40d9b61f7bcb347b7c11f7
| 2,031
|
cpp
|
C++
|
TinyWebServer/src/webserver.cpp
|
ho-229/Network-Learn
|
b87d112b2f93c5f4d0d522629c15f8bba254ff2d
|
[
"MIT"
] | 1
|
2022-02-01T18:50:18.000Z
|
2022-02-01T18:50:18.000Z
|
TinyWebServer/src/webserver.cpp
|
ho-229/Network-Learn
|
b87d112b2f93c5f4d0d522629c15f8bba254ff2d
|
[
"MIT"
] | null | null | null |
TinyWebServer/src/webserver.cpp
|
ho-229/Network-Learn
|
b87d112b2f93c5f4d0d522629c15f8bba254ff2d
|
[
"MIT"
] | null | null | null |
/**
* @author Ho 229
* @date 2021/7/26
*/
#include "webserver.h"
#include "util/util.h"
#include "core/tcpsocket.h"
#include "core/sslsocket.h"
#include "core/eventloop.h"
#include <signal.h>
WebServer::WebServer()
{
#ifdef _WIN32
if(!AbstractSocket::initializatWsa())
throw std::runtime_error("WebServer: initializat WinSock2 failed.");
#else // Unix
// Ignore SIGPIPE
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, 0);
#endif
}
WebServer::~WebServer()
{
#ifdef _WIN32
TcpSocket::cleanUpWsa();
#endif
SslSocket::cleanUpSsl();
m_runnable = false;
}
int WebServer::start()
{
if(m_listeners.empty() || !m_services || !m_loops.empty() || !m_loopCount)
return -1;
m_runnable = true;
EventLoop *loop = nullptr;
for(size_t i = 0; i < m_loopCount; ++i)
{
m_loops.emplace_back(loop = new EventLoop(
m_runnable, m_timeout, m_services.get(), m_handler));
loop->registerListeners(m_listeners.begin(), m_listeners.end());
loop->start();
}
return 0;
}
void WebServer::requestQuit()
{
for(auto &loop : m_loops)
loop->unregisterListeners(m_listeners.begin(), m_listeners.end());
for(auto &listener : m_listeners)
listener->close();
}
void WebServer::waitForFinished()
{
for(auto &loop : m_loops)
loop->waitForFinished();
m_listeners.clear();
m_loops.clear();
}
bool WebServer::listen(const std::string &hostName, const std::string &port,
bool sslEnable, std::pair<int, int> linger)
{
if(sslEnable && !SslSocket::isSslAvailable())
return false;
std::unique_ptr<AbstractSocket> socket(sslEnable ?
static_cast<AbstractSocket *>(new SslSocket()) :
static_cast<AbstractSocket *>(new TcpSocket()));
if(!socket->listen(hostName, port))
return false;
socket->setOption(SOL_SOCKET, SO_LINGER, linger);
m_listeners.emplace_back(std::move(socket));
return true;
}
| 21.378947
| 78
| 0.63614
|
ho-229
|
dc48d9a939c1ae9e558abd40c697af9ba3d29d75
| 2,240
|
cpp
|
C++
|
src/xalanc/XPath/XPathFactoryDefault.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
src/xalanc/XPath/XPathFactoryDefault.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
src/xalanc/XPath/XPathFactoryDefault.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.
*/
// Class header file.
#include "XPathFactoryDefault.hpp"
#include <algorithm>
#include "XPath.hpp"
#include <xalanc/Include/XalanMemMgrHelper.hpp>
XALAN_CPP_NAMESPACE_BEGIN
XPathFactoryDefault::XPathFactoryDefault(MemoryManagerType& theManager) :
XPathFactory(),
m_xpaths(theManager)
{
}
XPathFactoryDefault*
XPathFactoryDefault::createXPathFactoryDefault(MemoryManagerType& theManager)
{
typedef XPathFactoryDefault ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(theManager);
theGuard.release();
return theResult;
}
XPathFactoryDefault::~XPathFactoryDefault()
{
reset();
}
void
XPathFactoryDefault::reset()
{
XALAN_USING_STD(for_each)
for_each(m_xpaths.begin(),
m_xpaths.end(),
DeleteXPathFunctor(*this, true));
m_xpaths.clear();
}
bool
XPathFactoryDefault::doReturnObject(
const XPath* theXPath,
bool fInReset)
{
const CollectionType::size_type theCount =
fInReset == true ? m_xpaths.count(theXPath) : m_xpaths.erase(theXPath);
if (theCount == 0)
{
return false;
}
else
{
destroyObjWithMemMgr(theXPath, m_xpaths.getMemoryManager());
return true;
}
}
XPath*
XPathFactoryDefault::create()
{
XPath* const theXPath = XPath::create(m_xpaths.getMemoryManager());
m_xpaths.insert(theXPath);
return theXPath;
}
XALAN_CPP_NAMESPACE_END
| 20
| 114
| 0.691071
|
rherardi
|
dc4993741275b49e93e8a9825193fa0cb39c2349
| 48,174
|
cpp
|
C++
|
modules/core/src/norm.cpp
|
zhongshenxuexi/opencv
|
10ae0c4364ecf1bebf3a80f7a6570142e4da7632
|
[
"BSD-3-Clause"
] | 2
|
2020-01-05T21:34:22.000Z
|
2020-07-19T20:13:06.000Z
|
modules/core/src/norm.cpp
|
zhongshenxuexi/opencv
|
10ae0c4364ecf1bebf3a80f7a6570142e4da7632
|
[
"BSD-3-Clause"
] | null | null | null |
modules/core/src/norm.cpp
|
zhongshenxuexi/opencv
|
10ae0c4364ecf1bebf3a80f7a6570142e4da7632
|
[
"BSD-3-Clause"
] | 1
|
2021-07-12T08:03:07.000Z
|
2021-07-12T08:03:07.000Z
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "precomp.hpp"
#include "opencl_kernels_core.hpp"
#include "stat.hpp"
/****************************************************************************************\
* norm *
\****************************************************************************************/
namespace cv { namespace hal {
extern const uchar popCountTable[256] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
static const uchar popCountTable2[] =
{
0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3,
1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4,
2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4
};
static const uchar popCountTable4[] =
{
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
};
int normHamming(const uchar* a, int n, int cellSize)
{
if( cellSize == 1 )
return normHamming(a, n);
const uchar* tab = 0;
if( cellSize == 2 )
tab = popCountTable2;
else if( cellSize == 4 )
tab = popCountTable4;
else
return -1;
int i = 0;
int result = 0;
#if CV_ENABLE_UNROLLED
for( ; i <= n - 4; i += 4 )
result += tab[a[i]] + tab[a[i+1]] + tab[a[i+2]] + tab[a[i+3]];
#endif
for( ; i < n; i++ )
result += tab[a[i]];
return result;
}
int normHamming(const uchar* a, const uchar* b, int n, int cellSize)
{
if( cellSize == 1 )
return normHamming(a, b, n);
const uchar* tab = 0;
if( cellSize == 2 )
tab = popCountTable2;
else if( cellSize == 4 )
tab = popCountTable4;
else
return -1;
int i = 0;
int result = 0;
#if CV_ENABLE_UNROLLED
for( ; i <= n - 4; i += 4 )
result += tab[a[i] ^ b[i]] + tab[a[i+1] ^ b[i+1]] +
tab[a[i+2] ^ b[i+2]] + tab[a[i+3] ^ b[i+3]];
#endif
for( ; i < n; i++ )
result += tab[a[i] ^ b[i]];
return result;
}
float normL2Sqr_(const float* a, const float* b, int n)
{
int j = 0; float d = 0.f;
#if CV_AVX2
float CV_DECL_ALIGNED(32) buf[8];
__m256 d0 = _mm256_setzero_ps();
for( ; j <= n - 8; j += 8 )
{
__m256 t0 = _mm256_sub_ps(_mm256_loadu_ps(a + j), _mm256_loadu_ps(b + j));
#if CV_FMA3
d0 = _mm256_fmadd_ps(t0, t0, d0);
#else
d0 = _mm256_add_ps(d0, _mm256_mul_ps(t0, t0));
#endif
}
_mm256_store_ps(buf, d0);
d = buf[0] + buf[1] + buf[2] + buf[3] + buf[4] + buf[5] + buf[6] + buf[7];
#elif CV_SSE
float CV_DECL_ALIGNED(16) buf[4];
__m128 d0 = _mm_setzero_ps(), d1 = _mm_setzero_ps();
for( ; j <= n - 8; j += 8 )
{
__m128 t0 = _mm_sub_ps(_mm_loadu_ps(a + j), _mm_loadu_ps(b + j));
__m128 t1 = _mm_sub_ps(_mm_loadu_ps(a + j + 4), _mm_loadu_ps(b + j + 4));
d0 = _mm_add_ps(d0, _mm_mul_ps(t0, t0));
d1 = _mm_add_ps(d1, _mm_mul_ps(t1, t1));
}
_mm_store_ps(buf, _mm_add_ps(d0, d1));
d = buf[0] + buf[1] + buf[2] + buf[3];
#endif
{
for( ; j <= n - 4; j += 4 )
{
float t0 = a[j] - b[j], t1 = a[j+1] - b[j+1], t2 = a[j+2] - b[j+2], t3 = a[j+3] - b[j+3];
d += t0*t0 + t1*t1 + t2*t2 + t3*t3;
}
}
for( ; j < n; j++ )
{
float t = a[j] - b[j];
d += t*t;
}
return d;
}
float normL1_(const float* a, const float* b, int n)
{
int j = 0; float d = 0.f;
#if CV_SSE
float CV_DECL_ALIGNED(16) buf[4];
static const int CV_DECL_ALIGNED(16) absbuf[4] = {0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff};
__m128 d0 = _mm_setzero_ps(), d1 = _mm_setzero_ps();
__m128 absmask = _mm_load_ps((const float*)absbuf);
for( ; j <= n - 8; j += 8 )
{
__m128 t0 = _mm_sub_ps(_mm_loadu_ps(a + j), _mm_loadu_ps(b + j));
__m128 t1 = _mm_sub_ps(_mm_loadu_ps(a + j + 4), _mm_loadu_ps(b + j + 4));
d0 = _mm_add_ps(d0, _mm_and_ps(t0, absmask));
d1 = _mm_add_ps(d1, _mm_and_ps(t1, absmask));
}
_mm_store_ps(buf, _mm_add_ps(d0, d1));
d = buf[0] + buf[1] + buf[2] + buf[3];
#elif CV_NEON
float32x4_t v_sum = vdupq_n_f32(0.0f);
for ( ; j <= n - 4; j += 4)
v_sum = vaddq_f32(v_sum, vabdq_f32(vld1q_f32(a + j), vld1q_f32(b + j)));
float CV_DECL_ALIGNED(16) buf[4];
vst1q_f32(buf, v_sum);
d = buf[0] + buf[1] + buf[2] + buf[3];
#endif
{
for( ; j <= n - 4; j += 4 )
{
d += std::abs(a[j] - b[j]) + std::abs(a[j+1] - b[j+1]) +
std::abs(a[j+2] - b[j+2]) + std::abs(a[j+3] - b[j+3]);
}
}
for( ; j < n; j++ )
d += std::abs(a[j] - b[j]);
return d;
}
int normL1_(const uchar* a, const uchar* b, int n)
{
int j = 0, d = 0;
#if CV_SSE
__m128i d0 = _mm_setzero_si128();
for( ; j <= n - 16; j += 16 )
{
__m128i t0 = _mm_loadu_si128((const __m128i*)(a + j));
__m128i t1 = _mm_loadu_si128((const __m128i*)(b + j));
d0 = _mm_add_epi32(d0, _mm_sad_epu8(t0, t1));
}
for( ; j <= n - 4; j += 4 )
{
__m128i t0 = _mm_cvtsi32_si128(*(const int*)(a + j));
__m128i t1 = _mm_cvtsi32_si128(*(const int*)(b + j));
d0 = _mm_add_epi32(d0, _mm_sad_epu8(t0, t1));
}
d = _mm_cvtsi128_si32(_mm_add_epi32(d0, _mm_unpackhi_epi64(d0, d0)));
#elif CV_NEON
uint32x4_t v_sum = vdupq_n_u32(0.0f);
for ( ; j <= n - 16; j += 16)
{
uint8x16_t v_dst = vabdq_u8(vld1q_u8(a + j), vld1q_u8(b + j));
uint16x8_t v_low = vmovl_u8(vget_low_u8(v_dst)), v_high = vmovl_u8(vget_high_u8(v_dst));
v_sum = vaddq_u32(v_sum, vaddl_u16(vget_low_u16(v_low), vget_low_u16(v_high)));
v_sum = vaddq_u32(v_sum, vaddl_u16(vget_high_u16(v_low), vget_high_u16(v_high)));
}
uint CV_DECL_ALIGNED(16) buf[4];
vst1q_u32(buf, v_sum);
d = buf[0] + buf[1] + buf[2] + buf[3];
#endif
{
for( ; j <= n - 4; j += 4 )
{
d += std::abs(a[j] - b[j]) + std::abs(a[j+1] - b[j+1]) +
std::abs(a[j+2] - b[j+2]) + std::abs(a[j+3] - b[j+3]);
}
}
for( ; j < n; j++ )
d += std::abs(a[j] - b[j]);
return d;
}
}} //cv::hal
//==================================================================================================
namespace cv
{
template<typename T, typename ST> int
normInf_(const T* src, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result = std::max(result, normInf<T, ST>(src, len*cn));
}
else
{
for( int i = 0; i < len; i++, src += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
result = std::max(result, ST(cv_abs(src[k])));
}
}
*_result = result;
return 0;
}
template<typename T, typename ST> int
normL1_(const T* src, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result += normL1<T, ST>(src, len*cn);
}
else
{
for( int i = 0; i < len; i++, src += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
result += cv_abs(src[k]);
}
}
*_result = result;
return 0;
}
template<typename T, typename ST> int
normL2_(const T* src, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result += normL2Sqr<T, ST>(src, len*cn);
}
else
{
for( int i = 0; i < len; i++, src += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
T v = src[k];
result += (ST)v*v;
}
}
}
*_result = result;
return 0;
}
template<typename T, typename ST> int
normDiffInf_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result = std::max(result, normInf<T, ST>(src1, src2, len*cn));
}
else
{
for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
result = std::max(result, (ST)std::abs(src1[k] - src2[k]));
}
}
*_result = result;
return 0;
}
template<typename T, typename ST> int
normDiffL1_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result += normL1<T, ST>(src1, src2, len*cn);
}
else
{
for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
result += std::abs(src1[k] - src2[k]);
}
}
*_result = result;
return 0;
}
template<typename T, typename ST> int
normDiffL2_(const T* src1, const T* src2, const uchar* mask, ST* _result, int len, int cn)
{
ST result = *_result;
if( !mask )
{
result += normL2Sqr<T, ST>(src1, src2, len*cn);
}
else
{
for( int i = 0; i < len; i++, src1 += cn, src2 += cn )
if( mask[i] )
{
for( int k = 0; k < cn; k++ )
{
ST v = src1[k] - src2[k];
result += v*v;
}
}
}
*_result = result;
return 0;
}
#define CV_DEF_NORM_FUNC(L, suffix, type, ntype) \
static int norm##L##_##suffix(const type* src, const uchar* mask, ntype* r, int len, int cn) \
{ return norm##L##_(src, mask, r, len, cn); } \
static int normDiff##L##_##suffix(const type* src1, const type* src2, \
const uchar* mask, ntype* r, int len, int cn) \
{ return normDiff##L##_(src1, src2, mask, r, (int)len, cn); }
#define CV_DEF_NORM_ALL(suffix, type, inftype, l1type, l2type) \
CV_DEF_NORM_FUNC(Inf, suffix, type, inftype) \
CV_DEF_NORM_FUNC(L1, suffix, type, l1type) \
CV_DEF_NORM_FUNC(L2, suffix, type, l2type)
CV_DEF_NORM_ALL(8u, uchar, int, int, int)
CV_DEF_NORM_ALL(8s, schar, int, int, int)
CV_DEF_NORM_ALL(16u, ushort, int, int, double)
CV_DEF_NORM_ALL(16s, short, int, int, double)
CV_DEF_NORM_ALL(32s, int, int, double, double)
CV_DEF_NORM_ALL(32f, float, float, double, double)
CV_DEF_NORM_ALL(64f, double, double, double, double)
typedef int (*NormFunc)(const uchar*, const uchar*, uchar*, int, int);
typedef int (*NormDiffFunc)(const uchar*, const uchar*, const uchar*, uchar*, int, int);
static NormFunc getNormFunc(int normType, int depth)
{
static NormFunc normTab[3][8] =
{
{
(NormFunc)GET_OPTIMIZED(normInf_8u), (NormFunc)GET_OPTIMIZED(normInf_8s), (NormFunc)GET_OPTIMIZED(normInf_16u), (NormFunc)GET_OPTIMIZED(normInf_16s),
(NormFunc)GET_OPTIMIZED(normInf_32s), (NormFunc)GET_OPTIMIZED(normInf_32f), (NormFunc)normInf_64f, 0
},
{
(NormFunc)GET_OPTIMIZED(normL1_8u), (NormFunc)GET_OPTIMIZED(normL1_8s), (NormFunc)GET_OPTIMIZED(normL1_16u), (NormFunc)GET_OPTIMIZED(normL1_16s),
(NormFunc)GET_OPTIMIZED(normL1_32s), (NormFunc)GET_OPTIMIZED(normL1_32f), (NormFunc)normL1_64f, 0
},
{
(NormFunc)GET_OPTIMIZED(normL2_8u), (NormFunc)GET_OPTIMIZED(normL2_8s), (NormFunc)GET_OPTIMIZED(normL2_16u), (NormFunc)GET_OPTIMIZED(normL2_16s),
(NormFunc)GET_OPTIMIZED(normL2_32s), (NormFunc)GET_OPTIMIZED(normL2_32f), (NormFunc)normL2_64f, 0
}
};
return normTab[normType][depth];
}
static NormDiffFunc getNormDiffFunc(int normType, int depth)
{
static NormDiffFunc normDiffTab[3][8] =
{
{
(NormDiffFunc)GET_OPTIMIZED(normDiffInf_8u), (NormDiffFunc)normDiffInf_8s,
(NormDiffFunc)normDiffInf_16u, (NormDiffFunc)normDiffInf_16s,
(NormDiffFunc)normDiffInf_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffInf_32f),
(NormDiffFunc)normDiffInf_64f, 0
},
{
(NormDiffFunc)GET_OPTIMIZED(normDiffL1_8u), (NormDiffFunc)normDiffL1_8s,
(NormDiffFunc)normDiffL1_16u, (NormDiffFunc)normDiffL1_16s,
(NormDiffFunc)normDiffL1_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffL1_32f),
(NormDiffFunc)normDiffL1_64f, 0
},
{
(NormDiffFunc)GET_OPTIMIZED(normDiffL2_8u), (NormDiffFunc)normDiffL2_8s,
(NormDiffFunc)normDiffL2_16u, (NormDiffFunc)normDiffL2_16s,
(NormDiffFunc)normDiffL2_32s, (NormDiffFunc)GET_OPTIMIZED(normDiffL2_32f),
(NormDiffFunc)normDiffL2_64f, 0
}
};
return normDiffTab[normType][depth];
}
#ifdef HAVE_OPENCL
static bool ocl_norm( InputArray _src, int normType, InputArray _mask, double & result )
{
const ocl::Device & d = ocl::Device::getDefault();
#ifdef __ANDROID__
if (d.isNVidia())
return false;
#endif
const int cn = _src.channels();
if (cn > 4)
return false;
int type = _src.type(), depth = CV_MAT_DEPTH(type);
bool doubleSupport = d.doubleFPConfig() > 0,
haveMask = _mask.kind() != _InputArray::NONE;
if ( !(normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR) ||
(!doubleSupport && depth == CV_64F))
return false;
UMat src = _src.getUMat();
if (normType == NORM_INF)
{
if (!ocl_minMaxIdx(_src, NULL, &result, NULL, NULL, _mask,
std::max(depth, CV_32S), depth != CV_8U && depth != CV_16U))
return false;
}
else if (normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR)
{
Scalar sc;
bool unstype = depth == CV_8U || depth == CV_16U;
if ( !ocl_sum(haveMask ? src : src.reshape(1), sc, normType == NORM_L2 || normType == NORM_L2SQR ?
OCL_OP_SUM_SQR : (unstype ? OCL_OP_SUM : OCL_OP_SUM_ABS), _mask) )
return false;
double s = 0.0;
for (int i = 0; i < (haveMask ? cn : 1); ++i)
s += sc[i];
result = normType == NORM_L1 || normType == NORM_L2SQR ? s : std::sqrt(s);
}
return true;
}
#endif
#ifdef HAVE_IPP
static bool ipp_norm(Mat &src, int normType, Mat &mask, double &result)
{
CV_INSTRUMENT_REGION_IPP()
#if IPP_VERSION_X100 >= 700
size_t total_size = src.total();
int rows = src.size[0], cols = rows ? (int)(total_size/rows) : 0;
if( (src.dims == 2 || (src.isContinuous() && mask.isContinuous()))
&& cols > 0 && (size_t)rows*cols == total_size )
{
if( !mask.empty() )
{
IppiSize sz = { cols, rows };
int type = src.type();
typedef IppStatus (CV_STDCALL* ippiMaskNormFuncC1)(const void *, int, const void *, int, IppiSize, Ipp64f *);
ippiMaskNormFuncC1 ippiNorm_C1MR =
normType == NORM_INF ?
(type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_Inf_32f_C1MR :
0) :
normType == NORM_L1 ?
(type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_L1_32f_C1MR :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormFuncC1)ippiNorm_L2_32f_C1MR :
0) : 0;
if( ippiNorm_C1MR )
{
Ipp64f norm;
if( CV_INSTRUMENT_FUN_IPP(ippiNorm_C1MR, src.ptr(), (int)src.step[0], mask.ptr(), (int)mask.step[0], sz, &norm) >= 0 )
{
result = (normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm);
return true;
}
}
typedef IppStatus (CV_STDCALL* ippiMaskNormFuncC3)(const void *, int, const void *, int, IppiSize, int, Ipp64f *);
ippiMaskNormFuncC3 ippiNorm_C3CMR =
normType == NORM_INF ?
(type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_Inf_32f_C3CMR :
0) :
normType == NORM_L1 ?
(type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L1_32f_C3CMR :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormFuncC3)ippiNorm_L2_32f_C3CMR :
0) : 0;
if( ippiNorm_C3CMR )
{
Ipp64f norm1, norm2, norm3;
if( CV_INSTRUMENT_FUN_IPP(ippiNorm_C3CMR, src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 1, &norm1) >= 0 &&
CV_INSTRUMENT_FUN_IPP(ippiNorm_C3CMR, src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 2, &norm2) >= 0 &&
CV_INSTRUMENT_FUN_IPP(ippiNorm_C3CMR, src.data, (int)src.step[0], mask.data, (int)mask.step[0], sz, 3, &norm3) >= 0)
{
Ipp64f norm =
normType == NORM_INF ? std::max(std::max(norm1, norm2), norm3) :
normType == NORM_L1 ? norm1 + norm2 + norm3 :
normType == NORM_L2 || normType == NORM_L2SQR ? std::sqrt(norm1 * norm1 + norm2 * norm2 + norm3 * norm3) :
0;
result = (normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm);
return true;
}
}
}
else
{
IppiSize sz = { cols*src.channels(), rows };
int type = src.depth();
typedef IppStatus (CV_STDCALL* ippiNormFuncHint)(const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
typedef IppStatus (CV_STDCALL* ippiNormFuncNoHint)(const void *, int, IppiSize, Ipp64f *);
ippiNormFuncHint ippiNormHint =
normType == NORM_L1 ?
(type == CV_32FC1 ? (ippiNormFuncHint)ippiNorm_L1_32f_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_32FC1 ? (ippiNormFuncHint)ippiNorm_L2_32f_C1R :
0) : 0;
ippiNormFuncNoHint ippiNorm =
normType == NORM_INF ?
(type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_8u_C1R :
type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_16u_C1R :
type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_16s_C1R :
type == CV_32FC1 ? (ippiNormFuncNoHint)ippiNorm_Inf_32f_C1R :
0) :
normType == NORM_L1 ?
(type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_L1_8u_C1R :
type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_L1_16u_C1R :
type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_L1_16s_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC1 ? (ippiNormFuncNoHint)ippiNorm_L2_8u_C1R :
type == CV_16UC1 ? (ippiNormFuncNoHint)ippiNorm_L2_16u_C1R :
type == CV_16SC1 ? (ippiNormFuncNoHint)ippiNorm_L2_16s_C1R :
0) : 0;
if( ippiNormHint || ippiNorm )
{
Ipp64f norm;
IppStatus ret = ippiNormHint ? CV_INSTRUMENT_FUN_IPP(ippiNormHint, src.ptr(), (int)src.step[0], sz, &norm, ippAlgHintAccurate) :
CV_INSTRUMENT_FUN_IPP(ippiNorm, src.ptr(), (int)src.step[0], sz, &norm);
if( ret >= 0 )
{
result = (normType == NORM_L2SQR) ? norm * norm : norm;
return true;
}
}
}
}
#else
CV_UNUSED(src); CV_UNUSED(normType); CV_UNUSED(mask); CV_UNUSED(result);
#endif
return false;
}
#endif
} // cv::
double cv::norm( InputArray _src, int normType, InputArray _mask )
{
CV_INSTRUMENT_REGION()
normType &= NORM_TYPE_MASK;
CV_Assert( normType == NORM_INF || normType == NORM_L1 ||
normType == NORM_L2 || normType == NORM_L2SQR ||
((normType == NORM_HAMMING || normType == NORM_HAMMING2) && _src.type() == CV_8U) );
#if defined HAVE_OPENCL || defined HAVE_IPP
double _result = 0;
#endif
#ifdef HAVE_OPENCL
CV_OCL_RUN_(OCL_PERFORMANCE_CHECK(_src.isUMat()) && _src.dims() <= 2,
ocl_norm(_src, normType, _mask, _result),
_result)
#endif
Mat src = _src.getMat(), mask = _mask.getMat();
CV_IPP_RUN(IPP_VERSION_X100 >= 700, ipp_norm(src, normType, mask, _result), _result);
int depth = src.depth(), cn = src.channels();
if( src.isContinuous() && mask.empty() )
{
size_t len = src.total()*cn;
if( len == (size_t)(int)len )
{
if( depth == CV_32F )
{
const float* data = src.ptr<float>();
if( normType == NORM_L2 )
{
double result = 0;
GET_OPTIMIZED(normL2_32f)(data, 0, &result, (int)len, 1);
return std::sqrt(result);
}
if( normType == NORM_L2SQR )
{
double result = 0;
GET_OPTIMIZED(normL2_32f)(data, 0, &result, (int)len, 1);
return result;
}
if( normType == NORM_L1 )
{
double result = 0;
GET_OPTIMIZED(normL1_32f)(data, 0, &result, (int)len, 1);
return result;
}
if( normType == NORM_INF )
{
float result = 0;
GET_OPTIMIZED(normInf_32f)(data, 0, &result, (int)len, 1);
return result;
}
}
if( depth == CV_8U )
{
const uchar* data = src.ptr<uchar>();
if( normType == NORM_HAMMING )
{
return hal::normHamming(data, (int)len);
}
if( normType == NORM_HAMMING2 )
{
return hal::normHamming(data, (int)len, 2);
}
}
}
}
CV_Assert( mask.empty() || mask.type() == CV_8U );
if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
{
if( !mask.empty() )
{
Mat temp;
bitwise_and(src, mask, temp);
return norm(temp, normType);
}
int cellSize = normType == NORM_HAMMING ? 1 : 2;
const Mat* arrays[] = {&src, 0};
uchar* ptrs[1] = {};
NAryMatIterator it(arrays, ptrs);
int total = (int)it.size;
int result = 0;
for( size_t i = 0; i < it.nplanes; i++, ++it )
{
result += hal::normHamming(ptrs[0], total, cellSize);
}
return result;
}
NormFunc func = getNormFunc(normType >> 1, depth == CV_16F ? CV_32F : depth);
CV_Assert( func != 0 );
const Mat* arrays[] = {&src, &mask, 0};
uchar* ptrs[2] = {};
union
{
double d;
int i;
float f;
}
result;
result.d = 0;
NAryMatIterator it(arrays, ptrs);
int j, total = (int)it.size, blockSize = total;
bool blockSum = depth == CV_16F || (normType == NORM_L1 && depth <= CV_16S) ||
((normType == NORM_L2 || normType == NORM_L2SQR) && depth <= CV_8S);
int isum = 0;
int *ibuf = &result.i;
AutoBuffer<float> fltbuf_;
float* fltbuf = 0;
size_t esz = 0;
if( blockSum )
{
esz = src.elemSize();
if( depth == CV_16F )
{
blockSize = std::min(blockSize, 1024);
fltbuf_.allocate(blockSize);
fltbuf = fltbuf_.data();
}
else
{
int intSumBlockSize = (normType == NORM_L1 && depth <= CV_8S ? (1 << 23) : (1 << 15))/cn;
blockSize = std::min(blockSize, intSumBlockSize);
ibuf = &isum;
}
}
for( size_t i = 0; i < it.nplanes; i++, ++it )
{
for( j = 0; j < total; j += blockSize )
{
int bsz = std::min(total - j, blockSize);
const uchar* data = ptrs[0];
if( depth == CV_16F )
{
hal::cvt16f32f((const float16_t*)ptrs[0], fltbuf, bsz);
data = (const uchar*)fltbuf;
}
func( data, ptrs[1], (uchar*)ibuf, bsz, cn );
if( blockSum && depth != CV_16F )
{
result.d += isum;
isum = 0;
}
ptrs[0] += bsz*esz;
if( ptrs[1] )
ptrs[1] += bsz;
}
}
if( normType == NORM_INF )
{
if( depth == CV_64F )
;
else if( depth == CV_32F )
result.d = result.f;
else
result.d = result.i;
}
else if( normType == NORM_L2 )
result.d = std::sqrt(result.d);
return result.d;
}
//==================================================================================================
#ifdef HAVE_OPENCL
namespace cv {
static bool ocl_norm( InputArray _src1, InputArray _src2, int normType, InputArray _mask, double & result )
{
#ifdef __ANDROID__
if (ocl::Device::getDefault().isNVidia())
return false;
#endif
Scalar sc1, sc2;
int cn = _src1.channels();
if (cn > 4)
return false;
int type = _src1.type(), depth = CV_MAT_DEPTH(type);
bool relative = (normType & NORM_RELATIVE) != 0;
normType &= ~NORM_RELATIVE;
bool normsum = normType == NORM_L1 || normType == NORM_L2 || normType == NORM_L2SQR;
#ifdef __APPLE__
if(normType == NORM_L1 && type == CV_16UC3 && !_mask.empty())
return false;
#endif
if (normsum)
{
if (!ocl_sum(_src1, sc1, normType == NORM_L2 || normType == NORM_L2SQR ?
OCL_OP_SUM_SQR : OCL_OP_SUM, _mask, _src2, relative, sc2))
return false;
}
else
{
if (!ocl_minMaxIdx(_src1, NULL, &sc1[0], NULL, NULL, _mask, std::max(CV_32S, depth),
false, _src2, relative ? &sc2[0] : NULL))
return false;
cn = 1;
}
double s2 = 0;
for (int i = 0; i < cn; ++i)
{
result += sc1[i];
if (relative)
s2 += sc2[i];
}
if (normType == NORM_L2)
{
result = std::sqrt(result);
if (relative)
s2 = std::sqrt(s2);
}
if (relative)
result /= (s2 + DBL_EPSILON);
return true;
}
}
#endif
#ifdef HAVE_IPP
namespace cv
{
static bool ipp_norm(InputArray _src1, InputArray _src2, int normType, InputArray _mask, double &result)
{
CV_INSTRUMENT_REGION_IPP()
#if IPP_VERSION_X100 >= 700
Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();
if( normType & CV_RELATIVE )
{
normType &= NORM_TYPE_MASK;
size_t total_size = src1.total();
int rows = src1.size[0], cols = rows ? (int)(total_size/rows) : 0;
if( (src1.dims == 2 || (src1.isContinuous() && src2.isContinuous() && mask.isContinuous()))
&& cols > 0 && (size_t)rows*cols == total_size )
{
if( !mask.empty() )
{
IppiSize sz = { cols, rows };
int type = src1.type();
typedef IppStatus (CV_STDCALL* ippiMaskNormDiffFuncC1)(const void *, int, const void *, int, const void *, int, IppiSize, Ipp64f *);
ippiMaskNormDiffFuncC1 ippiNormRel_C1MR =
normType == NORM_INF ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_Inf_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_Inf_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_Inf_32f_C1MR :
0) :
normType == NORM_L1 ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L1_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L1_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L1_32f_C1MR :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L2_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L2_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormRel_L2_32f_C1MR :
0) : 0;
if( ippiNormRel_C1MR )
{
Ipp64f norm;
if( CV_INSTRUMENT_FUN_IPP(ippiNormRel_C1MR, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], mask.ptr(), (int)mask.step[0], sz, &norm) >= 0 )
{
result = (normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm);
return true;
}
}
}
else
{
IppiSize sz = { cols*src1.channels(), rows };
int type = src1.depth();
typedef IppStatus (CV_STDCALL* ippiNormRelFuncHint)(const void *, int, const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
typedef IppStatus (CV_STDCALL* ippiNormRelFuncNoHint)(const void *, int, const void *, int, IppiSize, Ipp64f *);
ippiNormRelFuncHint ippiNormRelHint =
normType == NORM_L1 ?
(type == CV_32F ? (ippiNormRelFuncHint)ippiNormRel_L1_32f_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_32F ? (ippiNormRelFuncHint)ippiNormRel_L2_32f_C1R :
0) : 0;
ippiNormRelFuncNoHint ippiNormRel =
normType == NORM_INF ?
(type == CV_8U ? (ippiNormRelFuncNoHint)ippiNormRel_Inf_8u_C1R :
type == CV_16U ? (ippiNormRelFuncNoHint)ippiNormRel_Inf_16u_C1R :
type == CV_16S ? (ippiNormRelFuncNoHint)ippiNormRel_Inf_16s_C1R :
type == CV_32F ? (ippiNormRelFuncNoHint)ippiNormRel_Inf_32f_C1R :
0) :
normType == NORM_L1 ?
(type == CV_8U ? (ippiNormRelFuncNoHint)ippiNormRel_L1_8u_C1R :
type == CV_16U ? (ippiNormRelFuncNoHint)ippiNormRel_L1_16u_C1R :
type == CV_16S ? (ippiNormRelFuncNoHint)ippiNormRel_L1_16s_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8U ? (ippiNormRelFuncNoHint)ippiNormRel_L2_8u_C1R :
type == CV_16U ? (ippiNormRelFuncNoHint)ippiNormRel_L2_16u_C1R :
type == CV_16S ? (ippiNormRelFuncNoHint)ippiNormRel_L2_16s_C1R :
0) : 0;
if( ippiNormRelHint || ippiNormRel )
{
Ipp64f norm;
IppStatus ret = ippiNormRelHint ? CV_INSTRUMENT_FUN_IPP(ippiNormRelHint, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], sz, &norm, ippAlgHintAccurate) :
CV_INSTRUMENT_FUN_IPP(ippiNormRel, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], sz, &norm);
if( ret >= 0 )
{
result = (normType == NORM_L2SQR) ? norm * norm : norm;
return true;
}
}
}
}
return false;
}
normType &= NORM_TYPE_MASK;
size_t total_size = src1.total();
int rows = src1.size[0], cols = rows ? (int)(total_size/rows) : 0;
if( (src1.dims == 2 || (src1.isContinuous() && src2.isContinuous() && mask.isContinuous()))
&& cols > 0 && (size_t)rows*cols == total_size )
{
if( !mask.empty() )
{
IppiSize sz = { cols, rows };
int type = src1.type();
typedef IppStatus (CV_STDCALL* ippiMaskNormDiffFuncC1)(const void *, int, const void *, int, const void *, int, IppiSize, Ipp64f *);
ippiMaskNormDiffFuncC1 ippiNormDiff_C1MR =
normType == NORM_INF ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_Inf_32f_C1MR :
0) :
normType == NORM_L1 ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L1_32f_C1MR :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_8u_C1MR :
type == CV_16UC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_16u_C1MR :
type == CV_32FC1 ? (ippiMaskNormDiffFuncC1)ippiNormDiff_L2_32f_C1MR :
0) : 0;
if( ippiNormDiff_C1MR )
{
Ipp64f norm;
if( CV_INSTRUMENT_FUN_IPP(ippiNormDiff_C1MR, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], mask.ptr(), (int)mask.step[0], sz, &norm) >= 0 )
{
result = (normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm);
return true;
}
}
typedef IppStatus (CV_STDCALL* ippiMaskNormDiffFuncC3)(const void *, int, const void *, int, const void *, int, IppiSize, int, Ipp64f *);
ippiMaskNormDiffFuncC3 ippiNormDiff_C3CMR =
normType == NORM_INF ?
(type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_Inf_32f_C3CMR :
0) :
normType == NORM_L1 ?
(type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L1_32f_C3CMR :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_8u_C3CMR :
type == CV_16UC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_16u_C3CMR :
type == CV_32FC3 ? (ippiMaskNormDiffFuncC3)ippiNormDiff_L2_32f_C3CMR :
0) : 0;
if (cv::ipp::getIppTopFeatures() & (
#if IPP_VERSION_X100 >= 201700
ippCPUID_AVX512F |
#endif
ippCPUID_AVX2)
) // IPP_DISABLE_NORM_16UC3_mask_small (#11399)
{
if (normType == NORM_L1 && type == CV_16UC3 && sz.width < 16)
return false;
}
if( ippiNormDiff_C3CMR )
{
Ipp64f norm1, norm2, norm3;
if( CV_INSTRUMENT_FUN_IPP(ippiNormDiff_C3CMR, src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 1, &norm1) >= 0 &&
CV_INSTRUMENT_FUN_IPP(ippiNormDiff_C3CMR, src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 2, &norm2) >= 0 &&
CV_INSTRUMENT_FUN_IPP(ippiNormDiff_C3CMR, src1.data, (int)src1.step[0], src2.data, (int)src2.step[0], mask.data, (int)mask.step[0], sz, 3, &norm3) >= 0)
{
Ipp64f norm =
normType == NORM_INF ? std::max(std::max(norm1, norm2), norm3) :
normType == NORM_L1 ? norm1 + norm2 + norm3 :
normType == NORM_L2 || normType == NORM_L2SQR ? std::sqrt(norm1 * norm1 + norm2 * norm2 + norm3 * norm3) :
0;
result = (normType == NORM_L2SQR ? (double)(norm * norm) : (double)norm);
return true;
}
}
}
else
{
IppiSize sz = { cols*src1.channels(), rows };
int type = src1.depth();
typedef IppStatus (CV_STDCALL* ippiNormDiffFuncHint)(const void *, int, const void *, int, IppiSize, Ipp64f *, IppHintAlgorithm hint);
typedef IppStatus (CV_STDCALL* ippiNormDiffFuncNoHint)(const void *, int, const void *, int, IppiSize, Ipp64f *);
ippiNormDiffFuncHint ippiNormDiffHint =
normType == NORM_L1 ?
(type == CV_32F ? (ippiNormDiffFuncHint)ippiNormDiff_L1_32f_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_32F ? (ippiNormDiffFuncHint)ippiNormDiff_L2_32f_C1R :
0) : 0;
ippiNormDiffFuncNoHint ippiNormDiff =
normType == NORM_INF ?
(type == CV_8U ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_8u_C1R :
type == CV_16U ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16u_C1R :
type == CV_16S ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_16s_C1R :
type == CV_32F ? (ippiNormDiffFuncNoHint)ippiNormDiff_Inf_32f_C1R :
0) :
normType == NORM_L1 ?
(type == CV_8U ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_8u_C1R :
type == CV_16U ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16u_C1R :
type == CV_16S ? (ippiNormDiffFuncNoHint)ippiNormDiff_L1_16s_C1R :
0) :
normType == NORM_L2 || normType == NORM_L2SQR ?
(type == CV_8U ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_8u_C1R :
type == CV_16U ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16u_C1R :
type == CV_16S ? (ippiNormDiffFuncNoHint)ippiNormDiff_L2_16s_C1R :
0) : 0;
if( ippiNormDiffHint || ippiNormDiff )
{
Ipp64f norm;
IppStatus ret = ippiNormDiffHint ? CV_INSTRUMENT_FUN_IPP(ippiNormDiffHint, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], sz, &norm, ippAlgHintAccurate) :
CV_INSTRUMENT_FUN_IPP(ippiNormDiff, src1.ptr(), (int)src1.step[0], src2.ptr(), (int)src2.step[0], sz, &norm);
if( ret >= 0 )
{
result = (normType == NORM_L2SQR) ? norm * norm : norm;
return true;
}
}
}
}
#else
CV_UNUSED(_src1); CV_UNUSED(_src2); CV_UNUSED(normType); CV_UNUSED(_mask); CV_UNUSED(result);
#endif
return false;
}
}
#endif
double cv::norm( InputArray _src1, InputArray _src2, int normType, InputArray _mask )
{
CV_INSTRUMENT_REGION()
CV_Assert( _src1.sameSize(_src2) && _src1.type() == _src2.type() );
#if defined HAVE_OPENCL || defined HAVE_IPP
double _result = 0;
#endif
#ifdef HAVE_OPENCL
CV_OCL_RUN_(OCL_PERFORMANCE_CHECK(_src1.isUMat()),
ocl_norm(_src1, _src2, normType, _mask, _result),
_result)
#endif
CV_IPP_RUN(IPP_VERSION_X100 >= 700, ipp_norm(_src1, _src2, normType, _mask, _result), _result);
if( normType & CV_RELATIVE )
{
return norm(_src1, _src2, normType & ~CV_RELATIVE, _mask)/(norm(_src2, normType, _mask) + DBL_EPSILON);
}
Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();
int depth = src1.depth(), cn = src1.channels();
normType &= 7;
CV_Assert( normType == NORM_INF || normType == NORM_L1 ||
normType == NORM_L2 || normType == NORM_L2SQR ||
((normType == NORM_HAMMING || normType == NORM_HAMMING2) && src1.type() == CV_8U) );
if( src1.isContinuous() && src2.isContinuous() && mask.empty() )
{
size_t len = src1.total()*src1.channels();
if( len == (size_t)(int)len )
{
if( src1.depth() == CV_32F )
{
const float* data1 = src1.ptr<float>();
const float* data2 = src2.ptr<float>();
if( normType == NORM_L2 )
{
double result = 0;
GET_OPTIMIZED(normDiffL2_32f)(data1, data2, 0, &result, (int)len, 1);
return std::sqrt(result);
}
if( normType == NORM_L2SQR )
{
double result = 0;
GET_OPTIMIZED(normDiffL2_32f)(data1, data2, 0, &result, (int)len, 1);
return result;
}
if( normType == NORM_L1 )
{
double result = 0;
GET_OPTIMIZED(normDiffL1_32f)(data1, data2, 0, &result, (int)len, 1);
return result;
}
if( normType == NORM_INF )
{
float result = 0;
GET_OPTIMIZED(normDiffInf_32f)(data1, data2, 0, &result, (int)len, 1);
return result;
}
}
}
}
CV_Assert( mask.empty() || mask.type() == CV_8U );
if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
{
if( !mask.empty() )
{
Mat temp;
bitwise_xor(src1, src2, temp);
bitwise_and(temp, mask, temp);
return norm(temp, normType);
}
int cellSize = normType == NORM_HAMMING ? 1 : 2;
const Mat* arrays[] = {&src1, &src2, 0};
uchar* ptrs[2] = {};
NAryMatIterator it(arrays, ptrs);
int total = (int)it.size;
int result = 0;
for( size_t i = 0; i < it.nplanes; i++, ++it )
{
result += hal::normHamming(ptrs[0], ptrs[1], total, cellSize);
}
return result;
}
NormDiffFunc func = getNormDiffFunc(normType >> 1, depth == CV_16F ? CV_32F : depth);
CV_Assert( func != 0 );
const Mat* arrays[] = {&src1, &src2, &mask, 0};
uchar* ptrs[3] = {};
union
{
double d;
float f;
int i;
unsigned u;
}
result;
result.d = 0;
NAryMatIterator it(arrays, ptrs);
int j, total = (int)it.size, blockSize = total;
bool blockSum = depth == CV_16F || (normType == NORM_L1 && depth <= CV_16S) ||
((normType == NORM_L2 || normType == NORM_L2SQR) && depth <= CV_8S);
unsigned isum = 0;
unsigned *ibuf = &result.u;
AutoBuffer<float> fltbuf_;
float* fltbuf = 0;
size_t esz = 0;
if( blockSum )
{
esz = src1.elemSize();
if( depth == CV_16F )
{
blockSize = std::min(blockSize, 1024);
fltbuf_.allocate(blockSize*2);
fltbuf = fltbuf_.data();
}
else
{
int intSumBlockSize = (normType == NORM_L1 && depth <= CV_8S ? (1 << 23) : (1 << 15))/cn;
blockSize = std::min(blockSize, intSumBlockSize);
ibuf = &isum;
}
}
for( size_t i = 0; i < it.nplanes; i++, ++it )
{
for( j = 0; j < total; j += blockSize )
{
int bsz = std::min(total - j, blockSize);
const uchar *data0 = ptrs[0], *data1 = ptrs[1];
if( depth == CV_16F )
{
hal::cvt16f32f((const float16_t*)ptrs[0], fltbuf, bsz);
hal::cvt16f32f((const float16_t*)ptrs[1], fltbuf + bsz, bsz);
data0 = (const uchar*)fltbuf;
data1 = (const uchar*)(fltbuf + bsz);
}
func( data0, data1, ptrs[2], (uchar*)ibuf, bsz, cn );
if( blockSum && depth != CV_16F )
{
result.d += isum;
isum = 0;
}
ptrs[0] += bsz*esz;
ptrs[1] += bsz*esz;
if( ptrs[2] )
ptrs[2] += bsz;
}
}
if( normType == NORM_INF )
{
if( depth == CV_64F )
;
else if( depth == CV_32F )
result.d = result.f;
else
result.d = result.u;
}
else if( normType == NORM_L2 )
result.d = std::sqrt(result.d);
return result.d;
}
cv::Hamming::ResultType cv::Hamming::operator()( const unsigned char* a, const unsigned char* b, int size ) const
{
return cv::hal::normHamming(a, b, size);
}
double cv::PSNR(InputArray _src1, InputArray _src2, double R)
{
CV_INSTRUMENT_REGION()
//Input arrays must have depth CV_8U
CV_Assert( _src1.type() == _src2.type() );
double diff = std::sqrt(norm(_src1, _src2, NORM_L2SQR)/(_src1.total()*_src1.channels()));
return 20*log10(R/(diff+DBL_EPSILON));
}
| 37.114022
| 187
| 0.513285
|
zhongshenxuexi
|
dc4ac3acb68def72225a5efc8e65a337dfda8be0
| 11,808
|
cpp
|
C++
|
Mitsuba/src/libcore/track.cpp
|
mkettune/temporal-gpt
|
e0a4ca6c6f29ff6c3733f88894289575d77313dc
|
[
"Unlicense"
] | 14
|
2016-11-30T22:51:45.000Z
|
2021-10-01T02:16:59.000Z
|
Mitsuba/src/libcore/track.cpp
|
mkettune/temporal-gpt
|
e0a4ca6c6f29ff6c3733f88894289575d77313dc
|
[
"Unlicense"
] | null | null | null |
Mitsuba/src/libcore/track.cpp
|
mkettune/temporal-gpt
|
e0a4ca6c6f29ff6c3733f88894289575d77313dc
|
[
"Unlicense"
] | 4
|
2016-12-01T14:55:48.000Z
|
2018-10-28T12:44:31.000Z
|
#include <mitsuba/core/track.h>
#include <mitsuba/core/aabb.h>
#include <Eigen/SVD>
MTS_NAMESPACE_BEGIN
AnimatedTransform::AnimatedTransform(const AnimatedTransform *trafo)
: m_transform(trafo->m_transform) {
m_tracks.reserve(trafo->getTrackCount());
for (size_t i=0; i<trafo->getTrackCount(); ++i) {
AbstractAnimationTrack *track = trafo->getTrack(i)->clone();
m_tracks.push_back(track);
track->incRef();
}
}
AnimatedTransform::AnimatedTransform(Stream *stream) {
size_t nTracks = stream->readSize();
if (nTracks == 0) {
m_transform = Transform(stream);
} else {
for (size_t i=0; i<nTracks; ++i) {
AbstractAnimationTrack::EType type =
(AbstractAnimationTrack::EType) stream->readUInt();
AbstractAnimationTrack *track = NULL;
switch (type) {
case AbstractAnimationTrack::ETranslationX:
case AbstractAnimationTrack::ETranslationY:
case AbstractAnimationTrack::ETranslationZ:
case AbstractAnimationTrack::EScaleX:
case AbstractAnimationTrack::EScaleY:
case AbstractAnimationTrack::EScaleZ:
case AbstractAnimationTrack::ERotationX:
case AbstractAnimationTrack::ERotationY:
case AbstractAnimationTrack::ERotationZ:
track = new FloatTrack(type, stream);
break;
case AbstractAnimationTrack::ETranslationXYZ:
case AbstractAnimationTrack::EScaleXYZ:
track = new VectorTrack(type, stream);
break;
case AbstractAnimationTrack::ERotationQuat:
track = new QuatTrack(type, stream);
break;
default:
Log(EError, "Encountered an unknown animation track type (%i)!", type);
}
track->incRef();
m_tracks.push_back(track);
}
}
}
void AnimatedTransform::addTrack(AbstractAnimationTrack *track) {
track->incRef();
m_tracks.push_back(track);
}
AABB1 AnimatedTransform::getTimeBounds() const {
if (m_tracks.size() == 0)
return AABB1(0.0f, 0.0f);
Float min = std::numeric_limits<Float>::infinity();
Float max = -std::numeric_limits<Float>::infinity();
for (size_t i=0; i<m_tracks.size(); ++i) {
const AbstractAnimationTrack *track = m_tracks[i];
size_t size = track->getSize();
SAssert(size > 0);
min = std::min(min, track->getTime(0));
max = std::max(max, track->getTime(size-1));
}
return AABB1(min, max);
}
AABB AnimatedTransform::getTranslationBounds() const {
if (m_tracks.size() == 0) {
Point p = m_transform(Point(0.0f));
return AABB(p, p);
}
AABB aabb;
for (size_t i=0; i<m_tracks.size(); ++i) {
const AbstractAnimationTrack *absTrack = m_tracks[i];
switch (absTrack->getType()) {
case AbstractAnimationTrack::ETranslationX:
case AbstractAnimationTrack::ETranslationY:
case AbstractAnimationTrack::ETranslationZ: {
int idx = absTrack->getType() - AbstractAnimationTrack::ETranslationX;
const FloatTrack *track =
static_cast<const FloatTrack *>(absTrack);
for (size_t j=0; j<track->getSize(); ++j) {
Float value = track->getValue(j);
aabb.max[idx] = std::max(aabb.max[idx], value);
aabb.min[idx] = std::min(aabb.min[idx], value);
}
}
break;
case AbstractAnimationTrack::ETranslationXYZ: {
const VectorTrack *track =
static_cast<const VectorTrack *>(absTrack);
for (size_t j=0; j<track->getSize(); ++j)
aabb.expandBy(Point(track->getValue(j)));
}
break;
default:
break;
}
}
for (int i=0; i<3; ++i) {
if (aabb.min[i] > aabb.max[i])
aabb.min[i] = aabb.max[i] = 0.0f;
}
return aabb;
}
AABB AnimatedTransform::getSpatialBounds(const AABB &aabb) const {
AABB result;
if (m_tracks.size() == 0) {
for (int j=0; j<8; ++j)
result.expandBy(m_transform(aabb.getCorner(j)));
} else {
/* Compute approximate bounds */
int nSteps = 100;
AABB1 timeBounds = getTimeBounds();
Float step = timeBounds.getExtents().x / (nSteps-1);
for (int i=0; i<nSteps; ++i) {
const Transform &trafo = eval(timeBounds.min.x + step * i);
for (int j=0; j<8; ++j)
result.expandBy(trafo(aabb.getCorner(j)));
}
}
return result;
}
AnimatedTransform::~AnimatedTransform() {
for (size_t i=0; i<m_tracks.size(); ++i)
m_tracks[i]->decRef();
}
void AnimatedTransform::sortAndSimplify() {
bool isStatic = true;
for (size_t i=0; i<m_tracks.size(); ++i) {
AbstractAnimationTrack *track = m_tracks[i];
bool isNeeded = false;
switch (track->getType()) {
case AbstractAnimationTrack::ETranslationX:
case AbstractAnimationTrack::ETranslationY:
case AbstractAnimationTrack::ETranslationZ:
case AbstractAnimationTrack::ERotationX:
case AbstractAnimationTrack::ERotationY:
case AbstractAnimationTrack::ERotationZ:
case AbstractAnimationTrack::EScaleX:
case AbstractAnimationTrack::EScaleY:
case AbstractAnimationTrack::EScaleZ:
isNeeded = static_cast<FloatTrack *>(track)->sortAndSimplify();
break;
case AbstractAnimationTrack::ETranslationXYZ:
case AbstractAnimationTrack::EScaleXYZ:
isNeeded = static_cast<VectorTrack *>(track)->sortAndSimplify();
break;
case AbstractAnimationTrack::ERotationQuat:
isNeeded = static_cast<QuatTrack *>(track)->sortAndSimplify();
break;
default:
Log(EError, "Encountered an unsupported "
"animation track type: %i!", track->getType());
}
if (isNeeded) {
isStatic &= track->getSize() == 1;
} else {
m_tracks.erase(m_tracks.begin() + i);
track->decRef();
--i;
}
}
if (isStatic) {
Transform temp;
temp = eval(0);
m_transform = temp;
for (size_t i=0; i<m_tracks.size(); ++i)
m_tracks[i]->decRef();
m_tracks.clear();
}
}
const AbstractAnimationTrack *AnimatedTransform::findTrack(AbstractAnimationTrack::EType type) const {
for (size_t i=0; i<m_tracks.size(); ++i) {
AbstractAnimationTrack *track = m_tracks[i];
if (track->getType() == type)
return track;
}
return NULL;
}
AbstractAnimationTrack *AnimatedTransform::findTrack(AbstractAnimationTrack::EType type) {
for (size_t i=0; i<m_tracks.size(); ++i) {
AbstractAnimationTrack *track = m_tracks[i];
if (track->getType() == type)
return track;
}
return NULL;
}
void AnimatedTransform::prependScale(const Vector &scale) {
FloatTrack *trackX = (FloatTrack *) findTrack(AbstractAnimationTrack::EScaleX);
FloatTrack *trackY = (FloatTrack *) findTrack(AbstractAnimationTrack::EScaleY);
FloatTrack *trackZ = (FloatTrack *) findTrack(AbstractAnimationTrack::EScaleZ);
VectorTrack *trackXYZ = (VectorTrack *) findTrack(AbstractAnimationTrack::EScaleXYZ);
if (m_tracks.empty()) {
m_transform = m_transform * Transform::scale(scale);
} else if (trackXYZ) {
trackXYZ->prependTransformation(scale);
} else if (trackX && trackY && trackZ) {
if (trackX) {
trackX->prependTransformation(scale.x);
} else {
trackX = new FloatTrack(AbstractAnimationTrack::EScaleX);
trackX->append(0.0f, scale.x); addTrack(trackX);
}
if (trackY) {
trackY->prependTransformation(scale.y);
} else {
trackY = new FloatTrack(AbstractAnimationTrack::EScaleY);
trackY->append(0.0f, scale.y); addTrack(trackY);
}
if (trackZ) {
trackZ->prependTransformation(scale.z);
} else {
trackZ = new FloatTrack(AbstractAnimationTrack::EScaleZ);
trackZ->append(0.0f, scale.z); addTrack(trackZ);
}
} else {
trackXYZ = new VectorTrack(AbstractAnimationTrack::EScaleXYZ);
trackXYZ->append(0.0f, scale);
addTrack(trackXYZ);
}
}
void AnimatedTransform::collectKeyframes(std::set<Float> &result) const {
for (size_t i=0; i<m_tracks.size(); ++i) {
const AbstractAnimationTrack *track = m_tracks[i];
for (size_t j=0; j<track->getSize(); ++j)
result.insert(track->getTime(j));
}
if (result.size() == 0)
result.insert((Float) 0);
}
void AnimatedTransform::serialize(Stream *stream) const {
stream->writeSize(m_tracks.size());
if (m_tracks.size() == 0) {
m_transform.serialize(stream);
} else {
for (size_t i=0; i<m_tracks.size(); ++i)
m_tracks[i]->serialize(stream);
}
}
void AnimatedTransform::TransformFunctor::operator()(const Float &t, Transform &trafo) const {
Vector translation(0.0f);
Vector scale(1.0f);
Quaternion rotation;
for (size_t i=0; i<m_tracks.size(); ++i) {
AbstractAnimationTrack *track = m_tracks[i];
switch (track->getType()) {
case AbstractAnimationTrack::ETranslationX:
translation.x = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::ETranslationY:
translation.y = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::ETranslationZ:
translation.z = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::ETranslationXYZ:
translation = static_cast<VectorTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::EScaleX:
scale.x = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::EScaleY:
scale.y = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::EScaleZ:
scale.z = static_cast<FloatTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::EScaleXYZ:
scale = static_cast<VectorTrack *>(track)->eval(t);
break;
case AbstractAnimationTrack::ERotationQuat:
rotation = static_cast<QuatTrack *>(track)->eval(t);
break;
default:
Log(EError, "Encountered an unsupported "
"animation track type: %i!", track->getType());
}
}
trafo = Transform::translate(translation);
if (!rotation.isIdentity())
trafo = trafo * rotation.toTransform();
if (scale != Vector(0.0f))
trafo = trafo * Transform::scale(scale);
}
void AnimatedTransform::appendTransform(Float time, const Transform &trafo) {
/* Compute the polar decomposition and insert into the animated transform;
uh oh.. we have to get rid of the two separate matrix libraries at some point :) */
typedef Eigen::Matrix<Float, 3, 3> EMatrix;
if (m_tracks.size() == 0) {
ref<VectorTrack> translation = new VectorTrack(VectorTrack::ETranslationXYZ);
ref<QuatTrack> rotation = new QuatTrack(VectorTrack::ERotationQuat);
ref<VectorTrack> scaling = new VectorTrack(VectorTrack::EScaleXYZ);
translation->reserve(2);
rotation->reserve(2);
scaling->reserve(2);
addTrack(translation);
addTrack(rotation);
addTrack(scaling);
} else if (m_tracks.size() != 3 ||
m_tracks[0]->getType() != VectorTrack::ETranslationXYZ ||
m_tracks[1]->getType() != VectorTrack::ERotationQuat ||
m_tracks[2]->getType() != VectorTrack::EScaleXYZ) {
Log(EError, "AnimatedTransform::appendTransform(): unsupported internal configuration!");
}
const Matrix4x4 m = trafo.getMatrix();
EMatrix A;
A << m(0, 0), m(0, 1), m(0, 2),
m(1, 0), m(1, 1), m(1, 2),
m(2, 0), m(2, 1), m(2, 2);
Eigen::JacobiSVD<EMatrix> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
EMatrix U = svd.matrixU(), V = svd.matrixV(), S = svd.singularValues().asDiagonal();
if (svd.singularValues().prod() < 0) {
S = -S; U = -U;
}
EMatrix Q = U*V.transpose();
EMatrix P = V*S*V.transpose();
VectorTrack *translation = (VectorTrack *) m_tracks[0];
QuatTrack *rotation = (QuatTrack *) m_tracks[1];
VectorTrack *scaling = (VectorTrack *) m_tracks[2];
rotation->append(time, Quaternion::fromMatrix(
Matrix4x4(
Q(0, 0), Q(0, 1), Q(0, 2), 0.0f,
Q(1, 0), Q(1, 1), Q(1, 2), 0.0f,
Q(2, 0), Q(2, 1), Q(2, 2), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
)
));
scaling->append(time, Vector(P(0, 0), P(1, 1), P(2, 2)));
translation->append(time, Vector(m(0, 3), m(1, 3), m(2, 3)));
}
std::string AnimatedTransform::toString() const {
if (m_tracks.size() == 0) {
return m_transform.toString();
} else {
std::ostringstream oss;
oss << "AnimatedTransform[tracks=" << m_tracks.size() << "]";
return oss.str();
}
}
MTS_IMPLEMENT_CLASS(AbstractAnimationTrack, true, Object)
MTS_IMPLEMENT_CLASS(AnimatedTransform, false, Object)
MTS_NAMESPACE_END
| 29.969543
| 102
| 0.685129
|
mkettune
|
dc4de7932dc0cbb48486452a7296468f4f7a63c8
| 3,571
|
hpp
|
C++
|
source/FAST/Visualization/Renderer.hpp
|
gjertmagne/FAST
|
acd6f6f365b8ed9e0cedf5a5de99870669b449b0
|
[
"BSD-2-Clause"
] | null | null | null |
source/FAST/Visualization/Renderer.hpp
|
gjertmagne/FAST
|
acd6f6f365b8ed9e0cedf5a5de99870669b449b0
|
[
"BSD-2-Clause"
] | null | null | null |
source/FAST/Visualization/Renderer.hpp
|
gjertmagne/FAST
|
acd6f6f365b8ed9e0cedf5a5de99870669b449b0
|
[
"BSD-2-Clause"
] | null | null | null |
#ifndef RENDERER_HPP_
#define RENDERER_HPP_
#include "FAST/ProcessObject.hpp"
#include "FAST/Data/BoundingBox.hpp"
#include "FAST/Data/SpatialDataObject.hpp"
#include <mutex>
#include <QOpenGLFunctions_3_3_Core>
namespace fast {
class View;
class BoundingBox;
class FAST_EXPORT Renderer : public ProcessObject, protected QOpenGLFunctions_3_3_Core {
public:
typedef SharedPointer<Renderer> pointer;
virtual void draw(Matrix4f perspectiveMatrix, Matrix4f viewingMatrix, bool mode2D) = 0;
virtual void postDraw();
/**
* Adds a new input connection
* @param port
* @return the input nr of the new connection
*/
virtual uint addInputConnection(DataPort::pointer port);
/**
* Adds a new input connection to a specific data object
* @param data
* @return the input nr of the new connection
*/
virtual uint addInputData(DataObject::pointer data);
virtual BoundingBox getBoundingBox(bool transform = true);
virtual void draw2D(
cl::Buffer PBO,
uint width,
uint height,
Affine3f pixelToViewportTransform,
float PBOspacing,
Vector2f translation
) {};
virtual void stopPipeline();
virtual void reset();
protected:
Renderer();
void execute() override;
/**
* Creates an OpenGL shader program. Should be used in the renderer constructor.
* @param shaderFilenames
* @param programName
*/
void createShaderProgram(std::vector<std::string> shaderFilenames, std::string programName = "default");
void attachShader(std::string filename, std::string programName = "default");
void activateShader(std::string programName = "default");
void deactivateShader();
uint getShaderProgram(std::string programName = "default");
void setShaderUniform(std::string name, Matrix4f matrix, std::string shaderProgramName = "default");
void setShaderUniform(std::string name, Affine3f matrix, std::string shaderProgramName = "default");
void setShaderUniform(std::string name, Vector3f vector, std::string shaderProgramName = "default");
void setShaderUniform(std::string name, float value, std::string shaderProgramName = "default");
void setShaderUniform(std::string name, bool value, std::string shaderProgramName = "default");
void setShaderUniform(std::string name, int value, std::string shaderProgramName = "default");
int getShaderUniformLocation(std::string name, std::string shaderProgramName = "default");
// Locking mechanisms to ensure thread safe synchronized rendering
bool mHasRendered = true;
bool mStop = false;
std::condition_variable_any mRenderedCV;
std::mutex mMutex;
/**
* This holds the current data to render for each input connection
*/
std::unordered_map<uint, SpatialDataObject::pointer> mDataToRender;
/**
* This will lock the renderer mutex. Used by the compute thread.
*/
void lock();
/**
* This will unlock the renderer mutex. Used by the compute thread.
*/
void unlock();
friend class View;
private:
/**
* OpenGL shader IDs. Program name -> OpenGL ID
*/
std::unordered_map<std::string, uint> mShaderProgramIDs;
};
}
#endif /* RENDERER_HPP_ */
| 35.71
| 112
| 0.639877
|
gjertmagne
|
dc5208a0bb484af3fafa27887ae45deb9752a81c
| 2,991
|
cc
|
C++
|
src/alpaka/plugin-PixelTriplets/alpaka/PixelTrackSoAFromAlpaka.cc
|
waredjeb/pixeltrack-standalone
|
d26e4c31db144b0068824ee77b681bd0dd8447c1
|
[
"Apache-2.0"
] | null | null | null |
src/alpaka/plugin-PixelTriplets/alpaka/PixelTrackSoAFromAlpaka.cc
|
waredjeb/pixeltrack-standalone
|
d26e4c31db144b0068824ee77b681bd0dd8447c1
|
[
"Apache-2.0"
] | 1
|
2020-05-04T09:09:55.000Z
|
2020-05-04T09:09:55.000Z
|
src/alpaka/plugin-PixelTriplets/alpaka/PixelTrackSoAFromAlpaka.cc
|
felicepantaleo/pixeltrack-standalone
|
6bc5445a9ecd2b71831a6c0152bf7a2c3650ba10
|
[
"Apache-2.0"
] | null | null | null |
#include "AlpakaCore/alpakaCommon.h"
#include "AlpakaDataFormats/PixelTrackAlpaka.h"
#include "Framework/EventSetup.h"
#include "Framework/Event.h"
#include "Framework/PluginFactory.h"
#include "Framework/EDProducer.h"
#include "AlpakaCore/ScopedContext.h"
namespace ALPAKA_ACCELERATOR_NAMESPACE {
#ifdef TODO
class PixelTrackSoAFromAlpaka : public edm::EDProducerExternalWork {
#else
class PixelTrackSoAFromAlpaka : public edm::EDProducer {
#endif
public:
explicit PixelTrackSoAFromAlpaka(edm::ProductRegistry& reg);
~PixelTrackSoAFromAlpaka() override = default;
private:
#ifdef TODO
void acquire(edm::Event const& iEvent,
edm::EventSetup const& iSetup,
edm::WaitingTaskWithArenaHolder waitingTaskHolder) override;
#endif
void produce(edm::Event& iEvent, edm::EventSetup const& iSetup) override;
edm::EDGetTokenT<PixelTrackAlpaka> tokenAlpaka_;
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
edm::EDPutTokenT<PixelTrackHost> tokenSOA_;
#endif
#ifdef TODO
cms::cuda::host::unique_ptr<pixelTrack::TrackSoA> m_soa;
#endif
};
PixelTrackSoAFromAlpaka::PixelTrackSoAFromAlpaka(edm::ProductRegistry& reg)
: tokenAlpaka_(reg.consumes<PixelTrackAlpaka>())
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
,
tokenSOA_(reg.produces<PixelTrackHost>())
#endif
{
}
#ifdef TODO
void PixelTrackSoAFromAlpaka::acquire(edm::Event const& iEvent,
edm::EventSetup const& iSetup,
edm::WaitingTaskWithArenaHolder waitingTaskHolder) {
cms::cuda::Product<PixelTrackHeterogeneous> const& inputDataWrapped = iEvent.get(tokenAlpaka_);
cms::cuda::ScopedContextAcquire ctx{inputDataWrapped, std::move(waitingTaskHolder)};
auto const& inputData = ctx.get(inputDataWrapped);
m_soa = inputData.toHostAsync(ctx.stream());
}
#endif
void PixelTrackSoAFromAlpaka::produce(edm::Event& iEvent, edm::EventSetup const& iSetup) {
/*
auto const & tsoa = *m_soa;
auto maxTracks = tsoa.stride();
std::cout << "size of SoA" << sizeof(tsoa) << " stride " << maxTracks << std::endl;
int32_t nt = 0;
for (int32_t it = 0; it < maxTracks; ++it) {
auto nHits = tsoa.nHits(it);
assert(nHits==int(tsoa.hitIndices.size(it)));
if (nHits == 0) break; // this is a guard: maybe we need to move to nTracks...
nt++;
}
std::cout << "found " << nt << " tracks in cpu SoA at " << &tsoa << std::endl;
*/
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
auto const& inputData = iEvent.get(tokenAlpaka_);
auto outputData = ::cms::alpakatools::allocHostBuf<pixelTrack::TrackSoA>(1u);
::cms::alpakatools::ScopedContextProduce<Queue> ctx{iEvent.streamID()};
alpaka::memcpy(ctx.stream(), outputData, inputData, 1u);
// DO NOT make a copy (actually TWO....)
ctx.emplace(iEvent, tokenSOA_, std::move(outputData));
#endif
}
} // namespace ALPAKA_ACCELERATOR_NAMESPACE
DEFINE_FWK_ALPAKA_MODULE(PixelTrackSoAFromAlpaka);
| 33.233333
| 99
| 0.699432
|
waredjeb
|
dc563487001b66759f829838886d6a365ef5ef4f
| 29,506
|
cpp
|
C++
|
tools/editor/plugins/polygon_2d_editor_plugin.cpp
|
literaldumb/godot
|
a2903fc51d1d20eba4dc451bdacbe477d6670163
|
[
"CC-BY-3.0",
"MIT"
] | null | null | null |
tools/editor/plugins/polygon_2d_editor_plugin.cpp
|
literaldumb/godot
|
a2903fc51d1d20eba4dc451bdacbe477d6670163
|
[
"CC-BY-3.0",
"MIT"
] | null | null | null |
tools/editor/plugins/polygon_2d_editor_plugin.cpp
|
literaldumb/godot
|
a2903fc51d1d20eba4dc451bdacbe477d6670163
|
[
"CC-BY-3.0",
"MIT"
] | 1
|
2019-01-13T00:44:17.000Z
|
2019-01-13T00:44:17.000Z
|
/*************************************************************************/
/* polygon_2d_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "polygon_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
#include "os/file_access.h"
#include "tools/editor/editor_settings.h"
#include "os/keyboard.h"
#include "os/input.h"
void Polygon2DEditor::_notification(int p_what) {
switch(p_what) {
case NOTIFICATION_READY: {
button_create->set_icon( get_icon("Edit","EditorIcons"));
button_edit->set_icon( get_icon("MovePoint","EditorIcons"));
button_edit->set_pressed(true);
button_uv->set_icon( get_icon("Uv","EditorIcons"));
uv_button[UV_MODE_EDIT_POINT]->set_icon(get_icon("ToolSelect","EditorIcons"));
uv_button[UV_MODE_MOVE]->set_icon(get_icon("ToolMove","EditorIcons"));
uv_button[UV_MODE_ROTATE]->set_icon(get_icon("ToolRotate","EditorIcons"));
uv_button[UV_MODE_SCALE]->set_icon(get_icon("ToolScale","EditorIcons"));
b_snap_grid->set_icon( get_icon("Grid", "EditorIcons"));
b_snap_enable->set_icon( get_icon("Snap", "EditorIcons"));
uv_icon_zoom->set_texture( get_icon("Zoom", "EditorIcons"));
get_tree()->connect("node_removed", this, "_node_removed");
} break;
case NOTIFICATION_FIXED_PROCESS: {
} break;
}
}
void Polygon2DEditor::_node_removed(Node *p_node) {
if(p_node==node) {
edit(NULL);
hide();
canvas_item_editor->get_viewport_control()->update();
}
}
void Polygon2DEditor::_menu_option(int p_option) {
switch(p_option) {
case MODE_CREATE: {
mode=MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
mode=MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
case MODE_EDIT_UV: {
if (node->get_texture().is_null()) {
error->set_text("No texture in this polygon.\nSet a texture to be able to edit UV.");
error->popup_centered_minsize();
return;
}
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size()!=points.size()) {
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node,"set_uv",points);
undo_redo->add_undo_method(node,"set_uv",uvs);
undo_redo->add_do_method(uv_edit_draw,"update");
undo_redo->add_undo_method(uv_edit_draw,"update");
undo_redo->commit_action();
}
uv_edit->popup_centered_ratio(0.85);
} break;
case UVEDIT_POLYGON_TO_UV: {
PoolVector<Vector2> points = node->get_polygon();
if (points.size()==0)
break;
PoolVector<Vector2> uvs = node->get_uv();
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node,"set_uv",points);
undo_redo->add_undo_method(node,"set_uv",uvs);
undo_redo->add_do_method(uv_edit_draw,"update");
undo_redo->add_undo_method(uv_edit_draw,"update");
undo_redo->commit_action();
} break;
case UVEDIT_UV_TO_POLYGON: {
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size()==0)
break;
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node,"set_polygon",uvs);
undo_redo->add_undo_method(node,"set_polygon",points);
undo_redo->add_do_method(uv_edit_draw,"update");
undo_redo->add_undo_method(uv_edit_draw,"update");
undo_redo->commit_action();
} break;
case UVEDIT_UV_CLEAR: {
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size()==0)
break;
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node,"set_uv",PoolVector<Vector2>());
undo_redo->add_undo_method(node,"set_uv",uvs);
undo_redo->add_do_method(uv_edit_draw,"update");
undo_redo->add_undo_method(uv_edit_draw,"update");
undo_redo->commit_action();
} break;
}
}
void Polygon2DEditor::_set_use_snap(bool p_use)
{
use_snap=p_use;
}
void Polygon2DEditor::_set_show_grid(bool p_show)
{
snap_show_grid=p_show;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_off_x(float p_val)
{
snap_offset.x=p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_off_y(float p_val)
{
snap_offset.y=p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_step_x(float p_val)
{
snap_step.x=p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_step_y(float p_val)
{
snap_step.y=p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_wip_close() {
undo_redo->create_action(TTR("Create Poly"));
undo_redo->add_undo_method(node,"set_polygon",node->get_polygon());
undo_redo->add_do_method(node,"set_polygon",wip);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->commit_action();
wip.clear();
wip_active=false;
mode=MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
edited_point=-1;
}
bool Polygon2DEditor::forward_gui_input(const InputEvent& p_event) {
if (node==NULL)
return false;
switch(p_event.type) {
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &mb=p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
Vector2 gpoint = Point2(mb.x,mb.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
cpoint=canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
Vector<Vector2> poly = Variant(node->get_polygon());
//first check if a point is to be added (segment split)
real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
switch(mode) {
case MODE_CREATE: {
if (mb.button_index==BUTTON_LEFT && mb.pressed) {
if (!wip_active) {
wip.clear();
wip.push_back( cpoint-node->get_offset() );
wip_active=true;
edited_point_pos=cpoint;
canvas_item_editor->get_viewport_control()->update();
edited_point=1;
return true;
} else {
if (wip.size()>1 && xform.xform(wip[0]+node->get_offset()).distance_to(gpoint)<grab_treshold) {
//wip closed
_wip_close();
return true;
} else {
wip.push_back( cpoint-node->get_offset() );
edited_point=wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
} else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
_wip_close();
}
} break;
case MODE_EDIT: {
if (mb.button_index==BUTTON_LEFT) {
if (mb.pressed) {
if (mb.mod.control) {
if (poly.size() < 3) {
undo_redo->create_action(TTR("Edit Poly"));
undo_redo->add_undo_method(node,"set_polygon",poly);
poly.push_back(cpoint);
undo_redo->add_do_method(node,"set_polygon",poly);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->commit_action();
return true;
}
//search edges
int closest_idx=-1;
Vector2 closest_pos;
real_t closest_dist=1e10;
for(int i=0;i<poly.size();i++) {
Vector2 points[2] ={ xform.xform(poly[i]+node->get_offset()),
xform.xform(poly[(i+1)%poly.size()]+node->get_offset()) };
Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
if (d<closest_dist && d<grab_treshold) {
closest_dist=d;
closest_pos=cp;
closest_idx=i;
}
}
if (closest_idx>=0) {
pre_move_edit=poly;
poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos)-node->get_offset());
edited_point=closest_idx+1;
edited_point_pos=xform.affine_inverse().xform(closest_pos);
node->set_polygon(Variant(poly));
canvas_item_editor->get_viewport_control()->update();
return true;
}
} else {
//look for points to move
int closest_idx=-1;
Vector2 closest_pos;
real_t closest_dist=1e10;
for(int i=0;i<poly.size();i++) {
Vector2 cp =xform.xform(poly[i]+node->get_offset());
real_t d = cp.distance_to(gpoint);
if (d<closest_dist && d<grab_treshold) {
closest_dist=d;
closest_pos=cp;
closest_idx=i;
}
}
if (closest_idx>=0) {
pre_move_edit=poly;
edited_point=closest_idx;
edited_point_pos=xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
if (edited_point!=-1) {
//apply
ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
poly[edited_point]=edited_point_pos-node->get_offset();
undo_redo->create_action(TTR("Edit Poly"));
undo_redo->add_do_method(node,"set_polygon",poly);
undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->commit_action();
edited_point=-1;
return true;
}
}
} if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {
int closest_idx=-1;
Vector2 closest_pos;
real_t closest_dist=1e10;
for(int i=0;i<poly.size();i++) {
Vector2 cp =xform.xform(poly[i]+node->get_offset());
real_t d = cp.distance_to(gpoint);
if (d<closest_dist && d<grab_treshold) {
closest_dist=d;
closest_pos=cp;
closest_idx=i;
}
}
if (closest_idx>=0) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
undo_redo->add_undo_method(node,"set_polygon",poly);
poly.remove(closest_idx);
undo_redo->add_do_method(node,"set_polygon",poly);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
undo_redo->commit_action();
return true;
}
}
} break;
}
} break;
case InputEvent::MOUSE_MOTION: {
const InputEventMouseMotion &mm=p_event.mouse_motion;
if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {
Vector2 gpoint = Point2(mm.x,mm.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
cpoint=canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
canvas_item_editor->get_viewport_control()->update();
}
} break;
}
return false;
}
void Polygon2DEditor::_canvas_draw() {
if (!node)
return;
Control *vpc = canvas_item_editor->get_viewport_control();
Vector<Vector2> poly;
if (wip_active)
poly=wip;
else
poly=Variant(node->get_polygon());
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
for(int i=0;i<poly.size();i++) {
Vector2 p,p2;
p = i==edited_point ? edited_point_pos : (poly[i]+node->get_offset());
if ((wip_active && i==poly.size()-1) || (((i+1)%poly.size())==edited_point))
p2=edited_point_pos;
else
p2 = poly[(i+1)%poly.size()]+node->get_offset();
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
Color col=Color(1,0.3,0.1,0.8);
vpc->draw_line(point,next_point,col,2);
vpc->draw_texture(handle,point-handle->get_size()*0.5);
}
}
void Polygon2DEditor::_uv_mode(int p_mode) {
uv_mode=UVMode(p_mode);
for(int i=0;i<UV_MODE_MAX;i++) {
uv_button[i]->set_pressed(p_mode==i);
}
}
void Polygon2DEditor::_uv_input(const InputEvent& p_input) {
Transform2D mtx;
mtx.elements[2]=-uv_draw_ofs;
mtx.scale_basis(Vector2(uv_draw_zoom,uv_draw_zoom));
if (p_input.type==InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &mb=p_input.mouse_button;
if (mb.button_index==BUTTON_LEFT) {
if (mb.pressed) {
uv_drag_from=Vector2(mb.x,mb.y);
uv_drag=true;
uv_prev=node->get_uv();
uv_move_current=uv_mode;
if (uv_move_current==UV_MODE_EDIT_POINT) {
if (mb.mod.shift && mb.mod.command)
uv_move_current=UV_MODE_SCALE;
else if (mb.mod.shift)
uv_move_current=UV_MODE_MOVE;
else if (mb.mod.command)
uv_move_current=UV_MODE_ROTATE;
}
if (uv_move_current==UV_MODE_EDIT_POINT) {
uv_drag_index=-1;
for(int i=0;i<uv_prev.size();i++) {
Vector2 tuv=mtx.xform(uv_prev[i]);
if (tuv.distance_to(Vector2(mb.x,mb.y))<8) {
uv_drag_from=tuv;
uv_drag_index=i;
}
}
if (uv_drag_index==-1) {
uv_drag=false;
}
}
} else if (uv_drag) {
undo_redo->create_action(TTR("Transform UV Map"));
undo_redo->add_do_method(node,"set_uv",node->get_uv());
undo_redo->add_undo_method(node,"set_uv",uv_prev);
undo_redo->add_do_method(uv_edit_draw,"update");
undo_redo->add_undo_method(uv_edit_draw,"update");
undo_redo->commit_action();
uv_drag=false;
}
} else if (mb.button_index==BUTTON_RIGHT && mb.pressed) {
if (uv_drag) {
uv_drag=false;
node->set_uv(uv_prev);
uv_edit_draw->update();
}
} else if (mb.button_index==BUTTON_WHEEL_UP && mb.pressed) {
uv_zoom->set_value( uv_zoom->get_value()/0.9 );
} else if (mb.button_index==BUTTON_WHEEL_DOWN && mb.pressed) {
uv_zoom->set_value( uv_zoom->get_value()*0.9);
}
} else if (p_input.type==InputEvent::MOUSE_MOTION) {
const InputEventMouseMotion &mm=p_input.mouse_motion;
if (mm.button_mask&BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
Vector2 drag(mm.relative_x,mm.relative_y);
uv_hscroll->set_value( uv_hscroll->get_value()-drag.x );
uv_vscroll->set_value( uv_vscroll->get_value()-drag.y );
} else if (uv_drag) {
Vector2 uv_drag_to=snap_point(Vector2(mm.x,mm.y));
Vector2 drag = mtx.affine_inverse().xform(uv_drag_to) - mtx.affine_inverse().xform(uv_drag_from);
switch(uv_move_current) {
case UV_MODE_EDIT_POINT: {
PoolVector<Vector2> uv_new=uv_prev;
uv_new.set( uv_drag_index, uv_new[uv_drag_index]+drag );
node->set_uv(uv_new);
} break;
case UV_MODE_MOVE: {
PoolVector<Vector2> uv_new=uv_prev;
for(int i=0;i<uv_new.size();i++)
uv_new.set( i, uv_new[i]+drag );
node->set_uv(uv_new);
} break;
case UV_MODE_ROTATE: {
Vector2 center;
PoolVector<Vector2> uv_new=uv_prev;
for(int i=0;i<uv_new.size();i++)
center+=uv_prev[i];
center/=uv_new.size();
float angle = (uv_drag_from - mtx.xform(center)).normalized().angle_to( (uv_drag_to - mtx.xform(center)).normalized() );
for(int i=0;i<uv_new.size();i++) {
Vector2 rel = uv_prev[i] - center;
rel=rel.rotated(angle);
uv_new.set(i,center+rel);
}
node->set_uv(uv_new);
} break;
case UV_MODE_SCALE: {
Vector2 center;
PoolVector<Vector2> uv_new=uv_prev;
for(int i=0;i<uv_new.size();i++)
center+=uv_prev[i];
center/=uv_new.size();
float from_dist = uv_drag_from.distance_to(mtx.xform(center));
float to_dist = uv_drag_to.distance_to(mtx.xform(center));
if (from_dist<2)
break;
float scale = to_dist/from_dist;
for(int i=0;i<uv_new.size();i++) {
Vector2 rel = uv_prev[i] - center;
rel=rel*scale;
uv_new.set(i,center+rel);
}
node->set_uv(uv_new);
} break;
}
uv_edit_draw->update();
}
}
}
void Polygon2DEditor::_uv_scroll_changed(float) {
if (updating_uv_scroll)
return;
uv_draw_ofs.x=uv_hscroll->get_value();
uv_draw_ofs.y=uv_vscroll->get_value();
uv_draw_zoom=uv_zoom->get_value();
uv_edit_draw->update();
}
void Polygon2DEditor::_uv_draw() {
Ref<Texture> base_tex = node->get_texture();
if (base_tex.is_null())
return;
Transform2D mtx;
mtx.elements[2]=-uv_draw_ofs;
mtx.scale_basis(Vector2(uv_draw_zoom,uv_draw_zoom));
VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(),mtx);
uv_edit_draw->draw_texture(base_tex,Point2());
VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(),Transform2D());
if (snap_show_grid) {
Size2 s = uv_edit_draw->get_size();
int last_cell;
if (snap_step.x!=0) {
for(int i=0;i<s.width;i++) {
int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i,0)).x-snap_offset.x)/snap_step.x));
if (i==0)
last_cell=cell;
if (last_cell!=cell)
uv_edit_draw->draw_line(Point2(i,0),Point2(i,s.height),Color(0.3,0.7,1,0.3));
last_cell=cell;
}
}
if (snap_step.y!=0) {
for(int i=0;i<s.height;i++) {
int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0,i)).y-snap_offset.y)/snap_step.y));
if (i==0)
last_cell=cell;
if (last_cell!=cell)
uv_edit_draw->draw_line(Point2(0,i),Point2(s.width,i),Color(0.3,0.7,1,0.3));
last_cell=cell;
}
}
}
PoolVector<Vector2> uvs = node->get_uv();
Ref<Texture> handle = get_icon("EditorHandle","EditorIcons");
Rect2 rect(Point2(),mtx.basis_xform(base_tex->get_size()));
rect.expand_to(mtx.basis_xform(uv_edit_draw->get_size()));
for(int i=0;i<uvs.size();i++) {
int next = (i+1)%uvs.size();
uv_edit_draw->draw_line(mtx.xform(uvs[i]),mtx.xform(uvs[next]),Color(0.9,0.5,0.5),2);
uv_edit_draw->draw_texture(handle,mtx.xform(uvs[i])-handle->get_size()*0.5);
rect.expand_to(mtx.basis_xform(uvs[i]));
}
rect=rect.grow(200);
updating_uv_scroll=true;
uv_hscroll->set_min(rect.pos.x);
uv_hscroll->set_max(rect.pos.x+rect.size.x);
uv_hscroll->set_page(uv_edit_draw->get_size().x);
uv_hscroll->set_value(uv_draw_ofs.x);
uv_hscroll->set_step(0.001);
uv_vscroll->set_min(rect.pos.y);
uv_vscroll->set_max(rect.pos.y+rect.size.y);
uv_vscroll->set_page(uv_edit_draw->get_size().y);
uv_vscroll->set_value(uv_draw_ofs.y);
uv_vscroll->set_step(0.001);
updating_uv_scroll=false;
}
void Polygon2DEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
canvas_item_editor=CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
node=p_collision_polygon->cast_to<Polygon2D>();
if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
wip.clear();
wip_active=false;
edited_point=-1;
} else {
node=NULL;
if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
}
}
void Polygon2DEditor::_bind_methods() {
ClassDB::bind_method(_MD("_menu_option"),&Polygon2DEditor::_menu_option);
ClassDB::bind_method(_MD("_canvas_draw"),&Polygon2DEditor::_canvas_draw);
ClassDB::bind_method(_MD("_uv_mode"),&Polygon2DEditor::_uv_mode);
ClassDB::bind_method(_MD("_uv_draw"),&Polygon2DEditor::_uv_draw);
ClassDB::bind_method(_MD("_uv_input"),&Polygon2DEditor::_uv_input);
ClassDB::bind_method(_MD("_uv_scroll_changed"),&Polygon2DEditor::_uv_scroll_changed);
ClassDB::bind_method(_MD("_node_removed"),&Polygon2DEditor::_node_removed);
ClassDB::bind_method(_MD("_set_use_snap"),&Polygon2DEditor::_set_use_snap);
ClassDB::bind_method(_MD("_set_show_grid"),&Polygon2DEditor::_set_show_grid);
ClassDB::bind_method(_MD("_set_snap_off_x"),&Polygon2DEditor::_set_snap_off_x);
ClassDB::bind_method(_MD("_set_snap_off_y"),&Polygon2DEditor::_set_snap_off_y);
ClassDB::bind_method(_MD("_set_snap_step_x"),&Polygon2DEditor::_set_snap_step_x);
ClassDB::bind_method(_MD("_set_snap_step_y"),&Polygon2DEditor::_set_snap_step_y);
}
inline float _snap_scalar(float p_offset, float p_step, float p_target) {
return p_step != 0 ? Math::stepify(p_target - p_offset, p_step) + p_offset : p_target;
}
Vector2 Polygon2DEditor::snap_point(Vector2 p_target) const {
if (use_snap) {
p_target.x = _snap_scalar(snap_offset.x*uv_draw_zoom-uv_draw_ofs.x, snap_step.x*uv_draw_zoom, p_target.x);
p_target.y = _snap_scalar(snap_offset.y*uv_draw_zoom-uv_draw_ofs.y, snap_step.y*uv_draw_zoom, p_target.y);
}
return p_target;
}
Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
node=NULL;
canvas_item_editor=NULL;
editor=p_editor;
undo_redo = editor->get_undo_redo();
snap_step=Vector2(10,10);
use_snap=false;
snap_show_grid=false;
add_child( memnew( VSeparator ));
button_create = memnew( ToolButton );
add_child(button_create);
button_create->connect("pressed",this,"_menu_option",varray(MODE_CREATE));
button_create->set_toggle_mode(true);
button_edit = memnew( ToolButton );
add_child(button_edit);
button_edit->connect("pressed",this,"_menu_option",varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
button_uv = memnew( ToolButton );
add_child(button_uv);
button_uv->connect("pressed",this,"_menu_option",varray(MODE_EDIT_UV));
//add_constant_override("separation",0);
#if 0
options = memnew( MenuButton );
add_child(options);
options->set_area_as_parent_rect();
options->set_text("Polygon");
//options->get_popup()->add_item("Parse BBCode",PARSE_BBCODE);
options->get_popup()->connect("id_pressed", this,"_menu_option");
#endif
mode = MODE_EDIT;
wip_active=false;
uv_mode=UV_MODE_EDIT_POINT;
uv_edit = memnew( AcceptDialog );
add_child(uv_edit);
uv_edit->set_title(TTR("Polygon 2D UV Editor"));
uv_edit->set_self_modulate(Color(1,1,1,0.9));
VBoxContainer *uv_main_vb = memnew( VBoxContainer );
uv_edit->add_child(uv_main_vb);
//uv_edit->set_child_rect(uv_main_vb);
HBoxContainer *uv_mode_hb = memnew( HBoxContainer );
uv_main_vb->add_child(uv_mode_hb);
for(int i=0;i<UV_MODE_MAX;i++) {
uv_button[i]=memnew( ToolButton );
uv_button[i]->set_toggle_mode(true);
uv_mode_hb->add_child(uv_button[i]);
uv_button[i]->connect("pressed",this,"_uv_mode",varray(i));
uv_button[i]->set_focus_mode(FOCUS_NONE);
}
uv_button[0]->set_tooltip(TTR("Move Point")+"\n"+TTR("Ctrl: Rotate")+"\n"+TTR("Shift: Move All")+"\n"+TTR("Shift+Ctrl: Scale"));
uv_button[1]->set_tooltip(TTR("Move Polygon"));
uv_button[2]->set_tooltip(TTR("Rotate Polygon"));
uv_button[3]->set_tooltip(TTR("Scale Polygon"));
uv_button[0]->set_pressed(true);
HBoxContainer *uv_main_hb = memnew( HBoxContainer );
uv_main_vb->add_child(uv_main_hb);
uv_edit_draw = memnew( Control );
uv_main_hb->add_child(uv_edit_draw);
uv_main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
uv_edit_draw->set_h_size_flags(SIZE_EXPAND_FILL);
uv_menu = memnew( MenuButton );
uv_mode_hb->add_child(uv_menu);
uv_menu->set_text(TTR("Edit"));
uv_menu->get_popup()->add_item(TTR("Polygon->UV"),UVEDIT_POLYGON_TO_UV);
uv_menu->get_popup()->add_item(TTR("UV->Polygon"),UVEDIT_UV_TO_POLYGON);
uv_menu->get_popup()->add_separator();
uv_menu->get_popup()->add_item(TTR("Clear UV"),UVEDIT_UV_CLEAR);
uv_menu->get_popup()->connect("id_pressed",this,"_menu_option");
uv_mode_hb->add_child( memnew( VSeparator ));
b_snap_enable = memnew( ToolButton );
uv_mode_hb->add_child(b_snap_enable);
b_snap_enable->set_text(TTR("Snap"));
b_snap_enable->set_focus_mode(FOCUS_NONE);
b_snap_enable->set_toggle_mode(true);
b_snap_enable->set_pressed(use_snap);
b_snap_enable->set_tooltip(TTR("Enable Snap"));
b_snap_enable->connect("toggled",this,"_set_use_snap");
b_snap_grid = memnew( ToolButton );
uv_mode_hb->add_child(b_snap_grid);
b_snap_grid->set_text(TTR("Grid"));
b_snap_grid->set_focus_mode(FOCUS_NONE);
b_snap_grid->set_toggle_mode(true);
b_snap_grid->set_pressed(snap_show_grid);
b_snap_grid->set_tooltip(TTR("Show Grid"));
b_snap_grid->connect("toggled",this,"_set_show_grid");
uv_mode_hb->add_child( memnew( VSeparator ));
uv_mode_hb->add_child( memnew( Label(TTR("Grid Offset:")) ) );
SpinBox *sb_off_x = memnew( SpinBox );
sb_off_x->set_min(-256);
sb_off_x->set_max(256);
sb_off_x->set_step(1);
sb_off_x->set_value(snap_offset.x);
sb_off_x->set_suffix("px");
sb_off_x->connect("value_changed", this, "_set_snap_off_x");
uv_mode_hb->add_child(sb_off_x);
SpinBox *sb_off_y = memnew( SpinBox );
sb_off_y->set_min(-256);
sb_off_y->set_max(256);
sb_off_y->set_step(1);
sb_off_y->set_value(snap_offset.y);
sb_off_y->set_suffix("px");
sb_off_y->connect("value_changed", this, "_set_snap_off_y");
uv_mode_hb->add_child(sb_off_y);
uv_mode_hb->add_child( memnew( VSeparator ));
uv_mode_hb->add_child( memnew( Label(TTR("Grid Step:")) ) );
SpinBox *sb_step_x = memnew( SpinBox );
sb_step_x->set_min(-256);
sb_step_x->set_max(256);
sb_step_x->set_step(1);
sb_step_x->set_value(snap_step.x);
sb_step_x->set_suffix("px");
sb_step_x->connect("value_changed", this, "_set_snap_step_x");
uv_mode_hb->add_child(sb_step_x);
SpinBox *sb_step_y = memnew( SpinBox );
sb_step_y->set_min(-256);
sb_step_y->set_max(256);
sb_step_y->set_step(1);
sb_step_y->set_value(snap_step.y);
sb_step_y->set_suffix("px");
sb_step_y->connect("value_changed", this, "_set_snap_step_y");
uv_mode_hb->add_child(sb_step_y);
uv_mode_hb->add_child( memnew( VSeparator ));
uv_icon_zoom = memnew( TextureRect );
uv_mode_hb->add_child( uv_icon_zoom );
uv_zoom = memnew( HSlider );
uv_zoom->set_min(0.01);
uv_zoom->set_max(4);
uv_zoom->set_value(1);
uv_zoom->set_step(0.01);
uv_mode_hb->add_child(uv_zoom);
uv_zoom->set_custom_minimum_size(Size2(200,0));
uv_zoom_value = memnew( SpinBox );
uv_zoom->share(uv_zoom_value);
uv_zoom_value->set_custom_minimum_size(Size2(50,0));
uv_mode_hb->add_child(uv_zoom_value);
uv_zoom->connect("value_changed",this,"_uv_scroll_changed");
uv_vscroll = memnew( VScrollBar);
uv_main_hb->add_child(uv_vscroll);
uv_vscroll->connect("value_changed",this,"_uv_scroll_changed");
uv_hscroll = memnew( HScrollBar );
uv_main_vb->add_child(uv_hscroll);
uv_hscroll->connect("value_changed",this,"_uv_scroll_changed");
uv_edit_draw->connect("draw",this,"_uv_draw");
uv_edit_draw->connect("gui_input",this,"_uv_input");
uv_draw_zoom=1.0;
uv_drag_index=-1;
uv_drag=false;
updating_uv_scroll=false;
error = memnew( AcceptDialog);
add_child(error);
uv_edit_draw->set_clip_contents(true);
}
void Polygon2DEditorPlugin::edit(Object *p_object) {
collision_polygon_editor->edit(p_object->cast_to<Node>());
}
bool Polygon2DEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("Polygon2D");
}
void Polygon2DEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
collision_polygon_editor->show();
} else {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
}
Polygon2DEditorPlugin::Polygon2DEditorPlugin(EditorNode *p_node) {
editor=p_node;
collision_polygon_editor = memnew( Polygon2DEditor(p_node) );
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
}
Polygon2DEditorPlugin::~Polygon2DEditorPlugin()
{
}
| 28.674441
| 129
| 0.680031
|
literaldumb
|
dc58662834e32c36f7131545d2eda0a1dbcccbc5
| 2,393
|
cpp
|
C++
|
src/dxgi/dxgi_main.cpp
|
dports/dxup
|
e961838d3d0d5db02cd065b782ad890bf876ceef
|
[
"Zlib"
] | 268
|
2018-04-27T14:05:01.000Z
|
2022-03-24T03:55:54.000Z
|
src/dxgi/dxgi_main.cpp
|
dports/dxup
|
e961838d3d0d5db02cd065b782ad890bf876ceef
|
[
"Zlib"
] | 49
|
2018-04-29T09:39:03.000Z
|
2019-09-14T12:33:44.000Z
|
src/dxgi/dxgi_main.cpp
|
dports/dxup
|
e961838d3d0d5db02cd065b782ad890bf876ceef
|
[
"Zlib"
] | 28
|
2018-05-16T12:07:49.000Z
|
2022-02-26T09:19:18.000Z
|
#include "dxgi_swapchain.h"
#include "dxgi_factory.h"
typedef HRESULT(__stdcall *CreateDXGIFactory1Func)(REFIID riid, void **ppFactory);
using namespace dxup;
class DXGIWrapper
{
public:
DXGIWrapper()
{
HMODULE dxgiModule = LoadLibraryA("dxgi_original.dll");
HMODULE dxgiModuleWindows = LoadLibraryA("C:\\Windows\\System32\\dxgi.dll");
if (!dxgiModuleWindows)
dxgiModuleWindows = LoadLibraryA("C:\\Windows\\SysWOW64\\dxgi.dll");
CreateDXGIFactory1Function = nullptr;
if (dxgiModule)
CreateDXGIFactory1Function = (CreateDXGIFactory1Func)GetProcAddress(dxgiModule, "CreateDXGIFactory1");
else
CreateDXGIFactory1Function = (CreateDXGIFactory1Func)GetProcAddress(dxgiModuleWindows, "CreateDXGIFactory1");
}
CreateDXGIFactory1Func CreateDXGIFactory1Function;
static DXGIWrapper& Get()
{
if (!s_dxgiWrapper)
s_dxgiWrapper = new DXGIWrapper();
return *s_dxgiWrapper;
}
private:
static DXGIWrapper* s_dxgiWrapper;
};
DXGIWrapper* DXGIWrapper::s_dxgiWrapper = nullptr;
extern "C"
{
void __stdcall DXUPWrapSwapChain(IDXGISwapChain** ppSwapChain)
{
auto* dxupSwapchain = new DXGISwapChain(*ppSwapChain);
*ppSwapChain = dxupSwapchain;
}
HRESULT __stdcall CreateDXGIFactory2(UINT Flags, REFIID riid, void **ppFactory)
{
IDXGIFactory2* pWrappedFactory = nullptr;
HRESULT result = DXGIWrapper::Get().CreateDXGIFactory1Function(__uuidof(IDXGIFactory1), (void**)&pWrappedFactory);
if (pWrappedFactory)
{
DXGIFactory* dxupFactory = new DXGIFactory(pWrappedFactory);
if (ppFactory)
*ppFactory = dxupFactory;
}
return result;
}
HRESULT __stdcall CreateDXGIFactory1(REFIID riid, void **ppFactory)
{
return CreateDXGIFactory2(0, riid, ppFactory);
}
HRESULT __stdcall CreateDXGIFactory(REFIID riid, void **ppFactory)
{
return CreateDXGIFactory2(0, riid, ppFactory);
}
HRESULT __stdcall DXGID3D10RegisterLayers(const struct dxgi_device_layer *layers, UINT layer_count)
{
return E_NOTIMPL;
}
HRESULT __stdcall DXGID3D10GetLayeredDeviceSize(const struct dxgi_device_layer *layers, UINT layer_count)
{
return E_NOTIMPL;
}
struct Byte20 { BYTE p[20]; };
HRESULT __stdcall DXGID3D10CreateLayeredDevice(Byte20 z)
{
return E_NOTIMPL;
}
HRESULT __stdcall DXGID3D10CreateDevice(HMODULE d3d10core, IDXGIFactory *factory, IDXGIAdapter *adapter, UINT flags, DWORD arg5, void **device)
{
return E_NOTIMPL;
}
}
| 25.457447
| 145
| 0.76682
|
dports
|
dc58bf29276a0af47fef8a09c3fbc0e716ba36ff
| 4,008
|
hpp
|
C++
|
3rdparty/stout/include/stout/cache.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 4,537
|
2015-01-01T03:26:40.000Z
|
2022-03-31T03:07:00.000Z
|
3rdparty/stout/include/stout/cache.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 227
|
2015-01-29T02:21:39.000Z
|
2022-03-29T13:35:50.000Z
|
3rdparty/stout/include/stout/cache.hpp
|
zagrev/mesos
|
eefec152dffc4977183089b46fbfe37dbd19e9d7
|
[
"Apache-2.0"
] | 1,992
|
2015-01-05T12:29:19.000Z
|
2022-03-31T03:07:07.000Z
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_CACHE_HPP__
#define __STOUT_CACHE_HPP__
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <unordered_map>
#include <utility>
#include <glog/logging.h>
#include "none.hpp"
#include "option.hpp"
// Forward declaration.
template <typename Key, typename Value>
class Cache;
// Outputs the key/value pairs from least to most-recently used.
template <typename Key, typename Value>
std::ostream& operator<<(std::ostream& stream, const Cache<Key, Value>& c);
// Provides a least-recently used (LRU) cache of some predefined
// capacity. A "write" and a "read" both count as uses.
template <typename Key, typename Value>
class Cache
{
public:
typedef std::list<Key> list;
typedef std::unordered_map<
Key, std::pair<Value, typename list::iterator>> map;
explicit Cache(size_t _capacity) : capacity(_capacity) {}
void put(const Key& key, const Value& value)
{
typename map::iterator i = values.find(key);
if (i == values.end()) {
insert(key, value);
} else {
(*i).second.first = value;
use(i);
}
}
Option<Value> get(const Key& key)
{
typename map::iterator i = values.find(key);
if (i != values.end()) {
use(i);
return (*i).second.first;
}
return None();
}
Option<Value> erase(const Key& key)
{
typename map::iterator i = values.find(key);
if (i != values.end()) {
Value value = i->second.first;
keys.erase(i->second.second);
values.erase(i);
return value;
}
return None();
}
size_t size() const { return keys.size(); }
private:
// Not copyable, not assignable.
Cache(const Cache&);
Cache& operator=(const Cache&);
// Give the operator access to our internals.
friend std::ostream& operator<<<>(
std::ostream& stream,
const Cache<Key, Value>& c);
// Insert key/value into the cache.
void insert(const Key& key, const Value& value)
{
if (keys.size() == capacity) {
evict();
}
// Get a "pointer" into the lru list for efficient update.
typename list::iterator i = keys.insert(keys.end(), key);
// Save key/value and "pointer" into lru list.
values.insert(std::make_pair(key, std::make_pair(value, i)));
}
// Updates the LRU ordering in the cache for the given iterator.
void use(const typename map::iterator& i)
{
// Move the "pointer" to the end of the lru list.
keys.splice(keys.end(), keys, (*i).second.second);
// Now update the "pointer" so we can do this again.
(*i).second.second = --keys.end();
}
// Evict the least-recently used element from the cache.
void evict()
{
const typename map::iterator i = values.find(keys.front());
CHECK(i != values.end());
values.erase(i);
keys.pop_front();
}
// Size of the cache.
const size_t capacity;
// Cache of values and "pointers" into the least-recently used list.
map values;
// Keys ordered by least-recently used.
list keys;
};
template <typename Key, typename Value>
std::ostream& operator<<(std::ostream& stream, const Cache<Key, Value>& c)
{
typename Cache<Key, Value>::list::const_iterator i1;
for (i1 = c.keys.begin(); i1 != c.keys.end(); i1++) {
stream << *i1 << ": ";
typename Cache<Key, Value>::map::const_iterator i2;
i2 = c.values.find(*i1);
CHECK(i2 != c.values.end());
stream << *i2 << std::endl;
}
return stream;
}
#endif // __STOUT_CACHE_HPP__
| 25.528662
| 75
| 0.65519
|
zagrev
|
dc5bf861cb6c7104998bc4b10fcee9fb9f8fcfae
| 8,748
|
cpp
|
C++
|
server_code/query_cursor_basic.cpp
|
InitialDLab/SampleIndex
|
c83d6f53f8419cdb78f49935f41eb39447918ced
|
[
"MIT"
] | 3
|
2017-09-30T22:34:57.000Z
|
2019-07-18T21:21:35.000Z
|
server_code/query_cursor_basic.cpp
|
InitialDLab/SONAR-SamplingIndex
|
c83d6f53f8419cdb78f49935f41eb39447918ced
|
[
"MIT"
] | null | null | null |
server_code/query_cursor_basic.cpp
|
InitialDLab/SONAR-SamplingIndex
|
c83d6f53f8419cdb78f49935f41eb39447918ced
|
[
"MIT"
] | null | null | null |
/*
Copyright 2017 InitialDLab
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 <time.h>
#include <memory>
#include <vector>
#include <glog/logging.h>
#include "query_cursor_basic.h"
#include "server_code/protobuf/sampling_api.pb.h"
query_cursor_basic::query_cursor_basic(std::shared_ptr<basic_rtree> source
, const serverProto::box& query_region
, bool returnOID
, bool returnTime
, bool returnLocation
, int ttl)
: m_queryRegion(query_region)
, m_source(source)
, m_datalock()
, m_returning_OID(returnOID)
, m_returning_location(returnLocation)
, m_returning_time(returnTime)
, m_elements_analyzed(0)
, m_ttl(ttl)
, m_cursor(source->sample_query(get_query_box3d(query_region)))
{
// we will set some max ttl. It only can be up to 5 minutes
m_ttl = std::min(60*5, m_ttl);
// setup query cursor
// count the number of elements in the region (or estimate count if that is the only thing available to us)
// we would like to get an exact count. We don't have good guarantees for approximate counts
m_elements_in_range = source->naive_sample_query(get_query_box3d()).get_count();
LOG(INFO) << "for new query, we think there are " << m_elements_in_range << " elements in the range";
// setup accumulators and accumulator list
// accumulators are already setup?
// set last used time to now
time(&last_used_time);
}
query_cursor_basic::~query_cursor_basic()
{
}
bool query_cursor_basic::returning_OID()
{
return m_returning_OID;
}
bool query_cursor_basic::returning_location()
{
return m_returning_location;
}
bool query_cursor_basic::returning_payload()
{
return false;
}
bool query_cursor_basic::returning_time()
{
return m_returning_time;
}
int query_cursor_basic::get_ttl()
{
return m_ttl;
}
bool query_cursor_basic::is_expired()
{
double seconds_since_use = difftime(time(NULL), last_used_time);
return seconds_since_use > m_ttl;
}
long query_cursor_basic::get_total_elements_in_query_range()
{
return m_elements_in_range;
}
long query_cursor_basic::get_elements_analyzed_count()
{
return m_elements_analyzed;
}
serverProto::box query_cursor_basic::get_query_region()
{
return m_queryRegion;
}
server_types::box3d query_cursor_basic::get_query_box3d() const
{
server_types::box3d box_builder;
box_builder.min_corner().set<0>(m_queryRegion.min_point().lat() );
box_builder.min_corner().set<1>(m_queryRegion.min_point().lon() );
box_builder.min_corner().set<2>(m_queryRegion.min_point().time());
box_builder.max_corner().set<0>(m_queryRegion.max_point().lat() );
box_builder.max_corner().set<1>(m_queryRegion.max_point().lon() );
box_builder.max_corner().set<2>(m_queryRegion.max_point().time());
return box_builder;
}
server_types::box3d query_cursor_basic::get_query_box3d(const serverProto::box& q_region)
{
server_types::box3d box_builder;
box_builder.min_corner().set<0>(q_region.min_point().lat());
box_builder.min_corner().set<1>(q_region.min_point().lon());
box_builder.min_corner().set<2>(q_region.min_point().time());
box_builder.max_corner().set<0>(q_region.max_point().lat());
box_builder.max_corner().set<1>(q_region.max_point().lon());
box_builder.max_corner().set<2>(q_region.max_point().time());
return box_builder;
}
void query_cursor_basic::get_stats(const StreamingStatistics_t& stats, serverProto::ElementStatistics &toRet) const
{
using namespace boost::accumulators;
//serverProto::ElementStatistics toRet;
toRet.set_type(serverProto::StatisicalType::FLOAT_TYPE);
toRet.set_sample_size(count(stats));
toRet.set_total_count(this->m_elements_in_range);
toRet.set_mean(mean(stats));
// TODO: SET CONFIDENCE REGION
// TODO: SET CONFICENCE LEVEL
toRet.set_stdev(variance(stats));
toRet.set_float_min(min(stats));
toRet.set_float_max(max(stats));
//return toRet;
}
void query_cursor_basic::perform_query(int count, serverProto::QueryResponse& toReturn)
{
m_datalock.lock();
// I assume the query will be short, so I only set it at the beginning of the query.
// so it is not cleaned up while a query is being done.
time(&last_used_time);
// setup accumulators running for this particular query
StreamingStatistics_t latRun;
StreamingStatistics_t lonRun;
StreamingStatistics_t timeRun;
int_minMax_accumulator_t timeMinMaxRun;
toReturn.Clear();
// query the data structure, filling the accumulators with the new data
// as we are filling the accumulators, also fill the QueryResponse.
// NOTE: if needed, we don't have to do it this way. We can implemented
// a back inserter function for QueryResponse which will also fill accumulators.
// doing this will allow only a single scan of the data. currently we are
// doing a double scan.
std::vector<server_types::basic_entry> query_buffer;
if (this->m_elements_in_range == 0)
{
// do nothing if there is not anything to query
}
else if (this->m_elements_in_range <= count) {
m_source->range_report(get_query_box3d(), back_inserter(query_buffer));
}
else{
m_cursor.get_samples(count, back_inserter(query_buffer));
}
// update the total query count
m_elements_analyzed += query_buffer.size();
for (size_t i = 0; i < query_buffer.size(); i++)
{
// add to accumulators
latRun(query_buffer[i].loc.lat);
m_latTotal(query_buffer[i].loc.lat);
lonRun(query_buffer[i].loc.lon);
m_lonTotal(query_buffer[i].loc.lon);
timeRun(query_buffer[i].timestamp);
m_timeTotal(query_buffer[i].timestamp);
timeMinMaxRun(query_buffer[i].timestamp);
m_timeMinMax(query_buffer[i].timestamp);
// insert the element in to queryResponse
serverProto::element* elm = toReturn.add_elements();
if (m_returning_OID)
elm->set_oid(query_buffer[i].oid.to_string());
if (m_returning_location)
{
auto sloc = elm->mutable_location();
sloc->set_lat(query_buffer[i].loc.lat);
sloc->set_lon(query_buffer[i].loc.lon);
}
if (m_returning_time)
{
auto sloc = elm->mutable_location();
sloc->set_time(query_buffer[i].timestamp);
}
}
// set the accumulator data.
using namespace boost::accumulators;
get_stats(latRun, *(toReturn.mutable_lat_last()));
get_stats(lonRun, *(toReturn.mutable_lon_last()));
get_stats(timeRun, *(toReturn.mutable_time_last()));
get_stats(m_latTotal, *(toReturn.mutable_lat_total()));
get_stats(m_lonTotal, *(toReturn.mutable_lon_total()));
get_stats(m_timeTotal, *(toReturn.mutable_time_total()));
toReturn.set_sample_count_last(query_buffer.size());
toReturn.set_sample_count_total(m_elements_analyzed);
time(&last_used_time);
m_datalock.unlock();
}
| 35.417004
| 116
| 0.652949
|
InitialDLab
|
dc5e89692718e5d1e7bd78a9c5b62b0634e487f4
| 873
|
cpp
|
C++
|
upload_voltage/libraries/Adafruit_IO_Arduino-master/src/blocks/MapBlock.cpp
|
sudhi345/mAhTime
|
bb8b03a6816d18aefe00f6014ff0b127fdea1843
|
[
"BSD-3-Clause"
] | 1
|
2019-09-21T01:48:09.000Z
|
2019-09-21T01:48:09.000Z
|
upload_voltage/libraries/Adafruit_IO_Arduino-master/src/blocks/MapBlock.cpp
|
sudhi345/mAhTime
|
bb8b03a6816d18aefe00f6014ff0b127fdea1843
|
[
"BSD-3-Clause"
] | null | null | null |
upload_voltage/libraries/Adafruit_IO_Arduino-master/src/blocks/MapBlock.cpp
|
sudhi345/mAhTime
|
bb8b03a6816d18aefe00f6014ff0b127fdea1843
|
[
"BSD-3-Clause"
] | null | null | null |
//
// Adafruit invests time and resources providing this open source code.
// Please support Adafruit and open source hardware by purchasing
// products from Adafruit!
//
// Copyright (c) 2015-2016 Adafruit Industries
// Authors: Tony DiCola, Todd Treece
// Licensed under the MIT license.
//
// All text above must be included in any redistribution.
//
#include "MapBlock.h"
MapBlock::MapBlock(AdafruitIO_Dashboard *d, AdafruitIO_Feed *f) : AdafruitIO_Block(d, f)
{
historyHours = 0;
tile = "contrast";
}
MapBlock::~MapBlock() {}
String MapBlock::properties()
{
if ((strcmp(tile, "contrast") != 0) && (strcmp(tile, "street") != 0) && (strcmp(tile, "sat") != 0))
{
tile = "contrast";
}
props = "{\"historyHours\":\"";
props += historyHours;
props += "\",\"tile\":\"";
props += tile;
props += "\"}";
return props;
}
| 22.973684
| 103
| 0.630011
|
sudhi345
|
dc5ecf0d9e9c408941c6d98343b4f4b3142f0ba2
| 2,969
|
cpp
|
C++
|
automated-tests/src/dali-platform-abstraction/utc-image-loading-load-completion.cpp
|
pwisbey/dali-adaptor
|
21d5e77316e53285fa1e210a93b13cf9889e3b54
|
[
"Apache-2.0"
] | null | null | null |
automated-tests/src/dali-platform-abstraction/utc-image-loading-load-completion.cpp
|
pwisbey/dali-adaptor
|
21d5e77316e53285fa1e210a93b13cf9889e3b54
|
[
"Apache-2.0"
] | null | null | null |
automated-tests/src/dali-platform-abstraction/utc-image-loading-load-completion.cpp
|
pwisbey/dali-adaptor
|
21d5e77316e53285fa1e210a93b13cf9889e3b54
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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 "utc-image-loading-common.h"
void utc_image_loading_load_completion_startup(void)
{
utc_dali_loading_startup();
}
void utc_image_loading_load_completion_cleanup(void)
{
utc_dali_loading_cleanup();
}
// Positive test case for loading. Load lots and be sure it has succeeded.
int UtcDaliLoadCompletion(void)
{
tet_printf("Running load completion test \n");
DALI_ASSERT_ALWAYS( gAbstraction != 0 );
// Start a bunch of loads that should work:
Dali::Integration::BitmapResourceType bitmapResourceType;
Dali::Integration::LoadResourcePriority priority = Dali::Integration::LoadPriorityNormal;
unsigned loadsLaunched = 0;
for( unsigned loadGroup = 0; loadGroup < NUM_LOAD_GROUPS_TO_ISSUE; ++loadGroup )
{
for( unsigned validImage = 0; validImage < NUM_VALID_IMAGES; ++validImage )
{
Dali::Integration::ResourceRequest request( loadGroup * NUM_VALID_IMAGES + validImage + 1, bitmapResourceType, VALID_IMAGES[validImage], priority );
gAbstraction->LoadResource( request );
}
loadsLaunched += NUM_VALID_IMAGES;
}
// Drain the completed loads:
Dali::Internal::Platform::ResourceCollector resourceSink;
gAbstraction->GetResources( resourceSink );
usleep( 500 * 1000 );
gAbstraction->GetResources( resourceSink );
const double startDrainTime = GetTimeMilliseconds( *gAbstraction );
while( resourceSink.mGrandTotalCompletions < loadsLaunched && GetTimeMilliseconds( *gAbstraction ) - startDrainTime < MAX_MILLIS_TO_WAIT_FOR_KNOWN_LOADS )
{
usleep( 100 * 40 );
gAbstraction->GetResources( resourceSink );
}
// Check the loads completed as expected:
tet_printf( "Issued Loads: %u, Completed Loads: %u, Successful Loads: %u, Failed Loads: %u \n", loadsLaunched, resourceSink.mGrandTotalCompletions, unsigned(resourceSink.mSuccessCounts.size()), unsigned(resourceSink.mFailureCounts.size()) );
DALI_TEST_CHECK( loadsLaunched == resourceSink.mGrandTotalCompletions );
DALI_TEST_CHECK( loadsLaunched == resourceSink.mSuccessCounts.size() );
DALI_TEST_CHECK( 0 == resourceSink.mFailureCounts.size() );
// Check that each success was reported exactly once:
for( ResourceCounterMap::const_iterator it = resourceSink.mSuccessCounts.begin(), end = resourceSink.mSuccessCounts.end(); it != end; ++it )
{
DALI_TEST_CHECK( it->second == 1u );
}
END_TEST;
}
| 36.654321
| 243
| 0.7484
|
pwisbey
|
dc6100e822bac72e8eaa767344aa985688c31857
| 34,188
|
cpp
|
C++
|
tests/unit/tests/block_tests.cpp
|
VIM-Arcange/hive
|
991c6cdfd195a4f97fc27d3f7f393c7dfb5f1bd2
|
[
"MIT"
] | 283
|
2020-03-20T02:13:12.000Z
|
2022-03-31T22:40:07.000Z
|
tests/unit/tests/block_tests.cpp
|
mlrequena78/hive
|
991c6cdfd195a4f97fc27d3f7f393c7dfb5f1bd2
|
[
"MIT"
] | 19
|
2020-03-20T03:09:16.000Z
|
2021-08-28T22:35:09.000Z
|
tests/unit/tests/block_tests.cpp
|
mlrequena78/hive
|
991c6cdfd195a4f97fc27d3f7f393c7dfb5f1bd2
|
[
"MIT"
] | 94
|
2020-03-20T01:53:05.000Z
|
2022-03-04T11:08:23.000Z
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifdef IS_TEST_NET
#include <boost/test/unit_test.hpp>
#include <hive/chain/hive_fwd.hpp>
#include <hive/protocol/exceptions.hpp>
#include <hive/chain/database.hpp>
#include <hive/chain/hive_objects.hpp>
#include <hive/chain/history_object.hpp>
#include <hive/plugins/account_history/account_history_plugin.hpp>
#include <hive/plugins/witness/block_producer.hpp>
#include <hive/utilities/tempdir.hpp>
#include <hive/utilities/database_configuration.hpp>
#include <fc/crypto/digest.hpp>
#include "../db_fixture/database_fixture.hpp"
using namespace hive;
using namespace hive::chain;
using namespace hive::protocol;
using namespace hive::plugins;
#define TEST_SHARED_MEM_SIZE (1024 * 1024 * 8)
BOOST_AUTO_TEST_SUITE(block_tests)
void open_test_database( database& db, const fc::path& dir )
{
hive::chain::open_args args;
args.data_dir = dir;
args.shared_mem_dir = dir;
args.initial_supply = INITIAL_TEST_SUPPLY;
args.hbd_initial_supply = HBD_INITIAL_TEST_SUPPLY;
args.shared_file_size = TEST_SHARED_MEM_SIZE;
args.database_cfg = hive::utilities::default_database_configuration();
db.open( args );
}
BOOST_AUTO_TEST_CASE( generate_empty_blocks )
{
try {
fc::time_point_sec now( HIVE_TESTING_GENESIS_TIMESTAMP );
fc::temp_directory data_dir( hive::utilities::temp_directory_path() );
signed_block b;
// TODO: Don't generate this here
auto init_account_priv_key = fc::ecc::private_key::regenerate( fc::sha256::hash( string( "init_key" ) ) );
signed_block cutoff_block;
{
database db;
witness::block_producer bp( db );
db._log_hardforks = false;
open_test_database( db, data_dir.path() );
b = bp.generate_block(db.get_slot_time(1), db.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
// TODO: Change this test when we correct #406
// n.b. we generate HIVE_MIN_UNDO_HISTORY+1 extra blocks which will be discarded on save
for( uint32_t i = 1; ; ++i )
{
BOOST_CHECK( db.head_block_id() == b.id() );
//witness_id_type prev_witness = b.witness;
string cur_witness = db.get_scheduled_witness(1);
//BOOST_CHECK( cur_witness != prev_witness );
b = bp.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key, database::skip_nothing);
BOOST_CHECK( b.witness == cur_witness );
uint32_t cutoff_height = db.get_last_irreversible_block_num();
if( cutoff_height >= 200 )
{
auto block = db.fetch_block_by_number( cutoff_height );
BOOST_REQUIRE( block.valid() );
cutoff_block = *block;
break;
}
}
db.close();
}
{
database db;
witness::block_producer bp( db );
db._log_hardforks = false;
open_test_database( db, data_dir.path() );
BOOST_CHECK_EQUAL( db.head_block_num(), cutoff_block.block_num() );
b = cutoff_block;
for( uint32_t i = 0; i < 200; ++i )
{
BOOST_CHECK( db.head_block_id() == b.id() );
//witness_id_type prev_witness = b.witness;
string cur_witness = db.get_scheduled_witness(1);
//BOOST_CHECK( cur_witness != prev_witness );
b = bp.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key, database::skip_nothing);
}
BOOST_CHECK_EQUAL( db.head_block_num(), cutoff_block.block_num()+200 );
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( undo_block )
{
try {
fc::temp_directory data_dir( hive::utilities::temp_directory_path() );
{
database db;
witness::block_producer bp( db );
db._log_hardforks = false;
open_test_database( db, data_dir.path() );
fc::time_point_sec now( HIVE_TESTING_GENESIS_TIMESTAMP );
std::vector< time_point_sec > time_stack;
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
for( uint32_t i = 0; i < 5; ++i )
{
now = db.get_slot_time(1);
time_stack.push_back( now );
auto b = bp.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing );
}
BOOST_CHECK( db.head_block_num() == 5 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 4 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 3 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 2 );
BOOST_CHECK( db.head_block_time() == now );
for( uint32_t i = 0; i < 5; ++i )
{
now = db.get_slot_time(1);
time_stack.push_back( now );
auto b = bp.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing );
}
BOOST_CHECK( db.head_block_num() == 7 );
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( fork_blocks )
{
try {
fc::temp_directory data_dir1( hive::utilities::temp_directory_path() );
fc::temp_directory data_dir2( hive::utilities::temp_directory_path() );
//TODO This test needs 6-7 ish witnesses prior to fork
database db1;
witness::block_producer bp1( db1 );
db1._log_hardforks = false;
open_test_database( db1, data_dir1.path() );
database db2;
witness::block_producer bp2( db2 );
db2._log_hardforks = false;
open_test_database( db2, data_dir2.path() );
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
for( uint32_t i = 0; i < 10; ++i )
{
auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
try {
PUSH_BLOCK( db2, b );
} FC_CAPTURE_AND_RETHROW( ("db2") );
}
for( uint32_t i = 10; i < 13; ++i )
{
auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
}
string db1_tip = db1.head_block_id().str();
uint32_t next_slot = 3;
for( uint32_t i = 13; i < 16; ++i )
{
auto b = bp2.generate_block(db2.get_slot_time(next_slot), db2.get_scheduled_witness(next_slot), init_account_priv_key, database::skip_nothing);
next_slot = 1;
// notify both databases of the new block.
// only db2 should switch to the new fork, db1 should not
PUSH_BLOCK( db1, b );
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip);
BOOST_CHECK_EQUAL(db2.head_block_id().str(), b.id().str());
}
//The two databases are on distinct forks now, but at the same height. Make a block on db2, make it invalid, then
//pass it to db1 and assert that db1 doesn't switch to the new fork.
signed_block good_block;
BOOST_CHECK_EQUAL(db1.head_block_num(), 13u);
BOOST_CHECK_EQUAL(db2.head_block_num(), 13u);
{
auto b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
good_block = b;
b.transactions.emplace_back(signed_transaction());
b.transactions.back().operations.emplace_back(transfer_operation());
b.sign( init_account_priv_key );
BOOST_CHECK_EQUAL(b.block_num(), 14u);
HIVE_CHECK_THROW(PUSH_BLOCK( db1, b ), fc::exception);
}
BOOST_CHECK_EQUAL(db1.head_block_num(), 13u);
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip);
// assert that db1 switches to new fork with good block
BOOST_CHECK_EQUAL(db2.head_block_num(), 14u);
PUSH_BLOCK( db1, good_block );
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db2.head_block_id().str());
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( switch_forks_undo_create )
{
try {
fc::temp_directory dir1( hive::utilities::temp_directory_path() ),
dir2( hive::utilities::temp_directory_path() );
database db1,
db2;
witness::block_producer bp1( db1 ),
bp2( db2 );
db1._log_hardforks = false;
open_test_database( db1, dir1.path() );
db2._log_hardforks = false;
open_test_database( db2, dir2.path() );
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
public_key_type init_account_pub_key = init_account_priv_key.get_public_key();
db1.get_index< account_index >();
//*
signed_transaction trx;
account_create_operation cop;
cop.new_account_name = "alice";
cop.creator = HIVE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key, 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
PUSH_TX( db1, trx );
//*/
// generate blocks
// db1 : A
// db2 : B C D
auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
auto alice_id = db1.get_account( "alice" ).get_id();
BOOST_CHECK( db1.get(alice_id).name == "alice" );
b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
db1.push_block(b);
b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
db1.push_block(b);
HIVE_REQUIRE_THROW(db2.get(alice_id), std::exception);
db1.get(alice_id); /// it should be included in the pending state
db1.clear_pending(); // clear it so that we can verify it was properly removed from pending state.
HIVE_REQUIRE_THROW(db1.get(alice_id), std::exception);
PUSH_TX( db2, trx );
b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
db1.push_block(b);
BOOST_CHECK( db1.get(alice_id).name == "alice");
BOOST_CHECK( db2.get(alice_id).name == "alice");
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( duplicate_transactions )
{
try {
fc::temp_directory dir1( hive::utilities::temp_directory_path() ),
dir2( hive::utilities::temp_directory_path() );
database db1,
db2;
witness::block_producer bp1( db1 );
db1._log_hardforks = false;
open_test_database( db1, dir1.path() );
db2._log_hardforks = false;
open_test_database( db2, dir2.path() );
BOOST_CHECK( db1.get_chain_id() == db2.get_chain_id() );
auto skip_sigs = database::skip_transaction_signatures | database::skip_authority_check;
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
public_key_type init_account_pub_key = init_account_priv_key.get_public_key();
signed_transaction trx;
account_create_operation cop;
cop.new_account_name = "alice";
cop.creator = HIVE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key, 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
PUSH_TX( db1, trx, skip_sigs );
trx = decltype(trx)();
transfer_operation t;
t.from = HIVE_INIT_MINER_NAME;
t.to = "alice";
t.amount = asset(500,HIVE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
PUSH_TX( db1, trx, skip_sigs );
HIVE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception);
auto b = bp1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key, skip_sigs );
PUSH_BLOCK( db2, b, skip_sigs );
HIVE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception);
HIVE_CHECK_THROW(PUSH_TX( db2, trx, skip_sigs ), fc::exception);
BOOST_CHECK_EQUAL(db1.get_balance( "alice", HIVE_SYMBOL ).amount.value, 500);
BOOST_CHECK_EQUAL(db2.get_balance( "alice", HIVE_SYMBOL ).amount.value, 500);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( tapos )
{
try {
fc::temp_directory dir1( hive::utilities::temp_directory_path() );
database db1;
witness::block_producer bp1( db1 );
db1._log_hardforks = false;
open_test_database( db1, dir1.path() );
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
public_key_type init_account_pub_key = init_account_priv_key.get_public_key();
auto b = bp1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing);
BOOST_TEST_MESSAGE( "Creating a transaction with reference block" );
idump((db1.head_block_id()));
signed_transaction trx;
//This transaction must be in the next block after its reference, or it is invalid.
trx.set_reference_block( db1.head_block_id() );
account_create_operation cop;
cop.new_account_name = "alice";
cop.creator = HIVE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key, 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
BOOST_TEST_MESSAGE( "Pushing Pending Transaction" );
idump((trx));
db1.push_transaction(trx);
BOOST_TEST_MESSAGE( "Generating a block" );
b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
trx.clear();
transfer_operation t;
t.from = HIVE_INIT_MINER_NAME;
t.to = "alice";
t.amount = asset(50,HIVE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db1.head_block_time() + fc::seconds(2) );
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
idump((trx)(db1.head_block_time()));
b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
idump((b));
b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing);
trx.signatures.clear();
trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical );
BOOST_REQUIRE_THROW( db1.push_transaction(trx, 0/*database::skip_transaction_signatures | database::skip_authority_check*/), fc::exception );
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_FIXTURE_TEST_CASE( optional_tapos, clean_database_fixture )
{
try
{
idump((db->get_account("initminer")));
ACTORS( (alice)(bob) );
generate_block();
BOOST_TEST_MESSAGE( "Create transaction" );
transfer( HIVE_INIT_MINER_NAME, "alice", asset( 1000000, HIVE_SYMBOL ) );
transfer_operation op;
op.from = "alice";
op.to = "bob";
op.amount = asset(1000,HIVE_SYMBOL);
signed_transaction tx;
tx.operations.push_back( op );
BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=0" );
tx.ref_block_num = 0;
tx.ref_block_prefix = 0;
tx.signatures.clear();
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
sign( tx, alice_private_key );
PUSH_TX( *db, tx );
BOOST_TEST_MESSAGE( "proper ref_block_num, ref_block_prefix" );
tx.signatures.clear();
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
sign( tx, alice_private_key );
PUSH_TX( *db, tx, database::skip_transaction_dupe_check );
BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=12345678" );
tx.ref_block_num = 0;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
sign( tx, alice_private_key );
HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception );
BOOST_TEST_MESSAGE( "ref_block_num=1, ref_block_prefix=12345678" );
tx.ref_block_num = 1;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
sign( tx, alice_private_key );
HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception );
BOOST_TEST_MESSAGE( "ref_block_num=9999, ref_block_prefix=12345678" );
tx.ref_block_num = 9999;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
sign( tx, alice_private_key );
HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception );
}
catch (fc::exception& e)
{
edump((e.to_detail_string()));
throw;
}
}
BOOST_FIXTURE_TEST_CASE( double_sign_check, clean_database_fixture )
{ try {
generate_block();
ACTOR(bob);
share_type amount = 1000;
transfer_operation t;
t.from = HIVE_INIT_MINER_NAME;
t.to = "bob";
t.amount = asset(amount,HIVE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
trx.validate();
db->push_transaction(trx, ~0);
trx.operations.clear();
t.from = "bob";
t.to = HIVE_INIT_MINER_NAME;
t.amount = asset(amount,HIVE_SYMBOL);
trx.operations.push_back(t);
trx.validate();
BOOST_TEST_MESSAGE( "Verify that not-signing causes an exception" );
HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), fc::exception );
BOOST_TEST_MESSAGE( "Verify that double-signing causes an exception" );
sign( trx, bob_private_key );
sign( trx, bob_private_key );
HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), tx_duplicate_sig );
BOOST_TEST_MESSAGE( "Verify that signing with an extra, unused key fails" );
trx.signatures.pop_back();
sign( trx, generate_private_key( "bogus" ) );
HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), tx_irrelevant_sig );
BOOST_TEST_MESSAGE( "Verify that signing once with the proper key passes" );
trx.signatures.pop_back();
db->push_transaction(trx, 0);
sign( trx, bob_private_key );
} FC_LOG_AND_RETHROW() }
BOOST_FIXTURE_TEST_CASE( pop_block_twice, clean_database_fixture )
{
try
{
uint32_t skip_flags = (
database::skip_witness_signature
| database::skip_transaction_signatures
| database::skip_authority_check
);
// Sam is the creator of accounts
auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) );
private_key_type sam_key = generate_private_key( "sam" );
account_create( "sam", sam_key.get_public_key() );
//Get a sane head block time
generate_block( skip_flags );
transaction tx;
signed_transaction ptx;
db->get_account( HIVE_INIT_MINER_NAME );
// transfer from committee account to Sam account
transfer( HIVE_INIT_MINER_NAME, "sam", asset( 100000, HIVE_SYMBOL ) );
generate_block(skip_flags);
account_create( "alice", generate_private_key( "alice" ).get_public_key() );
generate_block(skip_flags);
account_create( "bob", generate_private_key( "bob" ).get_public_key() );
generate_block(skip_flags);
db->pop_block();
db->pop_block();
} catch(const fc::exception& e) {
edump( (e.to_detail_string()) );
throw;
}
}
BOOST_FIXTURE_TEST_CASE( rsf_missed_blocks, clean_database_fixture )
{
try
{
generate_block();
auto rsf = [&]() -> string
{
fc::uint128 rsf = db->get_dynamic_global_properties().recent_slots_filled;
string result = "";
result.reserve(128);
for( int i=0; i<128; i++ )
{
result += ((rsf.lo & 1) == 0) ? '0' : '1';
rsf >>= 1;
}
return result;
};
auto pct = []( uint32_t x ) -> uint32_t
{
return uint64_t( HIVE_100_PERCENT ) * x / 128;
};
BOOST_TEST_MESSAGE("checking initial participation rate" );
BOOST_CHECK_EQUAL( rsf(),
"1111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), static_cast<uint32_t>(HIVE_100_PERCENT) );
BOOST_TEST_MESSAGE("Generating a block skipping 1" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 1 );
BOOST_CHECK_EQUAL( rsf(),
"0111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(127) );
BOOST_TEST_MESSAGE("Generating a block skipping 1" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 1 );
BOOST_CHECK_EQUAL( rsf(),
"0101111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(126) );
BOOST_TEST_MESSAGE("Generating a block skipping 2" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 2 );
BOOST_CHECK_EQUAL( rsf(),
"0010101111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(124) );
BOOST_TEST_MESSAGE("Generating a block for skipping 3" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 3 );
BOOST_CHECK_EQUAL( rsf(),
"0001001010111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(121) );
BOOST_TEST_MESSAGE("Generating a block skipping 5" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 5 );
BOOST_CHECK_EQUAL( rsf(),
"0000010001001010111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(116) );
BOOST_TEST_MESSAGE("Generating a block skipping 8" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 8 );
BOOST_CHECK_EQUAL( rsf(),
"0000000010000010001001010111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(108) );
BOOST_TEST_MESSAGE("Generating a block skipping 13" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 13 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000100000000100000100010010101111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) );
BOOST_TEST_MESSAGE("Generating a block skipping none" );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1000000000000010000000010000010001001010111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) );
BOOST_TEST_MESSAGE("Generating a block" );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1100000000000001000000001000001000100101011111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1110000000000000100000000100000100010010101111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1111000000000000010000000010000010001001010111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) );
generate_block( ~database::skip_fork_db, init_account_priv_key, 64 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000000000000000000000000000000000000000000000000000000"
"1111100000000000001000000001000001000100101011111111111111111111"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(31) );
generate_block( ~database::skip_fork_db, init_account_priv_key, 32 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000000000000000000000010000000000000000000000000000000"
"0000000000000000000000000000000001111100000000000001000000001000"
);
BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(8) );
}
FC_LOG_AND_RETHROW()
}
BOOST_FIXTURE_TEST_CASE( skip_block, clean_database_fixture )
{
try
{
BOOST_TEST_MESSAGE( "Skipping blocks through db" );
BOOST_REQUIRE( db->head_block_num() == 2 );
witness::block_producer bp( *db );
unsigned int init_block_num = db->head_block_num();
int miss_blocks = fc::minutes( 1 ).to_seconds() / HIVE_BLOCK_INTERVAL;
auto witness = db->get_scheduled_witness( miss_blocks );
auto block_time = db->get_slot_time( miss_blocks );
bp.generate_block( block_time , witness, init_account_priv_key, 0 );
BOOST_CHECK_EQUAL( db->head_block_num(), init_block_num + 1 );
BOOST_CHECK( db->head_block_time() == block_time );
BOOST_TEST_MESSAGE( "Generating a block through fixture" );
generate_block();
BOOST_CHECK_EQUAL( db->head_block_num(), init_block_num + 2 );
BOOST_CHECK( db->head_block_time() == block_time + HIVE_BLOCK_INTERVAL );
}
FC_LOG_AND_RETHROW();
}
BOOST_FIXTURE_TEST_CASE( hardfork_test, database_fixture )
{
try
{
try {
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
for( int i=1; i<argc; i++ )
{
const std::string arg = argv[i];
if( arg == "--record-assert-trip" )
fc::enable_record_assert_trip = true;
if( arg == "--show-test-names" )
std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl;
}
appbase::app().register_plugin< hive::plugins::account_history::account_history_plugin >();
db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >();
init_account_pub_key = init_account_priv_key.get_public_key();
appbase::app().initialize<
hive::plugins::account_history::account_history_plugin,
hive::plugins::debug_node::debug_node_plugin
>( argc, argv );
db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db();
BOOST_REQUIRE( db );
open_database();
generate_blocks( 2 );
vest( "initminer", 10000 );
// Fill up the rest of the required miners
for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ )
{
account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key );
fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value );
witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount );
}
validate_database();
} catch ( const fc::exception& e )
{
edump( (e.to_detail_string()) );
throw;
}
BOOST_TEST_MESSAGE( "Check hardfork not applied at genesis" );
BOOST_REQUIRE( db->has_hardfork( 0 ) );
BOOST_REQUIRE( !db->has_hardfork( HIVE_HARDFORK_0_1 ) );
BOOST_TEST_MESSAGE( "Generate blocks up to the hardfork time and check hardfork still not applied" );
generate_blocks( fc::time_point_sec( HIVE_HARDFORK_0_1_TIME - HIVE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db->has_hardfork( 0 ) );
BOOST_REQUIRE( !db->has_hardfork( HIVE_HARDFORK_0_1 ) );
auto itr = db->get_index< account_history_index >().indices().get< by_id >().end();
itr--;
const auto last_ah_id = itr->get_id();
BOOST_TEST_MESSAGE( "Generate a block and check hardfork is applied" );
generate_block();
string op_msg = "Testnet: Hardfork applied";
itr = db->get_index< account_history_index >().indices().get< by_id >().upper_bound(last_ah_id);
/// Skip another producer_reward_op generated at last produced block
++itr;
ilog("Looked up AH-id: ${a}, found: ${i}", ("a", last_ah_id)("i", itr->get_id()));
/// Original AH record points (by_id) actual operation data. We need to query for it again
const buffer_type& _serialized_op = db->get(itr->op).serialized_op;
auto last_op = fc::raw::unpack_from_vector< hive::chain::operation >(_serialized_op);
BOOST_REQUIRE( db->has_hardfork( 0 ) );
BOOST_REQUIRE( db->has_hardfork( HIVE_HARDFORK_0_1 ) );
operation hardfork_vop = hardfork_operation( HIVE_HARDFORK_0_1 );
BOOST_REQUIRE(last_op == hardfork_vop);
BOOST_REQUIRE(db->get(itr->op).timestamp == db->head_block_time());
BOOST_TEST_MESSAGE( "Testing hardfork is only applied once" );
generate_block();
auto processed_op = last_op;
/// Continue (starting from last HF op position), but skip last HF op
for(++itr; itr != db->get_index< account_history_index >().indices().get< by_id >().end(); ++itr)
{
const auto& ahRecord = *itr;
const buffer_type& _serialized_op = db->get(ahRecord.op).serialized_op;
processed_op = fc::raw::unpack_from_vector< hive::chain::operation >(_serialized_op);
}
/// There shall be no more hardfork ops after last one.
BOOST_REQUIRE(processed_op.which() != hardfork_vop.which());
BOOST_REQUIRE( db->has_hardfork( 0 ) );
BOOST_REQUIRE( db->has_hardfork( HIVE_HARDFORK_0_1 ) );
/// Search again for pre-HF operation
itr = db->get_index< account_history_index >().indices().get< by_id >().upper_bound(last_ah_id);
/// Skip another producer_reward_op generated at last produced block
++itr;
/// Here last HF vop shall be pointed, with its original time.
BOOST_REQUIRE( db->get(itr->op).timestamp == db->head_block_time() - HIVE_BLOCK_INTERVAL );
}
catch( fc::exception& e )
{
db->wipe( data_dir->path(), data_dir->path(), true );
throw e;
}
catch( std::exception& e )
{
db->wipe( data_dir->path(), data_dir->path(), true );
throw e;
}
db->wipe( data_dir->path(), data_dir->path(), true );
}
BOOST_FIXTURE_TEST_CASE( generate_block_size, clean_database_fixture )
{
try
{
db_plugin->debug_update( [=]( database& db )
{
db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo )
{
gpo.maximum_block_size = HIVE_MIN_BLOCK_SIZE_LIMIT;
});
});
generate_block();
signed_transaction tx;
tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION );
transfer_operation op;
op.from = HIVE_INIT_MINER_NAME;
op.to = HIVE_TEMP_ACCOUNT;
op.amount = asset( 1000, HIVE_SYMBOL );
// tx minus op is 79 bytes
// op is 33 bytes (32 for op + 1 byte static variant tag)
// total is 65254
// Original generation logic only allowed 115 bytes for the header
// We are targetting a size (minus header) of 65421 which creates a block of "size" 65535
// This block will actually be larger because the header estimates is too small
for( size_t i = 0; i < 1975; i++ )
{
tx.operations.push_back( op );
}
sign( tx, init_account_priv_key );
db->push_transaction( tx, 0 );
// Second transaction, tx minus op is 78 (one less byte for operation vector size)
// We need a 88 byte op. We need a 22 character memo (1 byte for length) 55 = 32 (old op) + 55 + 1
op.memo = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123";
tx.clear();
tx.operations.push_back( op );
sign( tx, init_account_priv_key );
db->push_transaction( tx, 0 );
generate_block();
// The last transfer should have been delayed due to size
auto head_block = db->fetch_block_by_number( db->head_block_num() );
BOOST_REQUIRE( head_block->transactions.size() == 1 );
}
FC_LOG_AND_RETHROW()
}
BOOST_AUTO_TEST_SUITE_END()
#endif
| 37.323144
| 155
| 0.700012
|
VIM-Arcange
|
dc610e697032f0d5d9c7a6524aeb34984041dec7
| 11,458
|
hpp
|
C++
|
3rdparty/libprocess/3rdparty/stout/include/stout/duration.hpp
|
yisun99/yisun
|
0bef3cdd0de61d4c5e10e1f995caffbaff0c6856
|
[
"Apache-2.0"
] | 5
|
2016-04-09T00:39:28.000Z
|
2019-10-08T18:10:24.000Z
|
include/stout/duration.hpp
|
euskadi31/stout-cpp
|
85850386348c9996a9700421993c71b13bf0c24c
|
[
"Apache-2.0"
] | null | null | null |
include/stout/duration.hpp
|
euskadi31/stout-cpp
|
85850386348c9996a9700421993c71b13bf0c24c
|
[
"Apache-2.0"
] | null | null | null |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_DURATION_HPP__
#define __STOUT_DURATION_HPP__
#include <ctype.h> // For 'isdigit'.
#include <limits.h> // For 'LLONG_(MAX|MIN)'.
// For 'timeval'.
#ifndef __WINDOWS__
#include <time.h>
#endif // __WINDOWS__
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include "error.hpp"
#include "numify.hpp"
#include "try.hpp"
class Duration
{
public:
static Try<Duration> parse(const std::string& s)
{
// TODO(benh): Support negative durations (i.e., starts with '-').
size_t index = 0;
while (index < s.size()) {
if (isdigit(s[index]) || s[index] == '.') {
index++;
continue;
}
Try<double> value = numify<double>(s.substr(0, index));
if (value.isError()) {
return Error(value.error());
}
const std::string unit = s.substr(index);
if (unit == "ns") {
return Duration(value.get(), NANOSECONDS);
} else if (unit == "us") {
return Duration(value.get(), MICROSECONDS);
} else if (unit == "ms") {
return Duration(value.get(), MILLISECONDS);
} else if (unit == "secs") {
return Duration(value.get(), SECONDS);
} else if (unit == "mins") {
return Duration(value.get(), MINUTES);
} else if (unit == "hrs") {
return Duration(value.get(), HOURS);
} else if (unit == "days") {
return Duration(value.get(), DAYS);
} else if (unit == "weeks") {
return Duration(value.get(), WEEKS);
} else {
return Error("Unknown duration unit '" + unit + "'");
}
}
return Error("Invalid duration '" + s + "'");
}
static Try<Duration> create(double seconds);
Duration() : nanos(0) {}
explicit Duration(const timeval& t)
{
nanos = t.tv_sec * SECONDS + t.tv_usec * MICROSECONDS;
}
int64_t ns() const { return nanos; }
double us() const { return static_cast<double>(nanos) / MICROSECONDS; }
double ms() const { return static_cast<double>(nanos) / MILLISECONDS; }
double secs() const { return static_cast<double>(nanos) / SECONDS; }
double mins() const { return static_cast<double>(nanos) / MINUTES; }
double hrs() const { return static_cast<double>(nanos) / HOURS; }
double days() const { return static_cast<double>(nanos) / DAYS; }
double weeks() const { return static_cast<double>(nanos) / WEEKS; }
struct timeval timeval() const
{
struct timeval t;
t.tv_sec = secs();
t.tv_usec = us() - (t.tv_sec * MILLISECONDS);
return t;
}
bool operator<(const Duration& d) const { return nanos < d.nanos; }
bool operator<=(const Duration& d) const { return nanos <= d.nanos; }
bool operator>(const Duration& d) const { return nanos > d.nanos; }
bool operator>=(const Duration& d) const { return nanos >= d.nanos; }
bool operator==(const Duration& d) const { return nanos == d.nanos; }
bool operator!=(const Duration& d) const { return nanos != d.nanos; }
Duration& operator+=(const Duration& that)
{
nanos += that.nanos;
return *this;
}
Duration& operator-=(const Duration& that)
{
nanos -= that.nanos;
return *this;
}
Duration& operator*=(double multiplier)
{
nanos = static_cast<int64_t>(nanos * multiplier);
return *this;
}
Duration& operator/=(double divisor)
{
nanos = static_cast<int64_t>(nanos / divisor);
return *this;
}
Duration operator+(const Duration& that) const
{
Duration sum = *this;
sum += that;
return sum;
}
Duration operator-(const Duration& that) const
{
Duration diff = *this;
diff -= that;
return diff;
}
Duration operator*(double multiplier) const
{
Duration product = *this;
product *= multiplier;
return product;
}
Duration operator/(double divisor) const
{
Duration quotient = *this;
quotient /= divisor;
return quotient;
}
// TODO(xujyan): Use constexpr for the following variables after
// switching to C++11.
// A constant holding the maximum value a Duration can have.
static Duration max();
// A constant holding the minimum (negative) value a Duration can
// have.
static Duration min();
// A constant holding a Duration of a "zero" value.
static Duration zero() { return Duration(); }
protected:
static const int64_t NANOSECONDS = 1;
static const int64_t MICROSECONDS = 1000 * NANOSECONDS;
static const int64_t MILLISECONDS = 1000 * MICROSECONDS;
static const int64_t SECONDS = 1000 * MILLISECONDS;
static const int64_t MINUTES = 60 * SECONDS;
static const int64_t HOURS = 60 * MINUTES;
static const int64_t DAYS = 24 * HOURS;
static const int64_t WEEKS = 7 * DAYS;
// For the Seconds, Minutes, Hours, Days & Weeks constructor.
Duration(int32_t value, int64_t unit)
: nanos(value * unit) {}
// For the Nanoseconds, Microseconds, Milliseconds constructor.
Duration(int64_t value, int64_t unit)
: nanos(value * unit) {}
private:
// Used only by "parse".
Duration(double value, int64_t unit)
: nanos(static_cast<int64_t>(value * unit)) {}
int64_t nanos;
friend std::ostream& operator<<(
std::ostream& stream,
const Duration& duration);
};
class Nanoseconds : public Duration
{
public:
explicit Nanoseconds(int64_t nanoseconds)
: Duration(nanoseconds, NANOSECONDS) {}
Nanoseconds(const Duration& d) : Duration(d) {}
double value() const { return static_cast<double>(this->ns()); }
static std::string units() { return "ns"; }
};
class Microseconds : public Duration
{
public:
explicit Microseconds(int64_t microseconds)
: Duration(microseconds, MICROSECONDS) {}
Microseconds(const Duration& d) : Duration(d) {}
double value() const { return this->us(); }
static std::string units() { return "us"; }
};
class Milliseconds : public Duration
{
public:
explicit Milliseconds(int64_t milliseconds)
: Duration(milliseconds, MILLISECONDS) {}
Milliseconds(const Duration& d) : Duration(d) {}
double value() const { return this->ms(); }
static std::string units() { return "ms"; }
};
class Seconds : public Duration
{
public:
explicit Seconds(int64_t seconds)
: Duration(seconds, SECONDS) {}
Seconds(const Duration& d) : Duration(d) {}
double value() const { return this->secs(); }
static std::string units() { return "secs"; }
};
class Minutes : public Duration
{
public:
explicit Minutes(int32_t minutes)
: Duration(minutes, MINUTES) {}
Minutes(const Duration& d) : Duration(d) {}
double value() const { return this->mins(); }
static std::string units() { return "mins"; }
};
class Hours : public Duration
{
public:
explicit Hours(int32_t hours)
: Duration(hours, HOURS) {}
Hours(const Duration& d) : Duration(d) {}
double value() const { return this->hrs(); }
static std::string units() { return "hrs"; }
};
class Days : public Duration
{
public:
explicit Days(int32_t days)
: Duration(days, DAYS) {}
Days(const Duration& d) : Duration(d) {}
double value() const { return this->days(); }
static std::string units() { return "days"; }
};
class Weeks : public Duration
{
public:
explicit Weeks(int32_t value) : Duration(value, WEEKS) {}
Weeks(const Duration& d) : Duration(d) {}
double value() const { return this->weeks(); }
static std::string units() { return "weeks"; }
};
inline std::ostream& operator<<(std::ostream& stream, const Duration& duration_)
{
long precision = stream.precision();
// Output the duration in full double precision.
stream.precision(std::numeric_limits<double>::digits10);
// Parse the duration as the sign and the absolute value.
Duration duration = duration_;
if (duration_ < Duration::zero()) {
stream << "-";
// Duration::min() may not be representable as a positive Duration.
if (duration_ == Duration::min()) {
duration = Duration::max();
} else {
duration = duration_ * -1;
}
}
// First determine which bucket of time unit the duration falls into
// then check whether the duration can be represented as a whole
// number with this time unit or a smaller one.
// e.g. 1.42857142857143weeks falls into the 'Weeks' bucket but
// reads better with a smaller unit: '10days'. So we use 'days'
// instead of 'weeks' to output the duration.
int64_t nanoseconds = duration.ns();
if (duration < Microseconds(1)) {
stream << duration.ns() << Nanoseconds::units();
} else if (duration < Milliseconds(1)) {
if (nanoseconds % Duration::MICROSECONDS != 0) {
// We can't get a whole number using this unit but we can at
// one level down.
stream << duration.ns() << Nanoseconds::units();
} else {
stream << duration.us() << Microseconds::units();
}
} else if (duration < Seconds(1)) {
if (nanoseconds % Duration::MILLISECONDS != 0 &&
nanoseconds % Duration::MICROSECONDS == 0) {
stream << duration.us() << Microseconds::units();
} else {
stream << duration.ms() << Milliseconds::units();
}
} else if (duration < Minutes(1)) {
if (nanoseconds % Duration::SECONDS != 0 &&
nanoseconds % Duration::MILLISECONDS == 0) {
stream << duration.ms() << Milliseconds::units();
} else {
stream << duration.secs() << Seconds::units();
}
} else if (duration < Hours(1)) {
if (nanoseconds % Duration::MINUTES != 0 &&
nanoseconds % Duration::SECONDS == 0) {
stream << duration.secs() << Seconds::units();
} else {
stream << duration.mins() << Minutes::units();
}
} else if (duration < Days(1)) {
if (nanoseconds % Duration::HOURS != 0 &&
nanoseconds % Duration::MINUTES == 0) {
stream << duration.mins() << Minutes::units();
} else {
stream << duration.hrs() << Hours::units();
}
} else if (duration < Weeks(1)) {
if (nanoseconds % Duration::DAYS != 0 &&
nanoseconds % Duration::HOURS == 0) {
stream << duration.hrs() << Hours::units();
} else {
stream << duration.days() << Days::units();
}
} else {
if (nanoseconds % Duration::WEEKS != 0 &&
nanoseconds % Duration::DAYS == 0) {
stream << duration.days() << Days::units();
} else {
stream << duration.weeks() << Weeks::units();
}
}
// Return the stream to original formatting state.
stream.precision(precision);
return stream;
}
inline Try<Duration> Duration::create(double seconds)
{
if (seconds * SECONDS > LLONG_MAX || seconds * SECONDS < LLONG_MIN) {
return Error("Argument out of the range that a Duration can represent due "
"to int64_t's size limit");
}
return Nanoseconds(static_cast<int64_t>(seconds * SECONDS));
}
inline Duration Duration::max() { return Nanoseconds(LLONG_MAX); }
inline Duration Duration::min() { return Nanoseconds(LLONG_MIN); }
#endif // __STOUT_DURATION_HPP__
| 27.346062
| 80
| 0.637459
|
yisun99
|
dc6cca282810a3b1d2e7698ba962062aa9a9be91
| 2,481
|
hpp
|
C++
|
test/core/point_swap.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
test/core/point_swap.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
test/core/point_swap.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2019 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
#ifndef CYNODELIC_TESELA_TEST_CORE_POINT_SWAP_HPP
#define CYNODELIC_TESELA_TEST_CORE_POINT_SWAP_HPP
CYNODELIC_TESTER_TEST_CASE(point_swap);
CYNODELIC_TESTER_SECTION(point_swap,member_function)
{
tsl::point pt1(37,98);
tsl::point pt2(11,90);
tsl::point pt1_new = pt1;
tsl::point pt2_new = pt2;
CYNODELIC_TESTER_MESSAGE
<< "**** Before swapping ****" << tst::newline
<< " pt1_new.x = " << pt1_new.x << tst::newline
<< " pt1_new.y = " << pt1_new.y << tst::newline
<< " pt2_new.x = " << pt2_new.x << tst::newline
<< " pt2_new.y = " << pt2_new.y;
pt1_new.swap(pt2_new);
CYNODELIC_TESTER_MESSAGE
<< "**** After swapping ****" << tst::newline
<< " pt1_new.x = " << pt1_new.x << tst::newline
<< " pt1_new.y = " << pt1_new.y << tst::newline
<< " pt2_new.x = " << pt2_new.x << tst::newline
<< " pt2_new.y = " << pt2_new.y;
CYNODELIC_TESTER_ASSERT_NOT_EQUALS(pt1_new.x,pt2_new.x);
CYNODELIC_TESTER_ASSERT_NOT_EQUALS(pt1_new.y,pt2_new.y);
CYNODELIC_TESTER_ASSERT_EQUALS(pt1.x,pt2_new.x);
CYNODELIC_TESTER_ASSERT_EQUALS(pt1.y,pt2_new.y);
CYNODELIC_TESTER_ASSERT_EQUALS(pt2.x,pt1_new.x);
CYNODELIC_TESTER_ASSERT_EQUALS(pt2.y,pt1_new.y);
}
CYNODELIC_TESTER_SECTION(point_swap,std_swap_function)
{
tsl::point pt1(37,98);
tsl::point pt2(11,90);
tsl::point pt1_new = pt1;
tsl::point pt2_new = pt2;
CYNODELIC_TESTER_MESSAGE
<< "**** Before swapping ****" << tst::newline
<< " pt1_new.x = " << pt1_new.x << tst::newline
<< " pt1_new.y = " << pt1_new.y << tst::newline
<< " pt2_new.x = " << pt2_new.x << tst::newline
<< " pt2_new.y = " << pt2_new.y;
std::swap(pt1_new,pt2_new);
CYNODELIC_TESTER_MESSAGE
<< "**** After swapping ****" << tst::newline
<< " pt1_new.x = " << pt1_new.x << tst::newline
<< " pt1_new.y = " << pt1_new.y << tst::newline
<< " pt2_new.x = " << pt2_new.x << tst::newline
<< " pt2_new.y = " << pt2_new.y;
CYNODELIC_TESTER_ASSERT_NOT_EQUALS(pt1_new.x,pt2_new.x);
CYNODELIC_TESTER_ASSERT_NOT_EQUALS(pt1_new.y,pt2_new.y);
CYNODELIC_TESTER_ASSERT_EQUALS(pt1.x,pt2_new.x);
CYNODELIC_TESTER_ASSERT_EQUALS(pt1.y,pt2_new.y);
CYNODELIC_TESTER_ASSERT_EQUALS(pt2.x,pt1_new.x);
CYNODELIC_TESTER_ASSERT_EQUALS(pt2.y,pt1_new.y);
}
#endif // CYNODELIC_TESELA_TEST_CORE_POINT_SWAP_HPP
| 32.220779
| 80
| 0.680371
|
cynodelic
|
dc6cd2aa48636d5639c5eb07fa16b75efc974c3f
| 11,593
|
cpp
|
C++
|
tests/DrawOpAtlasTest.cpp
|
Rusino/skia
|
b3929a01f476c63e5358e97128ba7eb9f14e806e
|
[
"BSD-3-Clause"
] | 1
|
2019-03-25T15:37:48.000Z
|
2019-03-25T15:37:48.000Z
|
tests/DrawOpAtlasTest.cpp
|
bryphe/esy-skia
|
9810a02f28270535de10b584bffc536182224c83
|
[
"BSD-3-Clause"
] | null | null | null |
tests/DrawOpAtlasTest.cpp
|
bryphe/esy-skia
|
9810a02f28270535de10b584bffc536182224c83
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#include "GrContext.h"
#include "GrContextFactory.h"
#include "GrContextPriv.h"
#include "GrDeferredUpload.h"
#include "GrDrawOpAtlas.h"
#include "GrDrawingManager.h"
#include "GrMemoryPool.h"
#include "GrOnFlushResourceProvider.h"
#include "GrOpFlushState.h"
#include "GrRenderTargetContext.h"
#include "GrSurfaceProxyPriv.h"
#include "GrTextureProxy.h"
#include "GrTypesPriv.h"
#include "GrXferProcessor.h"
#include "SkBitmap.h"
#include "SkColor.h"
#include "SkColorSpace.h"
#include "SkIPoint16.h"
#include "SkImageInfo.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkPoint.h"
#include "SkRefCnt.h"
#include "Test.h"
#include "ops/GrDrawOp.h"
#include "text/GrAtlasManager.h"
#include "text/GrTextContext.h"
#include "text/GrTextTarget.h"
#include <memory>
class GrResourceProvider;
static const int kNumPlots = 2;
static const int kPlotSize = 32;
static const int kAtlasSize = kNumPlots * kPlotSize;
int GrDrawOpAtlas::numAllocated_TestingOnly() const {
int count = 0;
for (uint32_t i = 0; i < this->maxPages(); ++i) {
if (fProxies[i]->isInstantiated()) {
++count;
}
}
return count;
}
void GrAtlasManager::setMaxPages_TestingOnly(uint32_t maxPages) {
for (int i = 0; i < kMaskFormatCount; i++) {
if (fAtlases[i]) {
fAtlases[i]->setMaxPages_TestingOnly(maxPages);
}
}
}
void GrDrawOpAtlas::setMaxPages_TestingOnly(uint32_t maxPages) {
SkASSERT(!fNumActivePages);
fMaxPages = maxPages;
}
void EvictionFunc(GrDrawOpAtlas::AtlasID atlasID, void*) {
SkASSERT(0); // The unit test shouldn't exercise this code path
}
static void check(skiatest::Reporter* r, GrDrawOpAtlas* atlas,
uint32_t expectedActive, uint32_t expectedMax, int expectedAlloced) {
REPORTER_ASSERT(r, expectedActive == atlas->numActivePages());
REPORTER_ASSERT(r, expectedMax == atlas->maxPages());
REPORTER_ASSERT(r, expectedAlloced == atlas->numAllocated_TestingOnly());
}
class TestingUploadTarget : public GrDeferredUploadTarget {
public:
TestingUploadTarget() { }
const GrTokenTracker* tokenTracker() final { return &fTokenTracker; }
GrTokenTracker* writeableTokenTracker() { return &fTokenTracker; }
GrDeferredUploadToken addInlineUpload(GrDeferredTextureUploadFn&&) final {
SkASSERT(0); // this test shouldn't invoke this code path
return fTokenTracker.nextDrawToken();
}
virtual GrDeferredUploadToken addASAPUpload(GrDeferredTextureUploadFn&& upload) final {
return fTokenTracker.nextTokenToFlush();
}
void issueDrawToken() { fTokenTracker.issueDrawToken(); }
void flushToken() { fTokenTracker.flushToken(); }
private:
GrTokenTracker fTokenTracker;
typedef GrDeferredUploadTarget INHERITED;
};
static bool fill_plot(GrDrawOpAtlas* atlas,
GrResourceProvider* resourceProvider,
GrDeferredUploadTarget* target,
GrDrawOpAtlas::AtlasID* atlasID,
int alpha) {
SkImageInfo ii = SkImageInfo::MakeA8(kPlotSize, kPlotSize);
SkBitmap data;
data.allocPixels(ii);
data.eraseARGB(alpha, 0, 0, 0);
SkIPoint16 loc;
GrDrawOpAtlas::ErrorCode code;
code = atlas->addToAtlas(resourceProvider, atlasID, target, kPlotSize, kPlotSize,
data.getAddr(0, 0), &loc);
return GrDrawOpAtlas::ErrorCode::kSucceeded == code;
}
// This is a basic DrawOpAtlas test. It simply verifies that multitexture atlases correctly
// add and remove pages. Note that this is simulating flush-time behavior.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(BasicDrawOpAtlas, reporter, ctxInfo) {
auto context = ctxInfo.grContext();
auto proxyProvider = context->priv().proxyProvider();
auto resourceProvider = context->priv().resourceProvider();
auto drawingManager = context->priv().drawingManager();
GrOnFlushResourceProvider onFlushResourceProvider(drawingManager);
TestingUploadTarget uploadTarget;
GrBackendFormat format =
context->priv().caps()->getBackendFormatFromColorType(kAlpha_8_SkColorType);
std::unique_ptr<GrDrawOpAtlas> atlas = GrDrawOpAtlas::Make(
proxyProvider,
format,
kAlpha_8_GrPixelConfig,
kAtlasSize, kAtlasSize,
kAtlasSize/kNumPlots, kAtlasSize/kNumPlots,
GrDrawOpAtlas::AllowMultitexturing::kYes,
EvictionFunc, nullptr);
check(reporter, atlas.get(), 0, 4, 0);
// Fill up the first level
GrDrawOpAtlas::AtlasID atlasIDs[kNumPlots * kNumPlots];
for (int i = 0; i < kNumPlots * kNumPlots; ++i) {
bool result = fill_plot(atlas.get(), resourceProvider, &uploadTarget, &atlasIDs[i], i*32);
REPORTER_ASSERT(reporter, result);
check(reporter, atlas.get(), 1, 4, 1);
}
atlas->instantiate(&onFlushResourceProvider);
check(reporter, atlas.get(), 1, 4, 1);
// Force allocation of a second level
GrDrawOpAtlas::AtlasID atlasID;
bool result = fill_plot(atlas.get(), resourceProvider, &uploadTarget, &atlasID, 4*32);
REPORTER_ASSERT(reporter, result);
check(reporter, atlas.get(), 2, 4, 2);
// Simulate a lot of draws using only the first plot. The last texture should be compacted.
for (int i = 0; i < 512; ++i) {
atlas->setLastUseToken(atlasIDs[0], uploadTarget.tokenTracker()->nextDrawToken());
uploadTarget.issueDrawToken();
uploadTarget.flushToken();
atlas->compact(uploadTarget.tokenTracker()->nextTokenToFlush());
}
check(reporter, atlas.get(), 1, 4, 1);
}
// This test verifies that the GrAtlasTextOp::onPrepare method correctly handles a failure
// when allocating an atlas page.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrAtlasTextOpPreparation, reporter, ctxInfo) {
auto context = ctxInfo.grContext();
auto gpu = context->priv().getGpu();
auto resourceProvider = context->priv().resourceProvider();
auto resourceCache = context->priv().getResourceCache();
auto drawingManager = context->priv().drawingManager();
auto textContext = drawingManager->getTextContext();
auto opMemoryPool = context->priv().opMemoryPool();
GrBackendFormat format =
context->priv().caps()->getBackendFormatFromColorType(kRGBA_8888_SkColorType);
auto rtc = context->priv().makeDeferredRenderTargetContext(format,
SkBackingFit::kApprox,
32, 32,
kRGBA_8888_GrPixelConfig,
nullptr);
SkPaint paint;
paint.setColor(SK_ColorRED);
SkFont font;
font.setEdging(SkFont::Edging::kAlias);
const char* text = "a";
std::unique_ptr<GrDrawOp> op = textContext->createOp_TestingOnly(
context, textContext, rtc.get(), paint, font, SkMatrix::I(), text, 16, 16);
op->finalize(*context->priv().caps(), nullptr, GrFSAAType::kNone, GrClampType::kAuto);
TestingUploadTarget uploadTarget;
GrOpFlushState flushState(gpu, resourceProvider, resourceCache,
uploadTarget.writeableTokenTracker());
GrOpFlushState::OpArgs opArgs = {
op.get(),
rtc->asRenderTargetProxy(),
nullptr,
GrXferProcessor::DstProxy(nullptr, SkIPoint::Make(0, 0))
};
// Cripple the atlas manager so it can't allocate any pages. This will force a failure
// in the preparation of the text op
auto atlasManager = context->priv().getAtlasManager();
unsigned int numProxies;
atlasManager->getProxies(kA8_GrMaskFormat, &numProxies);
atlasManager->setMaxPages_TestingOnly(0);
flushState.setOpArgs(&opArgs);
op->prepare(&flushState);
flushState.setOpArgs(nullptr);
opMemoryPool->release(std::move(op));
}
void test_atlas_config(skiatest::Reporter* reporter, int maxTextureSize, size_t maxBytes,
GrMaskFormat maskFormat, SkISize expectedDimensions,
SkISize expectedPlotDimensions) {
GrDrawOpAtlasConfig config(maxTextureSize, maxBytes);
REPORTER_ASSERT(reporter, config.atlasDimensions(maskFormat) == expectedDimensions);
REPORTER_ASSERT(reporter, config.plotDimensions(maskFormat) == expectedPlotDimensions);
}
DEF_GPUTEST(GrDrawOpAtlasConfig_Basic, reporter, options) {
// 1/4 MB
test_atlas_config(reporter, 65536, 256 * 1024, kARGB_GrMaskFormat,
{ 256, 256 }, { 256, 256 });
test_atlas_config(reporter, 65536, 256 * 1024, kA8_GrMaskFormat,
{ 512, 512 }, { 256, 256 });
// 1/2 MB
test_atlas_config(reporter, 65536, 512 * 1024, kARGB_GrMaskFormat,
{ 512, 256 }, { 256, 256 });
test_atlas_config(reporter, 65536, 512 * 1024, kA8_GrMaskFormat,
{ 1024, 512 }, { 256, 256 });
// 1 MB
test_atlas_config(reporter, 65536, 1024 * 1024, kARGB_GrMaskFormat,
{ 512, 512 }, { 256, 256 });
test_atlas_config(reporter, 65536, 1024 * 1024, kA8_GrMaskFormat,
{ 1024, 1024 }, { 256, 256 });
// 2 MB
test_atlas_config(reporter, 65536, 2 * 1024 * 1024, kARGB_GrMaskFormat,
{ 1024, 512 }, { 256, 256 });
test_atlas_config(reporter, 65536, 2 * 1024 * 1024, kA8_GrMaskFormat,
{ 2048, 1024 }, { 512, 256 });
// 4 MB
test_atlas_config(reporter, 65536, 4 * 1024 * 1024, kARGB_GrMaskFormat,
{ 1024, 1024 }, { 256, 256 });
test_atlas_config(reporter, 65536, 4 * 1024 * 1024, kA8_GrMaskFormat,
{ 2048, 2048 }, { 512, 512 });
// 8 MB
test_atlas_config(reporter, 65536, 8 * 1024 * 1024, kARGB_GrMaskFormat,
{ 2048, 1024 }, { 256, 256 });
test_atlas_config(reporter, 65536, 8 * 1024 * 1024, kA8_GrMaskFormat,
{ 2048, 2048 }, { 512, 512 });
// 16 MB (should be same as 8 MB)
test_atlas_config(reporter, 65536, 16 * 1024 * 1024, kARGB_GrMaskFormat,
{ 2048, 1024 }, { 256, 256 });
test_atlas_config(reporter, 65536, 16 * 1024 * 1024, kA8_GrMaskFormat,
{ 2048, 2048 }, { 512, 512 });
// 4MB, restricted texture size
test_atlas_config(reporter, 1024, 8 * 1024 * 1024, kARGB_GrMaskFormat,
{ 1024, 1024 }, { 256, 256 });
test_atlas_config(reporter, 1024, 8 * 1024 * 1024, kA8_GrMaskFormat,
{ 1024, 1024 }, { 256, 256 });
// 3 MB (should be same as 2 MB)
test_atlas_config(reporter, 65536, 3 * 1024 * 1024, kARGB_GrMaskFormat,
{ 1024, 512 }, { 256, 256 });
test_atlas_config(reporter, 65536, 3 * 1024 * 1024, kA8_GrMaskFormat,
{ 2048, 1024 }, { 512, 256 });
// minimum size
test_atlas_config(reporter, 65536, 0, kARGB_GrMaskFormat,
{ 256, 256 }, { 256, 256 });
test_atlas_config(reporter, 65536, 0, kA8_GrMaskFormat,
{ 512, 512 }, { 256, 256 });
}
| 38.643333
| 98
| 0.63038
|
Rusino
|
dc6d8aa6d6554e2b426e3e0a64295fff0e95d69c
| 1,678
|
hpp
|
C++
|
irohad/network/mst_transport.hpp
|
e-ivkov/iroha
|
5fec6c585721ec98a7e2e5220ca5525099e5f670
|
[
"Apache-2.0"
] | 1
|
2020-05-15T10:02:38.000Z
|
2020-05-15T10:02:38.000Z
|
irohad/network/mst_transport.hpp
|
e-ivkov/iroha
|
5fec6c585721ec98a7e2e5220ca5525099e5f670
|
[
"Apache-2.0"
] | 8
|
2017-12-25T05:25:58.000Z
|
2018-01-20T10:12:45.000Z
|
irohad/network/mst_transport.hpp
|
e-ivkov/iroha
|
5fec6c585721ec98a7e2e5220ca5525099e5f670
|
[
"Apache-2.0"
] | 1
|
2020-07-25T11:15:16.000Z
|
2020-07-25T11:15:16.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_MST_TRANSPORT_HPP
#define IROHA_MST_TRANSPORT_HPP
#include <memory>
#include "interfaces/common_objects/peer.hpp"
#include "multi_sig_transactions/state/mst_state.hpp"
namespace iroha {
namespace network {
/**
* Interface represents handler for multi-signature notifications
*/
class MstTransportNotification {
public:
/**
* Handler method for updating state, when new data received
* @param from - key of the peer emitted the state
* @param new_state - state propagated from peer
*/
virtual void onNewState(const shared_model::crypto::PublicKey &from,
MstState new_state) = 0;
virtual ~MstTransportNotification() = default;
};
/**
* Interface of transport
* for propagating multi-signature transactions in network
*/
class MstTransport {
public:
/**
* Subscribe object for receiving notifications
* @param notification - object that will be notified on updates
*/
virtual void subscribe(
std::shared_ptr<MstTransportNotification> notification) = 0;
/**
* Share state with other peer
* @param to - peer recipient of message
* @param providing_state - state for transmitting
*/
virtual void sendState(const shared_model::interface::Peer &to,
const MstState &providing_state) = 0;
virtual ~MstTransport() = default;
};
} // namespace network
} // namespace iroha
#endif // IROHA_MST_TRANSPORT_HPP
| 28.931034
| 74
| 0.648391
|
e-ivkov
|
dc6f1dd8e442ecb1f4ac1c1cc129613b287e3b5b
| 4,516
|
cpp
|
C++
|
ass5.cpp
|
anaghad01/OOP_assignments
|
6b1dccb9ef214d72b5be986bfc0fdb56a0838723
|
[
"MIT"
] | null | null | null |
ass5.cpp
|
anaghad01/OOP_assignments
|
6b1dccb9ef214d72b5be986bfc0fdb56a0838723
|
[
"MIT"
] | null | null | null |
ass5.cpp
|
anaghad01/OOP_assignments
|
6b1dccb9ef214d72b5be986bfc0fdb56a0838723
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
template <class T>
class vector
{
T *v;
int size,a;
public:
int i;
vector()
{ int a;
cout<<"\nWELCOME !!!\n";
cout<<"\nEnter size of vector: \n";
cin>>a;
size=a;
v= new T[size];
for(int i=0; i< size; i++)
{v[i]=0;}
}
void create();
void modify();
void multiply();
void bubbleSort();
void display();
};
//**********************************************************************************************************
template <class T>
void vector<T>::create()
{ cout<<"\nEnter values for vector:\n";
for( i=0; i< size; i++)
{
cin>>v[i];
}
/*cout<<"\nThe entered values for vector are: \n"<<"(";
for( i=0; i< size; i++)
{
cout<<v[i]<<", ";
}
cout<<")";*/
}
//**********************************************************************************************************
/*template <class T>
void vector<T>::modify()
{ int p,q;
cout<<"\nEnter the value to be changed :\n";
cin>>p;
cout<<"\nEnter your desired value:\n";
cin>>q;
for( i=0; i< size; i++)
{
if(v[i]==p)
{v[i]=q;}
}
cout<<"\nChanged vector values are:\n"<<"(";
for( i=0; i< size; i++)
{
cout<<v[i]<<", ";
}
cout<<")";
}*/
//************************************************************************************************************
/*template <class T>
void vector<T>::multiply()
{ int k;
cout<<"\nEnter the multiplier :\n";
cin>>k;
for(i=0; i< size; i++)
{
v[i]= k*v[i];
}
cout<<"\nChanged vector values are:\n"<<"(";
for( i=0; i< size; i++)
{
cout<<v[i]<<", ";
}
cout<<")";
}*/
//***********************************************************************************************************
template <class T>
void vector <T>::bubbleSort()
{
for(int i=0; i<size-1; i++){
for(int j=size-1; i<j; j--){
if(v[j]<v[j-1]){
T temp= v[j];
v[j]= v[j-1];
v[j-1]= temp;
}
}
}}
//**********************************************************************************************************
template <class T>
void vector<T>::display()
{
cout<<"\nChanged vector values after all above operations are performed is :\n"<<"(";
for( i=0; i< size; i++)
{
cout<<v[i]<<", ";
}
cout<<")";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main(){
vector <int> V1;
vector <float> V2;
vector <char> V3;
int ch, v;
cout<<"1. Int";
cout<<"2. Float";
cout<<"3. String";
cin>>v;
switch(v)
{
case 1:{
cout<<"\n1. Create";
//cout<<"\n2. Modify";
//cout<<"\n3. Multiply";
cout<<"\n4. Bubble Sort";
cout<<"\n5. Display\n";
cin>>ch;
switch(ch)
{
case 1:{ V1.create(); break;}
//case 2:{ V1.modify();break;}
//case 3: { V1.multiply(); break;}
case 4:{V1.bubbleSort(); break;}
case 5:{ V1.display(); break;}
}while(ch<6);break;
}
case 2:{
cout<<"\n1. Create";
//cout<<"\n2. Modify";
//cout<<"\n3. Multiply";
cout<<"\n4. Bubble Sort";
cout<<"\n5. Display\n";
cin>>ch;
switch(ch)
{
case 1:{ V2.create(); break;}
//case 2:{ V2.modify();break;}
//case 3: { V2.multiply(); break;}
case 4:{V2.bubbleSort(); break;}
case 5:{ V2.display(); break;}
}while(ch<6);break;
}
case 3:{
cout<<"\n1. Create";
//cout<<"\n2. Modify";
//cout<<"\n3. Multiply";
cout<<"\n4. Bubble Sort";
cout<<"\n5. Display\n";
cin>>ch;
switch(ch)
{
case 1:{ V3.create(); break;}
//case 2:{ V3.modify();break;}
//case 3: { V3.multiply(); break;}
case 4:{V3.bubbleSort(); break;}
case 5:{ V3.display(); break;}
}while(ch<6);break;
}
}while(v<=3);return 0;
}
| 26.409357
| 121
| 0.340788
|
anaghad01
|
dc7202f42cdc0224d9e771e14814374826086357
| 239
|
cpp
|
C++
|
COREDLL/mmsystem_wcecl.cpp
|
feel-the-dz3n/wcecl
|
ea29d587056625b40bf942d9cba0fb38cb848aed
|
[
"MIT"
] | 54
|
2019-07-05T22:03:30.000Z
|
2022-03-28T08:16:17.000Z
|
COREDLL/mmsystem_wcecl.cpp
|
feel-the-dz3n/wcecl
|
ea29d587056625b40bf942d9cba0fb38cb848aed
|
[
"MIT"
] | 16
|
2019-06-24T21:29:05.000Z
|
2020-06-16T19:04:57.000Z
|
COREDLL/mmsystem_wcecl.cpp
|
feel-the-dz3n/WinCeCompatLayer
|
ea29d587056625b40bf942d9cba0fb38cb848aed
|
[
"MIT"
] | 9
|
2019-07-31T23:49:09.000Z
|
2022-03-30T15:32:10.000Z
|
// mmsystem_wcecl.cpp : wce/mmsystem.h functions
#include "stdafx.h"
// Functions
BOOL APIENTRY sndPlaySoundW_WCECL(LPCWSTR lpszSoundName, UINT fuSound)
{
auto result = sndPlaySoundW(lpszSoundName, fuSound);
return result;
}
// Stubs
| 18.384615
| 70
| 0.76569
|
feel-the-dz3n
|
dc787d6417abc7b0023157a0a796afc511f0257b
| 676
|
cpp
|
C++
|
src/cpp/uml/forkNode.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | null | null | null |
src/cpp/uml/forkNode.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | 1
|
2022-02-25T18:14:21.000Z
|
2022-03-10T08:59:55.000Z
|
src/cpp/uml/forkNode.cpp
|
nemears/uml-cpp
|
d72c8b5506f391f2b6a5696972ff8da7ec10bd21
|
[
"MIT"
] | null | null | null |
#include "uml/forkNode.h"
#include "uml/activity.h"
#include "uml/activityEdge.h"
#include "uml/package.h"
#include "uml/property.h"
#include "uml/generalization.h"
#include "uml/dataType.h"
#include "uml/association.h"
#include "uml/interruptibleActivityRegion.h"
#include "uml/stereotype.h"
#include "uml/interface.h"
#include "uml/deployment.h"
#include "uml/umlPtr.h"
using namespace UML;
ForkNode::ForkNode() : Element(ElementType::FORK_NODE) {
}
ForkNode::~ForkNode() {
}
bool ForkNode::isSubClassOf(ElementType eType) const {
bool ret = ControlNode::isSubClassOf(eType);
if (!ret) {
ret = eType == ElementType::FORK_NODE;
}
return ret;
}
| 20.484848
| 56
| 0.70858
|
nemears
|
dc7bfda543d2a6308bc27a88a5bbbfde873090f9
| 2,639
|
cpp
|
C++
|
src/budget/UpdateConditionCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | 2
|
2016-07-17T02:12:44.000Z
|
2016-11-22T14:04:55.000Z
|
src/budget/UpdateConditionCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | null | null | null |
src/budget/UpdateConditionCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2013 Kyle Treubig
*
* 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.
*/
// Qt include(s)
#include <QtCore>
// UnderBudget include(s)
#include "budget/AssignmentRule.hpp"
#include "budget/AssignmentRules.hpp"
#include "budget/UpdateConditionCommand.hpp"
namespace ub {
//------------------------------------------------------------------------------
const int UpdateConditionCommand::ID = 723434;
//------------------------------------------------------------------------------
UpdateConditionCommand::UpdateConditionCommand(AssignmentRules* rules,
uint ruleId, int index, const AssignmentRule::Condition& condition,
QUndoCommand* parent)
: QUndoCommand(parent), rules(rules), ruleId(ruleId), index(index),
newCondition(condition)
{
AssignmentRule* rule = rules->find(ruleId);
if (rule)
{
oldCondition = rule->conditionAt(index);
}
}
//------------------------------------------------------------------------------
int UpdateConditionCommand::id() const
{
return ID;
}
//------------------------------------------------------------------------------
bool UpdateConditionCommand::mergeWith(const QUndoCommand* command)
{
if (command->id() != id())
return false;
// Only merge if change is for the same rule and condition index
uint otherId =
static_cast<const UpdateConditionCommand*>(command)->ruleId;
int otherIndex =
static_cast<const UpdateConditionCommand*>(command)->index;
if (otherId != ruleId)
return false;
if (otherIndex != index)
return false;
// Use new condition parameters from the merged command
newCondition = static_cast<const UpdateConditionCommand*>(command)->newCondition;
return true;
}
//------------------------------------------------------------------------------
void UpdateConditionCommand::redo()
{
AssignmentRule* rule = rules->find(ruleId);
if (rule)
{
rule->updateCondition(newCondition, index);
}
}
//------------------------------------------------------------------------------
void UpdateConditionCommand::undo()
{
AssignmentRule* rule = rules->find(ruleId);
if (rule)
{
rule->updateCondition(oldCondition, index);
}
}
}
| 28.074468
| 82
| 0.604396
|
vimofthevine
|
dc86fa125f226279be449d03ff0a504e483cf1ed
| 808
|
cpp
|
C++
|
testOpenCP/testConcat.cpp
|
norishigefukushima/OpenCP
|
63090131ec975e834f85b04e84ec29b2893845b2
|
[
"BSD-3-Clause"
] | 137
|
2015-03-27T07:11:19.000Z
|
2022-03-30T05:58:22.000Z
|
testOpenCP/testConcat.cpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 2
|
2016-05-18T06:33:16.000Z
|
2016-07-11T17:39:17.000Z
|
testOpenCP/testConcat.cpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 43
|
2015-02-20T15:34:25.000Z
|
2022-01-27T14:59:37.000Z
|
#include <opencp.hpp>
using namespace std;
using namespace cv;
using namespace cp;
void testConcat()
{
vector<Mat> kodak24;
for (int i = 1; i < 25; i++)
{
Mat temp = imread(format("img/kodak/kodim%02d.png", i), 1);
if (temp.cols < temp.rows)transpose(temp, temp);
//imshow("a", temp); waitKey();
kodak24.push_back(temp);
}
Mat img;
cp::concat(kodak24, img, 4, 6);
cp::imshowResize("kodak24", img, Size(), 0.25, 0.25);
Mat temp;
cp::concatExtract(img, Size(768, 512), temp, 1, 1);
imshow("extract (1,1)", temp);
cp::concatExtract(img, Size(768, 512), temp, 12);
imshow("extract 12", temp);
vector<Mat> v;
cp::concatSplit(img, v, Size(768, 512));
imshow("concatSplit[3]", v[3]);
vector<Mat> v2;
cp::concatSplit(img, v2, 4, 6);
imshow("concatSplit[3] v2", v2[3]);
waitKey();
}
| 21.263158
| 61
| 0.632426
|
norishigefukushima
|
dc8e36d16102526dc4e41250f03850326765c6fa
| 492
|
cpp
|
C++
|
LeetCode/374.Guess_Number_Higher_or_Lower.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
LeetCode/374.Guess_Number_Higher_or_Lower.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
LeetCode/374.Guess_Number_Higher_or_Lower.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
long long int l = 0, r = n;
while(l < r) {
int mid = (l + r) >> 1;
int res = guess(mid);
if(res == 0) return mid;
else if(res == 1) l = mid + 1;
else r = mid;
}
return l;
}
};
| 24.6
| 81
| 0.497967
|
w181496
|
dc8f710144abf3cb27b139a164d56d130cd493e0
| 5,790
|
cpp
|
C++
|
JammaLib/src/base/GuiElement.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
JammaLib/src/base/GuiElement.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
JammaLib/src/base/GuiElement.cpp
|
malisimo/Jamma
|
69831e79a64e652e82aa41f8141e082c3899896b
|
[
"MIT"
] | null | null | null |
#include "GuiElement.h"
#include "glm/glm.hpp"
#include "glm/ext.hpp"
using namespace base;
using namespace utils;
using namespace actions;
using graphics::GlDrawContext;
using graphics::ImageParams;
using resources::ResourceLib;
GuiElement::GuiElement(GuiElementParams params) :
Drawable(params),
Moveable(params),
Sizeable(params),
_changesMade(false),
_guiParams(params),
_state(STATE_NORMAL),
_texture(ImageParams(DrawableParams{ params.Texture }, SizeableParams{ params.Size,params.MinSize }, "texture")),
_overTexture(ImageParams(DrawableParams{ params.OverTexture }, SizeableParams{ params.Size,params.MinSize }, "texture")),
_downTexture(ImageParams(DrawableParams{ params.DownTexture }, SizeableParams{ params.Size,params.MinSize }, "texture")),
_outTexture(ImageParams(DrawableParams{ params.OutTexture }, SizeableParams{ params.Size,params.MinSize }, "texture")),
_children({})
{
}
void GuiElement::Init()
{
InitReceivers();
for (auto& child : _children)
{
child->SetParent(GuiElement::shared_from_this());
child->Init();
}
}
void GuiElement::InitResources(resources::ResourceLib& resourceLib, bool forceInit)
{
ResourceUser::InitResources(resourceLib, forceInit);
for (auto& child : _children)
child->InitResources(resourceLib, forceInit);
};
void GuiElement::SetSize(Size2d size)
{
Sizeable::SetSize(size);
_texture.SetSize(_sizeParams.Size);
_overTexture.SetSize(_sizeParams.Size);
_downTexture.SetSize(_sizeParams.Size);
_outTexture.SetSize(_sizeParams.Size);
}
std::vector<JobAction> GuiElement::CommitChanges()
{
std::vector<JobAction> jobList = {};
if (_changesMade)
{
auto jobs = _CommitChanges();
if (!jobs.empty())
jobList.insert(jobList.end(), jobs.begin(), jobs.end());
}
_changesMade = false;
for (auto& child : _children)
{
auto jobs = child->CommitChanges();
if (!jobs.empty())
jobList.insert(jobList.end(), jobs.begin(), jobs.end());
}
return jobList;
}
void GuiElement::Draw(DrawContext& ctx)
{
auto &glCtx = dynamic_cast<GlDrawContext&>(ctx);
auto pos = Position();
glCtx.PushMvp(glm::translate(glm::mat4(1.0), glm::vec3(pos.X, pos.Y, 0.f)));
switch (_state)
{
case STATE_OVER:
_overTexture.Draw(ctx);
break;
case STATE_DOWN:
_downTexture.Draw(ctx);
break;
case STATE_OUT:
_outTexture.Draw(ctx);
break;
default:
_texture.Draw(ctx);
break;
}
for (auto& child : _children)
child->Draw(ctx);
glCtx.PopMvp();
}
void GuiElement::Draw3d(DrawContext& ctx)
{
auto& glCtx = dynamic_cast<GlDrawContext&>(ctx);
auto pos = ModelPosition();
auto scale = ModelScale();
_modelScreenPos = glCtx.ProjectScreen(pos);
glCtx.PushMvp(glm::translate(glm::mat4(1.0), glm::vec3(pos.X, pos.Y, pos.Z)));
glCtx.PushMvp(glm::scale(glm::mat4(1.0), glm::vec3(scale, scale, scale)));
for (auto& child : _children)
child->Draw3d(ctx);
glCtx.PopMvp();
glCtx.PopMvp();
}
ActionResult GuiElement::OnAction(KeyAction action)
{
for (auto child = _children.rbegin();
child != _children.rend(); ++child)
{
auto res = (*child)->OnAction(action);
if (res.IsEaten)
return res;
}
return { false, "", ACTIONRESULT_DEFAULT, nullptr };
}
ActionResult GuiElement::OnAction(TouchAction action)
{
for (auto child = _children.rbegin();
child != _children.rend(); ++child)
{
auto res = (*child)->OnAction((*child)->ParentToLocal(action));
if (res.IsEaten)
return res;
}
if (Size2d::RectTest(_sizeParams.Size, action.Position))
return { true, "", ACTIONRESULT_DEFAULT, nullptr };
return { false, "", ACTIONRESULT_DEFAULT, nullptr };
}
ActionResult GuiElement::OnAction(TouchMoveAction action)
{
for (auto child = _children.rbegin();
child != _children.rend(); ++child)
{
auto res = (*child)->OnAction((*child)->ParentToLocal(action));
if (res.IsEaten)
return res;
}
return { false, "", ACTIONRESULT_DEFAULT, nullptr };
}
void GuiElement::SetParent(std::shared_ptr<GuiElement> parent)
{
_parent = parent;
}
TouchAction GuiElement::GlobalToLocal(actions::TouchAction action)
{
auto actionParent = nullptr == _parent ? action : _parent->GlobalToLocal(action);
actionParent.Position -= Position();
return actionParent;
}
TouchAction GuiElement::ParentToLocal(actions::TouchAction action)
{
action.Position -= Position();
return action;
}
TouchMoveAction GuiElement::GlobalToLocal(TouchMoveAction action)
{
auto actionParent = nullptr == _parent ? action : _parent->GlobalToLocal(action);
actionParent.Position -= Position();
return actionParent;
}
TouchMoveAction GuiElement::ParentToLocal(TouchMoveAction action)
{
action.Position -= Position();
return action;
}
utils::Position2d GuiElement::GlobalToLocal(utils::Position2d pos)
{
auto posParent = nullptr == _parent ? pos : _parent->GlobalToLocal(pos);
posParent -= Position();
return posParent;
}
utils::Position2d GuiElement::ParentToLocal(utils::Position2d pos)
{
pos -= Position();
return pos;
}
bool GuiElement::HitTest(Position2d localPos)
{
for (auto& child : _children)
{
if (child->HitTest(localPos))
return true;
}
return Size2d::RectTest(_sizeParams.Size, localPos);
return false;
}
void GuiElement::_InitResources(ResourceLib& resourceLib, bool forceInit)
{
_texture.InitResources(resourceLib, forceInit);
_overTexture.InitResources(resourceLib, forceInit);
_downTexture.InitResources(resourceLib, forceInit);
_outTexture.InitResources(resourceLib, forceInit);
for (auto& child : _children)
child->InitResources(resourceLib, forceInit);
}
void GuiElement::_ReleaseResources()
{
for (auto& child : _children)
child->ReleaseResources();
_texture.ReleaseResources();
_overTexture.ReleaseResources();
_downTexture.ReleaseResources();
_outTexture.ReleaseResources();
}
std::vector<JobAction> GuiElement::_CommitChanges()
{
return {};
}
| 22.97619
| 122
| 0.728325
|
malisimo
|
dc8fd468fce63293598dc5986824c3127ea39199
| 746
|
hpp
|
C++
|
src/classes/method.hpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | 10
|
2016-10-06T06:22:20.000Z
|
2022-02-28T05:33:09.000Z
|
src/classes/method.hpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | null | null | null |
src/classes/method.hpp
|
Zoxc/mirb
|
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
|
[
"BSD-3-Clause"
] | 3
|
2018-01-08T03:34:34.000Z
|
2021-09-12T12:12:22.000Z
|
#pragma once
#include "object.hpp"
#include "class.hpp"
namespace Mirb
{
class Method:
public Object
{
public:
// Used as DSL for native methods
enum Flags
{
Internal,
Singleton,
Private
};
public:
Method(Class *instance_of) : Object(Type::Method, instance_of), block(0), scope(0), scopes(0) {}
Method(Block *block, Tuple<Module> *scope, Tuple<> *scopes = 0) : Object(Type::Method, context->method_class), block(block), scope(scope), scopes(scopes) {}
Block *block;
Tuple<Module> *scope;
Tuple<> *scopes;
template<typename F> void mark(F mark)
{
Object::mark(mark);
mark(block);
mark(scope);
if(scopes)
mark(scopes);
}
static void initialize();
};
};
| 17.761905
| 159
| 0.620643
|
Zoxc
|
dc90e2fc04ea429b06fbccbec9f2498e7c11c6e5
| 1,522
|
cpp
|
C++
|
src/main.cpp
|
jamillosantos/mote-vision
|
31ebec5ced714fb497cb2740c9a65e66a2408078
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
jamillosantos/mote-vision
|
31ebec5ced714fb497cb2740c9a65e66a2408078
|
[
"MIT"
] | 16
|
2016-07-08T17:35:32.000Z
|
2016-07-24T02:11:07.000Z
|
src/main.cpp
|
jamillosantos/mote-vision
|
31ebec5ced714fb497cb2740c9a65e66a2408078
|
[
"MIT"
] | null | null | null |
/**
* @author J. Santos <jamillo@gmail.com>
* @date July 11, 2016
*/
#include <http/server.h>
#include "application.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <json/reader.h>
#include <json/value.h>
using namespace mote;
Application app;
void handleInt(int sig)
{
BOOST_LOG_TRIVIAL(trace) << "Interruption received";
app.stop();
}
int main(int argc, char **argv)
{
namespace po = boost::program_options;
std::string configFile;
po::options_description desc("Options");
desc.add_options()
("help,h", "displays this help message")
("config,c", po::value<std::string>(&configFile)->default_value(DEFAULT_CONFIG_FILE), "Specifies the config file")
("version,v", "displays the version of the system")
;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << "Usage: " << argv[0] << " [Options]" << std::endl << std::endl;
std::cout << desc << std::endl;
return 0;
}
else
{
BOOST_LOG_TRIVIAL(trace) << "Using config file: " << configFile;
boost::filesystem::path pathConfigFile(configFile);
if (boost::filesystem::exists(configFile))
{
signal(SIGINT, handleInt);
Json::Reader reader;
std::ifstream stream(configFile);
Json::Value configJson;
reader.parse(stream, configJson, false);
app.config(configJson);
return app.run();
}
else
{
BOOST_LOG_TRIVIAL(fatal) << "The config file was not found.";
return 1;
}
}
}
| 22.057971
| 116
| 0.673456
|
jamillosantos
|
dc952481a2cc7d4b45562b5039c0eb82d0b732e0
| 27,145
|
cc
|
C++
|
src/libxtp/gwbse/gwbse.cc
|
rubengerritsen/xtp
|
af4db53ca99853280d0e2ddc7f3c41bce8ae6e91
|
[
"Apache-2.0"
] | null | null | null |
src/libxtp/gwbse/gwbse.cc
|
rubengerritsen/xtp
|
af4db53ca99853280d0e2ddc7f3c41bce8ae6e91
|
[
"Apache-2.0"
] | null | null | null |
src/libxtp/gwbse/gwbse.cc
|
rubengerritsen/xtp
|
af4db53ca99853280d0e2ddc7f3c41bce8ae6e91
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Third party includes
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
// VOTCA includes
#include <stdexcept>
#include <votca/tools/constants.h>
// Local VOTCA includes
#include "votca/xtp/basisset.h"
#include "votca/xtp/bse.h"
#include "votca/xtp/ecpbasisset.h"
#include "votca/xtp/gwbse.h"
#include "votca/xtp/logger.h"
#include "votca/xtp/openmp_cuda.h"
#include "votca/xtp/orbitals.h"
#include "votca/xtp/vxc_grid.h"
#include "votca/xtp/vxc_potential.h"
using boost::format;
using namespace boost::filesystem;
using std::flush;
namespace votca {
namespace xtp {
Index GWBSE::CountCoreLevels() {
Index ignored_corelevels = 0;
if (!orbitals_.hasECPName()) {
ECPBasisSet basis;
basis.Load("corelevels");
Index coreElectrons = 0;
for (const auto& atom : orbitals_.QMAtoms()) {
coreElectrons += basis.getElement(atom.getElement()).getNcore();
}
ignored_corelevels = coreElectrons / 2;
}
return ignored_corelevels;
}
void GWBSE::Initialize(tools::Property& options) {
// getting level ranges
Index rpamax = 0;
Index rpamin = 0; // never changes
Index qpmin = 0;
Index qpmax = 0;
Index bse_vmin = 0;
Index bse_cmax = 0;
Index homo = orbitals_.getHomo(); // indexed from 0
Index num_of_levels = orbitals_.getBasisSetSize();
Index num_of_occlevels = orbitals_.getNumberOfAlphaElectrons();
std::string ranges = options.get(".ranges").as<std::string>();
// now check validity, and get rpa, qp, and bse level ranges accordingly
if (ranges == "factor") {
double rpamaxfactor = options.get(".rpamax").as<double>();
rpamax = Index(rpamaxfactor * double(num_of_levels)) -
1; // total number of levels
double qpminfactor = options.get(".qpmin").as<double>();
qpmin =
num_of_occlevels - Index(qpminfactor * double(num_of_occlevels)) - 1;
double qpmaxfactor = options.get(".qpmax").as<double>();
qpmax =
num_of_occlevels + Index(qpmaxfactor * double(num_of_occlevels)) - 1;
double bseminfactor = options.get(".bsemin").as<double>();
bse_vmin =
num_of_occlevels - Index(bseminfactor * double(num_of_occlevels)) - 1;
double bsemaxfactor = options.get(".bsemax").as<double>();
bse_cmax =
num_of_occlevels + Index(bsemaxfactor * double(num_of_occlevels)) - 1;
} else if (ranges == "explicit") {
// get explicit numbers
rpamax = options.get(".rpamax").as<Index>();
qpmin = options.get(".qpmin").as<Index>();
qpmax = options.get(".qpmax").as<Index>();
bse_vmin = options.get(".bsemin").as<Index>();
bse_cmax = options.get(".bsemax").as<Index>();
} else if (ranges == "default") {
rpamax = num_of_levels - 1;
qpmin = 0;
qpmax = 3 * homo + 1;
bse_vmin = 0;
bse_cmax = 3 * homo + 1;
} else if (ranges == "full") {
rpamax = num_of_levels - 1;
qpmin = 0;
qpmax = num_of_levels - 1;
bse_vmin = 0;
bse_cmax = num_of_levels - 1;
}
std::string ignore_corelevels =
options.get(".ignore_corelevels").as<std::string>();
if (ignore_corelevels == "RPA" || ignore_corelevels == "GW" ||
ignore_corelevels == "BSE") {
Index ignored_corelevels = CountCoreLevels();
if (ignore_corelevels == "RPA") {
rpamin = ignored_corelevels;
}
if (ignore_corelevels == "GW" || ignore_corelevels == "RPA") {
if (qpmin < ignored_corelevels) {
qpmin = ignored_corelevels;
}
}
if (ignore_corelevels == "GW" || ignore_corelevels == "RPA" ||
ignore_corelevels == "BSE") {
if (bse_vmin < ignored_corelevels) {
bse_vmin = ignored_corelevels;
}
}
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Ignoring " << ignored_corelevels
<< " core levels for " << ignore_corelevels << " and beyond." << flush;
}
// check maximum and minimum sizes
if (rpamax > num_of_levels) {
rpamax = num_of_levels - 1;
}
if (qpmax > num_of_levels) {
qpmax = num_of_levels - 1;
}
if (bse_cmax > num_of_levels) {
bse_cmax = num_of_levels - 1;
}
if (bse_vmin < 0) {
bse_vmin = 0;
}
if (qpmin < 0) {
qpmin = 0;
}
gwopt_.homo = homo;
gwopt_.qpmin = qpmin;
gwopt_.qpmax = qpmax;
gwopt_.rpamin = rpamin;
gwopt_.rpamax = rpamax;
bseopt_.vmin = bse_vmin;
bseopt_.cmax = bse_cmax;
bseopt_.homo = homo;
bseopt_.qpmin = qpmin;
bseopt_.qpmax = qpmax;
bseopt_.rpamin = rpamin;
bseopt_.rpamax = rpamax;
orbitals_.setRPAindices(rpamin, rpamax);
orbitals_.setGWindices(qpmin, qpmax);
orbitals_.setBSEindices(bse_vmin, bse_cmax);
orbitals_.SetFlagUseHqpOffdiag(bseopt_.use_Hqp_offdiag);
Index bse_vmax = homo;
Index bse_cmin = homo + 1;
Index bse_vtotal = bse_vmax - bse_vmin + 1;
Index bse_ctotal = bse_cmax - bse_cmin + 1;
Index bse_size = bse_vtotal * bse_ctotal;
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " RPA level range [" << rpamin
<< ":" << rpamax << "]" << flush;
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " GW level range [" << qpmin
<< ":" << qpmax << "]" << flush;
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " BSE level range occ[" << bse_vmin << ":" << bse_vmax
<< "] virt[" << bse_cmin << ":" << bse_cmax << "]" << flush;
gwopt_.reset_3c = options.get(".gw.rebuild_3c_freq").as<Index>();
bseopt_.nmax = options.get(".bse.exctotal").as<Index>();
if (bseopt_.nmax > bse_size || bseopt_.nmax < 0) {
bseopt_.nmax = bse_size;
}
bseopt_.davidson_correction =
options.get("bse.davidson.correction").as<std::string>();
bseopt_.davidson_tolerance =
options.get("bse.davidson.tolerance").as<std::string>();
bseopt_.davidson_update =
options.get("bse.davidson.update").as<std::string>();
bseopt_.davidson_maxiter = options.get("bse.davidson.maxiter").as<Index>();
bseopt_.useTDA = options.get("bse.useTDA").as<bool>();
orbitals_.setTDAApprox(bseopt_.useTDA);
if (!bseopt_.useTDA) {
XTP_LOG(Log::error, *pLog_) << " BSE type: full" << flush;
} else {
XTP_LOG(Log::error, *pLog_) << " BSE type: TDA" << flush;
}
Index full_bse_size = (bseopt_.useTDA) ? bse_size : 2 * bse_size;
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " BSE Hamiltonian has size "
<< full_bse_size << "x" << full_bse_size << flush;
bseopt_.use_Hqp_offdiag = options.get("bse.use_Hqp_offdiag").as<bool>();
if (!bseopt_.use_Hqp_offdiag) {
XTP_LOG(Log::error, *pLog_)
<< " BSE without Hqp offdiagonal elements" << flush;
} else {
XTP_LOG(Log::error, *pLog_)
<< " BSE with Hqp offdiagonal elements" << flush;
}
bseopt_.max_dyn_iter = options.get("bse.dyn_screen_max_iter").as<Index>();
bseopt_.dyn_tolerance = options.get("bse.dyn_screen_tol").as<double>();
if (bseopt_.max_dyn_iter > 0) {
do_dynamical_screening_bse_ = true;
}
functional_ = orbitals_.getXCFunctionalName();
grid_ = orbitals_.getXCGrid();
dftbasis_name_ = orbitals_.getDFTbasisName();
if (orbitals_.hasAuxbasisName()) {
auxbasis_name_ = orbitals_.getAuxbasisName();
} else if (options.exists(".auxbasisset")) {
auxbasis_name_ = options.get(".auxbasisset").as<std::string>();
} else {
auxbasis_name_ = "aux-" + dftbasis_name_;
try {
BasisSet b;
b.Load(auxbasis_name_);
} catch (std::runtime_error&) {
std::runtime_error(
"There is no auxbasis from the dftcalculation nor did you specify an "
"auxbasisset for the gwbse calculation. Also no auxiliary basisset "
"for basisset " +
dftbasis_name_ + " could be found!");
}
XTP_LOG(Log::error, *pLog_)
<< " Could not find an auxbasisset using " << auxbasis_name_ << flush;
}
std::string mode = options.get("gw.mode").as<std::string>();
if (mode == "G0W0") {
gwopt_.gw_sc_max_iterations = 1;
} else if (mode == "evGW") {
gwopt_.g_sc_limit = 0.1 * gwopt_.gw_sc_limit;
gwopt_.eta = 0.1;
}
XTP_LOG(Log::error, *pLog_) << " Running GW as: " << mode << flush;
gwopt_.ScaHFX = orbitals_.getScaHFX();
gwopt_.shift = options.get("gw.scissor_shift").as<double>();
gwopt_.g_sc_limit =
options.get("gw.qp_sc_limit").as<double>(); // convergence criteria
// for qp iteration
// [Hartree]]
gwopt_.g_sc_max_iterations =
options.get("gw.qp_sc_max_iter").as<Index>(); // convergence
// criteria for qp
// iteration
// [Hartree]]
if (mode == "evGW") {
gwopt_.gw_sc_max_iterations = options.get("gw.sc_max_iter").as<Index>();
}
gwopt_.gw_sc_limit =
options.get("gw.sc_limit").as<double>(); // convergence criteria
// for shift it
XTP_LOG(Log::error, *pLog_)
<< " qp_sc_limit [Hartree]: " << gwopt_.g_sc_limit << flush;
if (gwopt_.gw_sc_max_iterations > 1) {
XTP_LOG(Log::error, *pLog_)
<< " gw_sc_limit [Hartree]: " << gwopt_.gw_sc_limit << flush;
}
bseopt_.min_print_weight = options.get("bse.print_weight").as<double>();
// print exciton WF composition weight larger than minimum
// possible tasks
std::string tasks_string = options.get(".tasks").as<std::string>();
boost::algorithm::to_lower(tasks_string);
if (tasks_string.find("all") != std::string::npos) {
do_gw_ = true;
do_bse_singlets_ = true;
do_bse_triplets_ = true;
}
if (tasks_string.find("gw") != std::string::npos) {
do_gw_ = true;
}
if (tasks_string.find("singlets") != std::string::npos) {
do_bse_singlets_ = true;
}
if (tasks_string.find("triplets") != std::string::npos) {
do_bse_triplets_ = true;
}
XTP_LOG(Log::error, *pLog_) << " Tasks: " << flush;
if (do_gw_) {
XTP_LOG(Log::error, *pLog_) << " GW " << flush;
}
if (do_bse_singlets_) {
XTP_LOG(Log::error, *pLog_) << " singlets " << flush;
}
if (do_bse_triplets_) {
XTP_LOG(Log::error, *pLog_) << " triplets " << flush;
}
XTP_LOG(Log::error, *pLog_) << " Store: " << flush;
if (do_gw_) {
XTP_LOG(Log::error, *pLog_) << " GW " << flush;
}
if (options.exists("bse.fragments")) {
std::vector<tools::Property*> prop_region =
options.Select("bse.fragments.fragment");
Index index = 0;
for (tools::Property* prop : prop_region) {
std::string indices = prop->get("indices").as<std::string>();
fragments_.push_back(QMFragment<BSE_Population>(index, indices));
index++;
}
}
gwopt_.sigma_integration =
options.get("gw.sigma_integrator").as<std::string>();
XTP_LOG(Log::error, *pLog_)
<< " Sigma integration: " << gwopt_.sigma_integration << flush;
gwopt_.eta = options.get("gw.eta").as<double>();
XTP_LOG(Log::error, *pLog_) << " eta: " << gwopt_.eta << flush;
if (gwopt_.sigma_integration == "exact") {
XTP_LOG(Log::error, *pLog_)
<< " RPA Hamiltonian size: " << (homo + 1 - rpamin) * (rpamax - homo)
<< flush;
}
if (gwopt_.sigma_integration == "cda") {
gwopt_.order = options.get("gw.quadrature_order").as<Index>();
XTP_LOG(Log::error, *pLog_)
<< " Quadrature integration order : " << gwopt_.order << flush;
gwopt_.quadrature_scheme =
options.get(".quadrature_scheme").as<std::string>();
XTP_LOG(Log::error, *pLog_)
<< " Quadrature integration scheme : " << gwopt_.quadrature_scheme
<< flush;
gwopt_.alpha = options.get("gw.alpha").as<double>();
XTP_LOG(Log::error, *pLog_)
<< " Alpha smoothing parameter : " << gwopt_.alpha << flush;
}
gwopt_.qp_solver = options.get("gw.qp_solver").as<std::string>();
XTP_LOG(Log::error, *pLog_) << " QP solver: " << gwopt_.qp_solver << flush;
if (gwopt_.qp_solver == "grid") {
gwopt_.qp_grid_steps = options.get("gw.qp_grid_steps").as<Index>();
gwopt_.qp_grid_spacing = options.get("gw.qp_grid_spacing").as<double>();
XTP_LOG(Log::error, *pLog_)
<< " QP grid steps: " << gwopt_.qp_grid_steps << flush;
XTP_LOG(Log::error, *pLog_)
<< " QP grid spacing: " << gwopt_.qp_grid_spacing << flush;
}
gwopt_.gw_mixing_order =
options.get("gw.mixing_order").as<Index>(); // max history in
// mixing (0: plain,
// 1: linear, >1
// Anderson)
gwopt_.gw_mixing_alpha = options.get("gw.mixing_alpha").as<double>();
if (mode == "evGW") {
if (gwopt_.gw_mixing_order == 0) {
XTP_LOG(Log::error, *pLog_) << " evGW with plain update " << std::flush;
} else if (gwopt_.gw_mixing_order == 1) {
XTP_LOG(Log::error, *pLog_) << " evGW with linear update using alpha "
<< gwopt_.gw_mixing_alpha << std::flush;
} else {
XTP_LOG(Log::error, *pLog_) << " evGW with Anderson update with history "
<< gwopt_.gw_mixing_order << " using alpha "
<< gwopt_.gw_mixing_alpha << std::flush;
}
}
if (options.exists(".sigma_plot")) {
sigma_plot_states_ = options.get(".sigma_plot.states").as<std::string>();
sigma_plot_steps_ = options.get(".sigma_plot.steps").as<Index>();
sigma_plot_spacing_ = options.get(".sigma_plot.spacing").as<double>();
sigma_plot_filename_ =
options.get(".sigma_plot.filename").as<std::string>();
XTP_LOG(Log::error, *pLog_)
<< " Sigma plot states: " << sigma_plot_states_ << flush;
XTP_LOG(Log::error, *pLog_)
<< " Sigma plot steps: " << sigma_plot_steps_ << flush;
XTP_LOG(Log::error, *pLog_)
<< " Sigma plot spacing: " << sigma_plot_spacing_ << flush;
XTP_LOG(Log::error, *pLog_)
<< " Sigma plot filename: " << sigma_plot_filename_ << flush;
}
}
void GWBSE::addoutput(tools::Property& summary) {
const double hrt2ev = tools::conv::hrt2ev;
tools::Property& gwbse_summary = summary.add("GWBSE", "");
if (do_gw_) {
gwbse_summary.setAttribute("units", "eV");
gwbse_summary.setAttribute(
"DFTEnergy",
(format("%1$+1.6f ") % (orbitals_.getDFTTotalEnergy() * hrt2ev)).str());
tools::Property& dft_summary = gwbse_summary.add("dft", "");
dft_summary.setAttribute("HOMO", gwopt_.homo);
dft_summary.setAttribute("LUMO", gwopt_.homo + 1);
for (Index state = 0; state < gwopt_.qpmax + 1 - gwopt_.qpmin; state++) {
tools::Property& level_summary = dft_summary.add("level", "");
level_summary.setAttribute("number", state + gwopt_.qpmin);
level_summary.add(
"dft_energy",
(format("%1$+1.6f ") %
(orbitals_.MOs().eigenvalues()(state + gwopt_.qpmin) * hrt2ev))
.str());
level_summary.add(
"gw_energy",
(format("%1$+1.6f ") % (orbitals_.QPpertEnergies()(state) * hrt2ev))
.str());
level_summary.add("qp_energy",
(format("%1$+1.6f ") %
(orbitals_.QPdiag().eigenvalues()(state) * hrt2ev))
.str());
}
}
if (do_bse_singlets_) {
tools::Property& singlet_summary = gwbse_summary.add("singlets", "");
for (Index state = 0; state < bseopt_.nmax; ++state) {
tools::Property& level_summary = singlet_summary.add("level", "");
level_summary.setAttribute("number", state + 1);
level_summary.add(
"omega", (format("%1$+1.6f ") %
(orbitals_.BSESinglets().eigenvalues()(state) * hrt2ev))
.str());
if (orbitals_.hasTransitionDipoles()) {
const Eigen::Vector3d& dipoles = (orbitals_.TransitionDipoles())[state];
double f = 2 * dipoles.squaredNorm() *
orbitals_.BSESinglets().eigenvalues()(state) / 3.0;
level_summary.add("f", (format("%1$+1.6f ") % f).str());
tools::Property& dipol_summary = level_summary.add(
"Trdipole", (format("%1$+1.4f %2$+1.4f %3$+1.4f") % dipoles.x() %
dipoles.y() % dipoles.z())
.str());
dipol_summary.setAttribute("unit", "e*bohr");
dipol_summary.setAttribute("gauge", "length");
}
}
}
if (do_bse_triplets_) {
tools::Property& triplet_summary = gwbse_summary.add("triplets", "");
for (Index state = 0; state < bseopt_.nmax; ++state) {
tools::Property& level_summary = triplet_summary.add("level", "");
level_summary.setAttribute("number", state + 1);
level_summary.add(
"omega", (format("%1$+1.6f ") %
(orbitals_.BSETriplets().eigenvalues()(state) * hrt2ev))
.str());
}
}
return;
}
/*
* Many-body Green's fuctions theory implementation
*
* data required from orbitals file
* - atomic coordinates
* - DFT molecular orbitals (energies and coeffcients)
* - DFT exchange-correlation potential matrix in atomic orbitals
* - number of electrons, number of levels
*/
Eigen::MatrixXd GWBSE::CalculateVXC(const AOBasis& dftbasis) {
if (orbitals_.getXCFunctionalName().empty()) {
orbitals_.setXCFunctionalName(functional_);
} else {
if (!(functional_ == orbitals_.getXCFunctionalName())) {
throw std::runtime_error("Functionals from DFT " +
orbitals_.getXCFunctionalName() + " GWBSE " +
functional_ + " differ!");
}
}
Vxc_Grid grid;
grid.GridSetup(grid_, orbitals_.QMAtoms(), dftbasis);
XTP_LOG(Log::info, *pLog_)
<< TimeStamp() << " Setup grid for integration with gridsize: " << grid_
<< " with " << grid.getGridSize() << " points, divided into "
<< grid.getBoxesSize() << " boxes" << flush;
Vxc_Potential<Vxc_Grid> vxcpotential(grid);
vxcpotential.setXCfunctional(functional_);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Integrating Vxc with functional " << functional_
<< flush;
Eigen::MatrixXd DMAT = orbitals_.DensityMatrixGroundState();
Mat_p_Energy e_vxc_ao = vxcpotential.IntegrateVXC(DMAT);
XTP_LOG(Log::info, *pLog_) << TimeStamp() << " Calculated Vxc" << flush;
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Set hybrid exchange factor: " << orbitals_.getScaHFX()
<< flush;
Index qptotal = gwopt_.qpmax - gwopt_.qpmin + 1;
Eigen::MatrixXd mos =
orbitals_.MOs().eigenvectors().middleCols(gwopt_.qpmin, qptotal);
Eigen::MatrixXd vxc = mos.transpose() * e_vxc_ao.matrix() * mos;
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Calculated exchange-correlation expectation values "
<< flush;
return vxc;
}
bool GWBSE::Evaluate() {
// set the parallelization
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Using "
<< OPENMP::getMaxThreads() << " threads" << flush;
if (XTP_HAS_MKL_OVERLOAD()) {
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Using MKL overload for Eigen " << flush;
} else {
XTP_LOG(Log::error, *pLog_)
<< TimeStamp()
<< " Using native Eigen implementation, no BLAS overload " << flush;
}
Index nogpus = OpenMP_CUDA::UsingGPUs();
if (nogpus > 0) {
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Using CUDA support for tensor multiplication with "
<< nogpus << " GPUs." << flush;
}
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Molecule Coordinates [A] " << flush;
for (QMAtom& atom : orbitals_.QMAtoms()) {
std::string output = (boost::format("%5d"
"%5s"
" %1.4f %1.4f %1.4f") %
atom.getId() % atom.getElement() %
(atom.getPos().x() * tools::conv::bohr2ang) %
(atom.getPos().y() * tools::conv::bohr2ang) %
(atom.getPos().z() * tools::conv::bohr2ang))
.str();
XTP_LOG(Log::error, *pLog_) << output << flush;
}
std::string dft_package = orbitals_.getQMpackage();
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " DFT data was created by " << dft_package << flush;
BasisSet dftbs;
dftbs.Load(dftbasis_name_);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Loaded DFT Basis Set " << dftbasis_name_ << flush;
// fill DFT AO basis by going through all atoms
AOBasis dftbasis;
dftbasis.Fill(dftbs, orbitals_.QMAtoms());
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Filled DFT Basis of size "
<< dftbasis.AOBasisSize() << flush;
// load auxiliary basis set (element-wise information) from xml file
BasisSet auxbs;
auxbs.Load(auxbasis_name_);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Loaded Auxbasis Set " << auxbasis_name_ << flush;
// fill auxiliary AO basis by going through all atoms
AOBasis auxbasis;
auxbasis.Fill(auxbs, orbitals_.QMAtoms());
orbitals_.setAuxbasisName(auxbasis_name_);
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Filled Auxbasis of size "
<< auxbasis.AOBasisSize() << flush;
if ((do_bse_singlets_ || do_bse_triplets_) && fragments_.size() > 0) {
for (const auto& frag : fragments_) {
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " Fragment " << frag.getId()
<< " size:" << frag.size() << flush;
}
}
if (!do_gw_ && !orbitals_.hasQPdiag()) {
throw std::runtime_error(
"You want no GW calculation but the orb file has no QPcoefficients for "
"BSE");
}
TCMatrix_gwbse Mmn;
// rpamin here, because RPA needs till rpamin
Index max_3c = std::max(bseopt_.cmax, gwopt_.qpmax);
Mmn.Initialize(auxbasis.AOBasisSize(), gwopt_.rpamin, max_3c, gwopt_.rpamin,
gwopt_.rpamax);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp()
<< " Calculating Mmn_beta (3-center-repulsion x orbitals) " << flush;
Mmn.Fill(auxbasis, dftbasis, orbitals_.MOs().eigenvectors());
XTP_LOG(Log::info, *pLog_)
<< TimeStamp() << " Removed " << Mmn.Removedfunctions()
<< " functions from Aux Coulomb matrix to avoid near linear dependencies"
<< flush;
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Calculated Mmn_beta (3-center-repulsion x orbitals) "
<< flush;
Eigen::MatrixXd Hqp;
if (do_gw_) {
std::chrono::time_point<std::chrono::system_clock> start =
std::chrono::system_clock::now();
Eigen::MatrixXd vxc = CalculateVXC(dftbasis);
GW gw = GW(*pLog_, Mmn, vxc, orbitals_.MOs().eigenvalues());
gw.configure(gwopt_);
gw.CalculateGWPerturbation();
if (!sigma_plot_states_.empty()) {
gw.PlotSigma(sigma_plot_filename_, sigma_plot_steps_, sigma_plot_spacing_,
sigma_plot_states_);
}
// store perturbative QP energy data in orbitals object (DFT, S_x,S_c, V_xc,
// E_qp)
orbitals_.QPpertEnergies() = gw.getGWAResults();
orbitals_.RPAInputEnergies() = gw.RPAInputEnergies();
XTP_LOG(Log::info, *pLog_)
<< TimeStamp() << " Calculating offdiagonal part of Sigma " << flush;
gw.CalculateHQP();
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Calculated offdiagonal part of Sigma " << flush;
Hqp = gw.getHQP();
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
gw.DiagonalizeQPHamiltonian();
if (es.info() == Eigen::ComputationInfo::Success) {
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Diagonalized QP Hamiltonian " << flush;
}
orbitals_.QPdiag().eigenvectors() = es.eigenvectors();
orbitals_.QPdiag().eigenvalues() = es.eigenvalues();
std::chrono::duration<double> elapsed_time =
std::chrono::system_clock::now() - start;
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " GW calculation took "
<< elapsed_time.count() << " seconds." << flush;
} else {
if (orbitals_.getGWAmax() != gwopt_.qpmax ||
orbitals_.getGWAmin() != gwopt_.qpmin ||
orbitals_.getRPAmax() != gwopt_.rpamax ||
orbitals_.getRPAmin() != gwopt_.rpamin) {
throw std::runtime_error(
"The ranges for GW and RPA do not agree with the ranges from the "
".orb file, rerun your GW calculation");
}
const Eigen::MatrixXd& qpcoeff = orbitals_.QPdiag().eigenvectors();
Hqp = qpcoeff * orbitals_.QPdiag().eigenvalues().asDiagonal() *
qpcoeff.transpose();
}
// proceed only if BSE requested
if (do_bse_singlets_ || do_bse_triplets_) {
std::chrono::time_point<std::chrono::system_clock> start =
std::chrono::system_clock::now();
BSE bse = BSE(*pLog_, Mmn);
bse.configure(bseopt_, orbitals_.RPAInputEnergies(), Hqp);
// store the direct contribution to the static BSE results
Eigen::VectorXd Hd_static_contrib_triplet;
Eigen::VectorXd Hd_static_contrib_singlet;
if (do_bse_triplets_) {
bse.Solve_triplets(orbitals_);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Solved BSE for triplets " << flush;
bse.Analyze_triplets(fragments_, orbitals_);
}
if (do_bse_singlets_) {
bse.Solve_singlets(orbitals_);
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " Solved BSE for singlets " << flush;
bse.Analyze_singlets(fragments_, orbitals_);
}
// do perturbative dynamical screening in BSE
if (do_dynamical_screening_bse_) {
if (do_bse_triplets_) {
bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Triplet),
orbitals_);
}
if (do_bse_singlets_) {
bse.Perturbative_DynamicalScreening(QMStateType(QMStateType::Singlet),
orbitals_);
}
}
std::chrono::duration<double> elapsed_time =
std::chrono::system_clock::now() - start;
XTP_LOG(Log::error, *pLog_) << TimeStamp() << " BSE calculation took "
<< elapsed_time.count() << " seconds." << flush;
}
XTP_LOG(Log::error, *pLog_)
<< TimeStamp() << " GWBSE calculation finished " << flush;
return true;
}
} // namespace xtp
} // namespace votca
| 36.193333
| 80
| 0.603684
|
rubengerritsen
|
dc98d23bb301283ee98b5306d1beb954f93f4cf6
| 21,152
|
hh
|
C++
|
dstorm/include/dstorm_any2.hh
|
malt2/malt2
|
e3407e8483857979d191044d377674a2eb251508
|
[
"BSD-3-Clause"
] | null | null | null |
dstorm/include/dstorm_any2.hh
|
malt2/malt2
|
e3407e8483857979d191044d377674a2eb251508
|
[
"BSD-3-Clause"
] | null | null | null |
dstorm/include/dstorm_any2.hh
|
malt2/malt2
|
e3407e8483857979d191044d377674a2eb251508
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2017 NEC Laboratories America, Inc. ("NECLA"). All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree. An additional grant of patent rights
* can be found in the PATENTS file in the same directory.
*/
#ifndef DSTORM_ANY2_HH
#define DSTORM_ANY2_HH
#include "dstorm_any.hh"
// we additionally have access to SegImpl, FMT, ... in this header
#include "segImpl.hh"
#include "demangle.hpp"
#include <unistd.h> // sleep
namespace dStorm {
template< typename FMT, typename... Args >
void Dstorm::add_segment( SegNum const s,
IoNet_t const ionet,
SegPolicy const policy,
uint32_t const cnt,
Args&&... args )
{
int const verbose=0;
static_assert( is_segment_format<FMT>::value,
"ERROR: require is_segment_format<FMT>");
using detail::SegImpl;
{
// XXX scoped lock if multithreaded
ORM_NEED( seginfos.find( segKey<FMT>(s) ) == seginfos.end() );
if(verbose){
if(verbose>1 || (verbose==1 && iProc==0)){
SegPolicyIO policyIO{policy};
ORM_COUT(this->orm, "Dstorm::add_segment(SegNum="<<(unsigned)s<<", ionet="<<(unsigned short)ionet
<<":"<<(ionet < this->iographs.size()? this->iographs[ionet].shortname(): std::string("HUH?"))
<<", policy="<<dStorm::name(policyIO)<<", cnt="<<cnt<<",...)");
}
//this->barrier(300000);
ORM_COUT(this->orm, " r"<<iProc<<" seg"<<s<<" sendList "<<this->print_sync_list( ionet ));
}
if(verbose>1) ORM_COUT(this->orm, "Dstorm::add_segment -- new SegImpl...");
// Oh. we call SEGIMPL constructor AND SEGIMPL::add_segment.
// So who gets the arg pack? A: SegImpl constructor
SegImpl<FMT>* segimpl = new SegImpl<FMT>( std::forward<Args>(args)... );
assert( segimpl != nullptr );
SegInfo *seginfo = segimpl; // cast all-the-way-down
// These depend on FMT, and were moved from segimpl_add_segment
// XXX Can segimpl_add_segment, whose code is now indpt of FMT,
// become a non-templated Dstorm helper function ??? XXX
seginfo->sizeofMsgHeader = sizeof( MsgHeader<FMT> );
//seginfo->fmtValue = FMT::value; // <-- this const value is set during 'add_segment'
if(verbose>1) ORM_COUT(this->orm, "Dstorm::add_segment -- segimpl->add_segment(s,this,ionet,cnt) type "<<typeid(seginfo).name());
// next call invokes SegVec...::setSegInfo, finishes SegInfo setup, and invokes SegVec...:add_segment
segimpl->segimpl_add_segment( s, this, ionet, policy, cnt );
this->barrier(); // give time for internal messages to propagate
{ // throw if SegNum s already there
SegInfoMapType::iterator found = this->seginfos.find(s);
if( found != seginfos.end() ){
ORM_COUT(this->orm, " ERROR: add_segment( "<<s<<" ): segment already exists");
throw std::runtime_error("add_segment: segment already exists");
}
}
this->seginfos[ s ] = seginfo; // point SegNum s at its SegInfo base class
#if WITH_NOTIFYACK
// support structure for SEGSYNC_NOTIFY_ACK
this->segacks[(SegNum)s] = (((policy&SEGSYNC_MASK) == SEGSYNC_NOTIFY_ACK )
? new detail::SegSenderAcks( *seginfo )
: (detail::SegSenderAcks*)nullptr );
if( (policy&REDUCE_OP_MASK) == REDUCE_STREAM ){
// we will count NTF_DONE notificiations for the set of rbufs.
seginfo->reduceState = new detail::AwaitCountedSet( seginfo->rbufNotifyEnd() - seginfo->rbufNotifyBeg() );
}
#endif
}
{
// testing...
SegInfo *sInfo = this->seginfos[ s ];
#if !defined(__CUDA_ARCH__)
if( verbose>1 || (verbose==1 && iProc==0U))
ORM_COUT(this->orm, " TEST: +(*seginfo) --> "<<demangle(typeid(+(*sInfo)).name()) );
#endif
if(verbose>1 && iProc==0U) this->print_seg_info( s );
}
#if WITH_LIBORM // --> run-time, if this->transport==OMPI or GPU ??
std::vector<Tnode> send_list = segSendVec(s);
std::vector<Tnode> recv_list = segRecvVec(s);
Tnode* send_list1 = &send_list[0];
Tnode* recv_list1 = &recv_list[0];
int* sendlist = new int[send_list.size()];
int* recvlist = new int[recv_list.size()];
std::copy(send_list1, send_list1+send_list.size(), sendlist);
std::copy(recv_list1, recv_list1+recv_list.size(), recvlist);
if(verbose) ORM_COUT(this->orm, "group_create_mpi...");
orm->group_create_mpi( orm, s, &sendlist[0], send_list.size(), &recvlist[0], recv_list.size());
if(verbose) ORM_COUT(this->orm, "win_post...");
orm->win_post(orm, s);
if(sendlist) delete[] sendlist;
if(recvlist) delete[] recvlist;
#endif
// moved to Seg_VecGpu<T>::add_segment (Impl::add_segment call)
//if( this->transport == GPU ){
// 1. cudaMalloc and set segInfo->segInfoGpu
// 2. copy sInfoPod from host to device
//}
this->barrier(); // add_/delete_segment are rare, and must NEVER overlap
}//Dstorm::add_segment<FMT,Args...>
inline void Dstorm::delete_segment( SegNum const s ) // non-const because of seginfos erase
{
this->barrier(); // add_/delete_segment are rare, and must NEVER overlap
int const verbose=1;
SegInfo & sInfo = validSegInfo(s,__func__);
if(verbose>1 || (verbose==1 && iProc==0))
ORM_COUT(this->orm, "Dstorm::delete_segment("<<s<<"), type "<<demangle(typeid(+sInfo).name()));
#if WITH_LIBORM
orm->group_delete_mpi(orm, sInfo.seg_id);
orm->segment_delete(orm, sInfo.seg_id );
#endif
sInfo.delete_segment(); // SegVecFoo cleanup
// equiv. (+sInfo).delete_segment();
// Seg_VecGpu::delete_segment will delete gpu version of SegInfoPod
delete &sInfo; // DESTROY our top-level segment object
seginfos.erase(s); // and remove our pointer to it's SegInfo
this->barrier();
}//Dstorm::delete_segment
template< typename FMT, typename IN_CONST_ITER > inline
void Dstorm::store( SegNum const s,
IN_CONST_ITER iter, uint32_t cnt,
uint32_t offset/*=0U*/, double const wgt/*=1.0*/ ) const
{
static_assert( is_segment_format<FMT>::value,
"ERROR: require is_segment_format<FMT>");
// ASSUME iter valid for cnt + offset items
// iter::value_type must be convertible to SegTag<FMT>::type's data type
// TODO check above assumptions every time
int const verbose=0;
typedef typename std::iterator_traits<IN_CONST_ITER>::value_type T;
static_assert( std::is_arithmetic<T>::value || std::is_pod<T>::value,
"Dstorm::store IN_CONST_ITER::value_type must be POD" );
// gcc-4.8.2 still has not implemented this type trait
//static_assert( std::is_trivially_copyable<T>()::value,
// "Dstorm::store IN_CONST_ITER::value_type must be trivially copyable" );
// so require something more strict (above)
//static_assert( std::is_const<T>::value == true,
// "Dstorm::store IN_CONST_ITER::value_type must be const (paranoia)" );
if(verbose) ORM_COUT(this->orm, " Dstorm::store<"<<FMT::name<<">"
<<"( "<<type_str<IN_CONST_ITER>()<<" iter"
<<", cnt="<<cnt<<", offset="<<offset<<" wgt="<<wgt<<" )" );
SegInfo & sInfo = validSegInfo(s,__func__); // throw if non-existent or invalid
#if WITH_NOTIFYACK
// NOTIFY_ACK support
// NOTIFY only done during 'push'
// REDUCE_AVG_RBUF_OBUF modifies oBuf, during reduce, so await acks there.
// Others should await here, in 'store' write to oBuf, if not earlier (what function call?)
// Should be safe to always await acks here "just in case" ...
SegPolicy const segsync = (sInfo.policy & SEGSYNC_MASK);
// SegPolicy const red = sInfo.policy & REDUCE_OP_MASK;
if( // red==REDUCE_AVG_RBUF_OBUF &&
segsync==SEGSYNC_NOTIFY_ACK )
{
auto found = this->segacks.find(s);
if( found == this->segacks.end() ) throw std::runtime_error("expected SegSenderAcks NOT FOUND");
if( found->second == nullptr ) throw std::runtime_error("expected SegSenderAcks was a nullptr");
detail::SegSenderAcks *acks = found->second;
if(NOTACK_DBG) DST_COUT( "NotAck: store state "<<acks->str()<<", segacks["<<s<<"]->wait()...");
// await ACKs for whole SET of successful <tt>write_notify</tt>s
uint32_t const w = acks->wait(ORM_BLOCK);
if( w > 0U ){ // w == 0 means all sends acked
throw std::runtime_error("store acks->wait failure");
}
}
#endif
auto *sTop = dynamic_cast< detail::SegImpl<FMT>* >(&sInfo);
//assert( sTop != nullptr ); // give a better message...
if( sTop == nullptr ){
std::ostringstream oss;
oss<<" store<FMT>(SegNum "<<s<<",iter,cnt "<<cnt<<",offset "<<offset<<") wrong FMT for Segnum?";
throw std::runtime_error(oss.str());
}
// sTop can shunt us down to Impl if it has nothing to do (likely)
sTop->store( iter, cnt, offset, wgt );
}//Dstorm::store
template< typename FMT, typename IN_CONST_ITER >
inline void
Dstorm::store( SegNum const s, IN_CONST_ITER iter, IN_CONST_ITER const end,
uint32_t const offset/*=0U*/, double const wgt/*=1.0*/ ) const
{
// ASSUME iter valid for cnt + offset items
// iter::value_type must be convertible to SegTag<FMT>::type's data type
int const verbose=0;
//typedef typename IN_CONST_ITER::value_type T;
typedef typename std::iterator_traits<IN_CONST_ITER>::value_type T;
static_assert( std::is_pod<T>::value == true,
"Dstorm::store IN_CONST_ITER::value_type must be POD" );
// gcc-4.8.2 still has not implemented this type trait
//static_assert( std::is_trivially_copyable<T>()::value,
// "Dstorm::store IN_CONST_ITER::value_type must be trivially copyable" );
// so require something more strict (above)
//static_assert( std::is_const<T>::value == true,
// "Dstorm::store IN_CONST_ITER::value_type must be const (paranoia)" );
if(verbose) ORM_COUT(this->orm, " Dstorm::store<"<<FMT::name<<">"
<<"( "<<type_str<IN_CONST_ITER>()<<" iter beg,end"
", offset="<<offset<<", wgt="<<wgt<<" ) NB: CHECK buf ovflw in SegImpl?" );
//SegInfo * sInfo = this->seginfos.at(segKey<FMT>(s)); // throw if non-existent
//assert( sInfo != nullptr );
//assert( sInfo->valid == true );
SegInfo & sInfo = validSegInfo(s,__func__); // throw on err
assert( sInfo.valid == true );
//auto *sTop = sInfo->getSegImpl<FMT>();
auto *sTop = dynamic_cast< detail::SegImpl<FMT>* >(&sInfo);
assert( sTop != nullptr );
// sTop can shunt us down to Impl if it has nothing to do (likely)
sTop->store( iter, end, offset, wgt );
}//Dstorm::store
#if 1 //dstorm_any2
DSTORM_INLINE uint32_t
Dstorm::reduce( SegNum const s ) const
{
int const verbose=0;
SegInfo & sInfo = validSegInfo(s,__func__);
SegPolicy const segsync = sInfo.policy & SEGSYNC_MASK;
SegPolicy const red = sInfo.policy & REDUCE_OP_MASK;
uint32_t nReduce = 0U;
auto ackToIter = this->recv_src.end();
if( segsync == SEGSYNC_NOTIFY_ACK /*|| red == REDUCE_STREAM*/ ){
// reduce only uses the send queue for ACKs
ackToIter = this->recv_src.find( sInfo.ionet );
if( ackToIter == this->recv_src.end() ) throw std::runtime_error("recv_src incomplete");
}
assert( red != REDUCE_STREAM );
#if WITH_LIBORM
//
// Generic "wait for rdma data"
//
// How? According to segsync setting (Set by Orm::segment_create, Orm::sync)
// TBD copy above code blocks into liborm
//
NEED( orm->win_wait(orm, sInfo.seg_id) );
//
//
//
#elif WITH_NOTIFYACK
/** 0 : increase overlap by sending ack "perhaps a wee tad too soon".
* - This really separates SEGSYNC_NOTIFY_ACK into two distinct flavors
* - SAFER_ACK==1 is the "safe" version
* - SAFER_ACK==0 sends the ACK while the reduction is ongoing
* - should \b usually be OK if the calculation
* takes longer than the reduction (perhaps this could be measured,
* from time to time, within liborm and auto-adapted)
*/
#define SAFER_ACK 0
if( segsync==SEGSYNC_NOTIFY || segsync==SEGSYNC_NOTIFY_ACK ){
// XXX Q: SegSenderAcks::wait_write_notify_all() ?
// blocking notify_waitsome for ALL rBufs to have arrived
orm_notification_id_t const ntBeg = sInfo.rbufNotifyBeg();
orm_number_t const ntNum = recv.size(); // was sInfo.rbufNotifyEnd() - sInfo.rbufNotifyBeg();
assert( (unsigned)(sInfo.rbufNotifyEnd() - sInfo.rbufNotifyBeg()) == recv.size() ); // used to hold for dstsgd5
if(verbose>1) DST_COUT(" r"<<iProc<<" waiting for "<<" ntNum="<<ntNum<<" notifications at ntId "<<ntBeg<<".."<<ntBeg+ntNum-1);
if( ntNum <= 0U )
throw(" Ooops, is this SEGSYNC_NOTIFY with no receive buffers valid? SEG_ONE support might need some code mods!");
if( this->nDead() ) throw std::runtime_error("reduce: write_notify dead node support TBD");
std::ostringstream oss;
// many-to-one receipt of notifications
for( orm_number_t ntCnt = 0; ntCnt<ntNum; ++ntCnt)
{// block on ALL write notifications (and certainly their writes) having arrived
// NOTE: could also think of sequential reduce, so that the ACK gets sent back ASAP
orm_notification_id_t id; // which notification did we get? in range 0..rcvList.size()-1
if( orm_notify_waitsome( sInfo.seg_id, ntBeg, ntNum, &id, ORM_BLOCK ) != ORM_SUCCESS )
throw( "SEGSYNC_NOTIFY waitsome failure during reduce" );
if(verbose) oss<<(ntCnt>0?"\n\t\t":" ")<<"r"<<iProc<<" ntCnt "<<ntCnt<<" of "<<ntNum<<" notification id "<<id
<<" (rbuf "<<sInfo.rbufBeg() + (id - sInfo.rbufNotifyBeg())<<")"
<<" wait "<<ntCnt+1U<<"/"<<ntNum;
orm_notification_t val = 0;
if( orm_notify_reset( sInfo.seg_id, id, &val ) != ORM_SUCCESS )
throw( "SEGSYNC_NOTIFY reset failure during reduce" );
assert( val == NTF_RUNNING );
if( !SAFER_ACK && segsync==SEGSYNC_NOTIFY_ACK )
{ // immediately send back ACK meaning "write data received"
// this is a weak guarantee: modifying obuf after getting the ack
// MIGHT still cause mixed-version issues!
orm_rank_t const ackTo = recv[id]; // rank ackTo notified us.
SenderInfo const& sender = ackToIter->second[id]; // more sender info, about rank ackTo
// all ranks use recvlist_size write_notifies, followed by sendlist_size ack-notifies
// sendlist_index : which of ackTo's sendlist items point at us.
orm_notification_id_t ackId = sender.recvlist_size + sender.sendlist_index;
orm_notification_t ackVal = orm_notification_t(NTF_ACK);
if(NOTACK_DBG) DST_COUT( "NotAck: B reduce orm_notify( seg_id="<<(unsigned)sInfo.seg_id<<" ackTo="<<(unsigned)ackTo
<<" ackId="<<(unsigned)ackId<<" ackVal="<<(unsigned)ackVal
<<" q=0, ORM_BLOCK )");
WAIT_GQUEUE_ack_NOT_TOO_FULL;
NEED( orm_notify( sInfo.seg_id, ackTo, ackId, ackVal, GQUEUE_ack, ORM_BLOCK ));
}
}
if(verbose>1) DST_COUT(oss.str());
else if(verbose==1) DST_COUT(" r"<<iProc<<" "<<ntNum<<" notifications received");
}
#else
#warning "Warning: using a barrier in Dstorm::reduce(Segnum)"
this->barrier();
#endif
//#endif
if(1) // ( WITH_LIBORM || red != REDUCE_STREAM )
{ // Perform the [multiple-rbuf, nonstreaming] reduce:
if(verbose>1) ORM_COUT(this->orm, "Dstorm::reduce( s="<<s<<" ["<<demangle(typeid(+sInfo).name())<<"])");
SegPolicy const lay = sInfo.policy & SEG_LAYOUT_MASK;
if( SEG_FULL == lay ){
nReduce = sInfo.segimpl_reduce();
if(verbose>1) ORM_COUT(this->orm, "Dstorm::reduce( s="<<s<<") returning nReduce = "<<nReduce);
}else if( SEG_ONE == lay ){
if( red != REDUCE_NOP )
throw std::runtime_error("SEG_ONE layout does not support a delayed reduce operation");
if(verbose>1) ORM_COUT(this->orm, "Dstorm::reduce( s="<<s<<") REDUCE_NOP with SEG_ONE (no-op) is acceptable");
}else{
throw std::runtime_error("unsupported layout");
}
}
#if WITH_LIBORM
// FIXME: dstorm.cuh had at THIS POINT:
//
// if( segsync == SEGSYNC_NOTIFY_ACK /*|| red == REDUCE_STREAM*/ ){
// // reduce only uses the send queue for ACKs
// ackToIter = this->recv_src.find( sInfo.ionet );
// if( ackToIter == this->recv_src.end() ) throw std::runtime_error("recv_src incomplete");
//}
//
// Generic "my rbufs are ready to receive"
NEED( orm->win_post(orm, sInfo.seg_id) );
//
#elif WITH_NOTIFYACK
// ACK ** after ** reduce [above] is MUCH PREFERED (strong guarantee: you can modify your oBuf)
if( SAFER_ACK && segsync==SEGSYNC_NOTIFY_ACK )
{
assert( recv.size() > 1 ); // only if needed should we have delayed ACKing
for( uint32_t id=0; id<recv.size(); ++id )
{ // delayed send back ACK meaning "write data received AND you can push more to me"
orm_rank_t const ackTo = recv[id]; // rank ackTo notified us.
SenderInfo const& sender = ackToIter->second[id]; // more sender info, about rank ackTo
// all ranks use recvlist_size write_notifies, followed by sendlist_size ack-notifies
// sendlist_index : which of ackTo's sendlist items point at us.
orm_notification_id_t ackId = sender.recvlist_size + sender.sendlist_index;
orm_notification_t ackVal = orm_notification_t(NTF_ACK);
if(NOTACK_DBG) DST_COUT( "NotAck: C reduce orm_notify( seg_id="<<(unsigned)sInfo.seg_id<<" ackTo="<<(unsigned)ackTo
<<" ackId="<<(unsigned)ackId<<" ackVal="<<(unsigned)ackVal
<<" q=0, ORM_BLOCK )");
WAIT_GQUEUE_ack_NOT_TOO_FULL;
NEED( orm_notify( sInfo.seg_id, ackTo, ackId, ackVal, GQUEUE_ack, ORM_BLOCK ));
}
}
#else
#warning "Warning: using a barrier in dstorm.hh, function Dstorm::reduce"
this->barrier();
#endif
#undef SAFER_ACK
return nReduce;
}//Dstorm::reduce
#undef WAIT_GQUEUE_ack_NOT_TOO_FULL
#endif // dstorm_any2
}//dStorm::
#endif // DSTORM_ANY2_HH
| 54.797927
| 145
| 0.553565
|
malt2
|
dc9d41d23ce950310202cd085a0b172f6392e8b7
| 51
|
cpp
|
C++
|
Refureku/Library/Source/Object.cpp
|
Angelysse/Refureku
|
1f01107c94cd81998068ce3fde02bb21c180166b
|
[
"MIT"
] | 143
|
2020-04-07T21:38:21.000Z
|
2022-03-30T01:06:33.000Z
|
Refureku/Library/Source/Object.cpp
|
Angelysse/Refureku
|
1f01107c94cd81998068ce3fde02bb21c180166b
|
[
"MIT"
] | 7
|
2021-03-30T07:26:21.000Z
|
2022-03-28T16:31:02.000Z
|
Refureku/Library/Source/Object.cpp
|
Angelysse/Refureku
|
1f01107c94cd81998068ce3fde02bb21c180166b
|
[
"MIT"
] | 11
|
2020-06-06T09:45:12.000Z
|
2022-01-25T17:17:55.000Z
|
#include "Refureku/Object.h"
using namespace rfk;
| 12.75
| 28
| 0.764706
|
Angelysse
|
dc9f8640e8e2c66788d71354eee766cea6db8ac3
| 47,680
|
cpp
|
C++
|
src/Base/PositionTagGroupItem.cpp
|
team-FisMa/choreonoid
|
83265e8ffe96eb0aec977be7a43cd8c218fc5905
|
[
"MIT"
] | 66
|
2020-03-11T14:06:01.000Z
|
2022-03-23T23:18:27.000Z
|
src/Base/PositionTagGroupItem.cpp
|
team-FisMa/choreonoid
|
83265e8ffe96eb0aec977be7a43cd8c218fc5905
|
[
"MIT"
] | 12
|
2020-07-23T06:13:11.000Z
|
2022-01-13T14:25:01.000Z
|
src/Base/PositionTagGroupItem.cpp
|
team-FisMa/choreonoid
|
83265e8ffe96eb0aec977be7a43cd8c218fc5905
|
[
"MIT"
] | 18
|
2020-07-17T15:57:54.000Z
|
2022-03-29T13:18:59.000Z
|
#include "PositionTagGroupItem.h"
#include "ItemManager.h"
#include "SceneWidget.h"
#include "SceneWidgetEventHandler.h"
#include "PositionDragger.h"
#include "CoordinateFrameMarker.h"
#include "Dialog.h"
#include "Buttons.h"
#include "CheckBox.h"
#include "LazyCaller.h"
#include "Archive.h"
#include "PutPropertyFunction.h"
#include "MenuManager.h"
#include "UnifiedEditHistory.h"
#include "EditRecord.h"
#include <cnoid/PositionTagGroup>
#include <cnoid/SceneDrawables>
#include <cnoid/ConnectionSet>
#include <cnoid/EigenArchive>
#include <fmt/format.h>
#include <QBoxLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <map>
#include "gettext.h"
using namespace std;
using namespace cnoid;
using fmt::format;
namespace {
map<PositionTagGroupPtr, PositionTagGroupItem*> tagGroupToItemMap;
enum LocationMode { TagGroupLocation, TagLocation };
enum TagDisplayType { Normal, Selected, Highlighted };
constexpr float HighlightSizeRatio = 1.1f;
class SceneTag : public SgPosTransform
{
public:
SceneTag() : displayType(Normal) { }
TagDisplayType displayType;
};
class SceneTagGroup : public SgPosTransform, public SceneWidgetEventHandler
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PositionTagGroupItem::Impl* impl;
SgPosTransformPtr offsetTransform;
SgGroupPtr tagMarkerGroup;
SgNodePtr tagMarker;
SgNodePtr selectedTagMarker;
SgNodePtr highlightedTagMarker;
int highlightedTagIndex;
SgLineSetPtr markerLineSet;
CoordinateFrameMarkerPtr originMarker;
SgLineSetPtr edgeLineSet;
SgUpdate update;
ScopedConnectionSet tagGroupConnections;
PositionDraggerPtr positionDragger;
int draggingTagIndex;
Isometry3 initialDraggerPosition;
struct TagPosition
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
int index;
Isometry3 T;
TagPosition(int index, const Isometry3& T) : index(index), T(T) { }
};
vector<TagPosition, Eigen::aligned_allocator<TagPosition>> initialTagDragPositions;
SceneTagGroup(PositionTagGroupItem::Impl* itemImpl);
void finalize();
void addTagNode(int index, bool doUpdateEdges, bool doNotify);
SgNode* getOrCreateTagMarker();
SgNode* getOrCreateSelectedTagMarker();
SgNode* getOrCreateHighlightedTagMarker();
void removeTagNode(int index);
void updateTagNodePosition(int index);
void updateTagDisplayTypes();
bool updateTagDisplayType(int index, bool doNotify);
void updateEdges(bool doNotify);
void setOriginOffset(const Isometry3& T);
void setParentPosition(const Isometry3& T);
void setOriginMarkerVisibility(bool on);
void setEdgeVisiblility(bool on);
void setHighlightedTagIndex(int index);
void attachPositionDragger(int tagIndex);
void onDraggerDragStarted();
void onDraggerDragged();
void onDraggerDragFinished();
int findPointingTagIndex(SceneWidgetEvent* event);
virtual bool onPointerMoveEvent(SceneWidgetEvent* event) override;
virtual void onPointerLeaveEvent(SceneWidgetEvent* event) override;
virtual bool onButtonPressEvent(SceneWidgetEvent* event) override;
virtual void onFocusChanged(SceneWidgetEvent* event, bool on) override;
virtual bool onContextMenuRequest(SceneWidgetEvent* event, MenuManager* menu) override;
};
typedef ref_ptr<SceneTagGroup> SceneTagGroupPtr;
class TargetLocationProxy : public LocationProxy
{
public:
PositionTagGroupItem::Impl* impl;
TargetLocationProxy(PositionTagGroupItem::Impl* impl);
const PositionTag* getTargetTag() const;
virtual std::string getName() const override;
virtual Item* getCorrespondingItem() override;
virtual Isometry3 getLocation() const override;
virtual bool setLocation(const Isometry3& T) override;
virtual void finishLocationEditing() override;
virtual SignalProxy<void()> sigLocationChanged() override;
virtual LocationProxyPtr getParentLocationProxy() const override;
};
typedef ref_ptr<TargetLocationProxy> TargetLocationProxyPtr;
class TagParentLocationProxy : public LocationProxy
{
public:
PositionTagGroupItem::Impl* impl;
TagParentLocationProxy(PositionTagGroupItem::Impl* impl);
virtual std::string getName() const override;
virtual Isometry3 getLocation() const override;
virtual SignalProxy<void()> sigLocationChanged() override;
virtual LocationProxyPtr getParentLocationProxy() const override;
};
typedef ref_ptr<TagParentLocationProxy> TagParentLocationProxyPtr;
class OffsetEditRecord : public EditRecord
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PositionTagGroupItemPtr tagGroupItem;
Isometry3 T_new;
Isometry3 T_old;
OffsetEditRecord(
PositionTagGroupItem* tagGroupItem, const Isometry3& T_new, const Isometry3& T_old);
OffsetEditRecord(const OffsetEditRecord& org);
virtual EditRecord* clone() const override;
virtual std::string label() const override;
virtual bool undo() override;
virtual bool redo() override;
};
enum TagAction { AddAction = 1, UpdateAction, RemoveAction };
class TagEditRecord : public EditRecord
{
public:
PositionTagGroupItemPtr tagGroupItem;
PositionTagGroupItem::Impl* tagGroupItemImpl;
TagAction action;
int tagIndex;
PositionTagPtr newTag;
PositionTagPtr oldTag;
TagEditRecord(PositionTagGroupItem::Impl* tagGroupItemImpl, TagAction action, int tagIndex,
PositionTag* newTag, PositionTag* oldTag);
TagEditRecord(const TagEditRecord& org);
void setTags(PositionTag* newTag0, PositionTag* oldTag0);
virtual EditRecord* clone() const override;
virtual std::string label() const override;
virtual bool undo() override;
virtual bool redo() override;
};
class ConversionDialog : public Dialog
{
public:
QLabel descriptionLabel;
RadioButton globalCoordRadio;
RadioButton localCoordRadio;
CheckBox clearOriginOffsetCheck;
ConversionDialog();
void setTargets(PositionTagGroupItem* tagGroupItem, LocationProxyPtr newParentLocation);
};
}
namespace cnoid {
class PositionTagGroupItem::Impl
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PositionTagGroupItem* self;
PositionTagGroupPtr tagGroup;
Isometry3 T_parent;
Isometry3 T_offset;
ScopedConnectionSet tagGroupConnections;
Signal<void()> sigOriginOffsetPreviewRequested;
Signal<void()> sigOriginOffsetUpdated;
LazyCaller notifyUpdateLater;
UnifiedEditHistory* history;
Isometry3 lastEdit_T_offset;
PositionTagGroupPtr lastEditTagGroup;
bool isDoingUndoOrRedo;
bool needToUpdateSelectedTagIndices;
std::vector<bool> tagSelection;
int numSelectedTags;
std::vector<int> selectedTagIndices;
Signal<void()> sigTagSelectionChanged;
LocationMode locationMode;
int locationTargetTagIndex;
TargetLocationProxyPtr targetLocation;
Signal<void()> sigTargetLocationChanged;
LocationProxyPtr groupParentLocation;
ScopedConnection groupParentLocationConnection;
TagParentLocationProxyPtr tagParentLocation;
Signal<void()> sigTagParentLocationChanged;
SceneTagGroupPtr sceneTagGroup;
SgFixedPixelSizeGroupPtr fixedSizeTagMarker;
SgFixedPixelSizeGroupPtr fixedSizeSelectedTagMarker;
SgFixedPixelSizeGroupPtr fixedSizeHighlightedTagMarker;
SgMaterialPtr material;
bool originMarkerVisibility;
bool edgeVisibility;
Impl(PositionTagGroupItem* self, const Impl* org);
void setupHandlersForUnifiedEditHistory();
void onTagAdded(int index);
void onTagRemoved(int index, PositionTag* tag);
void onTagPositionUpdated(int index);
bool clearTagSelection(bool doNotify);
void selectAllTags();
void setTagSelected(int tagIndex, bool on, bool doNotify);
bool checkTagSelected(int tagIndex) const;
void onTagSelectionChanged(bool doUpdateTagDisplayTypes);
void removeSelectedTags();
void setParentItemLocationProxy(
LocationProxyPtr newParentLocation, bool doCoordinateConversion, bool doClearOriginOffset);
void convertLocalCoordinates(
LocationProxy* currentParentLocation, LocationProxy* newParentLocation, bool doClearOriginOffset);
void onParentItemLocationChanged();
};
}
void PositionTagGroupItem::initializeClass(ExtensionManager* ext)
{
static bool initialized = false;
if(!initialized){
auto& im = ext->itemManager();
im.registerClass<PositionTagGroupItem>(N_("PositionTagGroupItem"));
im.addCreationPanel<PositionTagGroupItem>();
initialized = true;
}
}
PositionTagGroupItem* PositionTagGroupItem::findItemOf(PositionTagGroup* tagGroup)
{
auto p = tagGroupToItemMap.find(tagGroup);
if(p != tagGroupToItemMap.end()){
return p->second;
}
return nullptr;
}
PositionTagGroupItem::PositionTagGroupItem()
{
impl = new Impl(this, nullptr);
}
PositionTagGroupItem::PositionTagGroupItem(const PositionTagGroupItem& org)
: Item(org)
{
impl = new Impl(this, org.impl);
}
PositionTagGroupItem::Impl::Impl(PositionTagGroupItem* self, const Impl* org)
: self(self),
notifyUpdateLater([this](){ this->self->notifyUpdate(); })
{
if(!org){
tagGroup = new PositionTagGroup;
} else {
tagGroup = new PositionTagGroup(*org->tagGroup);
}
tagGroupToItemMap[tagGroup] = self;
history = UnifiedEditHistory::instance();
isDoingUndoOrRedo = false;
needToUpdateSelectedTagIndices = false;
numSelectedTags = 0;
locationMode = TagGroupLocation;
locationTargetTagIndex = -1;
targetLocation = new TargetLocationProxy(this);
tagParentLocation = new TagParentLocationProxy(this);
fixedSizeTagMarker = new SgFixedPixelSizeGroup;
fixedSizeSelectedTagMarker = new SgFixedPixelSizeGroup;
fixedSizeHighlightedTagMarker = new SgFixedPixelSizeGroup;
material = new SgMaterial;
originMarkerVisibility = false;
edgeVisibility = false;
float s;
if(!org){
s = 24.0f;
originMarkerVisibility = false;
edgeVisibility = false;
T_parent.setIdentity();
T_offset.setIdentity();
} else {
s = org->fixedSizeTagMarker->pixelSizeRatio();
originMarkerVisibility = org->originMarkerVisibility;
edgeVisibility = org->edgeVisibility;
T_parent = org->T_parent;
T_offset = org->T_offset;
}
fixedSizeTagMarker->setPixelSizeRatio(s);
fixedSizeSelectedTagMarker->setPixelSizeRatio(s * HighlightSizeRatio);
fixedSizeHighlightedTagMarker->setPixelSizeRatio(s * HighlightSizeRatio);
}
PositionTagGroupItem::~PositionTagGroupItem()
{
tagGroupToItemMap.erase(impl->tagGroup);
delete impl;
}
Item* PositionTagGroupItem::doDuplicate() const
{
return new PositionTagGroupItem(*this);
}
void PositionTagGroupItem::onConnectedToRoot()
{
impl->setupHandlersForUnifiedEditHistory();
}
void PositionTagGroupItem::Impl::setupHandlersForUnifiedEditHistory()
{
lastEdit_T_offset = T_offset;
lastEditTagGroup = tagGroup->clone();
tagGroupConnections.add(
tagGroup->sigTagAdded().connect(
[&](int index){ onTagAdded(index); }));
tagGroupConnections.add(
tagGroup->sigTagRemoved().connect(
[&](int index, PositionTag* tag){ onTagRemoved(index, tag); }));
tagGroupConnections.add(
tagGroup->sigTagPositionUpdated().connect(
[&](int index){ onTagPositionUpdated(index); }));
}
void PositionTagGroupItem::onDisconnectedFromRoot()
{
impl->tagGroupConnections.disconnect();
}
bool PositionTagGroupItem::setName(const std::string& name)
{
impl->tagGroup->setName(name);
Item::setName(name);
return true;
}
const PositionTagGroup* PositionTagGroupItem::tagGroup() const
{
return impl->tagGroup;
}
PositionTagGroup* PositionTagGroupItem::tagGroup()
{
return impl->tagGroup;
}
const Isometry3& PositionTagGroupItem::parentFramePosition() const
{
return impl->T_parent;
}
const Isometry3& PositionTagGroupItem::originOffset() const
{
return impl->T_offset;
}
void PositionTagGroupItem::setOriginOffset(const Isometry3& T_offset, bool requestPreview)
{
impl->T_offset = T_offset;
if(requestPreview){
impl->sigOriginOffsetPreviewRequested();
impl->sigTargetLocationChanged();
if(impl->sceneTagGroup){
impl->sceneTagGroup->setOriginOffset(T_offset);
}
}
}
Isometry3 PositionTagGroupItem::originPosition() const
{
return impl->T_parent * impl->T_offset;
}
SignalProxy<void()> PositionTagGroupItem::sigOriginOffsetPreviewRequested()
{
return impl->sigOriginOffsetPreviewRequested;
}
SignalProxy<void()> PositionTagGroupItem::sigOriginOffsetUpdated()
{
return impl->sigOriginOffsetUpdated;
}
void PositionTagGroupItem::notifyOriginOffsetUpdate(bool requestPreview)
{
if(requestPreview){
impl->sigOriginOffsetPreviewRequested();
}
impl->sigOriginOffsetUpdated();
impl->history->addRecord(new OffsetEditRecord(this, impl->T_offset, impl->lastEdit_T_offset));
impl->lastEdit_T_offset = impl->T_offset;
}
void PositionTagGroupItem::Impl::onTagAdded(int index)
{
if(index < static_cast<int>(tagSelection.size())){
tagSelection.insert(tagSelection.begin() + index, false);
needToUpdateSelectedTagIndices = true;
}
auto tag = tagGroup->tagAt(index);
lastEditTagGroup->insert(index, new PositionTag(*tag));
if(!isDoingUndoOrRedo){
history->addRecord(new TagEditRecord(this, AddAction, index, tag, nullptr));
}
notifyUpdateLater();
}
void PositionTagGroupItem::Impl::onTagRemoved(int index, PositionTag* tag)
{
if(index < static_cast<int>(tagSelection.size())){
tagSelection.erase(tagSelection.begin() + index);
needToUpdateSelectedTagIndices = true;
}
lastEditTagGroup->removeAt(index);
if(!isDoingUndoOrRedo){
history->addRecord(new TagEditRecord(this, RemoveAction, index, nullptr, tag));
}
notifyUpdateLater();
}
void PositionTagGroupItem::Impl::onTagPositionUpdated(int index)
{
auto newTag = tagGroup->tagAt(index);
auto lastTag = lastEditTagGroup->tagAt(index);
if(!isDoingUndoOrRedo){
history->addRecord(new TagEditRecord(this, UpdateAction, index, newTag, lastTag));
}
*lastTag = *newTag;
if(locationMode == TagLocation && locationTargetTagIndex == index){
sigTargetLocationChanged();
}
notifyUpdateLater();
}
void PositionTagGroupItem::clearTagSelection()
{
impl->clearTagSelection(true);
}
bool PositionTagGroupItem::Impl::clearTagSelection(bool doNotify)
{
bool doClear = (numSelectedTags > 0);
tagSelection.clear();
if(doClear){
numSelectedTags = 0;
needToUpdateSelectedTagIndices = true;
if(doNotify){
onTagSelectionChanged(true);
}
}
return doClear;
}
void PositionTagGroupItem::Impl::selectAllTags()
{
tagSelection.clear();
numSelectedTags = tagGroup->numTags();
tagSelection.resize(numSelectedTags, true);
needToUpdateSelectedTagIndices = true;
onTagSelectionChanged(true);
}
void PositionTagGroupItem::setTagSelected(int tagIndex, bool on)
{
impl->setTagSelected(tagIndex, on, true);
}
void PositionTagGroupItem::Impl::setTagSelected(int tagIndex, bool on, bool doNotify)
{
if(tagIndex >= tagSelection.size()){
tagSelection.resize(tagIndex + 1);
}
if(on != tagSelection[tagIndex]){
tagSelection[tagIndex]= on;
if(on){
++numSelectedTags;
} else {
--numSelectedTags;
}
needToUpdateSelectedTagIndices = true;
if(doNotify){
if(sceneTagGroup){
sceneTagGroup->updateTagDisplayType(tagIndex, true);
}
onTagSelectionChanged(false);
}
}
}
bool PositionTagGroupItem::checkTagSelected(int tagIndex) const
{
return impl->checkTagSelected(tagIndex);
}
bool PositionTagGroupItem::Impl::checkTagSelected(int tagIndex) const
{
if(tagIndex < tagSelection.size()){
return tagSelection[tagIndex];
}
return false;
}
const std::vector<int>& PositionTagGroupItem::selectedTagIndices() const
{
if(impl->needToUpdateSelectedTagIndices){
impl->selectedTagIndices.clear();
for(size_t i=0; i < impl->tagSelection.size(); ++i){
if(impl->tagSelection[i]){
impl->selectedTagIndices.push_back(i);
}
}
impl->needToUpdateSelectedTagIndices = false;
}
return impl->selectedTagIndices;
}
void PositionTagGroupItem::setSelectedTagIndices(const std::vector<int>& indices)
{
auto prevIndices = selectedTagIndices();
if(indices != prevIndices){
impl->clearTagSelection(false);
for(auto& index : indices){
impl->setTagSelected(index, true, false);
}
impl->onTagSelectionChanged(true);
}
}
void PositionTagGroupItem::Impl::onTagSelectionChanged(bool doUpdateTagDisplayTypes)
{
if(sceneTagGroup && doUpdateTagDisplayTypes){
sceneTagGroup->updateTagDisplayTypes();
}
sigTagSelectionChanged();
if(numSelectedTags == 0){
locationMode = TagGroupLocation;
locationTargetTagIndex = -1;
} else {
locationMode = TagLocation;
locationTargetTagIndex = 0;
for(size_t i=0; i < tagSelection.size(); ++i){
if(tagSelection[i]){
locationTargetTagIndex = i;
break;
}
}
}
targetLocation->notifyAttributeChange();
sigTargetLocationChanged();
}
SignalProxy<void()> PositionTagGroupItem::sigTagSelectionChanged()
{
return impl->sigTagSelectionChanged;
}
void PositionTagGroupItem::Impl::removeSelectedTags()
{
auto selection = tagSelection;
size_t n = selection.size();
int numRemoved = 0;
for(int i=0; i < n; ++i){
if(selection[i]){
tagGroup->removeAt(i - numRemoved++);
}
}
}
SgNode* PositionTagGroupItem::getScene()
{
if(!impl->sceneTagGroup){
impl->sceneTagGroup = new SceneTagGroup(impl);
}
return impl->sceneTagGroup;
}
LocationProxyPtr PositionTagGroupItem::getLocationProxy()
{
return impl->targetLocation;
}
bool PositionTagGroupItem::onNewTreePositionCheck(bool isManualOperation, std::function<void()>& out_callbackWhenAdded)
{
bool accepted = true;
LocationProxyPtr newParentLocation;
if(auto parentLocatableItem = findOwnerItem<LocatableItem>()){
newParentLocation = parentLocatableItem->getLocationProxy();
}
bool isParentLocationChanged = (newParentLocation != impl->groupParentLocation);
bool doCoordinateConversion = false;
bool doClearOriginOffset = false;
if(isManualOperation && isParentLocationChanged){
static ConversionDialog* dialog = nullptr;
if(!dialog){
dialog = new ConversionDialog;
}
dialog->setTargets(this, newParentLocation);
if(dialog->exec() == QDialog::Accepted){
doCoordinateConversion = dialog->globalCoordRadio.isChecked();
doClearOriginOffset = dialog->clearOriginOffsetCheck.isChecked();
} else {
accepted = false;
}
}
if(accepted && isParentLocationChanged){
out_callbackWhenAdded =
[this, newParentLocation, doCoordinateConversion, doClearOriginOffset](){
impl->setParentItemLocationProxy(
newParentLocation, doCoordinateConversion, doClearOriginOffset);
};
}
return accepted;
}
void PositionTagGroupItem::Impl::setParentItemLocationProxy
(LocationProxyPtr newParentLocation, bool doCoordinateConversion, bool doClearOriginOffset)
{
groupParentLocationConnection.disconnect();
if(doCoordinateConversion){
convertLocalCoordinates(groupParentLocation, newParentLocation, doClearOriginOffset);
}
groupParentLocation = newParentLocation;
if(groupParentLocation){
groupParentLocationConnection =
groupParentLocation->sigLocationChanged().connect(
[&](){ onParentItemLocationChanged(); });
}
onParentItemLocationChanged();
// Notify the change of the parent location proxy
targetLocation->notifyAttributeChange();
}
void PositionTagGroupItem::Impl::convertLocalCoordinates
(LocationProxy* currentParentLocation, LocationProxy* newParentLocation, bool doClearOriginOffset)
{
Isometry3 T0 = self->originPosition();
if(doClearOriginOffset){
self->setOriginOffset(Isometry3::Identity(), false);
self->notifyOriginOffsetUpdate();
}
Isometry3 T1 = T_offset;
if(newParentLocation){
T1 = newParentLocation->getLocation() * T1;
}
Isometry3 Tc = T1.inverse(Eigen::Isometry) * T0;
int n = tagGroup->numTags();
for(int i=0; i < n; ++i){
auto tag = tagGroup->tagAt(i);
if(tag->hasAttitude()){
tag->setPosition(Tc * tag->position());
} else {
tag->setTranslation(Tc * tag->translation());
}
tagGroup->notifyTagPositionUpdate(i);
}
self->notifyUpdate();
}
void PositionTagGroupItem::Impl::onParentItemLocationChanged()
{
if(groupParentLocation){
T_parent = groupParentLocation->getLocation();
} else {
T_parent.setIdentity();
}
if(sceneTagGroup){
sceneTagGroup->setParentPosition(T_parent);
}
sigTargetLocationChanged();
}
double PositionTagGroupItem::tagMarkerSize() const
{
return impl->fixedSizeTagMarker->pixelSizeRatio();
}
void PositionTagGroupItem::setTagMarkerSize(double s)
{
auto& marker = impl->fixedSizeTagMarker;
if(s != marker->pixelSizeRatio()){
marker->setPixelSizeRatio(s);
impl->fixedSizeSelectedTagMarker->setPixelSizeRatio(s * HighlightSizeRatio);
impl->fixedSizeHighlightedTagMarker->setPixelSizeRatio(s * HighlightSizeRatio);
if(impl->sceneTagGroup){
impl->sceneTagGroup->notifyUpdate();
}
}
}
bool PositionTagGroupItem::originMarkerVisibility() const
{
return impl->originMarkerVisibility;
}
void PositionTagGroupItem::setOriginMarkerVisibility(bool on)
{
if(on != impl->originMarkerVisibility){
impl->originMarkerVisibility = on;
if(impl->sceneTagGroup){
impl->sceneTagGroup->setOriginMarkerVisibility(on);
}
}
}
bool PositionTagGroupItem::edgeVisibility() const
{
return impl->edgeVisibility;
}
void PositionTagGroupItem::setEdgeVisiblility(bool on)
{
if(on != impl->edgeVisibility){
impl->edgeVisibility = on;
if(impl->sceneTagGroup){
impl->sceneTagGroup->setEdgeVisiblility(on);
}
}
}
float PositionTagGroupItem::transparency() const
{
return impl->material->transparency();
}
void PositionTagGroupItem::setTransparency(float t)
{
impl->material->setTransparency(t);
impl->material->notifyUpdate();
}
void PositionTagGroupItem::doPutProperties(PutPropertyFunction& putProperty)
{
putProperty(_("Number of tags"), impl->tagGroup->numTags());
putProperty(_("Offset translation"), str(Vector3(impl->T_offset.translation())));
Vector3 rpy(degree(rpyFromRot(impl->T_offset.linear())));
putProperty(_("Offset rotation (RPY)"), str(rpy));
putProperty(_("Origin marker"), impl->originMarkerVisibility,
[&](bool on){ setOriginMarkerVisibility(on); return true; });
putProperty(_("Tag marker size"), tagMarkerSize(),
[&](double s){ setTagMarkerSize(s); return true; });
putProperty(_("Show edges"), impl->edgeVisibility,
[&](bool on){ setEdgeVisiblility(on); return true; });
putProperty(_("Transparency"), transparency(),
[&](float t){ setTransparency(t); return true; });
}
bool PositionTagGroupItem::store(Archive& archive)
{
impl->tagGroup->write(&archive);
archive.setFloatingNumberFormat("%.9g");
cnoid::write(archive, "offset_translation", impl->T_offset.translation());
cnoid::write(archive, "offset_rpy", degree(rpyFromRot(impl->T_offset.linear())));
archive.write("origin_marker", impl->originMarkerVisibility);
archive.write("tag_marker_size", tagMarkerSize());
archive.write("show_edges", impl->edgeVisibility);
return true;
}
bool PositionTagGroupItem::restore(const Archive& archive)
{
Vector3 v;
if(cnoid::read(archive, "offset_translation", v)){
impl->T_offset.translation() = v;
}
if(cnoid::read(archive, "offset_rpy", v)){
impl->T_offset.linear() = rotFromRpy(radian(v));
}
if(archive.get("origin_marker", false)){
setOriginMarkerVisibility(true);
}
double s;
if(archive.read("tag_marker_size", s)){
setTagMarkerSize(s);
}
bool on;
if(archive.read("show_edges", on)){
setEdgeVisiblility(on);
}
return impl->tagGroup->read(&archive);
}
namespace {
SceneTagGroup::SceneTagGroup(PositionTagGroupItem::Impl* impl)
: impl(impl)
{
auto tagGroup = impl->tagGroup;
setPosition(impl->T_parent);
offsetTransform = new SgPosTransform;
offsetTransform->setPosition(impl->T_offset);
addChild(offsetTransform);
tagMarkerGroup = new SgGroup;
offsetTransform->addChild(tagMarkerGroup);
highlightedTagIndex = -1;
int n = tagGroup->numTags();
for(int i=0; i < n; ++i){
addTagNode(i, false, false);
}
edgeLineSet = new SgLineSet;
edgeLineSet->setLineWidth(2.0f);
auto material = edgeLineSet->getOrCreateMaterial();
material->setDiffuseColor(Vector3f(0.9f, 0.9f, 0.9f));
if(impl->edgeVisibility){
setEdgeVisiblility(true);
}
if(impl->originMarkerVisibility){
setOriginMarkerVisibility(true);
}
draggingTagIndex = -1;
tagGroupConnections.add(
tagGroup->sigTagAdded().connect(
[&](int index){ addTagNode(index, true, true); }));
tagGroupConnections.add(
tagGroup->sigTagRemoved().connect(
[&](int index, PositionTag*){ removeTagNode(index); }));
tagGroupConnections.add(
tagGroup->sigTagPositionChanged().connect(
[&](int index){ updateTagNodePosition(index); }));
}
void SceneTagGroup::finalize()
{
tagGroupConnections.disconnect();
impl = nullptr;
}
void SceneTagGroup::addTagNode(int index, bool doUpdateEdges, bool doNotify)
{
auto tag = impl->tagGroup->tagAt(index);
auto tagNode = new SceneTag;
if(impl->checkTagSelected(index)){
tagNode->addChild(getOrCreateSelectedTagMarker());
tagNode->displayType = Selected;
} else {
tagNode->addChild(getOrCreateTagMarker());
}
tagNode->setPosition(tag->position());
tagMarkerGroup->insertChild(index, tagNode, doNotify ? &update : nullptr);
if(doUpdateEdges){
updateEdges(doNotify);
}
}
SgNode* SceneTagGroup::getOrCreateTagMarker()
{
if(!tagMarker){
auto lines = new SgLineSet;
auto& vertices = *lines->getOrCreateVertices(4);
constexpr float r = 3.0f;
constexpr float offset = -1.0f; // 0.0f or -1.0f
vertices[0] << 0.0f, 0.0f, offset; // Origin
vertices[1] << 0.0f, 0.0f, 1.0f + offset; // Z direction
vertices[2] << 1.0f / r, 0.0f, offset; // X direction
vertices[3] << 0.0f, 1.0f / r, offset; // Y direction
auto& colors = *lines->getOrCreateColors(3);
colors[0] << 0.9f, 0.0f, 0.0f; // Red
colors[1] << 0.0f, 0.8f, 0.0f; // Green
colors[2] << 0.0f, 0.0f, 0.8f; // Blue
lines->setNumLines(5);
lines->setLineWidth(1.0f);
lines->resizeColorIndicesForNumLines(5);
// Origin -> Z, Blue
lines->setLine(0, 0, 1);
lines->setLineColor(0, 2);
// Origin -> X, Red
lines->setLine(1, 0, 2);
lines->setLineColor(1, 0);
// Origin -> Y, Green
lines->setLine(2, 0, 3);
lines->setLineColor(2, 1);
// Z -> X, Red
lines->setLine(3, 1, 2);
lines->setLineColor(3, 0);
// Z -> Y, Green
lines->setLine(4, 1, 3);
lines->setLineColor(4, 1);
lines->setMaterial(impl->material);
impl->fixedSizeTagMarker->addChild(lines);
markerLineSet = lines;
tagMarker = impl->fixedSizeTagMarker;
}
return tagMarker;
}
SgNode* SceneTagGroup::getOrCreateSelectedTagMarker()
{
if(!selectedTagMarker){
if(!tagMarker){
getOrCreateTagMarker();
}
auto lines = new SgLineSet(*markerLineSet);
lines->setLineWidth(3.0f);
auto colors = new SgColorArray;
colors->reserve(3);
colors->emplace_back(1.0f, 0.3f, 0.3f); // Red
colors->emplace_back(0.2f, 1.0f, 0.2f); // Green
colors->emplace_back(0.3f, 0.3f, 1.0f); // Blue
lines->setColors(colors);
impl->fixedSizeSelectedTagMarker->addChild(lines);
selectedTagMarker = impl->fixedSizeSelectedTagMarker;
}
return selectedTagMarker;
}
SgNode* SceneTagGroup::getOrCreateHighlightedTagMarker()
{
if(!highlightedTagMarker){
if(!tagMarker){
getOrCreateTagMarker();
}
auto lines = new SgLineSet(*markerLineSet);
lines->setLineWidth(3.0f);
auto colors = new SgColorArray;
colors->reserve(3);
colors->emplace_back(1.0f, 1.0f, 0.0f); // Yellow
colors->emplace_back(1.0f, 1.0f, 0.0f); // Yellow
colors->emplace_back(1.0f, 1.0f, 0.0f); // Yellow
lines->setColors(colors);
impl->fixedSizeHighlightedTagMarker->addChild(lines);
highlightedTagMarker = impl->fixedSizeHighlightedTagMarker;
}
return highlightedTagMarker;
}
void SceneTagGroup::removeTagNode(int index)
{
tagMarkerGroup->removeChildAt(index, update);
updateEdges(true);
}
void SceneTagGroup::updateTagNodePosition(int index)
{
auto tag = impl->tagGroup->tagAt(index);
auto node = static_cast<SgPosTransform*>(tagMarkerGroup->child(index));
if(tag->hasAttitude()){
node->setPosition(tag->position());
} else {
node->setTranslation(tag->translation());
}
update.setAction(SgUpdate::MODIFIED);
node->notifyUpdate(update);
if(index == draggingTagIndex){
positionDragger->setPosition(tag->position());
positionDragger->notifyUpdate(update);
}
updateEdges(true);
}
void SceneTagGroup::updateTagDisplayTypes()
{
bool updated = false;
int n = tagMarkerGroup->numChildren();
for(int i=0; i < n; ++i){
if(updateTagDisplayType(i, false)){
updated = true;
}
}
if(updated){
tagMarkerGroup->notifyUpdate(update.withAction(SgUpdate::MODIFIED));
}
}
bool SceneTagGroup::updateTagDisplayType(int index, bool doNotify)
{
bool updated = false;
auto tagNode = static_cast<SceneTag*>(tagMarkerGroup->child(index));
TagDisplayType displayType;
if(index == highlightedTagIndex){
displayType = Highlighted;
} else if(impl->checkTagSelected(index)){
displayType = Selected;
} else {
displayType = Normal;
}
if(displayType != tagNode->displayType){
SgUpdate* pUpdate = doNotify ? &update : nullptr;
tagNode->clearChildren(pUpdate);
switch(displayType){
case Normal:
default:
tagNode->addChild(getOrCreateTagMarker(), pUpdate);
break;
case Selected:
tagNode->addChild(getOrCreateSelectedTagMarker(), pUpdate);
break;
case Highlighted:
tagNode->addChild(getOrCreateHighlightedTagMarker(), pUpdate);
break;
}
tagNode->displayType = displayType;
}
return updated;
}
void SceneTagGroup::updateEdges(bool doNotify)
{
if(!impl->edgeVisibility){
return;
}
auto& vertices = *edgeLineSet->getOrCreateVertices();
vertices.clear();
for(auto& tag : *impl->tagGroup){
vertices.push_back(tag->translation().cast<SgVertexArray::Scalar>());
}
int numLines = vertices.size() - 1;
if(numLines < 0){
numLines = 0;
}
int numLines0 = edgeLineSet->numLines();
edgeLineSet->setNumLines(numLines);
if(numLines > numLines0){
for(int i = numLines0; i < numLines; ++i){
edgeLineSet->setLine(i, i, i + 1);
}
}
if(doNotify){
vertices.notifyUpdate(update.withAction(SgUpdate::MODIFIED));
}
}
void SceneTagGroup::setOriginOffset(const Isometry3& T)
{
offsetTransform->setPosition(T);
offsetTransform->notifyUpdate(update.withAction(SgUpdate::MODIFIED));
}
void SceneTagGroup::setParentPosition(const Isometry3& T)
{
setPosition(T);
notifyUpdate(update.withAction(SgUpdate::MODIFIED));
}
void SceneTagGroup::setOriginMarkerVisibility(bool on)
{
if(on){
if(!originMarker){
originMarker = new CoordinateFrameMarker;
}
offsetTransform->addChild(originMarker, update);
} else {
if(originMarker){
offsetTransform->removeChild(originMarker, update);
}
}
}
void SceneTagGroup::setEdgeVisiblility(bool on)
{
if(on){
updateEdges(false);
offsetTransform->addChild(edgeLineSet, update);
} else {
offsetTransform->removeChild(edgeLineSet, update);
}
}
void SceneTagGroup::setHighlightedTagIndex(int index)
{
if(index != highlightedTagIndex){
int prevHighlightedTagIndex = highlightedTagIndex;
highlightedTagIndex = index;
if(prevHighlightedTagIndex >= 0){
updateTagDisplayType(prevHighlightedTagIndex, true);
}
if(highlightedTagIndex >= 0){
updateTagDisplayType(highlightedTagIndex, true);
}
}
}
void SceneTagGroup::attachPositionDragger(int tagIndex)
{
PositionTag* tag = nullptr;
if(tagIndex >= 0){
tag = impl->tagGroup->tagAt(tagIndex);
}
if(!tag){
draggingTagIndex = -1;
offsetTransform->removeChild(positionDragger, update);
} else {
if(!positionDragger){
positionDragger = new PositionDragger(PositionDragger::AllAxes, PositionDragger::PositiveOnlyHandle);
positionDragger->setOverlayMode(true);
positionDragger->setPixelSize(96, 3);
positionDragger->setDisplayMode(PositionDragger::DisplayInEditMode);
positionDragger->sigDragStarted().connect([&](){ onDraggerDragStarted(); });
positionDragger->sigPositionDragged().connect([&](){ onDraggerDragged(); });
positionDragger->sigDragFinished().connect([&](){ onDraggerDragFinished(); });
}
positionDragger->setPosition(tag->position());
offsetTransform->addChildOnce(positionDragger, update);
draggingTagIndex = tagIndex;
}
}
void SceneTagGroup::onDraggerDragStarted()
{
initialDraggerPosition = positionDragger->position();
auto& selection = impl->tagSelection;
initialTagDragPositions.clear();
initialTagDragPositions.reserve(impl->numSelectedTags);
int arrayIndex = 0;
for(size_t i=0; i < selection.size(); ++i){
if(selection[i]){
initialTagDragPositions.emplace_back(i, impl->tagGroup->tagAt(i)->position());
}
}
}
void SceneTagGroup::onDraggerDragged()
{
Isometry3 T = positionDragger->draggingPosition();
Isometry3 T_base = T * initialDraggerPosition.inverse(Eigen::Isometry);
for(auto& tagpos0 : initialTagDragPositions){
auto tag = impl->tagGroup->tagAt(tagpos0.index);
if(tagpos0.index == draggingTagIndex){
tag->setPosition(T);
positionDragger->setPosition(T);
positionDragger->notifyUpdate(update.withAction(SgUpdate::MODIFIED));
} else {
tag->setPosition(T_base * tagpos0.T);
}
impl->tagGroup->notifyTagPositionChange(tagpos0.index);
}
}
void SceneTagGroup::onDraggerDragFinished()
{
for(auto& tagpos0 : initialTagDragPositions){
impl->tagGroup->notifyTagPositionUpdate(tagpos0.index, false);
}
}
int SceneTagGroup::findPointingTagIndex(SceneWidgetEvent* event)
{
auto path = event->nodePath();
size_t tagNodeIndex = 0;
for(size_t i=0; i < path.size(); ++i){
auto node = path[i];
if(node == tagMarkerGroup){
tagNodeIndex = i + 1;
break;
}
}
int tagIndex = -1;
if(tagNodeIndex > 0 && tagNodeIndex < path.size()){
auto tagNode = dynamic_cast<SceneTag*>(path[tagNodeIndex]);
if(tagNode){
tagIndex = tagMarkerGroup->findChildIndex(tagNode);
}
}
return tagIndex;
}
bool SceneTagGroup::onPointerMoveEvent(SceneWidgetEvent* event)
{
int tagIndex = findPointingTagIndex(event);
setHighlightedTagIndex(tagIndex);
return (tagIndex >= 0);
}
void SceneTagGroup::onPointerLeaveEvent(SceneWidgetEvent* event)
{
setHighlightedTagIndex(-1);
}
bool SceneTagGroup::onButtonPressEvent(SceneWidgetEvent* event)
{
bool processed = false;
int tagIndex = findPointingTagIndex(event);
if(event->button() == Qt::LeftButton){
if(tagIndex >= 0){
bool selected = impl->checkTagSelected(tagIndex);
if(!(event->modifiers() & Qt::ControlModifier)){
if(impl->numSelectedTags >= 2 || !selected){
impl->clearTagSelection(true);
selected = false;
}
}
impl->setTagSelected(tagIndex, !selected, true);
processed = true;
}
} else if(event->button() == Qt::RightButton){
if(tagIndex >= 0 && !impl->checkTagSelected(tagIndex)){
impl->setTagSelected(tagIndex, true, true);
}
event->sceneWidget()->showContextMenuAtPointerPosition();
}
attachPositionDragger(-1);
return processed;
}
void SceneTagGroup::onFocusChanged(SceneWidgetEvent* event, bool on)
{
if(!on){
attachPositionDragger(-1);
}
}
bool SceneTagGroup::onContextMenuRequest(SceneWidgetEvent* event, MenuManager* menu)
{
int tagIndex = findPointingTagIndex(event);
auto moveAction = menu->addItem(_("Move"));
if(tagIndex < 0){
moveAction->setEnabled(false);
}
moveAction->sigTriggered().connect([this, tagIndex](){ attachPositionDragger(tagIndex); });
menu->addItem(_("Remove"))->sigTriggered().connect([&](){ impl->removeSelectedTags(); });
menu->addSeparator();
menu->addItem(_("Select all"))->sigTriggered().connect([&](){ impl->selectAllTags(); });
menu->addItem(_("Clear selection"))->sigTriggered().connect([&](){ impl->clearTagSelection(true); });
attachPositionDragger(-1);
return true;
}
TargetLocationProxy::TargetLocationProxy(PositionTagGroupItem::Impl* impl)
: LocationProxy(ParentRelativeLocation),
impl(impl)
{
}
const PositionTag* TargetLocationProxy::getTargetTag() const
{
return impl->tagGroup->tagAt(impl->locationTargetTagIndex);
}
std::string TargetLocationProxy::getName() const
{
if(impl->locationMode == TagGroupLocation){
return format(_("{0}: Origin"), impl->self->displayName());
} else {
auto tag = getTargetTag();
return format(_("{0}: Tag {1}"), impl->self->displayName(), impl->locationTargetTagIndex);
}
}
Item* TargetLocationProxy::getCorrespondingItem()
{
if(impl->locationMode == TagGroupLocation){
return impl->self;
} else {
return nullptr;
}
}
Isometry3 TargetLocationProxy::getLocation() const
{
if(impl->locationMode == TagGroupLocation){
return impl->T_offset;
} else {
return getTargetTag()->position();
}
}
bool TargetLocationProxy::setLocation(const Isometry3& T)
{
auto tagGroup = impl->tagGroup;
if(impl->locationMode == TagGroupLocation){
impl->self->setOriginOffset(T, true);
} else {
auto primaryTag = tagGroup->tagAt(impl->locationTargetTagIndex);
Isometry3 T_base = T * primaryTag->position().inverse(Eigen::Isometry);
primaryTag->setPosition(T);
for(size_t i=0; i < impl->tagSelection.size(); ++i){
if(impl->tagSelection[i]){
if(i != impl->locationTargetTagIndex){
auto tag = tagGroup->tagAt(i);
tag->setPosition(T_base * tag->position());
}
tagGroup->notifyTagPositionChange(i);
}
}
}
return true;
}
void TargetLocationProxy::finishLocationEditing()
{
auto tagGroup = impl->tagGroup;
if(impl->locationMode == TagGroupLocation){
impl->self->notifyOriginOffsetUpdate(false);
} else {
auto primaryTag = tagGroup->tagAt(impl->locationTargetTagIndex);
for(size_t i=0; i < impl->tagSelection.size(); ++i){
if(impl->tagSelection[i]){
tagGroup->notifyTagPositionUpdate(i, false);
}
}
}
}
SignalProxy<void()> TargetLocationProxy::sigLocationChanged()
{
return impl->sigTargetLocationChanged;
}
LocationProxyPtr TargetLocationProxy::getParentLocationProxy() const
{
if(impl->locationMode == TagGroupLocation){
return impl->groupParentLocation;
} else {
return impl->tagParentLocation;
}
}
TagParentLocationProxy::TagParentLocationProxy(PositionTagGroupItem::Impl* impl)
: LocationProxy(ParentRelativeLocation),
impl(impl)
{
}
std::string TagParentLocationProxy::getName() const
{
return format(_("{0}: Origin"), impl->self->name());
}
Isometry3 TagParentLocationProxy::getLocation() const
{
return impl->T_offset;
}
SignalProxy<void()> TagParentLocationProxy::sigLocationChanged()
{
return impl->sigTagParentLocationChanged;
}
LocationProxyPtr TagParentLocationProxy::getParentLocationProxy() const
{
if(impl->groupParentLocation){
return impl->groupParentLocation;
}
return nullptr;
}
OffsetEditRecord::OffsetEditRecord
(PositionTagGroupItem* tagGroupItem, const Isometry3& T_new, const Isometry3& T_old)
: tagGroupItem(tagGroupItem),
T_new(T_new),
T_old(T_old)
{
}
OffsetEditRecord::OffsetEditRecord(const OffsetEditRecord& org)
: EditRecord(org),
tagGroupItem(org.tagGroupItem),
T_new(org.T_new),
T_old(org.T_old)
{
}
EditRecord* OffsetEditRecord::clone() const
{
return new OffsetEditRecord(*this);
}
std::string OffsetEditRecord::label() const
{
return _("Change the origin offset of a position tag group");
}
bool OffsetEditRecord::undo()
{
tagGroupItem->setOriginOffset(T_old, true);
return true;
}
bool OffsetEditRecord::redo()
{
tagGroupItem->setOriginOffset(T_new, true);
return true;
}
TagEditRecord::TagEditRecord
(PositionTagGroupItem::Impl* tagGroupItemImpl, TagAction action, int tagIndex,
PositionTag* newTag, PositionTag* oldTag)
: tagGroupItem(tagGroupItemImpl->self),
tagGroupItemImpl(tagGroupItemImpl),
action(action),
tagIndex(tagIndex)
{
setTags(newTag, oldTag);
}
TagEditRecord::TagEditRecord(const TagEditRecord& org)
: EditRecord(org),
tagGroupItem(org.tagGroupItem),
tagGroupItemImpl(org.tagGroupItemImpl),
action(org.action),
tagIndex(org.tagIndex)
{
setTags(org.newTag, org.oldTag);
}
void TagEditRecord::setTags(PositionTag* newTag0, PositionTag* oldTag0)
{
if(newTag0){
newTag = new PositionTag(*newTag0);
}
if(oldTag0){
oldTag = new PositionTag(*oldTag0);
}
}
EditRecord* TagEditRecord::clone() const
{
return new TagEditRecord(*this);
}
std::string TagEditRecord::label() const
{
int actualAction = action;
if(isReverse()){
if(action == AddAction){
actualAction = RemoveAction;
} else if(action == RemoveAction){
actualAction = AddAction;
}
}
switch(action){
case AddAction:
return _("Add a position tag");
case UpdateAction:
return _("Update a position tag");
case RemoveAction:
return _("Remove a position tag");
default:
break;
}
return string();
}
bool TagEditRecord::undo()
{
bool done = false;
auto tagGroup = tagGroupItemImpl->tagGroup;
tagGroupItemImpl->isDoingUndoOrRedo = true;
switch(action){
case AddAction:
done = tagGroup->removeAt(tagIndex);
break;
case UpdateAction:
(*tagGroup->tagAt(tagIndex)) = *oldTag;
tagGroup->notifyTagPositionUpdate(tagIndex);
done = true;
break;
case RemoveAction:
tagGroup->insert(tagIndex, new PositionTag(*oldTag));
done = true;
break;
default:
break;
}
tagGroupItemImpl->isDoingUndoOrRedo = false;
return done;
}
bool TagEditRecord::redo()
{
bool done = false;
auto tagGroup = tagGroupItemImpl->tagGroup;
tagGroupItemImpl->isDoingUndoOrRedo = true;
switch(action){
case AddAction:
tagGroup->insert(tagIndex, new PositionTag(*newTag));
done = true;
break;
case UpdateAction:
(*tagGroup->tagAt(tagIndex)) = *newTag;
tagGroup->notifyTagPositionUpdate(tagIndex);
done = true;
break;
case RemoveAction:
done = tagGroup->removeAt(tagIndex);
break;
default:
break;
}
tagGroupItemImpl->isDoingUndoOrRedo = false;
return done;
}
ConversionDialog::ConversionDialog()
{
setWindowTitle(_("Tag Group Conversion"));
auto vbox = new QVBoxLayout;
descriptionLabel.setWordWrap(true);
vbox->addWidget(&descriptionLabel);
auto descriptionLabel2 = new QLabel;
descriptionLabel2->setWordWrap(true);
descriptionLabel2->setText(
_("Which type of positions do you want to keep in the coordinate system change?"));
vbox->addWidget(descriptionLabel2);
auto hbox = new QHBoxLayout;
globalCoordRadio.setText(_("Global positions"));
globalCoordRadio.setChecked(true);
hbox->addWidget(&globalCoordRadio);
clearOriginOffsetCheck.setText(_("Clear the origin offset"));
clearOriginOffsetCheck.setChecked(true);
hbox->addWidget(&clearOriginOffsetCheck);
hbox->addStretch();
vbox->addLayout(hbox);
localCoordRadio.setText(_("Local positions"));
vbox->addWidget(&localCoordRadio);
vbox->addStretch();
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
buttonBox->button(QDialogButtonBox::Ok)->setAutoDefault(true);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
vbox->addWidget(buttonBox);
setLayout(vbox);
}
void ConversionDialog::setTargets(PositionTagGroupItem* tagGroupItem, LocationProxyPtr newParentLocation)
{
if(newParentLocation){
descriptionLabel.setText(
QString(_("The parent coordinate system of \"%1\" is changed to the coordinate system of \"%2\"."))
.arg(tagGroupItem->displayName().c_str()).arg(newParentLocation->getName().c_str()));
} else {
descriptionLabel.setText(
QString(_("The parent coordinate system of \"%1\" is changed to the global coordinate system."))
.arg(tagGroupItem->displayName().c_str()));
}
}
}
| 27.014164
| 119
| 0.672273
|
team-FisMa
|
dca0a556c73c1bd59e8c05acc74bd7406b28e47a
| 619
|
cpp
|
C++
|
flood-fill/flood-fill.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | 1
|
2022-02-14T07:57:07.000Z
|
2022-02-14T07:57:07.000Z
|
flood-fill/flood-fill.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | null | null | null |
flood-fill/flood-fill.cpp
|
sharmishtha2401/leetcode
|
0c7389877afb64b3ff277f075ed9c87b24cb587b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
if(image[sr][sc]!=color)
change(image, sr, sc, image[sr][sc], color);
return image;
}
void change(vector<vector<int>>& image, int i, int j, int og, int color)
{
if(i<0 || j<0 || i>=image.size() || j>=image[0].size() || image[i][j]!=og)
return;
image[i][j]=color;
change(image,i,j+1,og,color);
change(image,i,j-1,og,color);
change(image,i+1,j,og,color);
change(image,i-1,j,og,color);
}
};
| 28.136364
| 90
| 0.526656
|
sharmishtha2401
|
dca0a879a4562be72836224867b8c99995e8b0ef
| 3,208
|
cpp
|
C++
|
src/lib/crypto/OSSLDHPublicKey.cpp
|
spacekpe/SoftHSMv2
|
fd5bdfd8289c5a156627cb8dfad574ec1055bdc4
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/crypto/OSSLDHPublicKey.cpp
|
spacekpe/SoftHSMv2
|
fd5bdfd8289c5a156627cb8dfad574ec1055bdc4
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/crypto/OSSLDHPublicKey.cpp
|
spacekpe/SoftHSMv2
|
fd5bdfd8289c5a156627cb8dfad574ec1055bdc4
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2010 SURFnet bv
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
OSSLDHPublicKey.cpp
OpenSSL Diffie-Hellman public key class
*****************************************************************************/
#include "config.h"
#include "log.h"
#include "OSSLDHPublicKey.h"
#include "OSSLUtil.h"
#include <openssl/bn.h>
#include <string.h>
// Constructors
OSSLDHPublicKey::OSSLDHPublicKey()
{
dh = DH_new();
// Use the OpenSSL implementation and not any engine
DH_set_method(dh, DH_OpenSSL());
}
OSSLDHPublicKey::OSSLDHPublicKey(const DH* inDH)
{
OSSLDHPublicKey();
setFromOSSL(inDH);
}
// Destructor
OSSLDHPublicKey::~OSSLDHPublicKey()
{
DH_free(dh);
}
// The type
/*static*/ const char* OSSLDHPublicKey::type = "OpenSSL DH Public Key";
// Set from OpenSSL representation
void OSSLDHPublicKey::setFromOSSL(const DH* dh)
{
if (dh->p) { ByteString p = OSSL::bn2ByteString(dh->p); setP(p); }
if (dh->g) { ByteString g = OSSL::bn2ByteString(dh->g); setG(g); }
if (dh->pub_key) { ByteString y = OSSL::bn2ByteString(dh->pub_key); setY(y); }
}
// Check if the key is of the given type
bool OSSLDHPublicKey::isOfType(const char* type)
{
return !strcmp(OSSLDHPublicKey::type, type);
}
// Setters for the DH public key components
void OSSLDHPublicKey::setP(const ByteString& p)
{
DHPublicKey::setP(p);
if (dh->p)
{
BN_clear_free(dh->p);
dh->p = NULL;
}
dh->p = OSSL::byteString2bn(p);
}
void OSSLDHPublicKey::setG(const ByteString& g)
{
DHPublicKey::setG(g);
if (dh->g)
{
BN_clear_free(dh->g);
dh->g = NULL;
}
dh->g = OSSL::byteString2bn(g);
}
void OSSLDHPublicKey::setY(const ByteString& y)
{
DHPublicKey::setY(y);
if (dh->pub_key)
{
BN_clear_free(dh->pub_key);
dh->pub_key = NULL;
}
dh->pub_key = OSSL::byteString2bn(y);
}
// Retrieve the OpenSSL representation of the key
DH* OSSLDHPublicKey::getOSSLKey()
{
return dh;
}
| 25.664
| 79
| 0.685162
|
spacekpe
|
dca1a8cabccbdc7ca7be7d0ff42fd6f8e1318bf2
| 551
|
cpp
|
C++
|
LinkingToDLL/MathFuncsDll/MathFuncsDll.cpp
|
edetoc/samples
|
3223b3111f77fd6cedad31b4685dd19615e91725
|
[
"MIT"
] | 2
|
2019-12-16T09:31:27.000Z
|
2021-09-03T01:12:24.000Z
|
LinkingToDLL/MathFuncsDll/MathFuncsDll.cpp
|
edetoc/samples
|
3223b3111f77fd6cedad31b4685dd19615e91725
|
[
"MIT"
] | 1
|
2021-08-23T14:52:46.000Z
|
2021-08-23T14:52:46.000Z
|
LinkingToDLL/MathFuncsDll/MathFuncsDll.cpp
|
edetoc/samples
|
3223b3111f77fd6cedad31b4685dd19615e91725
|
[
"MIT"
] | null | null | null |
// MathFuncsDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw invalid_argument("b cannot be zero!");
}
return a / b;
}
}
| 15.305556
| 78
| 0.664247
|
edetoc
|
dca260c7612b197bf23bfa54870b6428015e5963
| 4,814
|
cpp
|
C++
|
test/unit/alphabet/aminoacid/aa27_test.cpp
|
SGSSGene/seqan3
|
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
test/unit/alphabet/aminoacid/aa27_test.cpp
|
SGSSGene/seqan3
|
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
test/unit/alphabet/aminoacid/aa27_test.cpp
|
SGSSGene/seqan3
|
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
|
[
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include "../alphabet_constexpr_test_template.hpp"
#include "../alphabet_test_template.hpp"
#include "../semi_alphabet_constexpr_test_template.hpp"
#include "../semi_alphabet_test_template.hpp"
#include "aminoacid_test_template.hpp"
#include <seqan3/alphabet/aminoacid/aa27.hpp>
#include <seqan3/range/views/zip.hpp>
INSTANTIATE_TYPED_TEST_CASE_P(aa27, alphabet_, aa27);
INSTANTIATE_TYPED_TEST_CASE_P(aa27, semi_alphabet_test, aa27);
INSTANTIATE_TYPED_TEST_CASE_P(aa27, alphabet_constexpr, aa27);
INSTANTIATE_TYPED_TEST_CASE_P(aa27, semi_alphabet_constexpr, aa27);
INSTANTIATE_TYPED_TEST_CASE_P(aa27, aminoacid, aa27);
TEST(aa27, assign_char)
{
std::vector<char> chars
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'*', '!'
};
std::vector<aa27> alphabets
{
'A'_aa27, 'B'_aa27, 'C'_aa27, 'D'_aa27, 'E'_aa27, 'F'_aa27, 'G'_aa27,
'H'_aa27, 'I'_aa27, 'J'_aa27, 'K'_aa27, 'L'_aa27, 'M'_aa27,
'A'_aa27, 'B'_aa27, 'C'_aa27, 'D'_aa27, 'E'_aa27, 'F'_aa27, 'G'_aa27,
'H'_aa27, 'I'_aa27, 'J'_aa27, 'K'_aa27, 'L'_aa27, 'M'_aa27,
'N'_aa27, 'O'_aa27, 'P'_aa27, 'Q'_aa27, 'R'_aa27, 'S'_aa27, 'T'_aa27,
'U'_aa27, 'V'_aa27, 'W'_aa27, 'X'_aa27, 'Y'_aa27, 'Z'_aa27,
'N'_aa27, 'O'_aa27, 'P'_aa27, 'Q'_aa27, 'R'_aa27, 'S'_aa27, 'T'_aa27,
'U'_aa27, 'V'_aa27, 'W'_aa27, 'X'_aa27, 'Y'_aa27, 'Z'_aa27,
'*'_aa27, 'X'_aa27
};
for (auto [ chr, alp ] : views::zip(chars, alphabets))
EXPECT_EQ((assign_char_to(chr, aa27{})), alp);
}
TEST(aa27, to_char)
{
std::vector<char> chars
{
'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P',
'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'B', 'J', 'O', 'U', 'X', 'Z',
'*', 'X'
};
std::vector<aa27> alphabets
{
'A'_aa27, 'C'_aa27, 'D'_aa27, 'E'_aa27, 'F'_aa27, 'G'_aa27, 'H'_aa27,
'I'_aa27, 'K'_aa27, 'L'_aa27, 'M'_aa27, 'N'_aa27, 'P'_aa27,
'Q'_aa27, 'R'_aa27, 'S'_aa27, 'T'_aa27, 'V'_aa27, 'W'_aa27, 'Y'_aa27,
'B'_aa27, 'J'_aa27, 'O'_aa27, 'U'_aa27, 'X'_aa27, 'Z'_aa27,
'*'_aa27, 'X'_aa27
};
for (auto [ alp, chr ] : views::zip(alphabets, chars))
EXPECT_EQ(to_char(alp), chr);
}
// ------------------------------------------------------------------
// literals
// ------------------------------------------------------------------
TEST(literals, char_literal)
{
EXPECT_EQ(to_char('A'_aa27), 'A');
EXPECT_EQ(to_char('B'_aa27), 'B');
EXPECT_EQ(to_char('C'_aa27), 'C');
EXPECT_EQ(to_char('D'_aa27), 'D');
EXPECT_EQ(to_char('E'_aa27), 'E');
EXPECT_EQ(to_char('F'_aa27), 'F');
EXPECT_EQ(to_char('G'_aa27), 'G');
EXPECT_EQ(to_char('H'_aa27), 'H');
EXPECT_EQ(to_char('I'_aa27), 'I');
EXPECT_EQ(to_char('J'_aa27), 'J');
EXPECT_EQ(to_char('K'_aa27), 'K');
EXPECT_EQ(to_char('L'_aa27), 'L');
EXPECT_EQ(to_char('M'_aa27), 'M');
EXPECT_EQ(to_char('N'_aa27), 'N');
EXPECT_EQ(to_char('O'_aa27), 'O');
EXPECT_EQ(to_char('P'_aa27), 'P');
EXPECT_EQ(to_char('Q'_aa27), 'Q');
EXPECT_EQ(to_char('R'_aa27), 'R');
EXPECT_EQ(to_char('S'_aa27), 'S');
EXPECT_EQ(to_char('T'_aa27), 'T');
EXPECT_EQ(to_char('U'_aa27), 'U');
EXPECT_EQ(to_char('V'_aa27), 'V');
EXPECT_EQ(to_char('W'_aa27), 'W');
EXPECT_EQ(to_char('X'_aa27), 'X');
EXPECT_EQ(to_char('Y'_aa27), 'Y');
EXPECT_EQ(to_char('Z'_aa27), 'Z');
EXPECT_EQ(to_char('*'_aa27), '*');
EXPECT_EQ(to_char('!'_aa27), 'X');
}
TEST(literals, vector)
{
aa27_vector v27;
v27.resize(5, 'A'_aa27);
EXPECT_EQ(v27, "AAAAA"_aa27);
std::vector<aa27> w27{'A'_aa27, 'Y'_aa27, 'P'_aa27, 'T'_aa27, 'U'_aa27, 'N'_aa27, 'X'_aa27, '!'_aa27, '*'_aa27};
EXPECT_EQ(w27, "AYPTUNXX*"_aa27);
}
TEST(aa27, char_is_valid)
{
constexpr auto validator = is_alpha || is_char<'*'>;
for (char c : std::views::iota(std::numeric_limits<char>::min(), std::numeric_limits<char>::max()))
EXPECT_EQ(aa27::char_is_valid(c), validator(c));
}
| 38.206349
| 116
| 0.537599
|
SGSSGene
|
dca88b857836702bc865159d18ab471157781016
| 6,048
|
hh
|
C++
|
dist_apps/experimental/pr_bc_v2/pr_bc_v2_sync.hh
|
maleen89/Galois
|
babc933c4306a17a41f355d510734e17af4affff
|
[
"BSD-3-Clause"
] | null | null | null |
dist_apps/experimental/pr_bc_v2/pr_bc_v2_sync.hh
|
maleen89/Galois
|
babc933c4306a17a41f355d510734e17af4affff
|
[
"BSD-3-Clause"
] | null | null | null |
dist_apps/experimental/pr_bc_v2/pr_bc_v2_sync.hh
|
maleen89/Galois
|
babc933c4306a17a41f355d510734e17af4affff
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
////////////////////////////////////////////////////////////////////////////////
// Forward Phase
////////////////////////////////////////////////////////////////////////////////
struct ReduceAPSP {
using ValTy = std::pair<uint32_t, ShortPathType>;
static ValTy extract(uint32_t node_id, const struct NodeData& node,
unsigned vecIndex) {
return ValTy(node.minDistances[vecIndex], node.pathAccumulator[vecIndex]);
}
static bool extract_reset_batch(unsigned, unsigned long int*,
unsigned int*, ValTy*, size_t*,
DataCommMode*) {
return false;
}
static bool extract_reset_batch(unsigned, ValTy*) {
return false;
}
static bool reduce(uint32_t node_id, struct NodeData& node, ValTy y,
unsigned vecIndex) {
bool returnVar = false;
auto& myDistances = node.minDistances;
uint32_t oldDist = galois::min(myDistances[vecIndex], y.first);
// if there's a change, reset the shortestPathsAdd var +
if (oldDist > myDistances[vecIndex]) {
node.dTree.setDistance(vecIndex, oldDist, y.first);
node.shortestPathNumbers[vecIndex] = 0;
node.pathAccumulator[vecIndex] = y.second;
returnVar = true;
} else if (oldDist == myDistances[vecIndex]) {
// no change to distance => add to path accumulator
node.pathAccumulator[vecIndex] += y.second;
returnVar = true;
}
return returnVar;
}
static bool reduce_batch(unsigned, unsigned long int*, unsigned int *,
ValTy*, size_t, DataCommMode) {
return false;
}
/**
* reset accumulator
*/
static void reset(uint32_t node_id, struct NodeData &node, unsigned vecIndex) {
node.pathAccumulator[vecIndex] = 0;
}
};
struct BroadcastAPSP {
using ValTy = std::pair<uint32_t, ShortPathType>;
static ValTy extract(uint32_t node_id, const struct NodeData& node,
unsigned vecIndex) {
return ValTy(node.minDistances[vecIndex], node.pathAccumulator[vecIndex]);
}
// defined to make compiler not complain
static ValTy extract(uint32_t node_id, const struct NodeData & node) {
GALOIS_DIE("Execution shouldn't get here this function needs an index arg\n");
return ValTy(0, 0);
}
static bool extract_batch(unsigned, uint64_t*, unsigned int*, ValTy*, size_t*,
DataCommMode*) {
return false;
}
static bool extract_batch(unsigned, ValTy*) {
return false;
}
// if min distance is changed by the broadcast, then shortest path to add
// becomes obsolete/incorrect, so it must be changed to 0
static void setVal(uint32_t node_id, struct NodeData & node, ValTy y,
unsigned vecIndex) {
assert(node.minDistances[vecIndex] >= y.first);
// reset short path count if necessary
if (node.minDistances[vecIndex] != y.first) {
node.shortestPathNumbers[vecIndex] = 0;
}
uint32_t oldDistance = node.minDistances[vecIndex];
node.minDistances[vecIndex] = y.first;
node.dTree.setDistance(vecIndex, oldDistance, y.first);
node.pathAccumulator[vecIndex] = y.second;
}
// defined so compiler won't complain
static void setVal(uint32_t node_id, struct NodeData & node, ValTy y) {
GALOIS_DIE("Execution shouldn't get here; needs index arg\n");
}
static bool setVal_batch(unsigned, uint64_t*, unsigned int*, ValTy*,
size_t, DataCommMode) {
return false;
}
};
struct BitsetAPSP {
static unsigned numBitsets() { return bitset_APSP.size(); }
static constexpr bool is_vector_bitset() { return true; }
static constexpr bool is_valid() { return true; }
static galois::DynamicBitSet& get(unsigned i) {
return bitset_APSP[i];
}
static void reset_range(size_t begin, size_t end) {
for (unsigned i = 0; i < bitset_APSP.size(); i++) {
bitset_APSP[i].reset(begin, end);
}
}
};
////////////////////////////////////////////////////////////////////////////////
// Backphase
////////////////////////////////////////////////////////////////////////////////
GALOIS_SYNC_STRUCTURE_REDUCE_PAIR_WISE_ADD_ARRAY_SINGLE(depAccumulator,
galois::CopyableAtomic<float>);
GALOIS_SYNC_STRUCTURE_BROADCAST_VECTOR_SINGLE(depAccumulator,
galois::CopyableAtomic<float>);
struct BitsetDep {
static unsigned numBitsets() { return bitset_depAccumulator.size(); }
static constexpr bool is_vector_bitset() { return true; }
static constexpr bool is_valid() { return true; }
static galois::DynamicBitSet& get(unsigned i) {
return bitset_depAccumulator[i];
}
static void reset_range(size_t begin, size_t end) {
for (unsigned i = 0; i < bitset_depAccumulator.size(); i++) {
bitset_depAccumulator[i].reset(begin, end);
}
}
};
| 36.878049
| 87
| 0.643353
|
maleen89
|
dca8b571dc0770fdd3c243f9b606499f42d0f4b4
| 220
|
hh
|
C++
|
extern/polymesh/src/polymesh/pm.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
extern/polymesh/src/polymesh/pm.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
extern/polymesh/src/polymesh/pm.hh
|
rovedit/Fort-Candle
|
445fb94852df56c279c71b95c820500e7fb33cf7
|
[
"MIT"
] | null | null | null |
#pragma once
// Includes most commonly used polymesh features
#include <polymesh/Mesh.hh>
#include <polymesh/properties.hh>
#include <polymesh/formats.hh>
#include <polymesh/objects.hh>
#include <polymesh/hash.hh>
| 15.714286
| 48
| 0.759091
|
rovedit
|
dca966cd02fb2937dbe63203ebd356f39c5c136d
| 421
|
cpp
|
C++
|
HackerRank/Interview Preparation Kit/String Manipulation/AlternatingCharacters.cpp
|
Anni1123/competitive-programming
|
bfcc72ff3379d09dee22f30f71751a32c0cc511b
|
[
"MIT"
] | 1
|
2021-04-03T13:33:00.000Z
|
2021-04-03T13:33:00.000Z
|
HackerRank/Interview Preparation Kit/String Manipulation/AlternatingCharacters.cpp
|
iamsuryakant/competitive-programming
|
413000f5bc4a627407e1335c35dcdbee516e8cc1
|
[
"MIT"
] | null | null | null |
HackerRank/Interview Preparation Kit/String Manipulation/AlternatingCharacters.cpp
|
iamsuryakant/competitive-programming
|
413000f5bc4a627407e1335c35dcdbee516e8cc1
|
[
"MIT"
] | 2
|
2021-01-23T14:35:48.000Z
|
2021-03-15T05:04:24.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int q;
string s;
cin >> q;
while (q--) {
cin >> s;
int ans = 0;
for (int i = 0; i < s.size() - 1; i++) {
if (s[i] == s[i + 1])
ans++;
}
cout << ans << endl;
}
return 0;
}
| 19.136364
| 49
| 0.391924
|
Anni1123
|
dcad8c0031e013da49c7475886ecbe9d36bd7622
| 2,330
|
cc
|
C++
|
mars/sdt/sdt_logic.cc
|
20150723/mars
|
916f895d5d6c31a1f4720b189bb0a83e92e0161c
|
[
"Apache-2.0",
"BSD-2-Clause"
] | 325
|
2016-12-28T14:19:10.000Z
|
2021-11-24T07:01:51.000Z
|
mars/sdt/sdt_logic.cc
|
wblzu/mars
|
4396e753aee627a92b55ae7a1bc12b4d6f4f6445
|
[
"Apache-2.0"
] | 2
|
2019-10-22T02:57:02.000Z
|
2019-10-31T23:30:17.000Z
|
mars/sdt/sdt_logic.cc
|
pengjinning/mars
|
227aff64a5b819555091a7d6eae6727701e9fff0
|
[
"Apache-2.0",
"BSD-2-Clause"
] | 114
|
2016-12-28T14:36:15.000Z
|
2021-12-08T09:05:50.000Z
|
// Tencent is pleased to support the open source community by making Mars available.
// Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
// 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.
/*
* sdt_logic.cc
*
* Created on: 2016年3月18日
* Author: caoshaokun
*/
#include "mars/sdt/sdt_logic.h"
#include "mars/baseevent/baseevent.h"
#include "mars/baseevent/baseprjevent.h"
#include "mars/comm/xlogger/xlogger.h"
#include "mars/comm/bootrun.h"
#include "mars/sdt/constants.h"
#include "sdt/src/sdt_core.h"
namespace mars {
namespace sdt {
static Callback* sg_callback = NULL;
static const std::string kLibName = "sdt";
#define SDT_WEAK_CALL(func) \
boost::shared_ptr<SdtCore> sdt_ptr = SdtCore::Singleton::Instance_Weak().lock();\
if (!sdt_ptr) {\
xwarn2(TSF"sdt uncreate");\
return;\
}\
sdt_ptr->func
static void onCreate() {
xinfo2(TSF"sdt oncreate");
SdtCore::Singleton::Instance();
}
static void onDestroy() {
xinfo2(TSF"sdt onDestroy");
SdtCore::Singleton::Release();
}
static void __initbind_baseprjevent() {
#ifdef ANDROID
mars::baseevent::addLoadModule(kLibName);
#endif
GetSignalOnCreate().connect(&onCreate);
GetSignalOnDestroy().connect(5, &onDestroy);
}
BOOT_RUN_STARTUP(__initbind_baseprjevent);
//active netcheck interface
void StartActiveCheck(CheckIPPorts& _longlink_check_items, CheckIPPorts& _shortlink_check_items, int _mode, int _timeout) {
SDT_WEAK_CALL(StartCheck(_longlink_check_items, _shortlink_check_items, _mode, _timeout));
}
void CancelActiveCheck() {
SDT_WEAK_CALL(CancelCheck());
}
void SetCallBack(Callback* const callback) {
sg_callback = callback;
}
#ifndef ANDROID
void (*ReportNetCheckResult)(const std::vector<CheckResultProfile>& _check_results)
= [](const std::vector<CheckResultProfile>& _check_results) {
};
#endif
}}
| 26.179775
| 123
| 0.742918
|
20150723
|
dcb62a421c9dac7d3123ec069e665e3a3f73f446
| 2,233
|
cpp
|
C++
|
common/src/constants.cpp
|
tyoma/micro-profiler
|
32f6981c643b93997752d414f631fd6684772b28
|
[
"MIT"
] | 194
|
2015-07-27T09:54:24.000Z
|
2022-03-21T20:50:22.000Z
|
common/src/constants.cpp
|
tyoma/micro-profiler
|
32f6981c643b93997752d414f631fd6684772b28
|
[
"MIT"
] | 63
|
2015-08-19T16:42:33.000Z
|
2022-02-22T20:30:49.000Z
|
common/src/constants.cpp
|
tyoma/micro-profiler
|
32f6981c643b93997752d414f631fd6684772b28
|
[
"MIT"
] | 33
|
2015-08-21T17:48:03.000Z
|
2022-02-23T03:54:17.000Z
|
// Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.org)
//
// 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 <common/constants.h>
#include <common/path.h>
#include <common/string.h>
#include <stdlib.h>
using namespace std;
namespace micro_profiler
{
#ifdef _WIN32
const char *constants::home_ev = "LOCALAPPDATA";
#else
const char *constants::home_ev = "HOME";
#endif
const char *constants::profiler_name = ".microprofiler";
const char *constants::profilerdir_ev = "MICROPROFILERDIR";
const char *constants::profiler_injected_ev = "MICROPROFILERINJECTED";
const char *constants::frontend_id_ev = "MICROPROFILERFRONTEND";
// {0ED7654C-DE8A-4964-9661-0B0C391BE15E}
const guid_t constants::standalone_frontend_id = {
{ 0x4c, 0x65, 0xd7, 0x0e, 0x8a, 0xde, 0x64, 0x49, 0x96, 0x61, 0x0b, 0x0c, 0x39, 0x1b, 0xe1, 0x5e, }
};
// {91C0CE12-C677-4A50-A522-C86040AC5052}
const guid_t constants::integrated_frontend_id = {
{ 0x12, 0xce, 0xc0, 0x91, 0x77, 0xc6, 0x50, 0x4a, 0xa5, 0x22, 0xc8, 0x60, 0x40, 0xac, 0x50, 0x52, }
};
string constants::data_directory()
{
const char *localdata = getenv(home_ev);
return string(localdata ? localdata : ".") & string(profiler_name);
}
}
| 38.5
| 101
| 0.744738
|
tyoma
|
dcb7f2b0929a6c474a1e85cc56a4b526b48e08e3
| 2,402
|
cpp
|
C++
|
HAPI/optix/main.cpp
|
Geerthan/HAPI-GPU
|
a9ffe70b1b43392344fef2ba552965b4eb8cc4a2
|
[
"MIT"
] | null | null | null |
HAPI/optix/main.cpp
|
Geerthan/HAPI-GPU
|
a9ffe70b1b43392344fef2ba552965b4eb8cc4a2
|
[
"MIT"
] | null | null | null |
HAPI/optix/main.cpp
|
Geerthan/HAPI-GPU
|
a9ffe70b1b43392344fef2ba552965b4eb8cc4a2
|
[
"MIT"
] | null | null | null |
/*
nvcc -ptx -ccbin "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\Hostx64\x64" -I "C:\ProgramData\NVIDIA Corporation\OptiX SDK 6.0.0\include" bounding_box.cu
http://blog.three-eyed-games.com/2018/05/03/gpu-ray-tracing-in-unity-part-1/
*/
#include <string>
#include "Renderer.h"
#include "SceneTree.h"
#include <optixu/optixu_matrix.h>
int main(int argc, char* argv[]) {
optix::float3 camPos;
camPos.x = 0.0f;
camPos.y = 0.0f;
camPos.z = 2.0f;
optix::float3 camU;
camU.x = 1.0f;
camU.y = 0.0f;
camU.z = 0.0f;
optix::float3 camV;
camV.x = 0.0f;
camV.y = 1.0f;
camV.z = 0.0f;
optix::float3 camW;
camW.x = 0.0f;
camW.y = 0.0f;
camW.z = -1.0f;
int width = 512u;
int height = 384u;
int rayCount = 1;
int entryPoint = 1;
std::string outputBuffer = "result_buffer";
Renderer renderer(width, height, rayCount, entryPoint, 800);
ProgramCreator progCreator(renderer.getContext());
SceneTree sceneTree(renderer.getContext());
renderer.createBuffer(outputBuffer);
progCreator.createRaygenProgram("ray_generation.ptx", "rayGeneration", 0);
progCreator.createMissProgram("miss.ptx", "miss_environment_constant", 0);
progCreator.createProgramVariable3f("rayGeneration", "sysCameraPosition", camPos.x, camPos.y, camPos.z);
progCreator.createProgramVariable3f("rayGeneration", "sysCameraU", camU.x, camU.y, camU.z);
progCreator.createProgramVariable3f("rayGeneration", "sysCameraV", camV.x, camV.y, camV.z);
progCreator.createProgramVariable3f("rayGeneration", "sysCameraW", camW.x, camW.y, camW.z);
progCreator.createProgramVariable1i("rayGeneration", "maxDepth", 2);
optix::Program boundBox = progCreator.createProgram("bounding_box.ptx", "boundbox_triangle_indexed");
optix::Program intersectProg = progCreator.createProgram("intersection.ptx", "intersect_triangle_indexed");
optix::Program closeHitProg = progCreator.createProgram("closest_hit.ptx", "closestHit");
optix::Program redHit = progCreator.createProgram("red_hit.ptx", "closestHit");
sceneTree.createMaterial(closeHitProg, "firstMat");
sceneTree.createGeometry(boundBox, intersectProg, width, height, "sphere");
sceneTree.createMaterial(redHit, "secondMat");
sceneTree.createGeometry(boundBox, intersectProg, width, height, "monkey");
sceneTree.initScene();
renderer.render(0);
renderer.display(&argc,argv, outputBuffer);
renderer.cleanUp();
}
| 32.90411
| 201
| 0.745629
|
Geerthan
|
dcbd7f8c807e528787d051e65e39103f23aaeceb
| 11,017
|
hxx
|
C++
|
src/algorithm/frames.hxx
|
ikalevatykh/pinocchio
|
2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38
|
[
"BSD-2-Clause-FreeBSD"
] | 1
|
2020-04-07T07:23:34.000Z
|
2020-04-07T07:23:34.000Z
|
src/algorithm/frames.hxx
|
ikalevatykh/pinocchio
|
2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
src/algorithm/frames.hxx
|
ikalevatykh/pinocchio
|
2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
//
// Copyright (c) 2015-2020 CNRS INRIA
//
#ifndef __pinocchio_frames_hxx__
#define __pinocchio_frames_hxx__
#include "pinocchio/algorithm/kinematics.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
#include "pinocchio/algorithm/check.hpp"
namespace pinocchio
{
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
inline void updateFramePlacements(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
DataTpl<Scalar,Options,JointCollectionTpl> & data)
{
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef typename Model::Frame Frame;
typedef typename Model::FrameIndex FrameIndex;
typedef typename Model::JointIndex JointIndex;
// The following for loop starts by index 1 because the first frame is fixed
// and corresponds to the universe.s
for(FrameIndex i=1; i < (FrameIndex) model.nframes; ++i)
{
const Frame & frame = model.frames[i];
const JointIndex & parent = frame.parent;
data.oMf[i] = data.oMi[parent]*frame.placement;
}
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
inline const typename DataTpl<Scalar,Options,JointCollectionTpl>::SE3 &
updateFramePlacement(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
DataTpl<Scalar,Options,JointCollectionTpl> & data,
const typename ModelTpl<Scalar,Options,JointCollectionTpl>::FrameIndex frame_id)
{
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
const typename Model::Frame & frame = model.frames[frame_id];
const typename Model::JointIndex & parent = frame.parent;
data.oMf[frame_id] = data.oMi[parent]*frame.placement;
return data.oMf[frame_id];
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType>
inline void framesForwardKinematics(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
DataTpl<Scalar,Options,JointCollectionTpl> & data,
const Eigen::MatrixBase<ConfigVectorType> & q)
{
assert(model.check(data) && "data is not consistent with model.");
forwardKinematics(model, data, q);
updateFramePlacements(model, data);
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
inline MotionTpl<Scalar, Options>
getFrameVelocity(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
const DataTpl<Scalar,Options,JointCollectionTpl> & data,
const typename ModelTpl<Scalar,Options,JointCollectionTpl>::FrameIndex frame_id)
{
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
const typename Model::Frame & frame = model.frames[frame_id];
const typename Model::JointIndex & parent = frame.parent;
return frame.placement.actInv(data.v[parent]);
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
inline MotionTpl<Scalar, Options>
getFrameAcceleration(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
const DataTpl<Scalar,Options,JointCollectionTpl> & data,
const typename ModelTpl<Scalar,Options,JointCollectionTpl>::FrameIndex frame_id)
{
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
const typename Model::Frame & frame = model.frames[frame_id];
const typename Model::JointIndex & parent = frame.parent;
return frame.placement.actInv(data.a[parent]);
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename Matrix6xLike>
inline void getFrameJacobian(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
const DataTpl<Scalar,Options,JointCollectionTpl> & data,
const typename ModelTpl<Scalar,Options,JointCollectionTpl>::FrameIndex frame_id,
const ReferenceFrame rf,
const Eigen::MatrixBase<Matrix6xLike> & J)
{
PINOCCHIO_CHECK_INPUT_ARGUMENT(J.rows() == 6);
PINOCCHIO_CHECK_INPUT_ARGUMENT(J.cols() == model.nv);
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef typename Model::Frame Frame;
typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
typedef typename Model::JointIndex JointIndex;
const Frame & frame = model.frames[frame_id];
const JointIndex & joint_id = frame.parent;
if(rf == WORLD)
{
getJointJacobian(model,data,joint_id,WORLD,PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,J));
return;
}
else if(rf == LOCAL || rf == LOCAL_WORLD_ALIGNED)
{
Matrix6xLike & J_ = PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,J);
const typename Data::SE3 & oMframe = data.oMf[frame_id];
const int colRef = nv(model.joints[joint_id])+idx_v(model.joints[joint_id])-1;
for(Eigen::DenseIndex j=colRef;j>=0;j=data.parents_fromRow[(size_t) j])
{
typedef typename Data::Matrix6x::ConstColXpr ConstColXprIn;
const MotionRef<ConstColXprIn> v_in(data.J.col(j));
typedef typename Matrix6xLike::ColXpr ColXprOut;
MotionRef<ColXprOut> v_out(J_.col(j));
if (rf == LOCAL)
v_out = oMframe.actInv(v_in);
else
{
v_out = v_in;
v_out.linear() -= oMframe.translation().cross(v_in.angular());
}
}
}
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename ConfigVectorType, typename Matrix6xLike>
inline void computeFrameJacobian(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
DataTpl<Scalar,Options,JointCollectionTpl> & data,
const Eigen::MatrixBase<ConfigVectorType> & q,
const FrameIndex frameId,
const ReferenceFrame reference_frame,
const Eigen::MatrixBase<Matrix6xLike> & J)
{
assert(model.check(data) && "data is not consistent with model.");
PINOCCHIO_CHECK_INPUT_ARGUMENT(q.size() == model.nq, "The configuration vector is not of right size");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
typedef typename Model::Frame Frame;
typedef typename Model::JointIndex JointIndex;
typedef typename Model::IndexVector IndexVector;
const Frame & frame = model.frames[frameId];
const JointIndex & joint_id = frame.parent;
const IndexVector & joint_support = model.supports[joint_id];
switch(reference_frame)
{
case WORLD:
case LOCAL_WORLD_ALIGNED:
{
typedef JointJacobiansForwardStep<Scalar,Options,JointCollectionTpl,ConfigVectorType,Matrix6xLike> Pass;
for(size_t k = 1; k < joint_support.size(); k++)
{
JointIndex parent = joint_support[k];
Pass::run(model.joints[parent],data.joints[parent],
typename Pass::ArgsType(model,data,q.derived(),
PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,J)));
}
if(reference_frame == LOCAL_WORLD_ALIGNED)
{
typename Data::SE3 & oMframe = data.oMf[frameId];
oMframe = data.oMi[joint_id] * frame.placement;
Matrix6xLike & J_ = PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,J);
const int colRef = nv(model.joints[joint_id])+idx_v(model.joints[joint_id])-1;
for(Eigen::DenseIndex j=colRef;j>=0;j=data.parents_fromRow[(size_t) j])
{
typedef typename Matrix6xLike::ColXpr ColXprOut;
MotionRef<ColXprOut> J_col(J_.col(j));
J_col.linear() -= oMframe.translation().cross(J_col.angular());
}
}
break;
}
case LOCAL:
{
data.iMf[joint_id] = frame.placement;
typedef JointJacobianForwardStep<Scalar,Options,JointCollectionTpl,ConfigVectorType,Matrix6xLike> Pass;
for(JointIndex i=joint_id; i>0; i=model.parents[i])
{
Pass::run(model.joints[i],data.joints[i],
typename Pass::ArgsType(model,data,q.derived(),
PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,J)));
}
break;
}
default:
{
assert(false && "must never happened");
}
}
}
template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl, typename Matrix6xLike>
void getFrameJacobianTimeVariation(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
const DataTpl<Scalar,Options,JointCollectionTpl> & data,
const typename ModelTpl<Scalar,Options,JointCollectionTpl>::FrameIndex frame_id,
const ReferenceFrame rf,
const Eigen::MatrixBase<Matrix6xLike> & dJ)
{
PINOCCHIO_CHECK_INPUT_ARGUMENT( dJ.rows() == data.dJ.rows() );
PINOCCHIO_CHECK_INPUT_ARGUMENT( dJ.cols() == data.dJ.cols() );
assert(model.check(data) && "data is not consistent with model.");
typedef ModelTpl<Scalar,Options,JointCollectionTpl> Model;
typedef typename Model::Frame Frame;
typedef typename Model::SE3 SE3;
const Frame & frame = model.frames[frame_id];
const typename Model::JointIndex & joint_id = frame.parent;
if(rf == WORLD)
{
getJointJacobianTimeVariation(model,data,joint_id,WORLD,PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,dJ));
return;
}
if(rf == LOCAL)
{
Matrix6xLike & dJ_ = PINOCCHIO_EIGEN_CONST_CAST(Matrix6xLike,dJ);
const SE3 & oMframe = data.oMf[frame_id];
const int colRef = nv(model.joints[joint_id])+idx_v(model.joints[joint_id])-1;
for(Eigen::DenseIndex j=colRef;j>=0;j=data.parents_fromRow[(size_t) j])
{
typedef typename Data::Matrix6x::ConstColXpr ConstColXprIn;
const MotionRef<ConstColXprIn> v_in(data.dJ.col(j));
typedef typename Matrix6xLike::ColXpr ColXprOut;
MotionRef<ColXprOut> v_out(dJ_.col(j));
v_out = oMframe.actInv(v_in);
}
return;
}
}
} // namespace pinocchio
#endif // ifndef __pinocchio_frames_hxx__
| 41.573585
| 139
| 0.651992
|
ikalevatykh
|
dcbd8f2721d67d564bc26a2a38ae1464d690b7f1
| 8,879
|
cpp
|
C++
|
openstudiocore/src/model/CoilSystemCoolingWaterHeatExchangerAssisted.cpp
|
BIMDataHub/OpenStudio-1
|
13ec115b00aa6a2af1426ceb26446f05014c8c8d
|
[
"blessing"
] | 4
|
2015-05-02T21:04:15.000Z
|
2015-10-28T09:47:22.000Z
|
openstudiocore/src/model/CoilSystemCoolingWaterHeatExchangerAssisted.cpp
|
BIMDataHub/OpenStudio-1
|
13ec115b00aa6a2af1426ceb26446f05014c8c8d
|
[
"blessing"
] | null | null | null |
openstudiocore/src/model/CoilSystemCoolingWaterHeatExchangerAssisted.cpp
|
BIMDataHub/OpenStudio-1
|
13ec115b00aa6a2af1426ceb26446f05014c8c8d
|
[
"blessing"
] | 1
|
2020-11-12T21:52:36.000Z
|
2020-11-12T21:52:36.000Z
|
/**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <model/CoilSystemCoolingWaterHeatExchangerAssisted.hpp>
#include <model/CoilSystemCoolingWaterHeatExchangerAssisted_Impl.hpp>
#include <model/AirToAirComponent.hpp>
#include <model/AirToAirComponent_Impl.hpp>
#include <model/ControllerWaterCoil.hpp>
#include <model/ControllerWaterCoil_Impl.hpp>
#include <model/WaterToAirComponent.hpp>
#include <model/WaterToAirComponent_Impl.hpp>
#include <model/CoilCoolingWater.hpp>
#include <model/CoilCoolingWater_Impl.hpp>
#include <model/Model.hpp>
#include <model/Model_Impl.hpp>
#include <model/Node.hpp>
#include <model/Node_Impl.hpp>
#include <model/AirLoopHVAC.hpp>
#include <model/AirLoopHVAC_Impl.hpp>
#include <model/HeatExchangerAirToAirSensibleAndLatent.hpp>
#include <model/HeatExchangerAirToAirSensibleAndLatent_Impl.hpp>
#include <utilities/idd/OS_CoilSystem_Cooling_Water_HeatExchangerAssisted_FieldEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
#include <utilities/core/Assert.hpp>
namespace openstudio {
namespace model {
namespace detail {
CoilSystemCoolingWaterHeatExchangerAssisted_Impl::CoilSystemCoolingWaterHeatExchangerAssisted_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == CoilSystemCoolingWaterHeatExchangerAssisted::iddObjectType());
}
CoilSystemCoolingWaterHeatExchangerAssisted_Impl::CoilSystemCoolingWaterHeatExchangerAssisted_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == CoilSystemCoolingWaterHeatExchangerAssisted::iddObjectType());
}
CoilSystemCoolingWaterHeatExchangerAssisted_Impl::CoilSystemCoolingWaterHeatExchangerAssisted_Impl(const CoilSystemCoolingWaterHeatExchangerAssisted_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& CoilSystemCoolingWaterHeatExchangerAssisted_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType CoilSystemCoolingWaterHeatExchangerAssisted_Impl::iddObjectType() const {
return CoilSystemCoolingWaterHeatExchangerAssisted::iddObjectType();
}
AirToAirComponent CoilSystemCoolingWaterHeatExchangerAssisted_Impl::heatExchanger() const {
boost::optional<AirToAirComponent> value = optionalHeatExchanger();
if (!value) {
LOG_AND_THROW(briefDescription() << " does not have an Heat Exchanger attached.");
}
return value.get();
}
WaterToAirComponent CoilSystemCoolingWaterHeatExchangerAssisted_Impl::coolingCoil() const {
auto value = optionalCoolingCoil();
if (!value) {
LOG_AND_THROW(briefDescription() << " does not have an Cooling Coil attached.");
}
return value.get();
}
bool CoilSystemCoolingWaterHeatExchangerAssisted_Impl::setHeatExchanger(const AirToAirComponent& heatExchanger) {
bool result = setPointer(OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::HeatExchanger, heatExchanger.handle());
return result;
}
bool CoilSystemCoolingWaterHeatExchangerAssisted_Impl::setCoolingCoil(const WaterToAirComponent& coolingCoil) {
bool result = setPointer(OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::CoolingCoil, coolingCoil.handle());
return result;
}
boost::optional<AirToAirComponent> CoilSystemCoolingWaterHeatExchangerAssisted_Impl::optionalHeatExchanger() const {
return getObject<ModelObject>().getModelObjectTarget<AirToAirComponent>(OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::HeatExchanger);
}
boost::optional<WaterToAirComponent> CoilSystemCoolingWaterHeatExchangerAssisted_Impl::optionalCoolingCoil() const {
return getObject<ModelObject>().getModelObjectTarget<WaterToAirComponent>(OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::CoolingCoil);
}
unsigned CoilSystemCoolingWaterHeatExchangerAssisted_Impl::inletPort() {
return OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::AirInletNodeName;
}
unsigned CoilSystemCoolingWaterHeatExchangerAssisted_Impl::outletPort() {
return OS_CoilSystem_Cooling_Water_HeatExchangerAssistedFields::AirOutletNodeName;
}
bool CoilSystemCoolingWaterHeatExchangerAssisted_Impl::addToNode(Node & node)
{
bool result = false;
if( boost::optional<AirLoopHVAC> airLoop = node.airLoopHVAC() ) {
if( ! airLoop->demandComponent(node.handle()) ) {
result = StraightComponent_Impl::addToNode( node );
if( result ) {
auto t_coolingCoil = coolingCoil();
if( auto waterInletModelObject = t_coolingCoil.waterInletModelObject() ) {
if( auto coilCoolingWater = t_coolingCoil.optionalCast<CoilCoolingWater>() ) {
if( auto oldController = coilCoolingWater->controllerWaterCoil() ) {
oldController->remove();
}
}
auto t_model = model();
ControllerWaterCoil controller(t_model);
auto coilWaterInletNode = waterInletModelObject->optionalCast<Node>();
OS_ASSERT(coilWaterInletNode);
controller.setActuatorNode(coilWaterInletNode.get());
// sensor node will be established in translator since that node does not yet exist
controller.setAction("Reverse");
}
}
}
}
return result;
}
} // detail
CoilSystemCoolingWaterHeatExchangerAssisted::CoilSystemCoolingWaterHeatExchangerAssisted(const Model& model)
: StraightComponent(CoilSystemCoolingWaterHeatExchangerAssisted::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl>());
CoilCoolingWater coolingCoil(model);
setCoolingCoil(coolingCoil);
HeatExchangerAirToAirSensibleAndLatent heatExchanger(model);
heatExchanger.setSupplyAirOutletTemperatureControl(false);
setHeatExchanger(heatExchanger);
}
IddObjectType CoilSystemCoolingWaterHeatExchangerAssisted::iddObjectType() {
return IddObjectType(IddObjectType::OS_CoilSystem_Cooling_Water_HeatExchangerAssisted);
}
AirToAirComponent CoilSystemCoolingWaterHeatExchangerAssisted::heatExchanger() const {
return getImpl<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl>()->heatExchanger();
}
WaterToAirComponent CoilSystemCoolingWaterHeatExchangerAssisted::coolingCoil() const {
return getImpl<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl>()->coolingCoil();
}
bool CoilSystemCoolingWaterHeatExchangerAssisted::setHeatExchanger(const AirToAirComponent& heatExchanger) {
return getImpl<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl>()->setHeatExchanger(heatExchanger);
}
bool CoilSystemCoolingWaterHeatExchangerAssisted::setCoolingCoil(const WaterToAirComponent& coolingCoil) {
return getImpl<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl>()->setCoolingCoil(coolingCoil);
}
/// @cond
CoilSystemCoolingWaterHeatExchangerAssisted::CoilSystemCoolingWaterHeatExchangerAssisted(std::shared_ptr<detail::CoilSystemCoolingWaterHeatExchangerAssisted_Impl> impl)
: StraightComponent(impl)
{}
/// @endcond
} // model
} // openstudio
| 44.395
| 168
| 0.721703
|
BIMDataHub
|
dcbd99d4a42cc15ce1b6e28f863dd3cabf2e8f31
| 1,380
|
cpp
|
C++
|
taichi/analysis/check_fields_registered.cpp
|
zf38473013/taichi
|
ad4d7ae04f4e559e84f6dee4a64ad57c3cf0c7fb
|
[
"MIT"
] | 1
|
2020-04-08T08:55:13.000Z
|
2020-04-08T08:55:13.000Z
|
taichi/analysis/check_fields_registered.cpp
|
zf38473013/taichi
|
ad4d7ae04f4e559e84f6dee4a64ad57c3cf0c7fb
|
[
"MIT"
] | null | null | null |
taichi/analysis/check_fields_registered.cpp
|
zf38473013/taichi
|
ad4d7ae04f4e559e84f6dee4a64ad57c3cf0c7fb
|
[
"MIT"
] | null | null | null |
#include "taichi/ir/ir.h"
TLANG_NAMESPACE_BEGIN
class FieldsRegisteredChecker : public BasicStmtVisitor {
public:
using BasicStmtVisitor::visit;
FieldsRegisteredChecker() {
allow_undefined_visitor = true;
invoke_default_visitor = true;
}
void visit(Stmt *stmt) override {
TI_ASSERT(stmt->fields_registered);
}
void visit(IfStmt *if_stmt) override {
TI_ASSERT(if_stmt->fields_registered);
if (if_stmt->true_statements)
if_stmt->true_statements->accept(this);
if (if_stmt->false_statements) {
if_stmt->false_statements->accept(this);
}
}
void visit(WhileStmt *stmt) override {
TI_ASSERT(stmt->fields_registered);
stmt->body->accept(this);
}
void visit(RangeForStmt *for_stmt) override {
TI_ASSERT(for_stmt->fields_registered);
for_stmt->body->accept(this);
}
void visit(StructForStmt *for_stmt) override {
TI_ASSERT(for_stmt->fields_registered);
for_stmt->body->accept(this);
}
void visit(OffloadedStmt *stmt) override {
TI_ASSERT(stmt->fields_registered);
if (stmt->body)
stmt->body->accept(this);
}
static void run(IRNode *root) {
FieldsRegisteredChecker checker;
root->accept(&checker);
}
};
namespace irpass {
void check_fields_registered(IRNode *root) {
return FieldsRegisteredChecker::run(root);
}
} // namespace irpass
TLANG_NAMESPACE_END
| 22.622951
| 57
| 0.708696
|
zf38473013
|
dcbf5af72cce16de6a893ab0df7f244b86d27cac
| 5,575
|
cpp
|
C++
|
src/fdm/models/fdm_Stabilizer.cpp
|
fe5084/mscsim
|
2b0025a9e4bda69b0d83147b1e701375fef437f8
|
[
"MIT"
] | 1
|
2020-02-11T08:17:23.000Z
|
2020-02-11T08:17:23.000Z
|
src/fdm/models/fdm_Stabilizer.cpp
|
fe5084/mscsim
|
2b0025a9e4bda69b0d83147b1e701375fef437f8
|
[
"MIT"
] | null | null | null |
src/fdm/models/fdm_Stabilizer.cpp
|
fe5084/mscsim
|
2b0025a9e4bda69b0d83147b1e701375fef437f8
|
[
"MIT"
] | null | null | null |
/****************************************************************************//*
* Copyright (C) 2020 Marek M. Cel
*
* 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 <fdm/models/fdm_Stabilizer.h>
#include <fdm/main/fdm_Aerodynamics.h>
#include <fdm/utils/fdm_String.h>
#include <fdm/xml/fdm_XmlUtils.h>
////////////////////////////////////////////////////////////////////////////////
using namespace fdm;
////////////////////////////////////////////////////////////////////////////////
Stabilizer::Stabilizer() :
_type ( Horizontal ),
_area ( 0.0 ),
_incidence ( 0.0 ),
_downwash ( 0.0 )
{
_cx = Table::createOneRecordTable( 0.0 );
_cy = Table::createOneRecordTable( 0.0 );
_cz = Table::createOneRecordTable( 0.0 );
}
////////////////////////////////////////////////////////////////////////////////
Stabilizer::~Stabilizer() {}
////////////////////////////////////////////////////////////////////////////////
void Stabilizer::readData( XmlNode &dataNode )
{
if ( dataNode.isValid() )
{
int result = FDM_SUCCESS;
std::string type = dataNode.getAttribute( "type" );
if ( 0 == String::icompare( type, "horizontal" ) ) _type = Horizontal;
else if ( 0 == String::icompare( type, "vertical" ) ) _type = Vertical;
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _r_ac_bas, "aero_center" );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _area, "area" );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _incidence , "incidence" , true );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _downwash , "downwash" , true );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _cx, "cx" );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _cy, "cy", _type == Horizontal );
if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, _cz, "cz", _type == Vertical );
if ( result != FDM_SUCCESS ) XmlUtils::throwError( __FILE__, __LINE__, dataNode );
}
else
{
XmlUtils::throwError( __FILE__, __LINE__, dataNode );
}
}
////////////////////////////////////////////////////////////////////////////////
void Stabilizer::computeForceAndMoment( const Vector3 &vel_air_bas,
const Vector3 &omg_air_bas,
double airDensity,
double wingAngleOfAttack )
{
// stabilizer velocity
Vector3 vel_stab_bas = vel_air_bas + ( omg_air_bas % _r_ac_bas );
// TODO: main rotor downwash according to:
// [NASA-TM-84281, p.26] and [NASA-MEMO-4-15-59L]
// stabilizer angle of attack and sideslip angle
double angleOfAttack = getAngleOfAttack( vel_stab_bas, wingAngleOfAttack );
double sideslipAngle = Aerodynamics::getSideslipAngle( vel_stab_bas );
double angle = ( _type == Horizontal ) ? angleOfAttack : sideslipAngle;
// dynamic pressure
double dynPress = 0.5 * airDensity * vel_stab_bas.getLength2();
Vector3 for_aero( dynPress * getCx( angle ) * _area,
dynPress * getCy( angle ) * _area,
dynPress * getCz( angle ) * _area );
_for_bas = Aerodynamics::getAero2BAS( angleOfAttack, sideslipAngle ) * for_aero;
_mom_bas = _r_ac_bas % _for_bas;
if ( !_for_bas.isValid() || !_mom_bas.isValid() )
{
Exception e;
e.setType( Exception::UnexpectedNaN );
e.setInfo( "NaN detected in the stabilizer model." );
FDM_THROW( e );
}
}
////////////////////////////////////////////////////////////////////////////////
double Stabilizer::getAngleOfAttack( const Vector3 &vel_air_bas,
double wingAngleOfAttack )
{
return Aerodynamics::getAngleOfAttack( vel_air_bas )
+ _incidence - _downwash * wingAngleOfAttack;
}
////////////////////////////////////////////////////////////////////////////////
double Stabilizer::getCx( double angle ) const
{
return _cx.getValue( angle );
}
////////////////////////////////////////////////////////////////////////////////
double Stabilizer::getCy( double angle ) const
{
return _cy.getValue( angle );
}
////////////////////////////////////////////////////////////////////////////////
double Stabilizer::getCz( double angle ) const
{
return _cz.getValue( angle );
}
| 36.92053
| 106
| 0.547982
|
fe5084
|
dcbfcfbeee2b7aad507d1fe0b233d413bdea18d6
| 1,178
|
cpp
|
C++
|
src/9000/9370.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/9000/9370.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/9000/9370.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int INF = 111111111;
vector<vector<pair<int, int> > >adj;
void dijk(int start, vector<int> &dist)
{
priority_queue<pair<int, int> > pq;
dist[start] = 0;
pq.push({ 0, start });
while (!pq.empty())
{
int cur = pq.top().second;
pq.pop();
for (auto &i : adj[cur])
{
if (dist[i.first] > dist[cur] + i.second)
{
dist[i.first] = dist[cur] + i.second;
pq.push({ -dist[i.first], i.first });
}
}
}
}
int main()
{
int tc;
scanf("%d", &tc);
while (tc--)
{
int n, m, t, s, g, h;
scanf("%d %d %d %d %d %d", &n, &m, &t, &s, &g, &h);
adj.assign(n + 1, vector<pair<int, int> >());
vector<int> dist1(n + 1, INF), dist2(n + 1, INF), dst(t);
while (m--)
{
int a, b, d;
scanf("%d %d %d", &a, &b, &d);
adj[b].push_back({ a, d });
adj[a].push_back({ b, d });
}
dijk(s, dist1);
int mid = (dist1[g] > dist1[h] ? g : h);
dijk(mid, dist2);
for (int i = 0; i < t; i++)
scanf("%d", &dst[i]);
sort(dst.begin(), dst.end());
for (int i : dst)
if (dist1[mid] + dist2[i] == dist1[i])
printf("%d ", i);
printf("\n");
}
}
| 18.698413
| 59
| 0.511036
|
upple
|
dcc08d6db537229fa01af75ceb1a75486172d55b
| 783
|
hpp
|
C++
|
ragnarok/ds10/branches/network/netbase.hpp
|
kaina/sandbox
|
15a464fe1a1f17f4d475947ceeffa41df4b3eba5
|
[
"WTFPL"
] | 5
|
2015-10-30T12:12:37.000Z
|
2018-04-23T15:46:26.000Z
|
ragnarok/ds10/trunk/network/netbase.hpp
|
yuiAs/sandbox
|
15a464fe1a1f17f4d475947ceeffa41df4b3eba5
|
[
"WTFPL"
] | null | null | null |
ragnarok/ds10/trunk/network/netbase.hpp
|
yuiAs/sandbox
|
15a464fe1a1f17f4d475947ceeffa41df4b3eba5
|
[
"WTFPL"
] | 2
|
2016-11-29T10:14:53.000Z
|
2017-10-23T18:05:11.000Z
|
#ifndef NETBASE_HPP_3F0121D8_C486_401c_88F4_771280BFC85D
#define NETBASE_HPP_3F0121D8_C486_401c_88F4_771280BFC85D
#include <winsock2.h>
////////////////////////////////////////////////////////////////////////////////
class CNetBase
{
u_char* m_backBuf;
int m_backLen;
int m_backCnt;
enum { MAX_BUFFERSIZE=2048, };
protected:
bool m_clear;
public:
CNetBase();
virtual ~CNetBase();
public:
virtual int recv(char* buf, int len);
virtual int send(const char* buf, int len);
private:
void inc_backBuf(int require);
void clear_backBuf();
private:
virtual int parse_r(u_char* buf, int len) = 0;
virtual int parse_s(u_char* buf, int len) = 0;
virtual int getLength(u_char* buf) = 0;
};
#endif // #ifndef NETBASE_HPP
| 17.4
| 81
| 0.619413
|
kaina
|
dcc351e4b0764504e8127d5d7ce7b734cfbf6f81
| 17,775
|
cpp
|
C++
|
connectivity/lorawan/lorastack/mac/LoRaMacCrypto.cpp
|
Lljiro/mbed-os
|
3af9e4ece78b84fe95ca65b5433bb6452f41aac2
|
[
"Apache-2.0"
] | null | null | null |
connectivity/lorawan/lorastack/mac/LoRaMacCrypto.cpp
|
Lljiro/mbed-os
|
3af9e4ece78b84fe95ca65b5433bb6452f41aac2
|
[
"Apache-2.0"
] | null | null | null |
connectivity/lorawan/lorastack/mac/LoRaMacCrypto.cpp
|
Lljiro/mbed-os
|
3af9e4ece78b84fe95ca65b5433bb6452f41aac2
|
[
"Apache-2.0"
] | null | null | null |
/**
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013 Semtech
* ___ _____ _ ___ _ _____ ___ ___ ___ ___
* / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
* \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
* |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
* embedded.connectivity.solutions===============
*
* Description: LoRa MAC crypto implementation
*
* License: Revised BSD License, see LICENSE.TXT file include in the project
*
* Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jäckle ( STACKFORCE )
*
*
* Copyright (c) 2017, Arm Limited and affiliates.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "LoRaMacCrypto.h"
#include "system/lorawan_data_structures.h"
#include "mbedtls/platform.h"
#if defined(MBEDTLS_CMAC_C) && defined(MBEDTLS_AES_C) && defined(MBEDTLS_CIPHER_C)
/*
* LoRaWAN spec 6.2: AppKey is AES-128 key
*/
#define APPKEY_KEY_LENGTH 128
LoRaMacCrypto::LoRaMacCrypto() : _dev_addr(0)
{
#if defined(MBEDTLS_PLATFORM_C)
int ret = mbedtls_platform_setup(NULL);
if (ret != 0) {
MBED_ASSERT(0 && "LoRaMacCrypto: Fail in mbedtls_platform_setup.");
}
#endif /* MBEDTLS_PLATFORM_C */
memset(&_keys, 0, sizeof(_keys));
}
LoRaMacCrypto::~LoRaMacCrypto()
{
#if defined(MBEDTLS_PLATFORM_C)
mbedtls_platform_teardown(NULL);
#endif /* MBEDTLS_PLATFORM_C */
}
lorawan_status_t LoRaMacCrypto::set_keys(uint8_t *nwk_key, uint8_t *app_key, uint8_t *nwk_skey,
uint8_t *app_skey, uint8_t *snwk_sintkey, uint8_t *nwk_senckey)
{
_keys.nwk_key = nwk_key;
_keys.app_key = app_key;
//ABP mode only, so all needs to be valid
if (nwk_skey && app_skey && snwk_sintkey && nwk_senckey) {
memcpy(_keys.nwk_skey, nwk_skey,
sizeof(_keys.nwk_skey));
memcpy(_keys.app_skey, app_skey,
sizeof(_keys.app_skey));
memcpy(_keys.nwk_skey, snwk_sintkey,
sizeof(_keys.nwk_skey));
memcpy(_keys.app_skey, nwk_senckey,
sizeof(_keys.app_skey));
}
return LORAWAN_STATUS_OK;
}
int LoRaMacCrypto::compute_mic(const uint8_t *buffer, uint16_t size,
uint32_t args, uint32_t address,
uint8_t dir, uint32_t seq_counter,
uint8_t block, uint32_t *mic)
{
uint8_t computed_mic[16] = {};
uint8_t mic_block[16] = {};
int ret = 0;
uint8_t *key;
switch (dir) {
case 0:
switch (block) {
case 0:
key = _keys.nwk_skey;
break;
case 1:
key = _keys.snwk_sintkey;
break;
default:
MBED_ASSERT(false);
break;
}
break;
case 1:
MBED_ASSERT(block == 0);
key = _keys.snwk_sintkey;
break;
default:
MBED_ASSERT(false);
break;
}
//TODO: handle multicast based on address
//_dev_addr
mic_block[0] = 0x49;
mic_block[1] = (args) & 0xFF;
mic_block[2] = (args >> 8) & 0xFF;
mic_block[3] = (args >> 16) & 0xFF;
mic_block[4] = (args >> 24) & 0xFF;
mic_block[5] = dir;
mic_block[6] = (address) & 0xFF;
mic_block[7] = (address >> 8) & 0xFF;
mic_block[8] = (address >> 16) & 0xFF;
mic_block[9] = (address >> 24) & 0xFF;
mic_block[10] = (seq_counter) & 0xFF;
mic_block[11] = (seq_counter >> 8) & 0xFF;
mic_block[12] = (seq_counter >> 16) & 0xFF;
mic_block[13] = (seq_counter >> 24) & 0xFF;
mic_block[14] = 0;
mic_block[15] = size & 0xFF;
mbedtls_cipher_init(aes_cmac_ctx);
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB);
if (NULL != cipher_info) {
ret = mbedtls_cipher_setup(aes_cmac_ctx, cipher_info);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_starts(aes_cmac_ctx, key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, mic_block, sizeof(mic_block));
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, buffer, size & 0xFF);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_finish(aes_cmac_ctx, computed_mic);
if (0 != ret) {
goto exit;
}
*mic = (uint32_t)((uint32_t) computed_mic[3] << 24
| (uint32_t) computed_mic[2] << 16
| (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]);
} else {
ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED;
}
exit:
mbedtls_cipher_free(aes_cmac_ctx);
return ret;
}
int LoRaMacCrypto::encrypt_payload(const uint8_t *buffer, uint16_t size,
uint32_t address, uint8_t dir, uint32_t seq_counter,
seq_counter_type_t seq_cnt_type,
payload_type_t pld_type,
uint8_t *enc_buffer,
server_type_t serv_type, bool is_fopts)
{
uint16_t i;
uint8_t bufferIndex = 0;
int ret = 0;
uint16_t ctr = 1;
uint8_t a_block[16] = {0};
uint8_t s_block[16] = {0};
const uint8_t *key;
if (is_fopts) {
key = _keys.nwk_senckey;
} else {
key = _keys.app_skey;
//TODO: handle multicast based on address
//_dev_addr
}
mbedtls_aes_init(&aes_ctx);
ret = mbedtls_aes_setkey_enc(&aes_ctx, key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
a_block[0] = 0x01;
if (serv_type == LW1_1 && pld_type == FOPTS) {
if ((seq_cnt_type == FCNT_UP || seq_cnt_type == NFCNT_DOWN)) {
a_block[4] = 0x01;
} else if (seq_cnt_type == AFCNT_DOWN) {
a_block[4] = 0x02;
}
}
a_block[5] = dir;
a_block[6] = (address) & 0xFF;
a_block[7] = (address >> 8) & 0xFF;
a_block[8] = (address >> 16) & 0xFF;
a_block[9] = (address >> 24) & 0xFF;
a_block[10] = (seq_counter) & 0xFF;
a_block[11] = (seq_counter >> 8) & 0xFF;
a_block[12] = (seq_counter >> 16) & 0xFF;
a_block[13] = (seq_counter >> 24) & 0xFF;
a_block[15] = 0x01;
while (size >= 16) {
a_block[15] = ((ctr) & 0xFF);
ctr++;
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, a_block,
s_block);
if (0 != ret) {
goto exit;
}
for (i = 0; i < 16; i++) {
enc_buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ s_block[i];
}
size -= 16;
bufferIndex += 16;
}
if (size > 0) {
a_block[15] = ((ctr) & 0xFF);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, a_block,
s_block);
if (0 != ret) {
goto exit;
}
for (i = 0; i < size; i++) {
enc_buffer[bufferIndex + i] = buffer[bufferIndex + i] ^ s_block[i];
}
}
exit:
mbedtls_aes_free(&aes_ctx);
return ret;
}
int LoRaMacCrypto::decrypt_payload(const uint8_t *buffer, uint16_t size,
uint32_t address, uint8_t dir, uint32_t seq_counter,
seq_counter_type_t seq_cnt_type,
payload_type_t pld_type,
uint8_t *dec_buffer,
server_type_t serv_type, bool is_fopts)
{
return encrypt_payload(buffer, size, address, dir, seq_counter,
seq_cnt_type, pld_type, dec_buffer, serv_type, is_fopts);
}
int LoRaMacCrypto::compute_join_frame_mic(const uint8_t *buffer, uint16_t size,
join_frame_type_t type, uint32_t *mic)
{
uint8_t computed_mic[16] = {};
int ret = 0;
uint8_t *key;
if (type == JOIN_ACCEPT || type == REJOIN1_REQ) {
key = _keys.js_intkey;
} else if (type == JOIN_REQ) {
key = _keys.nwk_key;
} else { // REJOIN0_REQ || REJOIN2_REQ
key = _keys.snwk_sintkey;
}
mbedtls_cipher_init(aes_cmac_ctx);
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB);
if (NULL != cipher_info) {
ret = mbedtls_cipher_setup(aes_cmac_ctx, cipher_info);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_starts(aes_cmac_ctx, key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_update(aes_cmac_ctx, buffer, size & 0xFF);
if (0 != ret) {
goto exit;
}
ret = mbedtls_cipher_cmac_finish(aes_cmac_ctx, computed_mic);
if (0 != ret) {
goto exit;
}
*mic = (uint32_t)((uint32_t) computed_mic[3] << 24
| (uint32_t) computed_mic[2] << 16
| (uint32_t) computed_mic[1] << 8 | (uint32_t) computed_mic[0]);
} else {
ret = MBEDTLS_ERR_CIPHER_ALLOC_FAILED;
}
exit:
mbedtls_cipher_free(aes_cmac_ctx);
return ret;
}
int LoRaMacCrypto::decrypt_join_frame(const uint8_t *buffer, uint16_t size,
uint8_t *dec_buffer, bool is_join_req)
{
int ret = 0;
mbedtls_aes_init(&aes_ctx);
uint8_t *key;
if (is_join_req) {
key = _keys.nwk_key;
} else {
key = _keys.js_enckey;
}
ret = mbedtls_aes_setkey_enc(&aes_ctx, key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, buffer,
dec_buffer);
if (0 != ret) {
goto exit;
}
// Check if optional CFList is included
if (size >= 16) {
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, buffer + 16,
dec_buffer + 16);
}
exit:
mbedtls_aes_free(&aes_ctx);
return ret;
}
void LoRaMacCrypto::unset_js_keys()
{
memcpy(_keys.js_intkey, _keys.nwk_key, sizeof(_keys.nwk_skey));
memcpy(_keys.js_enckey, _keys.nwk_key, sizeof(_keys.nwk_skey));
}
int LoRaMacCrypto::compute_skeys_for_join_frame(const uint8_t *args, uint8_t args_size,
server_type_t stype)
{
uint8_t nonce[16];
int ret = 0;
mbedtls_aes_init(&aes_ctx);
ret = mbedtls_aes_setkey_enc(&aes_ctx, _keys.app_key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x02;
memcpy(nonce + 1, args, args_size);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.app_skey);
if (0 != ret) {
goto exit;
}
mbedtls_aes_free(&aes_ctx);
mbedtls_aes_init(&aes_ctx);
ret = mbedtls_aes_setkey_enc(&aes_ctx, _keys.nwk_key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x01;
memcpy(nonce + 1, args, args_size);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.nwk_skey);
if (0 != ret) {
goto exit;
}
if (stype == LW1_0_2) {
memcpy(_keys.nwk_senckey, _keys.nwk_skey, APPKEY_KEY_LENGTH / 8);
memcpy(_keys.snwk_sintkey, _keys.nwk_skey, APPKEY_KEY_LENGTH / 8);
} else {
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x03;
memcpy(nonce + 1, args, args_size);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.snwk_sintkey);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x04;
memcpy(nonce + 1, args, args_size);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.nwk_senckey);
if (0 != ret) {
goto exit;
}
}
exit:
mbedtls_aes_free(&aes_ctx);
return ret;
}
int LoRaMacCrypto::compute_join_server_keys(const uint8_t *eui)
{
uint8_t nonce[16];
int ret = 0;
if (MBED_CONF_LORA_VERSION == LORAWAN_VERSION_1_0_2) {
memcpy(_keys.js_intkey, _keys.nwk_key, APPKEY_KEY_LENGTH / 8);
memcpy(_keys.js_enckey, _keys.nwk_key, APPKEY_KEY_LENGTH / 8);
return ret;
}
mbedtls_aes_init(&aes_ctx);
ret = mbedtls_aes_setkey_enc(&aes_ctx, _keys.nwk_key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x05;
memcpy(nonce + 1, eui, 8);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.js_enckey);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = 0x06;
memcpy(nonce + 1, eui, 8);
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, _keys.js_intkey);
if (0 != ret) {
goto exit;
}
exit:
mbedtls_aes_free(&aes_ctx);
return ret;
}
int LoRaMacCrypto::compute_ping_slot_random_offset(uint32_t beacon_time, uint32_t dev_addr, uint16_t *rand)
{
uint8_t nonce[16];
uint8_t key[16];
uint8_t output[16];
int ret = 0;
mbedtls_aes_init(&aes_ctx);
memset(key, 0, sizeof(key));
ret = mbedtls_aes_setkey_enc(&aes_ctx, key, APPKEY_KEY_LENGTH);
if (0 != ret) {
goto exit;
}
memset(nonce, 0, sizeof(nonce));
nonce[0] = beacon_time & 0xFF;
nonce[1] = (beacon_time >> 8) & 0xFF;
nonce[2] = (beacon_time >> 16) & 0xFF;
nonce[3] = (beacon_time >> 24) & 0xFF;
nonce[4] = dev_addr & 0xFF;
nonce[5] = (dev_addr >> 8) & 0xFF;
nonce[6] = (dev_addr >> 16) & 0xFF;
nonce[7] = (dev_addr >> 24) & 0xFF;
ret = mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, nonce, output);
if (0 != ret) {
goto exit;
}
*rand = output[0] + (output[1] * 256);
exit:
mbedtls_aes_free(&aes_ctx);
return ret;
}
#else
LoRaMacCrypto::LoRaMacCrypto()
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
}
LoRaMacCrypto::~LoRaMacCrypto()
{
}
lorawan_status_t LoRaMacCrypto::set_keys(uint8_t *, uint8_t *, uint8_t *, uint8_t *, uint8_t *, uint8_t *)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
// If mbedTLS is not configured properly, these dummies will ensure that
// user knows what is wrong and in addition to that these ensure that
// Mbed-OS compiles properly under normal conditions where LoRaWAN in conjunction
// with mbedTLS is not being used.
int LoRaMacCrypto::compute_mic(const uint8_t *, uint16_t, uint32_t, uint32_t,
uint8_t, uint32_t, uint32_t *)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::encrypt_payload(const uint8_t *, uint16_t,
uint32_t, uint8_t, uint32_t,
seq_counter_type_t,
payload_type_t,
uint8_t *,
server_type_t, bool)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::decrypt_payload(const uint8_t *, uint16_t,
uint32_t, uint8_t, uint32_t,
seq_counter_type_t,
payload_type_t,
uint8_t *,
server_type_t, bool)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::compute_join_frame_mic(const uint8_t *, uint16_t, join_frame_type_t, uint32_t *)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::decrypt_join_frame(const uint8_t *, uint16_t, uint8_t *, bool)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::compute_skeys_for_join_frame(const uint8_t *, uint8_t,
server_type_t)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::compute_join_server_keys(const uint8_t *)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
int LoRaMacCrypto::compute_ping_slot_random_offset(uint32_t beacon_time, uint32_t dev_addr, uint16_t *rand)
{
MBED_ASSERT(0 && "[LoRaCrypto] Must enable AES, CMAC & CIPHER from mbedTLS");
// Never actually reaches here
return LORAWAN_STATUS_CRYPTO_FAIL;
}
#endif
| 28.57717
| 107
| 0.576653
|
Lljiro
|
dcc5f9d504b814705fe38a5ef790a15c5bf2b30b
| 3,413
|
cpp
|
C++
|
src/engine/audio/src/audio_mixer.cpp
|
sunhay/halley
|
fc4f153956cc34d7fa02b76850e22183b8e30e25
|
[
"Apache-2.0"
] | null | null | null |
src/engine/audio/src/audio_mixer.cpp
|
sunhay/halley
|
fc4f153956cc34d7fa02b76850e22183b8e30e25
|
[
"Apache-2.0"
] | null | null | null |
src/engine/audio/src/audio_mixer.cpp
|
sunhay/halley
|
fc4f153956cc34d7fa02b76850e22183b8e30e25
|
[
"Apache-2.0"
] | null | null | null |
#include "audio_mixer.h"
#include "halley/utils/utils.h"
#include "audio_mixer_sse.h"
#include "audio_mixer_avx.h"
using namespace Halley;
void AudioMixer::mixAudio(gsl::span<const AudioSamplePack> src, gsl::span<AudioSamplePack> dst, float gain0, float gain1)
{
const size_t nPacks = size_t(src.size());
if (gain0 == gain1) {
// If the gain doesn't change, the code is faster
for (size_t i = 0; i < nPacks; ++i) {
for (size_t j = 0; j < AudioSamplePack::NumSamples; ++j) {
dst[i].samples[j] += src[i].samples[j] * gain0;
}
}
} else {
// Interpolate the gain
const float scale = 1.0f / (dst.size() * AudioSamplePack::NumSamples);
for (size_t i = 0; i < nPacks; ++i) {
for (size_t j = 0; j < AudioSamplePack::NumSamples; ++j) {
dst[i].samples[j] += src[i].samples[j] * lerp(gain0, gain1, (i * AudioSamplePack::NumSamples + j) * scale);
}
}
}
}
void AudioMixer::interleaveChannels(gsl::span<AudioSamplePack> dstBuffer, gsl::span<AudioBuffer*> srcs)
{
Expects(srcs.size() == 2);
size_t n = 0;
for (size_t i = 0; i < size_t(dstBuffer.size()); ++i) {
gsl::span<AudioConfig::SampleFormat> dst = dstBuffer[i].samples;
size_t srcIdx = i >> 1;
size_t srcOff = (i & 1) << 3;
for (size_t j = 0; j < AudioSamplePack::NumSamples / 2; ++j) {
size_t srcPos = j + srcOff;
dst[2 * j] = srcs[0]->packs[srcIdx].samples[srcPos];
dst[2 * j + 1] = srcs[1]->packs[srcIdx].samples[srcPos];
n += 2;
}
}
}
void AudioMixer::concatenateChannels(gsl::span<AudioSamplePack> dst, gsl::span<AudioBuffer*> srcs)
{
size_t pos = 0;
for (size_t i = 0; i < size_t(srcs.size()); ++i) {
const size_t nBytes = srcs[i]->packs.size() * sizeof(AudioSamplePack);
memcpy(dst.subspan(pos, nBytes).data(), srcs[i]->packs.data(), nBytes);
pos += nBytes;
}
}
void AudioMixer::compressRange(gsl::span<AudioSamplePack> buffer)
{
for (ptrdiff_t i = 0; i < buffer.size(); ++i) {
for (size_t j = 0; j < AudioSamplePack::NumSamples; ++j) {
float& sample = buffer[i].samples[j];
sample = std::max(-0.99995f, std::min(sample, 0.99995f));
}
}
}
#ifdef HAS_SSE
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <cpuid.h>
static inline unsigned long long _xgetbv(unsigned int index){
unsigned int eax, edx;
__asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index));
return ((unsigned long long)edx << 32) | eax;
}
#define _XCR_XFEATURE_ENABLED_MASK 0
#endif
#endif
#ifdef HAS_AVX
static bool hasAVX()
{
#ifndef _MSC_VER
// It's crashing on Linux :(
return false;
#endif
#ifdef HAS_SSE
int regs[4];
int i = 1;
#ifdef _WIN32
__cpuid(regs, i);
#else
asm volatile
("cpuid" : "=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3])
: "a" (i), "c" (0));
// ECX is set to zero for CPUID function 4
#endif
bool osUsesXSAVE_XRSTORE = regs[2] & (1 << 27) || false;
bool cpuAVXSuport = regs[2] & (1 << 28) || false;
if (osUsesXSAVE_XRSTORE && cpuAVXSuport) {
unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
return (xcrFeatureMask & 0x6) == 0x6;
} else {
return false;
}
#else
return false;
#endif
}
#endif
std::unique_ptr<AudioMixer> AudioMixer::makeMixer()
{
#ifdef HAS_AVX
if (hasAVX()) {
return std::make_unique<AudioMixerAVX>();
} else {
return std::make_unique<AudioMixerSSE>();
}
#elif HAS_SEE
return std::make_unique<AudioMixerSSE>();
#else
return std::make_unique<AudioMixer>();
#endif
}
| 24.553957
| 121
| 0.648696
|
sunhay
|
dcc75e92d1b0bef4585d1d90c1dbb0e40bb9aa41
| 25,261
|
cpp
|
C++
|
src/game/WorldHandlers/LFGHandler.cpp
|
tbayart/mangostwoserver
|
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | 1
|
2021-04-30T05:18:37.000Z
|
2021-04-30T05:18:37.000Z
|
src/game/WorldHandlers/LFGHandler.cpp
|
tbayart/mangostwoserver
|
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
src/game/WorldHandlers/LFGHandler.cpp
|
tbayart/mangostwoserver
|
fc26f650b9f72c1f7376207f9b9d3fdf66387a1e
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2017 MaNGOS project <https://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "WorldSession.h"
#include "LFGMgr.h"
#include "Log.h"
#include "Player.h"
#include "WorldPacket.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "World.h"
void WorldSession::HandleLfgJoinOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_JOIN");
uint8 dungeonsCount, counter2;
uint32 roles;
std::string comment;
std::set<uint32> dungeons;
recv_data >> roles; // lfg roles
recv_data >> Unused<uint8>(); // lua: GetLFGInfoLocal
recv_data >> Unused<uint8>(); // lua: GetLFGInfoLocal
recv_data >> dungeonsCount;
for (uint8 i = 0; i < dungeonsCount; ++i)
{
uint32 dungeonEntry;
recv_data >> dungeonEntry;
dungeons.insert((dungeonEntry & 0x00FFFFFF)); // just dungeon id
}
recv_data >> counter2; // const count = 3, lua: GetLFGInfoLocal
for (uint8 i = 0; i < counter2; ++i)
recv_data >> Unused<uint8>(); // lua: GetLFGInfoLocal
recv_data >> comment; // lfg comment
sLFGMgr.JoinLFG(roles, dungeons, comment, GetPlayer()); // Attempt to join lfg system
}
void WorldSession::HandleLfgLeaveOpcode(WorldPacket& /*recv_data*/)
{
DEBUG_LOG("CMSG_LFG_LEAVE");
Player* pPlayer = GetPlayer();
ObjectGuid guid = pPlayer->GetObjectGuid();
Group* pGroup = pPlayer->GetGroup();
// If it's just one player they can leave, otherwise just the group leader
if (!pGroup)
sLFGMgr.LeaveLFG(pPlayer, false);
else if (pGroup && pGroup->IsLeader(guid))
sLFGMgr.LeaveLFG(pPlayer, true);
// SendLfgUpdate(false, LFG_UPDATE_LEAVE, 0);
}
void WorldSession::HandleSearchLfgJoinOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_SEARCH_JOIN");
uint32 temp, entry;
recv_data >> temp;
entry = (temp & 0x00FFFFFF);
// LfgType type = LfgType((temp >> 24) & 0x000000FF);
// SendLfgSearchResults(type, entry);
}
void WorldSession::HandleSearchLfgLeaveOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_SEARCH_LEAVE");
recv_data >> Unused<uint32>(); // join id?
}
void WorldSession::HandleSetLfgCommentOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_SET_LFG_COMMENT");
ObjectGuid guid = GetPlayer()->GetObjectGuid();
std::string comment;
recv_data >> comment;
DEBUG_LOG("LFG comment \"%s\"", comment.c_str());
sLFGMgr.SetPlayerComment(guid, comment);
}
void WorldSession::HandleLfgGetPlayerInfo(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_GET_PLAYER_INFO");
Player* pPlayer = GetPlayer();
uint32 level = pPlayer->getLevel();
uint8 expansion = pPlayer->GetSession()->Expansion();
dungeonEntries availableDungeons = sLFGMgr.FindRandomDungeonsForPlayer(level, expansion);
dungeonForbidden lockedDungeons = sLFGMgr.FindRandomDungeonsNotForPlayer(pPlayer);
uint32 availableSize = uint32(availableDungeons.size());
uint32 forbiddenSize = uint32(lockedDungeons.size());
DEBUG_LOG("Sending SMSG_LFG_PLAYER_INFO...");
WorldPacket data(SMSG_LFG_PLAYER_INFO, 1+(availableSize*34)+4+(forbiddenSize*30));
data << uint8(availableDungeons.size()); // amount of available dungeons
for (dungeonEntries::iterator it = availableDungeons.begin(); it != availableDungeons.end(); ++it)
{
DEBUG_LOG("Parsing a dungeon entry for packet");
data << uint32(it->second); // dungeon entry
DungeonTypes type = sLFGMgr.GetDungeonType(it->first); // dungeon type
const DungeonFinderRewards* rewards = sObjectMgr.GetDungeonFinderRewards(level); // get xp and money rewards
ItemRewards itemRewards = sLFGMgr.GetDungeonItemRewards(it->first, type); // item rewards
int32 multiplier;
bool hasDoneToday = sLFGMgr.HasPlayerDoneDaily(pPlayer->GetGUIDLow(), type); // using variable to send later in packet
(hasDoneToday) ? multiplier = 1 : multiplier = 2; // 2x base reward if first dungeon of the day
data << uint8(hasDoneToday);
data << uint32(multiplier*rewards->baseMonetaryReward); // cash/gold reward
data << uint32(((uint32)multiplier)*rewards->baseXPReward); // experience reward
data << uint32(0); // null
data << uint32(0); // null
if (!hasDoneToday)
{
ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(itemRewards.itemId);
if (pProto)
{
data << uint8(1); // 1 item rewarded per dungeon
data << uint32(itemRewards.itemId); // entry of item
data << uint32(pProto->DisplayInfoID); // display id of item
data << uint32(itemRewards.itemAmount); // amount of item reward
}
else
data << uint8(0); // couldn't find the item reward
}
else if (hasDoneToday && (type == DUNGEON_WOTLK_HEROIC)) // special case
{
if (ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(WOTLK_SPECIAL_HEROIC_ITEM))
{
data << uint8(1);
data << uint32(WOTLK_SPECIAL_HEROIC_ITEM);
data << uint32(pProto->DisplayInfoID);
data << uint32(WOTLK_SPECIAL_HEROIC_AMNT);
}
else
data << uint8(0);
}
else
data << uint8(0);
}
data << uint32(lockedDungeons.size());
for (dungeonForbidden::iterator it = lockedDungeons.begin(); it != lockedDungeons.end(); ++it)
{
data << uint32(it->first); // dungeon entry
data << uint32(it->second); // reason for being locked
}
SendPacket(&data);
}
void WorldSession::HandleLfgGetPartyInfo(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_GET_PARTY_INFO");
Player* pPlayer = GetPlayer();
uint64 guid = pPlayer->GetObjectGuid().GetRawValue(); // send later in packet
Group* pGroup = pPlayer->GetGroup();
if (!pGroup)
return;
partyForbidden groupMap;
for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupPlayer = itr->getSource();
if (!pGroupPlayer)
continue;
ObjectGuid pPlayerGuid = pGroupPlayer->GetObjectGuid();
if (pPlayerGuid.GetRawValue() != guid)
groupMap[pPlayerGuid] = sLFGMgr.FindRandomDungeonsNotForPlayer(pGroupPlayer);
}
uint32 packetSize = 0;
for (partyForbidden::iterator it = groupMap.begin(); it != groupMap.end(); ++it)
packetSize += 12 + uint32(it->second.size()) * 8;
DEBUG_LOG("Sending SMSG_LFG_PARTY_INFO...");
WorldPacket data(SMSG_LFG_PARTY_INFO, packetSize);
data << uint8(groupMap.size());
for (partyForbidden::iterator it = groupMap.begin(); it != groupMap.end(); ++it)
{
dungeonForbidden dungeonInfo = it->second;
data << uint64(it->first); // object guid of player
data << uint32(dungeonInfo.size()); // amount of their locked dungeons
for (dungeonForbidden::iterator itr = dungeonInfo.begin(); itr != dungeonInfo.end(); ++itr)
{
data << uint32(itr->first); // dungeon entry
data << uint32(itr->second); // reason for dungeon being forbidden/locked
}
}
SendPacket(&data);
}
void WorldSession::HandleLfgGetStatus(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_GET_STATUS");
Player* pPlayer = GetPlayer();
ObjectGuid guid = pPlayer->GetObjectGuid();
LFGPlayerStatus currentStatus = sLFGMgr.GetPlayerStatus(guid);
if (pPlayer->GetGroup())
{
SendLfgUpdate(true, currentStatus);
currentStatus.dungeonList.clear();
SendLfgUpdate(false, currentStatus);
}
else
{
// reverse order
SendLfgUpdate(false, currentStatus);
currentStatus.dungeonList.clear();
SendLfgUpdate(true, currentStatus);
}
}
void WorldSession::HandleLfgSetRoles(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_SET_ROLES");
Player* pPlayer = GetPlayer();
Group* pGroup = pPlayer->GetGroup();
if (!pGroup) // role check/set is only done in groups
return;
uint8 roles;
recv_data >> roles;
sLFGMgr.PerformRoleCheck(pPlayer, pGroup, roles); // handle the rules/logic in lfgmgr
}
void WorldSession::HandleLfgProposalResponse(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_PROPOSAL_RESPONSE");
ObjectGuid guid = GetPlayer()->GetObjectGuid();
uint32 proposalID;
bool accepted;
recv_data >> proposalID; // internal proposal id
recv_data >> accepted; // their response
sLFGMgr.ProposalUpdate(proposalID, guid, accepted);
}
void WorldSession::HandleLfgTeleportRequest(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_TELEPORT");
bool out;
recv_data >> out; // exit instance
sLFGMgr.TeleportPlayer(GetPlayer(), out);
}
void WorldSession::HandleLfgBootVote(WorldPacket& recv_data)
{
DEBUG_LOG("CMSG_LFG_BOOT_PLAYER_VOTE");
bool vote;
recv_data >> vote;
sLFGMgr.CastVote(GetPlayer(), vote);
}
void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry)
{
WorldPacket data(SMSG_LFG_SEARCH_RESULTS);
data << uint32(type); // type
data << uint32(entry); // entry from LFGDungeons.dbc
uint8 isGuidsPresent = 0;
data << uint8(isGuidsPresent);
if (isGuidsPresent)
{
uint32 guids_count = 0;
data << uint32(guids_count);
for (uint32 i = 0; i < guids_count; ++i)
{
data << uint64(0); // player/group guid
}
}
uint32 groups_count = 1;
data << uint32(groups_count); // groups count
data << uint32(groups_count); // groups count (total?)
for (uint32 i = 0; i < groups_count; ++i)
{
data << uint64(1); // group guid
uint32 flags = 0x92;
data << uint32(flags); // flags
if (flags & 0x2)
{
data << uint8(0); // comment string, max len 256
}
if (flags & 0x10)
{
for (uint32 j = 0; j < 3; ++j)
data << uint8(0); // roles
}
if (flags & 0x80)
{
data << uint64(0); // instance guid
data << uint32(0); // completed encounters
}
}
// TODO: Guard Player map
HashMapHolder<Player>::MapType const& players = sObjectAccessor.GetPlayers();
uint32 playersSize = players.size();
data << uint32(playersSize); // players count
data << uint32(playersSize); // players count (total?)
for (HashMapHolder<Player>::MapType::const_iterator iter = players.begin(); iter != players.end(); ++iter)
{
Player* plr = iter->second;
if (!plr || plr->GetTeam() != _player->GetTeam())
continue;
if (!plr->IsInWorld())
continue;
data << plr->GetObjectGuid(); // guid
uint32 flags = 0xFF;
data << uint32(flags); // flags
if (flags & 0x1)
{
data << uint8(plr->getLevel());
data << uint8(plr->getClass());
data << uint8(plr->getRace());
for (uint32 i = 0; i < 3; ++i)
data << uint8(0); // talent spec x/x/x
data << uint32(0); // armor
data << uint32(0); // spd/heal
data << uint32(0); // spd/heal
data << uint32(0); // HasteMelee
data << uint32(0); // HasteRanged
data << uint32(0); // HasteSpell
data << float(0); // MP5
data << float(0); // MP5 Combat
data << uint32(0); // AttackPower
data << uint32(0); // Agility
data << uint32(0); // Health
data << uint32(0); // Mana
data << uint32(0); // Unk1
data << float(0); // Unk2
data << uint32(0); // Defence
data << uint32(0); // Dodge
data << uint32(0); // Block
data << uint32(0); // Parry
data << uint32(0); // Crit
data << uint32(0); // Expertise
}
if (flags & 0x2)
data << ""; // comment
if (flags & 0x4)
data << uint8(0); // group leader
if (flags & 0x8)
data << uint64(1); // group guid
if (flags & 0x10)
data << uint8(0); // roles
if (flags & 0x20)
data << uint32(plr->GetZoneId()); // areaid
if (flags & 0x40)
data << uint8(0); // status
if (flags & 0x80)
{
data << uint64(0); // instance guid
data << uint32(0); // completed encounters
}
}
SendPacket(&data);
}
void WorldSession::SendLfgJoinResult(LfgJoinResult result, LFGState state, partyForbidden const& lockedDungeons)
{
uint32 packetSize = 0;
for (partyForbidden::const_iterator it = lockedDungeons.begin(); it != lockedDungeons.end(); ++it)
packetSize += 12 + uint32(it->second.size()) * 8;
WorldPacket data(SMSG_LFG_JOIN_RESULT, packetSize);
data << uint32(result);
data << uint32(state);
if (!lockedDungeons.empty())
{
for (partyForbidden::const_iterator it = lockedDungeons.begin(); it != lockedDungeons.end(); ++it)
{
dungeonForbidden dungeonInfo = it->second;
data << uint64(it->first); // object guid of player
data << uint32(dungeonInfo.size()); // amount of their locked dungeons
for (dungeonForbidden::iterator itr = dungeonInfo.begin(); itr != dungeonInfo.end(); ++itr)
{
data << uint32(itr->first); // dungeon entry
data << uint32(itr->second); // reason for dungeon being forbidden/locked
}
}
}
SendPacket(&data);
}
void WorldSession::SendLfgUpdate(bool isGroup, LFGPlayerStatus status)
{
uint8 dungeonSize = uint8(status.dungeonList.size());
bool isQueued = false, joinLFG = false;
switch (status.updateType)
{
case LFG_UPDATE_JOIN:
case LFG_UPDATE_ADDED_TO_QUEUE:
isQueued = true;
case LFG_UPDATE_PROPOSAL_BEGIN:
if (isGroup)
joinLFG = true;
break;
case LFG_UPDATE_STATUS:
isQueued = (status.state == LFG_STATE_QUEUED);
if (isGroup)
joinLFG = (status.state != LFG_STATE_ROLECHECK) && (status.state != LFG_STATE_NONE);
break;
default:
break;
}
WorldPacket data(isGroup ? SMSG_LFG_UPDATE_PARTY : SMSG_LFG_UPDATE_PLAYER);
data << uint8(status.updateType);
data << uint8(dungeonSize > 0);
if (dungeonSize)
{
if (isGroup)
data << uint8(joinLFG);
data << uint8(isQueued);
data << uint8(0);
data << uint8(0);
if (isGroup)
{
for (uint32 i = 0; i < 3; ++i)
data << uint8(0);
}
data << uint8(dungeonSize);
for (std::set<uint32>::iterator it = status.dungeonList.begin(); it != status.dungeonList.end(); ++it)
data << uint32(*it);
data << status.comment;
}
SendPacket(&data);
}
void WorldSession::SendLfgQueueStatus(LFGQueueStatus const& status)
{
WorldPacket data(SMSG_LFG_QUEUE_STATUS, 31);
data << uint32(status.dungeonID);
data << int32(status.playerAvgWaitTime);
data << int32(status.avgWaitTime);
data << int32(status.tankAvgWaitTime);
data << int32(status.healerAvgWaitTime);
data << int32(status.dpsAvgWaitTime);
data << uint8(status.neededTanks);
data << uint8(status.neededHeals);
data << uint8(status.neededDps);
data << uint32(status.timeSpentInQueue);
SendPacket(&data);
}
void WorldSession::SendLfgRoleCheckUpdate(LFGRoleCheck const& roleCheck)
{
WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE);
data << uint32(roleCheck.state);
data << uint8(roleCheck.state == LFG_ROLECHECK_INITIALITING);
std::set<uint32> dungeons;
if (roleCheck.randomDungeonID)
dungeons.insert(roleCheck.randomDungeonID);
else
dungeons = roleCheck.dungeonList;
data << uint8(dungeons.size());
if (!dungeons.empty())
for (std::set<uint32>::iterator it = dungeons.begin(); it != dungeons.end(); ++it)
data << uint32(sLFGMgr.GetDungeonEntry(*it));
data << uint8(roleCheck.currentRoles.size());
if (!roleCheck.currentRoles.empty())
{
ObjectGuid leaderGuid = ObjectGuid(roleCheck.leaderGuidRaw);
uint8 leaderRoles = roleCheck.currentRoles.find(leaderGuid)->second;
Player* pLeader = ObjectAccessor::FindPlayer(leaderGuid);
data << uint64(leaderGuid.GetRawValue());
data << uint8(leaderRoles > 0);
data << uint32(leaderRoles);
data << uint8(pLeader->getLevel());
for (roleMap::const_iterator rItr = roleCheck.currentRoles.begin(); rItr != roleCheck.currentRoles.end(); ++rItr)
{
if (rItr->first == leaderGuid)
continue; // exclude the leader
ObjectGuid plrGuid = rItr->first;
Player* pPlayer = ObjectAccessor::FindPlayer(plrGuid);
data << uint64(plrGuid.GetRawValue());
data << uint8(rItr->second > 0);
data << uint32(rItr->second);
data << uint8(pPlayer->getLevel());
}
}
SendPacket(&data);
}
void WorldSession::SendLfgRoleChosen(uint64 rawGuid, uint8 roles)
{
WorldPacket data(SMSG_ROLE_CHOSEN, 13);
data << uint64(rawGuid);
data << uint8(roles > 0);
data << uint32(roles);
SendPacket(&data);
}
void WorldSession::SendLfgProposalUpdate(LFGProposal const& proposal)
{
Player* pPlayer = GetPlayer();
ObjectGuid plrGuid = pPlayer->GetObjectGuid();
ObjectGuid plrGroupGuid = proposal.groups.find(plrGuid)->second;
uint32 dungeonEntry = sLFGMgr.GetDungeonEntry(proposal.dungeonID);
bool showProposal = !proposal.isNew && proposal.groupRawGuid == plrGroupGuid.GetRawValue();
WorldPacket data(SMSG_LFG_PROPOSAL_UPDATE, 15+(9*proposal.currentRoles.size()));
data << uint32(dungeonEntry); // Dungeon Entry
data << uint8(proposal.state); // Proposal state
data << uint32(proposal.id); // ID of proposal
data << uint32(proposal.encounters); // Encounters done
data << uint8(showProposal); // Show or hide proposal window [todo-this]
data << uint8(proposal.currentRoles.size()); // Size of group
for (playerGroupMap::const_iterator it = proposal.groups.begin(); it != proposal.groups.end(); ++it)
{
ObjectGuid grpPlrGuid = it->first;
uint8 grpPlrRole = proposal.currentRoles.find(grpPlrGuid)->second;
LFGProposalAnswer grpPlrAnswer = proposal.answers.find(grpPlrGuid)->second;
data << uint32(grpPlrRole); // Player's role
data << uint8(grpPlrGuid == plrGuid); // Is this player me?
if (it->second != 0)
{
data << uint8(it->second == ObjectGuid(proposal.groupRawGuid)); // Is player in the proposed group?
data << uint8(it->second == plrGroupGuid); // Is player in the same group as myself?
}
else
{
data << uint8(0);
data << uint8(0);
}
data << uint8(grpPlrAnswer != LFG_ANSWER_PENDING); // Has the player selected an answer?
data << uint8(grpPlrAnswer == LFG_ANSWER_AGREE); // Has the player agreed to do the dungeon?
}
SendPacket(&data);
}
void WorldSession::SendLfgTeleportError(uint8 error)
{
DEBUG_LOG("SMSG_LFG_TELEPORT_DENIED");
WorldPacket data(SMSG_LFG_TELEPORT_DENIED, 4);
data << uint32(error);
SendPacket(&data);
}
void WorldSession::SendLfgRewards(LFGRewards const& rewards)
{
DEBUG_LOG("SMSG_LFG_PLAYER_REWARD");
WorldPacket data(SMSG_LFG_PLAYER_REWARD, 42);
data << uint32(rewards.randomDungeonEntry);
data << uint32(rewards.groupDungeonEntry);
data << uint8(rewards.hasDoneDaily);
data << uint32(1);
data << uint32(rewards.moneyReward);
data << uint32(rewards.expReward);
data << uint32(0);
data << uint32(0);
if (rewards.itemID != 0)
{
ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(rewards.itemID);
if (pProto)
{
data << uint8(1);
data << uint32(rewards.itemID);
data << uint32(pProto->DisplayInfoID);
data << uint32(rewards.itemAmount);
}
}
else
data << uint8(0);
SendPacket(&data);
}
void WorldSession::SendLfgBootUpdate(LFGBoot const& boot)
{
DEBUG_LOG("SMSG_LFG_BOOT_PLAYER");
ObjectGuid plrGuid = GetPlayer()->GetObjectGuid();
LFGProposalAnswer plrAnswer = boot.answers.find(plrGuid)->second;
uint32 voteCount = 0, yayCount = 0;
for (proposalAnswerMap::const_iterator it = boot.answers.begin(); it != boot.answers.end(); ++it)
{
if (it->second != LFG_ANSWER_PENDING)
{
++voteCount;
if (it->second == LFG_ANSWER_AGREE)
++yayCount;
}
}
uint32 timeLeft = uint8( ((boot.startTime+LFG_TIME_BOOT)-time(NULL)) / 1000 );
WorldPacket data(SMSG_LFG_BOOT_PLAYER, 27+boot.reason.length());
data << uint8(boot.inProgress); // Is boot still ongoing?
data << uint8(plrAnswer != LFG_ANSWER_PENDING); // Did this player vote yet?
data << uint8(plrAnswer == LFG_ANSWER_AGREE); // Did this player agree to boot them?
data << uint64(boot.playerVotedOn.GetRawValue()); // Potentially booted player's objectguid value
data << uint32(voteCount); // Number of players who've voted so far
data << uint32(yayCount); // Number of players who've voted against the plr so far
data << uint32(timeLeft); // Time left in seconds
data << uint32(REQUIRED_VOTES_FOR_BOOT); // Number of votes needed to win
data << boot.reason.c_str(); // Reason given for booting
SendPacket(&data);
}
| 35.379552
| 130
| 0.562131
|
tbayart
|
dccb449154a126cd7fe82ce4158a0bf3639bc2a7
| 16,263
|
hpp
|
C++
|
test/algorithms/buffer/test_buffer_svg.hpp
|
onlykzy/geometry
|
be6794b606d25cf53fe2fd312f9b5fe30ddda6fb
|
[
"BSL-1.0"
] | null | null | null |
test/algorithms/buffer/test_buffer_svg.hpp
|
onlykzy/geometry
|
be6794b606d25cf53fe2fd312f9b5fe30ddda6fb
|
[
"BSL-1.0"
] | null | null | null |
test/algorithms/buffer/test_buffer_svg.hpp
|
onlykzy/geometry
|
be6794b606d25cf53fe2fd312f9b5fe30ddda6fb
|
[
"BSL-1.0"
] | null | null | null |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test Helper
// Copyright (c) 2010-2015 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2020-2021.
// Modifications copyright (c) 2020-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_TEST_BUFFER_SVG_HPP
#define BOOST_GEOMETRY_TEST_BUFFER_SVG_HPP
#include <fstream>
#include <sstream>
// Uncomment next lines if you want to have a zoomed view
//#define BOOST_GEOMETRY_BUFFER_TEST_SVG_USE_ALTERNATE_BOX
// If possible define box before including this unit with the right view
#ifdef BOOST_GEOMETRY_BUFFER_TEST_SVG_USE_ALTERNATE_BOX
# ifndef BOOST_GEOMETRY_BUFFER_TEST_SVG_ALTERNATE_BOX
# define BOOST_GEOMETRY_BUFFER_TEST_SVG_ALTERNATE_BOX "BOX(0 0,100 100)"
# endif
#endif
#include <boost/geometry/io/svg/svg_mapper.hpp>
#include <boost/geometry/algorithms/buffer.hpp>
#include <boost/geometry/algorithms/intersection.hpp>
namespace detail
{
template <typename Ring, typename cstag = typename bg::cs_tag<Ring>::type>
struct get_labelpoint
{
using point_type = typename bg::point_type<Ring>::type;
template <typename Piece>
static point_type apply(Ring const& , Piece const& piece)
{
return piece.m_label_point;
}
};
template <typename Ring>
struct get_labelpoint<Ring, bg::cartesian_tag>
{
using point_type = typename bg::point_type<Ring>::type;
template <typename Piece>
static point_type apply(Ring const& ring, Piece const& piece)
{
// Centroid is currently only available for cartesian
return ring.empty()
? piece.m_label_point
: bg::return_centroid<point_type>(ring);
}
};
}
template <typename Ring, typename Piece>
inline typename bg::point_type<Ring>::type
get_labelpoint(Ring const& ring, Piece const& piece)
{
if ((piece.type == bg::strategy::buffer::buffered_concave
|| piece.type == bg::strategy::buffer::buffered_flat_end)
&& ring.size() >= 2u)
{
// Return a point between the first two points on the ring
typename bg::point_type<Ring>::type result;
bg::set<0>(result, (bg::get<0>(ring[0]) + bg::get<0>(ring[1])) / 2.0);
bg::set<1>(result, (bg::get<1>(ring[0]) + bg::get<1>(ring[1])) / 2.0);
return result;
}
else
{
// Return the piece's labelpoint or the centroid
return detail::get_labelpoint<Ring>::apply(ring, piece);
}
}
inline char piece_type_char(bg::strategy::buffer::piece_type const& type)
{
using namespace bg::strategy::buffer;
switch(type)
{
case buffered_segment : return 's';
case buffered_join : return 'j';
case buffered_round_end : return 'r';
case buffered_flat_end : return 'f';
case buffered_point : return 'p';
case buffered_concave : return 'c';
default : return '?';
}
}
template <typename SvgMapper, typename Box>
class svg_visitor
{
public :
svg_visitor(SvgMapper& mapper)
: m_mapper(mapper)
, m_zoom(false)
{
bg::assign_inverse(m_alternate_box);
}
void set_alternate_box(Box const& box)
{
m_alternate_box = box;
m_zoom = true;
}
template <typename PieceCollection>
inline void apply(PieceCollection const& collection, int phase)
{
// Comment next return if you want to see pieces, turns, etc.
return;
if(phase == 0)
{
map_pieces(collection.m_pieces, collection.offsetted_rings, true, true);
}
if (phase == 1)
{
map_turns(collection.m_turns, true, false);
}
if (phase == 2 && ! m_zoom)
{
// map_traversed_rings(collection.traversed_rings);
// map_offsetted_rings(collection.offsetted_rings);
}
}
private :
class si
{
private :
bg::segment_identifier m_id;
public :
inline si(bg::segment_identifier const& id)
: m_id(id)
{}
template <typename Char, typename Traits>
inline friend std::basic_ostream<Char, Traits>& operator<<(
std::basic_ostream<Char, Traits>& os,
si const& s)
{
os << s.m_id.multi_index << "." << s.m_id.segment_index;
return os;
}
};
template <typename Turns>
inline void map_turns(Turns const& turns, bool label_good_turns, bool label_wrong_turns)
{
namespace bgdb = boost::geometry::detail::buffer;
using turn_type = typename boost::range_value<Turns const>::type;
using point_type = typename turn_type::point_type;
std::map<point_type, int, bg::less<point_type> > offsets;
for (auto it = boost::begin(turns); it != boost::end(turns); ++it)
{
if (m_zoom && bg::disjoint(it->point, m_alternate_box))
{
continue;
}
bool is_good = true;
std::string fill = "fill:rgb(0,255,0);";
if (! it->is_turn_traversable)
{
fill = "fill:rgb(255,0,0);";
is_good = false;
}
if (it->blocked())
{
fill = "fill:rgb(128,128,128);";
is_good = false;
}
fill += "fill-opacity:0.7;";
m_mapper.map(it->point, fill, 4);
if ((label_good_turns && is_good) || (label_wrong_turns && ! is_good))
{
std::ostringstream out;
out << it->turn_index;
if (it->cluster_id >= 0)
{
out << " (" << it->cluster_id << ")";
}
out
<< " " << it->operations[0].piece_index << "/" << it->operations[1].piece_index
<< " " << si(it->operations[0].seg_id) << "/" << si(it->operations[1].seg_id)
// If you want to see travel information
<< std::endl
<< " nxt " << it->operations[0].enriched.get_next_turn_index()
<< "/" << it->operations[1].enriched.get_next_turn_index()
//<< " frac " << it->operations[0].fraction
// If you want to see point coordinates (e.g. to find duplicates)
<< std::endl << std::setprecision(16) << bg::wkt(it->point)
<< std::endl;
out << " " << bg::method_char(it->method)
<< ":" << bg::operation_char(it->operations[0].operation)
<< "/" << bg::operation_char(it->operations[1].operation);
out << " "
<< (it->is_turn_traversable ? "" : "w")
;
offsets[it->point] += 10;
int offset = offsets[it->point];
m_mapper.text(it->point, out.str(), "fill:rgb(0,0,0);font-family='Arial';font-size:9px;", 5, offset);
offsets[it->point] += 25;
}
}
}
template <typename Pieces, typename OffsettedRings>
inline void map_pieces(Pieces const& pieces,
OffsettedRings const& offsetted_rings,
bool do_pieces, bool do_indices)
{
using piece_type = typename boost::range_value<Pieces const>::type ;
using ring_type = typename boost::range_value<OffsettedRings const>::type;
for (auto it = boost::begin(pieces); it != boost::end(pieces); ++it)
{
const piece_type& piece = *it;
bg::segment_identifier seg_id = piece.first_seg_id;
if (seg_id.segment_index < 0)
{
continue;
}
ring_type const& ring = offsetted_rings[seg_id.multi_index];
#if 0 // Does not compile (SVG is not enabled by default)
if (m_zoom && bg::disjoint(corner, m_alternate_box))
{
continue;
}
#endif
// NOTE: ring is returned by copy here
auto const corner = piece.m_piece_border.get_full_ring();
if (m_zoom && do_pieces)
{
try
{
std::string style = "opacity:0.3;stroke:rgb(0,0,0);stroke-width:1;";
bg::model::multi_polygon
<
bg::model::polygon<typename bg::point_type<Box>::type>
> clipped;
bg::intersection(ring, m_alternate_box, clipped);
m_mapper.map(clipped,
piece.type == bg::strategy::buffer::buffered_segment
? style + "fill:rgb(255,128,0);"
: style + "fill:rgb(255,0,0);");
}
catch (...)
{
std::cerr << "Error for piece " << piece.index << std::endl;
}
}
else if (do_pieces && ! corner.empty())
{
std::string style = "opacity:0.3;stroke:rgb(0,0,0);stroke-width:1;";
m_mapper.map(corner,
piece.type == bg::strategy::buffer::buffered_segment
? style + "fill:rgb(255,128,0);"
: style + "fill:rgb(255,0,0);");
}
if (do_indices)
{
// Label starting piece_index / segment_index
std::ostringstream out;
out << piece.index
<< (piece.is_flat_start ? " FS" : "")
<< (piece.is_flat_end ? " FE" : "")
<< " (" << piece_type_char(piece.type) << ") "
<< piece.first_seg_id.segment_index
<< ".." << piece.beyond_last_segment_index - 1
;
m_mapper.text(get_labelpoint(corner, piece), out.str(),
"fill:rgb(255,0,0);font-family='Arial';font-size:10px;", 5, 5);
}
}
}
template <typename TraversedRings>
inline void map_traversed_rings(TraversedRings const& traversed_rings)
{
for (auto it = boost::begin(traversed_rings); it != boost::end(traversed_rings); ++it)
{
m_mapper.map(*it, "opacity:0.4;fill:none;stroke:rgb(0,255,0);stroke-width:2");
}
}
template <typename OffsettedRings>
inline void map_offsetted_rings(OffsettedRings const& offsetted_rings)
{
for (auto it = boost::begin(offsetted_rings); it != boost::end(offsetted_rings); ++it)
{
if (it->discarded())
{
m_mapper.map(*it, "opacity:0.4;fill:none;stroke:rgb(255,0,0);stroke-width:2");
}
else
{
m_mapper.map(*it, "opacity:0.4;fill:none;stroke:rgb(0,0,255);stroke-width:2");
}
}
}
SvgMapper& m_mapper;
Box m_alternate_box;
bool m_zoom;
};
template <typename Point>
class buffer_svg_mapper
{
public :
buffer_svg_mapper(std::string const& casename)
: m_casename(casename)
{
bg::assign_inverse(m_alternate_box);
}
template <typename Mapper, typename Visitor, typename Envelope, typename DistanceType>
void prepare(Mapper& mapper, Visitor& visitor, Envelope const& envelope,
const DistanceType& box_buffer_distance)
{
#ifdef BOOST_GEOMETRY_BUFFER_TEST_SVG_USE_ALTERNATE_BOX
// Create a zoomed-in view
bg::model::box<Point> alternate_box;
bg::read_wkt(BOOST_GEOMETRY_BUFFER_TEST_SVG_ALTERNATE_BOX, alternate_box);
mapper.add(alternate_box);
// Take care non-visible elements are skipped
visitor.set_alternate_box(alternate_box);
set_alternate_box(alternate_box);
#else
bg::model::box<Point> box = envelope;
bg::buffer(box, box, box_buffer_distance);
mapper.add(box);
#endif
boost::ignore_unused(visitor);
}
void set_alternate_box(bg::model::box<Point> const& box)
{
m_alternate_box = box;
m_zoom = true;
}
template <typename Mapper, typename Geometry, typename GeometryBuffer>
void map_input_output(Mapper& mapper, Geometry const& geometry,
GeometryBuffer const& buffered, bool negative)
{
bool const areal = bg::util::is_areal<Geometry>::value;
if (m_zoom)
{
map_io_zoomed(mapper, geometry, buffered, negative, areal);
}
else
{
map_io(mapper, geometry, buffered, negative, areal);
}
}
template <typename Mapper, typename Geometry, typename Strategy, typename RescalePolicy>
void map_self_ips(Mapper& mapper, Geometry const& geometry, Strategy const& strategy, RescalePolicy const& rescale_policy)
{
using turn_info = bg::detail::overlay::turn_info
<
Point,
typename bg::detail::segment_ratio_type<Point, RescalePolicy>::type
>;
std::vector<turn_info> turns;
bg::detail::self_get_turn_points::no_interrupt_policy policy;
bg::self_turns
<
bg::detail::overlay::assign_null_policy
>(geometry, strategy, rescale_policy, turns, policy);
for (turn_info const& turn : turns)
{
mapper.map(turn.point, "fill:rgb(255,128,0);stroke:rgb(0,0,100);stroke-width:1", 3);
}
}
private :
template <typename Mapper, typename Geometry, typename GeometryBuffer>
void map_io(Mapper& mapper, Geometry const& geometry,
GeometryBuffer const& buffered, bool negative, bool areal)
{
// Map input geometry in green
if (areal)
{
mapper.map(geometry, "opacity:0.5;fill:rgb(0,128,0);stroke:rgb(0,64,0);stroke-width:2");
}
else
{
// TODO: clip input points/linestring
mapper.map(geometry, "opacity:0.5;stroke:rgb(0,128,0);stroke-width:10");
}
{
// Map buffer in yellow (inflate) and with orange-dots (deflate)
std::string style = negative
? "opacity:0.4;fill:rgb(255,255,192);stroke:rgb(255,128,0);stroke-width:3"
: "opacity:0.4;fill:rgb(255,255,128);stroke:rgb(0,0,0);stroke-width:3";
mapper.map(buffered, style);
}
}
template <typename Mapper, typename Geometry, typename GeometryBuffer>
void map_io_zoomed(Mapper& mapper, Geometry const& geometry,
GeometryBuffer const& buffered, bool negative, bool areal)
{
// Map input geometry in green
if (areal)
{
// Assuming input is areal
GeometryBuffer clipped;
// TODO: the next line does NOT compile for multi-point, TODO: implement that line
// bg::intersection(geometry, m_alternate_box, clipped);
mapper.map(clipped, "opacity:0.5;fill:rgb(0,128,0);stroke:rgb(0,64,0);stroke-width:2");
}
else
{
// TODO: clip input (multi)point/linestring
mapper.map(geometry, "opacity:0.5;stroke:rgb(0,128,0);stroke-width:10");
}
{
// Map buffer in yellow (inflate) and with orange-dots (deflate)
std::string style = negative
? "opacity:0.4;fill:rgb(255,255,192);stroke:rgb(255,128,0);stroke-width:3"
: "opacity:0.4;fill:rgb(255,255,128);stroke:rgb(0,0,0);stroke-width:3";
try
{
// Clip output multi-polygon with box
GeometryBuffer clipped;
bg::intersection(buffered, m_alternate_box, clipped);
mapper.map(clipped, style);
}
catch (...)
{
std::cout << "Error for buffered output " << m_casename << std::endl;
}
}
}
bool m_zoom{false};
bg::model::box<Point> m_alternate_box;
std::string m_casename;
};
#endif
| 32.921053
| 126
| 0.562811
|
onlykzy
|
dccd3305767f42e9f303f34f8eaa85baf1f5f45f
| 670
|
cpp
|
C++
|
engine/Engine.UI/src/ui/control/ControlParent.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | 66
|
2018-12-16T21:03:36.000Z
|
2022-03-26T12:23:57.000Z
|
engine/Engine.UI/src/ui/control/ControlParent.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | 57
|
2018-04-24T20:53:01.000Z
|
2021-02-21T12:14:20.000Z
|
engine/Engine.UI/src/ui/control/ControlParent.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | 7
|
2019-07-16T08:25:25.000Z
|
2022-03-21T08:29:46.000Z
|
#include "ghuipch.h"
#include "ControlParent.h"
#include "core/reflection/Property.h"
namespace Ghurund::UI {
const Ghurund::Core::Type& ControlParent::GET_TYPE() {
using namespace Ghurund::Core;
static auto PROPERTY_FOCUS = Property<ControlParent, Control*>("Focus", &getFocus, &setFocus);
static const auto CONSTRUCTOR = Constructor<ControlParent>();
static const Ghurund::Core::Type TYPE = TypeBuilder<ControlParent>(Ghurund::UI::NAMESPACE_NAME, "ControlParent")
.withProperty(PROPERTY_FOCUS)
.withConstructor(CONSTRUCTOR)
.withSupertype(__super::GET_TYPE());
return TYPE;
}
}
| 30.454545
| 120
| 0.676119
|
Kartikeyapan598
|
dcce5854944c4dd15df9063e1b3311d673c7145b
| 28,937
|
cpp
|
C++
|
src/openms/source/ANALYSIS/ID/PILISModelGenerator.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
src/openms/source/ANALYSIS/ID/PILISModelGenerator.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
src/openms/source/ANALYSIS/ID/PILISModelGenerator.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/ID/PILISModelGenerator.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/ANALYSIS/ID/PILISCrossValidation.h>
#include <OpenMS/ANALYSIS/ID/HiddenMarkovModel.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
using namespace std;
namespace OpenMS
{
PILISModelGenerator::PILISModelGenerator() :
DefaultParamHandler("PILISModelGenerator")
{
defaults_.setValue("model_depth", 4, "The number of explicitly modeled backbone cleavages from N-terminus and C-terminus, would be 9 for the default value");
defaults_.setValue("visible_model_depth", 30, "The maximal possible size of a peptide to be modeled");
defaults_.setValue("variable_modifications", ListUtils::create<String>("Oxidation (M),Carbamidomethyl (C)"), "Modifications which should be included in the model, represented by PSI-MOD accessions.");
defaults_.setValue("fixed_modifications", ListUtils::create<String>(""), "Modifications which should replace the unmodified amino acid, represented by PSI-MOD accessions.");
defaultsToParam_();
}
PILISModelGenerator::PILISModelGenerator(const PILISModelGenerator& rhs) :
DefaultParamHandler(rhs)
{
}
PILISModelGenerator& PILISModelGenerator::operator=(const PILISModelGenerator& rhs)
{
if (this != &rhs)
{
DefaultParamHandler::operator=(rhs);
}
return *this;
}
PILISModelGenerator::~PILISModelGenerator()
{
}
void PILISModelGenerator::getModel(HiddenMarkovModel& model)
{
UInt visible_model_depth = (UInt)param_.getValue("visible_model_depth");
UInt model_depth = (UInt)param_.getValue("model_depth");
model.addNewState(new HMMState("endcenter", false));
model.addNewState(new HMMState("end", false));
model.addNewState("BBcenter");
model.addNewState("AAcenter");
model.addNewState("CRcenter");
model.addNewState("Acenter");
model.addNewState("SCcenter");
model.addNewState("ASCcenter");
model.addNewState(new HMMState("axyz_center-prefix-ions", false));
model.addNewState(new HMMState("axyz_center-suffix-ions", false));
model.addNewState(new HMMState("axyz_center-prefix"));
model.addNewState(new HMMState("axyz_center-suffix"));
model.addNewState(new HMMState("bxyz_center-prefix-ions", false));
model.addNewState(new HMMState("bxyz_center-suffix-ions", false));
model.addNewState(new HMMState("bxyz_center-prefix"));
model.addNewState(new HMMState("bxyz_center-suffix"));
model.addNewState(new HMMState("D_center-prefix-ions", false));
model.addNewState(new HMMState("D_center-suffix-ions", false));
model.addNewState(new HMMState("D_center-prefix"));
model.addNewState(new HMMState("D_center-suffix"));
model.addNewState(new HMMState("E_center-prefix-ions", false));
model.addNewState(new HMMState("E_center-suffix-ions", false));
model.addNewState(new HMMState("E_center-prefix"));
model.addNewState(new HMMState("E_center-suffix"));
model.addNewState(new HMMState("K_center-prefix-ions", false));
model.addNewState(new HMMState("K_center-suffix-ions", false));
model.addNewState(new HMMState("K_center-prefix"));
model.addNewState(new HMMState("K_center-suffix"));
model.addNewState(new HMMState("R_center-prefix-ions", false));
model.addNewState(new HMMState("R_center-suffix-ions", false));
model.addNewState(new HMMState("R_center-prefix"));
model.addNewState(new HMMState("R_center-suffix"));
model.addNewState(new HMMState("H_center-prefix-ions", false));
model.addNewState(new HMMState("H_center-suffix-ions", false));
model.addNewState(new HMMState("H_center-prefix"));
model.addNewState(new HMMState("H_center-suffix"));
model.addNewState("bxyz");
model.addNewState("axyz");
model.addNewState("D");
model.addNewState("E");
model.addNewState("AABase1");
model.addNewState("AABase2");
model.addNewState("K");
model.addNewState("H");
model.addNewState("R");
//
set<const Residue*> residues(ResidueDB::getInstance()->getResidues("Natural20"));
StringList variable_modifications = param_.getValue("variable_modifications");
for (StringList::const_iterator it = variable_modifications.begin(); it != variable_modifications.end(); ++it)
{
residues.insert(ResidueDB::getInstance()->getModifiedResidue(*it));
}
cerr << "Using " << residues.size() << " residues" << endl;
//const String residues("ACDEFGHIKLMNPQRSTVWY");
// create the residue states states
for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it)
{
AASequence first_aa;
first_aa += *it;
String first(first_aa.toString());
model.addNewState(first + "_D");
model.addNewState(first + "_E");
model.addNewState(first + "_K");
model.addNewState(first + "_H");
model.addNewState(first + "_R");
for (set<const Residue*>::const_iterator jt = residues.begin(); jt != residues.end(); ++jt)
{
AASequence second_aa;
second_aa += *jt;
String second(second_aa.toString());
model.addNewState(first + second + "_bxyz");
model.addNewState(first + second + "_axyz");
}
model.addNewState(first + "_bk-1");
model.addNewState(first + "_bk-2");
}
model.addNewState("bk-1");
model.addNewState("bk-2");
model.addNewState(new HMMState("bk-1_-ions", false));
model.addNewState(new HMMState("bk-2_-ions", false));
model.addNewState(new HMMState("bk-1_-prefix-ions", false));
model.addNewState(new HMMState("bk-1_-suffix-ions", false));
model.addNewState(new HMMState("bk-1_-prefix"));
model.addNewState(new HMMState("bk-1_-suffix"));
model.addNewState(new HMMState("bk-2_-prefix-ions", false));
model.addNewState(new HMMState("bk-2_-suffix-ions", false));
model.addNewState(new HMMState("bk-2_-prefix"));
model.addNewState(new HMMState("bk-2_-suffix"));
for (Size i = 1; i <= visible_model_depth; ++i)
{
// these states are really created
// charge states
String num(i);
model.addNewState("BB" + num);
model.addNewState("BBk-" + num);
model.addNewState("CR" + num);
model.addNewState("CRk-" + num);
model.addNewState("SC" + num);
model.addNewState("SCk-" + num);
// states for trans mapping
model.addNewState("AA" + num);
model.addNewState("AAk-" + num);
model.addNewState("A" + num);
model.addNewState("Ak-" + num);
model.addNewState("ASC" + num);
model.addNewState("ASCk-" + num);
// emitting ion states
model.addNewState(new HMMState("axyz_" + num + "-prefix-ions", false));
model.addNewState(new HMMState("axyz_" + num + "-suffix-ions", false));
model.addNewState(new HMMState("axyz_" + num + "-prefix"));
model.addNewState(new HMMState("axyz_" + num + "-suffix"));
model.addNewState(new HMMState("axyz_k-" + num + "-prefix-ions", false));
model.addNewState(new HMMState("axyz_k-" + num + "-suffix-ions", false));
model.addNewState(new HMMState("axyz_k-" + num + "-prefix"));
model.addNewState(new HMMState("axyz_k-" + num + "-suffix"));
model.addNewState(new HMMState("bxyz_" + num + "-prefix-ions", false));
model.addNewState(new HMMState("bxyz_" + num + "-suffix-ions", false));
model.addNewState(new HMMState("bxyz_" + num + "-prefix"));
model.addNewState(new HMMState("bxyz_" + num + "-suffix"));
model.addNewState(new HMMState("bxyz_k-" + num + "-prefix-ions", false));
model.addNewState(new HMMState("bxyz_k-" + num + "-suffix-ions", false));
model.addNewState(new HMMState("bxyz_k-" + num + "-prefix"));
model.addNewState(new HMMState("bxyz_k-" + num + "-suffix"));
String sc_and_cr("DEHKR");
for (String::ConstIterator it = sc_and_cr.begin(); it != sc_and_cr.end(); ++it)
{
String aa(*it);
model.addNewState(new HMMState(aa + "_" + num + "-prefix-ions", false));
model.addNewState(new HMMState(aa + "_" + num + "-suffix-ions", false));
model.addNewState(new HMMState(aa + "_" + num + "-prefix"));
model.addNewState(new HMMState(aa + "_" + num + "-suffix"));
model.addNewState(new HMMState(aa + "_k-" + num + "-prefix-ions", false));
model.addNewState(new HMMState(aa + "_k-" + num + "-suffix-ions", false));
model.addNewState(new HMMState(aa + "_k-" + num + "-prefix"));
model.addNewState(new HMMState(aa + "_k-" + num + "-suffix"));
}
model.addNewState(new HMMState("end" + num, false));
model.addNewState(new HMMState("endk-" + num, false));
// post AA collector states
model.addNewState("bxyz" + num);
model.addNewState("bxyzk-" + num);
model.addNewState("axyz" + num);
model.addNewState("axyzk-" + num);
model.addNewState("D" + num);
model.addNewState("Dk-" + num);
model.addNewState("E" + num);
model.addNewState("Ek-" + num);
model.addNewState("K" + num);
model.addNewState("Kk-" + num);
model.addNewState("H" + num);
model.addNewState("Hk-" + num);
model.addNewState("R" + num);
model.addNewState("Rk-" + num);
// map the residue states
for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it)
{
AASequence first_aa;
first_aa += *it;
String first(first_aa.toString());
model.addNewState(first + "_D" + num);
model.addNewState(first + "_Dk-" + num);
model.addNewState(first + "_E" + num);
model.addNewState(first + "_Ek-" + num);
model.addNewState(first + "_K" + num);
model.addNewState(first + "_Kk-" + num);
model.addNewState(first + "_H" + num);
model.addNewState(first + "_Hk-" + num);
model.addNewState(first + "_R" + num);
model.addNewState(first + "_Rk-" + num);
for (set<const Residue*>::const_iterator jt = residues.begin(); jt != residues.end(); ++jt)
{
AASequence second_aa;
second_aa += *jt;
String second(second_aa.toString());
model.addNewState(first + second + "_bxyz" + num);
model.addNewState(first + second + "_bxyzk-" + num);
model.addNewState(first + second + "_axyz" + num);
model.addNewState(first + second + "_axyzk-" + num);
}
}
}
model.setTransitionProbability("AABase1", "AABase2", 1);
// CR bk-1, bk-2
for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it)
{
AASequence first_aa;
first_aa += *it;
String first(first_aa.toString());
model.addSynonymTransition("AABase1", "AABase2", "Ak-1", first + "_bk-1");
model.setTransitionProbability(first + "_bk-1", "bk-1", 0.5);
model.setTransitionProbability(first + "_bk-1", "endk-1", 0.5);
model.addSynonymTransition("AABase1", "AABase2", "Ak-2", first + "_bk-2");
model.setTransitionProbability(first + "_bk-2", "bk-2", 0.5);
model.setTransitionProbability(first + "_bk-2", "endk-2", 0.5);
}
model.setTransitionProbability("bk-1_-prefix", "bk-1_-prefix-ions", 0.9);
model.setTransitionProbability("bk-1_-prefix", "endk-1", 0.1);
model.setTransitionProbability("bk-1_-suffix", "bk-1_-suffix-ions", 0.9);
model.setTransitionProbability("bk-1_-suffix", "endk-1", 0.1);
model.setTransitionProbability("bk-2_-prefix", "bk-2_-prefix-ions", 0.9);
model.setTransitionProbability("bk-2_-prefix", "endk-1", 0.1);
model.setTransitionProbability("bk-2_-suffix", "bk-2_-suffix-ions", 0.9);
model.setTransitionProbability("bk-2_-suffix", "endk-1", 0.1);
// set the initial transitions
for (Size i = 1; i <= visible_model_depth; ++i)
{
String num(i);
if (i <= model_depth)
{
model.setTransitionProbability("axyz_" + num + "-prefix", "axyz_" + num + "-prefix-ions", 0.9);
model.setTransitionProbability("axyz_" + num + "-prefix", "end" + num, 0.1);
model.setTransitionProbability("axyz_" + num + "-suffix", "axyz_" + num + "-suffix-ions", 0.9);
model.setTransitionProbability("axyz_" + num + "-suffix", "end" + num, 0.1);
model.setTransitionProbability("axyz_k-" + num + "-prefix", "axyz_k-" + num + "-prefix-ions", 0.9);
model.setTransitionProbability("axyz_k-" + num + "-prefix", "endk-" + num, 0.1);
model.setTransitionProbability("axyz_k-" + num + "-suffix", "axyz_k-" + num + "-suffix-ions", 0.9);
model.setTransitionProbability("axyz_k-" + num + "-suffix", "endk-" + num, 0.1);
model.setTransitionProbability("bxyz_" + num + "-prefix", "bxyz_" + num + "-prefix-ions", 0.9);
model.setTransitionProbability("bxyz_" + num + "-prefix", "end" + num, 0.1);
model.setTransitionProbability("bxyz_" + num + "-suffix", "bxyz_" + num + "-suffix-ions", 0.9);
model.setTransitionProbability("bxyz_" + num + "-suffix", "end" + num, 0.1);
model.setTransitionProbability("bxyz_k-" + num + "-prefix", "bxyz_k-" + num + "-prefix-ions", 0.9);
model.setTransitionProbability("bxyz_k-" + num + "-prefix", "endk-" + num, 0.1);
model.setTransitionProbability("bxyz_k-" + num + "-suffix", "bxyz_k-" + num + "-suffix-ions", 0.9);
model.setTransitionProbability("bxyz_k-" + num + "-suffix", "endk-" + num, 0.1);
String sc_and_cr("DEHRK");
for (String::ConstIterator it = sc_and_cr.begin(); it != sc_and_cr.end(); ++it)
{
String aa(*it);
model.setTransitionProbability(aa + "_" + num + "-prefix", aa + "_" + num + "-prefix-ions", 0.9);
model.setTransitionProbability(aa + "_" + num + "-prefix", "end" + num, 0.1);
model.setTransitionProbability(aa + "_" + num + "-suffix", aa + "_" + num + "-suffix-ions", 0.9);
model.setTransitionProbability(aa + "_" + num + "-suffix", "end" + num, 0.1);
model.setTransitionProbability(aa + "_k-" + num + "-prefix", aa + "_k-" + num + "-prefix-ions", 0.9);
model.setTransitionProbability(aa + "_k-" + num + "-prefix", "endk-" + num, 0.1);
model.setTransitionProbability(aa + "_k-" + num + "-suffix", aa + "_k-" + num + "-suffix-ions", 0.9);
model.setTransitionProbability(aa + "_k-" + num + "-suffix", "endk-" + num, 0.1);
}
model.setTransitionProbability("BB" + num, "end" + num, 0.5);
model.setTransitionProbability("BBk-" + num, "endk-" + num, 0.5);
model.setTransitionProbability("SC" + num, "end" + num, 0.5);
model.setTransitionProbability("SCk-" + num, "endk-" + num, 0.5);
model.setTransitionProbability("CR" + num, "end" + num, 0.5);
model.setTransitionProbability("CRk-" + num, "endk-" + num, 0.5);
model.setTransitionProbability("BB" + num, "AA" + num, 0.5);
model.setTransitionProbability("BBk-" + num, "AAk-" + num, 0.5);
model.setTransitionProbability("CR" + num, "A" + num, 0.5);
model.setTransitionProbability("CRk-" + num, "Ak-" + num, 0.5);
model.setTransitionProbability("SC" + num, "ASC" + num, 0.5);
model.setTransitionProbability("SCk-" + num, "ASCk-" + num, 0.5);
}
else
{
model.addSynonymTransition("axyz_center-prefix", "axyz_center-prefix-ions", "axyz_" + num + "-prefix", "axyz_" + num + "-prefix-ions");
model.addSynonymTransition("axyz_center-prefix", "endcenter", "axyz_" + num + "-prefix", "end" + num);
model.addSynonymTransition("axyz_center-suffix", "axyz_center-suffix-ions", "axyz_" + num + "-suffix", "axyz_" + num + "-suffix-ions");
model.addSynonymTransition("axyz_center-suffix", "endcenter", "axyz_" + num + "-suffix", "end" + num);
model.addSynonymTransition("axyz_center-prefix", "axyz_center-prefix-ions", "axyz_k-" + num + "-prefix", "axyz_k-" + num + "-prefix-ions");
model.addSynonymTransition("axyz_center-prefix", "endcenter", "axyz_k-" + num + "-prefix", "endk-" + num);
model.addSynonymTransition("axyz_center-suffix", "axyz_center-suffix-ions", "axyz_k-" + num + "-suffix", "axyz_k-" + num + "-suffix-ions");
model.addSynonymTransition("axyz_center-suffix", "endcenter", "axyz_k-" + num + "-suffix", "endk-" + num);
model.addSynonymTransition("bxyz_center-prefix", "bxyz_center-prefix-ions", "bxyz_" + num + "-prefix", "bxyz_" + num + "-prefix-ions");
model.addSynonymTransition("bxyz_center-prefix", "endcenter", "bxyz_" + num + "-prefix", "end" + num);
model.addSynonymTransition("bxyz_center-suffix", "bxyz_center-suffix-ions", "bxyz_" + num + "-suffix", "bxyz_" + num + "-suffix-ions");
model.addSynonymTransition("bxyz_center-suffix", "endcenter", "bxyz_" + num + "-suffix", "end" + num);
model.addSynonymTransition("bxyz_center-prefix", "bxyz_center-prefix-ions", "bxyz_k-" + num + "-prefix", "bxyz_k-" + num + "-prefix-ions");
model.addSynonymTransition("bxyz_center-prefix", "endcenter", "bxyz_k-" + num + "-prefix", "endk-" + num);
model.addSynonymTransition("bxyz_center-suffix", "bxyz_center-suffix-ions", "bxyz_k-" + num + "-suffix", "bxyz_k-" + num + "-suffix-ions");
model.addSynonymTransition("bxyz_center-suffix", "endcenter", "bxyz_k-" + num + "-suffix", "endk-" + num);
String sc_and_cr("DEHRK");
for (String::ConstIterator it = sc_and_cr.begin(); it != sc_and_cr.end(); ++it)
{
String aa(*it);
model.addSynonymTransition(aa + "_center-prefix", aa + "_center-prefix-ions", aa + "_" + num + "-prefix", aa + "_" + num + "-prefix-ions");
model.addSynonymTransition(aa + "_center-prefix", "endcenter", aa + "_" + num + "-prefix", "end" + num);
model.addSynonymTransition(aa + "_center-prefix", aa + "_center-prefix-ions", aa + "_k-" + num + "-prefix", aa + "_k-" + num + "-prefix-ions");
model.addSynonymTransition(aa + "_center-prefix", "endcenter", aa + "_k-" + num + "-prefix", "endk-" + num);
model.addSynonymTransition(aa + "_center-suffix", aa + "_center-suffix-ions", aa + "_" + num + "-suffix", aa + "_" + num + "-suffix-ions");
model.addSynonymTransition(aa + "_center-suffix", "endcenter", aa + "_" + num + "-suffix", "end" + num);
model.addSynonymTransition(aa + "_center-suffix", aa + "_center-suffix-ions", aa + "_k-" + num + "-suffix", aa + "_k-" + num + "-suffix-ions");
model.addSynonymTransition(aa + "_center-suffix", "endcenter", aa + "_k-" + num + "-suffix", "endk-" + num);
}
model.addSynonymTransition("BBcenter", "endcenter", "BB" + num, "end" + num);
model.addSynonymTransition("BBcenter", "endcenter", "BBk-" + num, "endk-" + num);
model.setTransitionProbability("BBcenter", "endcenter", 0.5);
model.addSynonymTransition("CRcenter", "endcenter", "CR" + num, "end" + num);
model.addSynonymTransition("CRcenter", "endcenter", "CRk-" + num, "endk-" + num);
model.setTransitionProbability("CRcenter", "endcenter", 0.5);
model.addSynonymTransition("SCcenter", "endcenter", "SC" + num, "end" + num);
model.addSynonymTransition("SCcenter", "endcenter", "SCk-" + num, "endk-" + num);
model.setTransitionProbability("SCcenter", "endcenter", 0.5);
model.addSynonymTransition("BBcenter", "AAcenter", "BB" + num, "AA" + num);
model.addSynonymTransition("BBcenter", "AAcenter", "BBk-" + num, "AAk-" + num);
model.setTransitionProbability("BBcenter", "AAcenter", 0.5);
model.addSynonymTransition("CRcenter", "Acenter", "CR" + num, "A" + num);
model.addSynonymTransition("CRcenter", "Acenter", "CRk-" + num, "Ak-" + num);
model.setTransitionProbability("CRcenter", "Acenter", 0.5);
model.addSynonymTransition("SCcenter", "ASCcenter", "SC" + num, "ASC" + num);
model.addSynonymTransition("SCcenter", "ASCcenter", "SCk-" + num, "ASCk-" + num);
model.setTransitionProbability("SCcenter", "ASCcenter", 0.5);
}
for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it)
{
AASequence first_aa;
first_aa += *it;
String first(first_aa.toString());
// CR D
model.addSynonymTransition("AABase1", "AABase2", "A" + num, first + "_D" + num);
model.addSynonymTransition("AABase1", "AABase2", "Ak-" + num, first + "_Dk-" + num);
model.addSynonymTransition(first + "_D", "D", first + "_D" + num, "D" + num);
model.addSynonymTransition(first + "_D", "end", first + "_D" + num, "end" + num);
model.addSynonymTransition(first + "_D", "D", first + "_Dk-" + num, "Dk-" + num);
model.addSynonymTransition(first + "_D", "end", first + "_Dk-" + num, "endk-" + num);
model.setTransitionProbability(first + "_D", "D", 0.5);
model.setTransitionProbability(first + "_D", "end", 0.5);
// CR E
model.addSynonymTransition("AABase1", "AABase2", "A" + num, first + "_E" + num);
model.addSynonymTransition("AABase1", "AABase2", "Ak-" + num, first + "_Ek-" + num);
model.addSynonymTransition(first + "_E", "E", first + "_E" + num, "E" + num);
model.addSynonymTransition(first + "_E", "end", first + "_E" + num, "end" + num);
model.addSynonymTransition(first + "_E", "E", first + "_Ek-" + num, "Ek-" + num);
model.addSynonymTransition(first + "_E", "end", first + "_Ek-" + num, "endk-" + num);
model.setTransitionProbability(first + "_E", "E", 0.5);
model.setTransitionProbability(first + "_E", "end", 0.5);
// SC K
model.addSynonymTransition("AABase1", "AABase2", "ASC" + num, first + "_K" + num);
model.addSynonymTransition("AABase1", "AABase2", "ASCk-" + num, first + "_Kk-" + num);
model.addSynonymTransition(first + "_K", "K", first + "_K" + num, "K" + num);
model.addSynonymTransition(first + "_K", "end", first + "_K" + num, "end" + num);
model.addSynonymTransition(first + "_K", "K", first + "_Kk-" + num, "Kk-" + num);
model.addSynonymTransition(first + "_K", "end", first + "_Kk-" + num, "endk-" + num);
model.setTransitionProbability(first + "_K", "K", 0.5);
model.setTransitionProbability(first + "_K", "end", 0.5);
// SC H
model.addSynonymTransition("AABase1", "AABase2", "ASC" + num, first + "_H" + num);
model.addSynonymTransition("AABase1", "AABase2", "ASCk-" + num, first + "_Hk-" + num);
model.addSynonymTransition(first + "_H", "H", first + "_H" + num, "H" + num);
model.addSynonymTransition(first + "_H", "end", first + "_H" + num, "end" + num);
model.addSynonymTransition(first + "_H", "H", first + "_Hk-" + num, "Hk-" + num);
model.addSynonymTransition(first + "_H", "end", first + "_Hk-" + num, "endk-" + num);
model.setTransitionProbability(first + "_H", "H", 0.5);
model.setTransitionProbability(first + "_H", "end", 0.5);
// SC R
model.addSynonymTransition("AABase1", "AABase2", "ASC" + num, first + "_R" + num);
model.addSynonymTransition("AABase1", "AABase2", "ASCk-" + num, first + "_Rk-" + num);
model.addSynonymTransition(first + "_R", "R", first + "_R" + num, "R" + num);
model.addSynonymTransition(first + "_R", "end", first + "_R" + num, "end" + num);
model.addSynonymTransition(first + "_R", "R", first + "_Rk-" + num, "Rk-" + num);
model.addSynonymTransition(first + "_R", "end", first + "_Rk-" + num, "endk-" + num);
model.setTransitionProbability(first + "_R", "R", 0.5);
model.setTransitionProbability(first + "_R", "end", 0.5);
for (set<const Residue*>::const_iterator jt = residues.begin(); jt != residues.end(); ++jt)
{
AASequence second_aa;
second_aa += *jt;
String second(second_aa.toString());
model.addSynonymTransition("AABase1", "AABase2", "AA" + num, first + second + "_bxyz" + num);
model.addSynonymTransition("AABase1", "AABase2", "AAk-" + num, first + second + "_bxyzk-" + num);
model.addSynonymTransition("AABase1", "AABase2", "AA" + num, first + second + "_axyz" + num);
model.addSynonymTransition("AABase1", "AABase2", "AAk-" + num, first + second + "_axyzk-" + num);
if (i <= 2)
{
model.setTransitionProbability(first + second + "_bxyz" + num, "bxyz" + num, 0.5);
model.addSynonymTransition(first + second + "_bxyz" + num, "end", first + second + "_bxyz" + num, "end" + num);
model.setTransitionProbability(first + second + "_bxyz" + num, "end", 0.5);
model.setTransitionProbability(first + second + "_axyz" + num, "axyz" + num, 0.5);
model.addSynonymTransition(first + second + "_axyz" + num, "end", first + second + "_axyz" + num, "end" + num);
model.setTransitionProbability(first + second + "_axyz" + num, "end", 0.5);
}
else
{
model.addSynonymTransition(first + second + "_bxyz", "bxyz", first + second + "_bxyz" + num, "bxyz" + num);
model.addSynonymTransition(first + second + "_bxyz", "end", first + second + "_bxyz" + num, "end" + num);
model.addSynonymTransition(first + second + "_axyz", "axyz", first + second + "_axyz" + num, "axyz" + num);
model.addSynonymTransition(first + second + "_axyz", "end", first + second + "_axyz" + num, "end" + num);
}
model.addSynonymTransition(first + second + "_bxyz", "bxyz", first + second + "_bxyzk-" + num, "bxyzk-" + num);
model.addSynonymTransition(first + second + "_bxyz", "end", first + second + "_bxyzk-" + num, "endk-" + num);
model.setTransitionProbability(first + second + "_bxyz", "bxyz", 0.5);
model.setTransitionProbability(first + second + "_bxyz", "end", 0.5);
model.addSynonymTransition(first + second + "_bxyz", "end", first + second + "_bxyzk-" + num, "end" + num);
model.addSynonymTransition(first + second + "_axyz", "axyz", first + second + "_axyzk-" + num, "axyzk-" + num);
model.addSynonymTransition(first + second + "_axyz", "end", first + second + "_axyzk-" + num, "endk-" + num);
model.setTransitionProbability(first + second + "_axyz", "axyz", 0.5);
model.setTransitionProbability(first + second + "_axyz", "end", 0.5);
model.addSynonymTransition(first + second + "_axyz", "end", first + second + "_axyzk-" + num, "end" + num);
}
}
}
model.disableTransitions();
}
} // namespace OpenMS
| 50.766667
| 204
| 0.615544
|
mrurik
|
dcd08add3e77bcc5eef000d7274663a04977ea69
| 10,913
|
cpp
|
C++
|
src/tests/class_tests/openms/source/ConsensusID_test.cpp
|
aiche/OpenMS
|
5d212db863ff1ef48b3a70fe4d556ef179ae4f49
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
src/tests/class_tests/openms/source/ConsensusID_test.cpp
|
aiche/OpenMS
|
5d212db863ff1ef48b3a70fe4d556ef179ae4f49
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
src/tests/class_tests/openms/source/ConsensusID_test.cpp
|
aiche/OpenMS
|
5d212db863ff1ef48b3a70fe4d556ef179ae4f49
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Sven Nahnsen $
// $Authors: Marc Sturm, Andreas Bertsch, Sven Nahnsen $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/ConsensusID.h>
#include <OpenMS/KERNEL/Feature.h>
using namespace OpenMS;
using namespace std;
///////////////////////////
START_TEST(ResidueDB, "$Id$")
/////////////////////////////////////////////////////////////
ConsensusID* ptr = 0;
ConsensusID* nullPointer = 0;
START_SECTION(ConsensusID())
ptr = new ConsensusID();
TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION
START_SECTION(~ConsensusID())
delete(ptr);
END_SECTION
// PeptideIdentification with 3 id runs is created
vector<PeptideIdentification> ids(3);
vector<PeptideHit> hits;
cout<<"HELLO"<<endl;
// the first ID has 5 hits
hits.resize(5);
hits[0].setRank(1);
hits[0].setSequence(AASequence::fromString("A"));
hits[0].setScore(31);
hits[1].setRank(2);
hits[1].setSequence(AASequence::fromString("B"));
hits[1].setScore(28);
hits[2].setRank(3);
hits[2].setSequence(AASequence::fromString("C"));
hits[2].setScore(17);
hits[3].setRank(4);
hits[3].setSequence(AASequence::fromString("D"));
hits[3].setScore(7);
hits[4].setRank(5);
hits[4].setSequence(AASequence::fromString("E"));
hits[4].setScore(3);
ids[0].setHits(hits);
// the second ID has 3 hits
hits.resize(3);
hits[0].setRank(1);
hits[0].setSequence(AASequence::fromString("C"));
hits[0].setScore(32);
hits[1].setRank(2);
hits[1].setSequence(AASequence::fromString("A"));
hits[1].setScore(30);
hits[2].setRank(3);
hits[2].setSequence(AASequence::fromString("B"));
hits[2].setScore(29);
ids[1].setHits(hits);
// the third ID has 10 hits
hits.resize(10);
hits[0].setRank(1);
hits[0].setSequence(AASequence::fromString("F"));
hits[0].setScore(81);
hits[1].setRank(2);
hits[1].setSequence(AASequence::fromString("C"));
hits[1].setScore(60);
hits[2].setRank(3);
hits[2].setSequence(AASequence::fromString("G"));
hits[2].setScore(50);
hits[3].setRank(4);
hits[3].setSequence(AASequence::fromString("D"));
hits[3].setScore(40);
hits[4].setRank(5);
hits[4].setSequence(AASequence::fromString("B"));
hits[4].setScore(25);
hits[5].setRank(6);
hits[5].setSequence(AASequence::fromString("E"));
hits[5].setScore(5);
hits[6].setRank(7);
hits[6].setSequence(AASequence::fromString("H"));
hits[6].setScore(4);
hits[7].setRank(8);
hits[7].setSequence(AASequence::fromString("I"));
hits[7].setScore(3);
hits[8].setRank(9);
hits[8].setSequence(AASequence::fromString("J"));
hits[8].setScore(2);
hits[9].setRank(10);
hits[9].setSequence(AASequence::fromString("K"));
hits[9].setScore(1);
ids[2].setHits(hits);
START_SECTION(void apply(std::vector<PeptideIdentification>& ids))
TOLERANCE_ABSOLUTE(0.01)
// ***** Ranked ********
ConsensusID consensus;
//define parameters
Param param;
param.setValue("algorithm","ranked");
param.setValue("considered_hits",5);
consensus.setParameters(param);
//apply
vector<PeptideIdentification> f = ids;
consensus.apply(f);
TEST_EQUAL(f.size(),1);
hits = f[0].getHits();
TEST_EQUAL(hits.size(),7);
TEST_EQUAL(hits[0].getRank(),1);
TEST_EQUAL(hits[0].getSequence(),AASequence::fromString("C"));
TEST_REAL_SIMILAR(hits[0].getScore(),80.0f);
TEST_EQUAL(hits[1].getRank(),2);
TEST_EQUAL(hits[1].getSequence(),AASequence::fromString("A"));
TEST_REAL_SIMILAR(hits[1].getScore(),60.0f);
TEST_EQUAL(hits[2].getRank(),3);
TEST_EQUAL(hits[2].getSequence(),AASequence::fromString("B"));
TEST_REAL_SIMILAR(hits[2].getScore(),53.33f);
TEST_EQUAL(hits[3].getRank(),4);
TEST_EQUAL(hits[3].getSequence(),AASequence::fromString("F"));
TEST_REAL_SIMILAR(hits[3].getScore(),33.333f);
TEST_EQUAL(hits[4].getRank(),5);
TEST_EQUAL(hits[4].getSequence(),AASequence::fromString("D"));
TEST_REAL_SIMILAR(hits[4].getScore(),26.666f);
TEST_EQUAL(hits[5].getRank(),6);
TEST_EQUAL(hits[5].getSequence(),AASequence::fromString("G"));
TEST_REAL_SIMILAR(hits[5].getScore(),20.0f);
TEST_EQUAL(hits[6].getRank(),7);
TEST_EQUAL(hits[6].getSequence(),AASequence::fromString("E"));
TEST_REAL_SIMILAR(hits[6].getScore(),6.666f);
//~ // ***** Merge ********
//~ //define parameters
//~ param.clear();
//~ param.setValue("algorithm","merge");
//~ param.setValue("considered_hits",6);
//~ consensus.setParameters(param);
//~ //apply
//~ f = ids;
//~ consensus.apply(f);
//~ TEST_EQUAL(f.size(),1);
//~ hits = f[0].getHits();
//~ TEST_EQUAL(hits.size(),7);
//~ TEST_EQUAL(hits[0].getRank(),1);
//~ TEST_EQUAL(hits[0].getSequence(),"F");
//~ TEST_REAL_SIMILAR(hits[0].getScore(),81.0f);
//~ TEST_EQUAL(hits[1].getRank(),2);
//~ TEST_EQUAL(hits[1].getSequence(),"C");
//~ TEST_REAL_SIMILAR(hits[1].getScore(),60.0f);
//~ TEST_EQUAL(hits[2].getRank(),3);
//~ TEST_EQUAL(hits[2].getSequence(),"G");
//~ TEST_REAL_SIMILAR(hits[2].getScore(),50.0f);
//~ TEST_EQUAL(hits[3].getRank(),4);
//~ TEST_EQUAL(hits[3].getSequence(),"D");
//~ TEST_REAL_SIMILAR(hits[3].getScore(),40.0f);
//~ TEST_EQUAL(hits[4].getRank(),5);
//~ TEST_EQUAL(hits[4].getSequence(),"A");
//~ TEST_REAL_SIMILAR(hits[4].getScore(),31.0f);
//~ TEST_EQUAL(hits[5].getRank(),6);
//~ TEST_EQUAL(hits[5].getSequence(),"B");
//~ TEST_REAL_SIMILAR(hits[5].getScore(),29.0f);
//~ TEST_EQUAL(hits[6].getRank(),7);
//~ TEST_EQUAL(hits[6].getSequence(),"E");
//~ TEST_REAL_SIMILAR(hits[6].getScore(),5.0f);
// ***** Average ********
//define parameters
param.clear();
param.setValue("algorithm","average");
param.setValue("considered_hits",4);
consensus.setParameters(param);
//apply
f = ids;
consensus.apply(f);
TEST_EQUAL(f.size(),1);
hits = f[0].getHits();
TEST_EQUAL(hits.size(),6);
TEST_EQUAL(hits[0].getRank(),1);
TEST_EQUAL(hits[0].getSequence(),AASequence::fromString("C"));
TEST_REAL_SIMILAR(hits[0].getScore(),36.333f);
TEST_EQUAL(hits[1].getRank(),2);
TEST_EQUAL(hits[1].getSequence(),AASequence::fromString("F"));
TEST_REAL_SIMILAR(hits[1].getScore(),27.0f);
TEST_EQUAL(hits[2].getRank(),3);
TEST_EQUAL(hits[2].getSequence(),AASequence::fromString("A"));
TEST_REAL_SIMILAR(hits[2].getScore(),20.333f);
TEST_EQUAL(hits[3].getRank(),4);
TEST_EQUAL(hits[3].getSequence(),AASequence::fromString("B"));
TEST_REAL_SIMILAR(hits[3].getScore(),19.0f);
TEST_EQUAL(hits[4].getRank(),5);
TEST_EQUAL(hits[4].getSequence(),AASequence::fromString("G"));
TEST_REAL_SIMILAR(hits[4].getScore(),16.666f);
TEST_EQUAL(hits[5].getRank(),6);
TEST_EQUAL(hits[5].getSequence(),AASequence::fromString("D"));
TEST_REAL_SIMILAR(hits[5].getScore(),15.666f);
// ***** Average, Inverse Order ********
//define parameters
param.clear();
param.setValue("algorithm","average");
param.setValue("considered_hits",1);
consensus.setParameters(param);
f = ids;
for (Size i = 0; i < f.size(); ++i)
{
f[i].setHigherScoreBetter(false);
}
//apply
consensus.apply(f);
TEST_EQUAL(f.size(),1);
hits = f[0].getHits();
TEST_EQUAL(hits.size(),3);
TEST_EQUAL(hits[0].getRank(),1);
TEST_EQUAL(hits[0].getSequence(),AASequence::fromString("K"));
TEST_REAL_SIMILAR(hits[0].getScore(),0.333f);
TEST_EQUAL(hits[1].getRank(),2);
TEST_EQUAL(hits[1].getSequence(),AASequence::fromString("E"));
TEST_REAL_SIMILAR(hits[1].getScore(),1.0f);
TEST_EQUAL(hits[2].getRank(),3);
TEST_EQUAL(hits[2].getSequence(),AASequence::fromString("B"));
TEST_REAL_SIMILAR(hits[2].getScore(),9.666f);
// ***** probability ********
/* //define parameters
param.clear();
param.setValue("algorithm","probability");
param.setValue("considered_hits",5);
consensus.setParameters(param);
//apply
f = ids;
consensus.apply(f);
TEST_EQUAL(f.size(),1);
hits = f[0].getHits();
TEST_EQUAL(hits.size(),7);
TEST_EQUAL(hits[0].getRank(),1);
TEST_EQUAL(hits[0].getSequence(),"C");
TEST_REAL_SIMILAR(hits[0].getScore(),32640.0f);
TEST_EQUAL(hits[1].getRank(),2);
TEST_EQUAL(hits[1].getSequence(),"B");
TEST_REAL_SIMILAR(hits[1].getScore(),20300.0f);
TEST_EQUAL(hits[2].getRank(),3);
TEST_EQUAL(hits[2].getSequence(),"A");
TEST_REAL_SIMILAR(hits[2].getScore(),930.0f);
TEST_EQUAL(hits[3].getRank(),4);
TEST_EQUAL(hits[3].getSequence(),"D");
TEST_REAL_SIMILAR(hits[3].getScore(),280.0f);
TEST_EQUAL(hits[4].getRank(),5);
TEST_EQUAL(hits[4].getSequence(),"F");
TEST_REAL_SIMILAR(hits[4].getScore(),81.0f);
TEST_EQUAL(hits[5].getRank(),6);
TEST_EQUAL(hits[5].getSequence(),"G");
TEST_REAL_SIMILAR(hits[5].getScore(),50.0f);
*/
// ***** Exception ********
param.setValue("algorithm","Bla4711");
TEST_EXCEPTION(Exception::InvalidParameter,consensus.setParameters(param));
END_SECTION
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| 32.19174
| 78
| 0.65115
|
aiche
|
dcd2b7beca4d9af31d73352c94323eaecff7c248
| 3,851
|
cpp
|
C++
|
src/data/dictionary.cpp
|
jonasstrandstedt/owl
|
463e2761cf1407378d5ca18bd176f316c5c65151
|
[
"MIT"
] | null | null | null |
src/data/dictionary.cpp
|
jonasstrandstedt/owl
|
463e2761cf1407378d5ca18bd176f316c5c65151
|
[
"MIT"
] | null | null | null |
src/data/dictionary.cpp
|
jonasstrandstedt/owl
|
463e2761cf1407378d5ca18bd176f316c5c65151
|
[
"MIT"
] | null | null | null |
/*****************************************************************************************
* *
* owl *
* *
* Copyright (c) 2014 Jonas Strandstedt *
* *
* 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 <owl/data/dictionary.h>
namespace {
const std::string _loggerCat = "Dictionary";
}
namespace owl {
Dictionary::Dictionary() {}
Dictionary::Dictionary(const Dictionary& rhs): _map(rhs._map.begin(),rhs._map.end()) {}
Dictionary Dictionary::operator=(const Dictionary& rhs) {
if (this != &rhs) {
_map = std::map<std::string, owl::Any>(rhs._map.begin(),rhs._map.end());
}
return *this;
}
Dictionary::iterator Dictionary::begin() {
return _map.begin();
}
Dictionary::const_iterator Dictionary::begin() const {
return _map.begin();
}
Dictionary::iterator Dictionary::end() {
return _map.end();
}
Dictionary::const_iterator Dictionary::end() const {
return _map.end();
}
bool Dictionary::empty() const {
return _map.empty();
}
std::vector<std::string> Dictionary::keys() const {
std::vector<std::string> keys;
for(auto m: _map) {
keys.push_back(m.first);
}
return keys;
}
bool Dictionary::insert(const std::string& key, Any value){
size_t sep = key.find_first_of(Separator);
std::string k = key.substr(0, sep);
// is this a single key?
if(sep == std::string::npos) {
_map[k] = value;
return true;
}
// do I have this key?
if(_map.count(k)==0) {
_map[k] = Dictionary();
} else if( ! _map[k].is<Dictionary>()) {
return false;
}
return _map[k].as<Dictionary>().insert(_rest(key, sep), value);
}
bool Dictionary::insert(const std::string& key, const char* value){
return insert(key, std::string(value));
}
std::string Dictionary::_rest(const std::string& key, size_t separator) const {
return key.substr(separator+SeparatorLength,key.length() - separator - SeparatorLength);
}
}
| 38.89899
| 92
| 0.511555
|
jonasstrandstedt
|
dcd2c836a9fba413b998d20d38725a5a0fe2806c
| 10,904
|
cpp
|
C++
|
heap_storage.cpp
|
klundeen/5300-Hyena
|
268a4f31a028215f1182ef0b5c14c770870324f5
|
[
"MIT"
] | null | null | null |
heap_storage.cpp
|
klundeen/5300-Hyena
|
268a4f31a028215f1182ef0b5c14c770870324f5
|
[
"MIT"
] | null | null | null |
heap_storage.cpp
|
klundeen/5300-Hyena
|
268a4f31a028215f1182ef0b5c14c770870324f5
|
[
"MIT"
] | 1
|
2021-05-02T22:26:14.000Z
|
2021-05-02T22:26:14.000Z
|
// heap_storage.cpp
#include "heap_storage.h"
#include <cstring>
#include <map>
#include <vector>
// test function -- returns true if all tests pass
bool test_heap_storage() {
ColumnNames column_names;
column_names.push_back("a");
column_names.push_back("b");
ColumnAttributes column_attributes;
ColumnAttribute ca(ColumnAttribute::INT);
column_attributes.push_back(ca);
ca.set_data_type(ColumnAttribute::TEXT);
column_attributes.push_back(ca);
HeapTable table1("_test_create_drop_cpp", column_names, column_attributes);
table1.create();
std::cout << "create ok" << std::endl;
table1.drop(); // drop makes the object unusable because of BerkeleyDB restriction -- maybe want to fix this some day
std::cout << "drop ok" << std::endl;
HeapTable table("_test_data_cpp", column_names, column_attributes);
table.create_if_not_exists();
std::cout << "create_if_not_exsts ok" << std::endl;
ValueDict row;
row["a"] = Value(12);
row["b"] = Value("Hello!");
std::cout << "try insert" << std::endl;
table.insert(&row);
std::cout << "insert ok" << std::endl;
Handles* handles = table.select();
std::cout << "select ok " << handles->size() << std::endl;
ValueDict *result = table.project((*handles)[0]);
std::cout << "project ok" << std::endl;
Value value = (*result)["a"];
if (value.n != 12)
return false;
value = (*result)["b"];
if (value.s != "Hello!")
return false;
table.drop();
return true;
}
SlottedPage::SlottedPage(Dbt &block, BlockID block_id, bool is_new): DbBlock(block, block_id, is_new)
{
std::cout << "a";
if (is_new) {
this->num_records = 0;
this->end_free = DbBlock::BLOCK_SZ - 1;
put_header();
}
else {
get_header(this->num_records, this->end_free);
}
}
RecordID SlottedPage::add(const Dbt *data) {
if (!has_room(data->get_size())){
throw DbBlockNoRoomError("Not enough room in block");
}
this->num_records += 1;
u_int16_t record_id = this->num_records;
u_int16_t size = data->get_size();
this->end_free -= size;
u_int16_t loc = this->end_free + 1;
put_header();
put_header(record_id, size, loc);
memcpy(this->address(loc), data->get_data(), size);
return record_id;
}
Dbt* SlottedPage::get(RecordID record_id) {
u_int16_t size;
u_int16_t loc;
get_header(size, loc, record_id);
if (loc == 0){
return NULL;
}
return new Dbt(this->address(loc), size);
}
void SlottedPage::put(RecordID record_id, const Dbt &data){
u_int16_t size;
u_int16_t loc;
u_int16_t new_size = data.get_size();
u_int16_t extra;
get_header(size, loc, record_id);
if(new_size > size){
extra = new_size - size;
if(!has_room(extra)){
throw DbBlockNoRoomError("Not enough room in block");
}
slide(loc, loc - extra);
memcpy(this->address(loc - extra), data.get_data(), size);
}
else{
memcpy(this->address(loc), data.get_data(), new_size);
slide(loc + new_size, loc + size);
}
get_header(size, loc, record_id);
put_header(record_id, new_size, loc);
}
void SlottedPage::del(RecordID record_id){
u_int16_t size;
u_int16_t loc;
get_header(size, loc, record_id);
put_header(record_id, 0, 0);
slide(loc, loc + size);
}
RecordIDs* SlottedPage::ids(void){
RecordIDs *id(0);
u_int16_t size;
u_int16_t loc;
for(u_int16_t i = 1; i < this->num_records + 1; i++){
get_header(size, loc, i);
if(loc != 0){
id->push_back(i);
}
}
return id;
}
void SlottedPage::get_header(u_int16_t &size, u_int16_t &loc, RecordID record_id){
size = get_n(4 * record_id);
loc = get_n(4 * record_id + 2);
}
void SlottedPage::put_header(RecordID id, u_int16_t size, u_int16_t loc) {
if (id == 0) {
size = this->num_records;
loc = this->end_free;
}
put_n(4*id, size);
put_n(4*id + 2, loc);
}
bool SlottedPage::has_room(u_int16_t size){
u_int16_t avalaible = (this->end_free - (this->num_records + 2)*4);
return size <= avalaible;
}
void SlottedPage::slide(u_int16_t start, u_int16_t end){
u_int16_t shifted = end - start;
if(shifted == 0){
return;
}
memcpy(this->address(this->end_free + 1 + shifted), this->address(end_free + 1), start - (end_free + 1));
for(u_int16_t i = 0; i < this->ids()->size(); i++){
u_int16_t size;
u_int16_t loc;
get_header(size, loc, i);
if(loc <= start){
loc += start;
put_header(i, size, loc);
}
}
this->end_free += shifted;
put_header();
}
u_int16_t SlottedPage::get_n(u_int16_t offset) {
return *(u_int16_t*)this->address(offset);
}
void SlottedPage::put_n(u_int16_t offset, u_int16_t n) {
*(u_int16_t*)this->address(offset) = n;
}
void* SlottedPage::address(u_int16_t offset) {
return (void*)((char*)this->block.get_data() + offset);
}
//--------------------------------HEAP FILE-----------------------------------
void HeapFile::create(void) {
this-> db_open(DB_CREATE);
SlottedPage *block = this->get_new();
this->put(block);
}
void HeapFile::drop(void){
open();
close();
remove(this->dbfilename.c_str());
}
void HeapFile::open(void) {
db_open(DB_CREATE);
}
void HeapFile::close(void) {
if (!closed) {
db.close(0);
closed = true;
}
}
SlottedPage* HeapFile::get_new(void) {
char block[DbBlock::BLOCK_SZ];
std::memset(block, 0, sizeof(block));
Dbt data(block, sizeof(block));
int block_id = ++this->last;
Dbt key(&block_id, sizeof(block_id));
SlottedPage* page = new SlottedPage(data, this->last, true);
std::cout<<"after slot";
this->db.put(nullptr, &key, &data, 0);
std::cout<<"between";
this->db.get(nullptr, &key, &data, 0);
return page;
}
SlottedPage* HeapFile::get(BlockID block_id) {
Dbt key(&block_id, sizeof(block_id));
Dbt data;
this->db.get(nullptr, &key, &data, 0);
return new SlottedPage(data, block_id, false);
}
void HeapFile::put(DbBlock *block) {
std::cout<<"put success" << std::endl;
BlockID block_id = block->get_block_id();
Dbt key(&block_id, sizeof(block_id));
std::cout<<"put success" << std::endl;
this->db.put(nullptr, &key, block->get_block(), 0);
}
BlockIDs* HeapFile::block_ids() {
BlockIDs* block_id(0);
for (BlockID i = 1; i < (BlockID)this->last+1; i++) {
block_id->push_back(i);
}
return block_id;
}
void HeapFile::db_open(uint flags) {
if (this->closed == false) {
return;
}
this->db.set_re_len(DbBlock::BLOCK_SZ);
this->dbfilename = this->name + ".db";
this->db.open(nullptr, this->dbfilename.c_str(), nullptr, DB_RECNO, flags, 0644);
DB_BTREE_STAT *stat_type;
this->db.stat(nullptr, &stat_type, DB_FAST_STAT);
this->last = stat_type->bt_ndata;
this->closed = false;
}
//--------------------------------HEAP TABLE-----------------------------------
HeapTable::HeapTable(Identifier table_name, ColumnNames column_names, ColumnAttributes column_attributes): DbRelation(table_name, column_names, column_attributes), file(table_name)
{}
void HeapTable::create(){
this->file.create();
}
void HeapTable::create_if_not_exists(){
try
{
this->open();
}
catch(DbRelationError const&)
{
this->create();
}
}
void HeapTable::drop(){
this->file.drop();
}
void HeapTable::open(){
this->file.open();
}
void HeapTable::close(){
this->file.close();
}
Handle HeapTable::insert(const ValueDict *row){
std::cout<<"insert open" << std::endl;
this->open();
return this->append(this->validate(row));
std::cout<<"insert after" << std::endl;
}
void HeapTable::update(const Handle handle, const ValueDict *new_values){
}
void HeapTable::del(const Handle handle){
}
Handles* HeapTable::select(){
Handles* handles = new Handles();
return handles;
}
Handles* HeapTable::select(const ValueDict *where){
Handles* handles = new Handles();
BlockIDs* block_ids = file.block_ids();
for (auto const& block_id: *block_ids) {
SlottedPage* block = file.get(block_id);
RecordIDs* record_ids = block->ids();
for (auto const& record_id: *record_ids)
handles->push_back(Handle(block_id, record_id));
delete record_ids;
delete block;
}
delete block_ids;
return handles;
}
ValueDict* HeapTable::project(Handle handle){
ValueDict *v_Dict = new ValueDict();
return v_Dict ;
}
ValueDict* HeapTable::project(Handle handle, const ColumnNames *column_names){
ValueDict *v_Dict = new ValueDict();
return v_Dict ;
}
ValueDict* HeapTable::validate(const ValueDict *row){
ValueDict *full_row = new ValueDict();
uint col_num = 0;
for (auto const& column_name: this->column_names) {
ColumnAttribute column_attributes = this->column_attributes[col_num++];
ValueDict::const_iterator column = row->find(column_name);
Value value = column->second;
if((column_attributes.get_data_type() != ColumnAttribute::DataType::INT) &&
(column_attributes.get_data_type() != ColumnAttribute::DataType::TEXT)){
throw DbRelationError ("Dont know how to handle Nulls, defaults, etc. yet");
}
else{
value = row->at(column_name);
}
full_row->insert(std::pair<Identifier, Value>(column_name, value));
}
return full_row;
}
Handle HeapTable::append(const ValueDict *row){
Dbt *data = this->marshal(row);
SlottedPage *block = this->file.get(this->file.get_last_block_id());
u_int16_t record_id;;
try
{
record_id = block->add(data);
}
catch(DbRelationError const&)
{
block = this->file.get_new();
record_id = block->add(data);
}
this->file.put(block);
return Handle(this->file.get_last_block_id(), record_id);
}
Dbt* HeapTable::marshal(const ValueDict *row){
char *bytes = new char[DbBlock::BLOCK_SZ];
uint offset = 0;
uint col_num = 0;
for (auto const& column_name: this->column_names) {
ColumnAttribute ca = this->column_attributes[col_num++];
ValueDict::const_iterator column = row->find(column_name);
Value value = column->second;
if (ca.get_data_type() == ColumnAttribute::DataType::INT) {
*(u_int32_t*) (bytes + offset) = value.n;
offset += sizeof(int32_t);
} else if (ca.get_data_type() == ColumnAttribute::DataType::TEXT) {
u_int16_t size = value.s.length();
*(u_int16_t*) (bytes + offset) = size;
offset += sizeof(u_int16_t);
memcpy(bytes+offset, value.s.c_str(), size); // assume ascii for now
offset += size;
} else {
throw DbRelationError("Only know how to marshal INT and TEXT");
}
}
char *right_size_bytes = new char[offset];
memcpy(right_size_bytes, bytes, offset);
delete[] bytes;
Dbt *data = new Dbt(right_size_bytes, offset);
return data;
}
ValueDict* HeapTable::unmarshal(Dbt *data){
ValueDict *v_Dict = new ValueDict();
return v_Dict ;
}
| 23.004219
| 180
| 0.641049
|
klundeen
|
dcd4e3d875f6d2d46662a71f11df9abe700b509a
| 801
|
hpp
|
C++
|
source/framework/algorithm/include/lue/framework/algorithm/default_policies/aspect.hpp
|
pcraster/lue
|
e64c18f78a8b6d8a602b7578a2572e9740969202
|
[
"MIT"
] | 1
|
2019-04-14T15:51:12.000Z
|
2019-04-14T15:51:12.000Z
|
source/framework/algorithm/include/lue/framework/algorithm/default_policies/aspect.hpp
|
pcraster/lue
|
e64c18f78a8b6d8a602b7578a2572e9740969202
|
[
"MIT"
] | 262
|
2016-08-11T10:12:02.000Z
|
2020-10-13T18:09:16.000Z
|
source/framework/algorithm/include/lue/framework/algorithm/default_policies/aspect.hpp
|
pcraster/lue
|
e64c18f78a8b6d8a602b7578a2572e9740969202
|
[
"MIT"
] | 1
|
2020-03-11T09:49:41.000Z
|
2020-03-11T09:49:41.000Z
|
#pragma once
#include "lue/framework/algorithm/aspect.hpp"
namespace lue {
namespace policy::aspect {
template<
typename Element>
using DefaultPolicies = policy::DefaultSpatialOperationPolicies<
AllValuesWithinDomain<Element>,
OutputElements<Element>,
InputElements<Element>>;
} // namespace aspect::policy
namespace default_policies {
template<
typename Element,
Rank rank>
PartitionedArray<Element, rank> aspect(
PartitionedArray<Element, rank> const& elevation)
{
using Policies = policy::aspect::DefaultPolicies<Element>;
return aspect(Policies{}, elevation);
}
} // namespace default_policies
} // namespace lue
| 24.272727
| 72
| 0.615481
|
pcraster
|
dcd720273ba24ae52d22547a011c5c2021a699c9
| 442
|
cpp
|
C++
|
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Demos/15.Returning-STL-Vectors-from-Functions.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Demos/15.Returning-STL-Vectors-from-Functions.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Demos/15.Returning-STL-Vectors-from-Functions.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<double> getSquareRoots(int from, int to) {
vector<double> roots;
for (int i = from; i <= to; i++) {
roots.push_back(sqrt(i));
}
return roots;
}
void print(vector<double> numbers) {
for (int number : numbers) {
cout << number << " "
}
cout << endl;
}
int main() {
print (getSquareRoots(4, 25));
return 0;
}
| 17
| 49
| 0.58371
|
Knightwalker
|
dcd72522fddf796a6fba66e293079926bec596a9
| 2,427
|
cpp
|
C++
|
examples/tsp/Main.cpp
|
sk177y/sexy
|
d3384044f91f442341edb0928267c86d80697c33
|
[
"Apache-2.0"
] | 5
|
2018-03-12T14:39:44.000Z
|
2021-12-21T23:31:53.000Z
|
examples/tsp/Main.cpp
|
sk177y/sexy
|
d3384044f91f442341edb0928267c86d80697c33
|
[
"Apache-2.0"
] | null | null | null |
examples/tsp/Main.cpp
|
sk177y/sexy
|
d3384044f91f442341edb0928267c86d80697c33
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <sstream>
#include <stdlib.h>
using namespace std;
#include "PropertiesMap.h"
#include "mtrand.h"
#include "AlgorithmTSPAIS.h"
#include "AlgorithmTSPAIS2.h"
#include "AlgorithmTSPGA.h"
#include "AlgorithmTSPGA2.h"
/**
* Prints default usage of the program.
*/
void usage(){
cout << "Usage: AIS-TravelSalesman algorithm propertiesfile" << endl << endl;
cout << "\t algorithm: " << endl;
cout << "\t AISi artificial immune algorithm" << endl;
cout << "\t AISd artificial immune algorithm with random keys" << endl;
cout << "\t GAi genetic algorithm" << endl;
cout << "\t GAd genetic algorithm with random keys" << endl;
cout << endl;
}
/**
* Main method of the program. First argument must be the algorithm and the second must be the properties file.
*/
int main( int argc, const char* argv[] )
{
string algorithm;
string properties;
if(argc != 3){
usage();
}else{
algorithm = argv[1];
properties = argv[2];
cout << "Loading properties file: "<< properties << endl;
bool ok = PropertiesMap::instance()->load(properties);
if(!ok){
cerr << "Error loading properties file" << endl;
}else{
cout << "Properties file loaded" << endl;
}
string aux;
unsigned long int seed = 0;
aux = PropertiesMap::instance()->get("randomSeed");
if(aux.length() > 0){
char* finalPtr = 0;
seed = strtol(aux.c_str(),&finalPtr, 10);
}
if(seed == 0){
cout << "Generating random seed..." << endl;
seed = time(NULL);
std::stringstream buf;
buf << seed;
string seedstring = buf.str();
cout << seedstring << endl;
PropertiesMap::instance()->setProperty("randomSeed",seedstring);
}
MTRand_int32 irand(seed);
cout << "Saving properties file..." << endl;
PropertiesMap::instance()->save(properties+".last");
cout << "Saved properties file as " << properties << ".last" << endl;
cout << "Algorithm: " << algorithm << endl;
if(algorithm == "AISi"){
AlgorithmTSPAIS* a = new AlgorithmTSPAIS();
a->run();
}else if (algorithm == "AISd"){
AlgorithmTSPAIS2* a = new AlgorithmTSPAIS2();
a->run();
}else if (algorithm == "GAi"){
AlgorithmTSPGA* a = new AlgorithmTSPGA();
a->run();
}else if (algorithm == "GAd"){
AlgorithmTSPGA2* a = new AlgorithmTSPGA2();
a->run();
}else{
cerr << "No valid algorithm selected" << endl;
}
}
return 0;
}
| 25.819149
| 111
| 0.624227
|
sk177y
|
dcdd933b1d352927f8e42dab3db7ccfac35f5dfa
| 372
|
cpp
|
C++
|
Projects/009 first letter of string/first letter of string/main.cpp
|
RoundBearChoi/CPP_Tutorial_Projects
|
19b52a054f4c8c83ed7f09d834109ddb57e423ad
|
[
"Unlicense"
] | 2
|
2020-11-02T18:47:33.000Z
|
2021-04-12T15:28:14.000Z
|
Projects/009 first letter of string/first letter of string/main.cpp
|
RoundBearChoi/CPP_Tutorial_Projects
|
19b52a054f4c8c83ed7f09d834109ddb57e423ad
|
[
"Unlicense"
] | null | null | null |
Projects/009 first letter of string/first letter of string/main.cpp
|
RoundBearChoi/CPP_Tutorial_Projects
|
19b52a054f4c8c83ed7f09d834109ddb57e423ad
|
[
"Unlicense"
] | 3
|
2021-02-15T13:54:36.000Z
|
2021-11-23T06:22:51.000Z
|
#include <iostream>
int main()
{
std::string yourString;
while (yourString[0] != 'q')
{
std::cout << "say something: ";
std::cin >> yourString;
std::cout << std::endl;
std::cout << "you said: " << yourString << std::endl;
std::cout << "first letter: " << yourString[0] << std::endl;
std::cin.clear(); // clear error flags
std::cout << std::endl;
}
}
| 18.6
| 62
| 0.575269
|
RoundBearChoi
|
dcde3b3d1c3e8513e9d6929a1b029d0708650e72
| 2,247
|
cpp
|
C++
|
Sources/engine/vulkangfx/private/Device.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 20
|
2019-12-22T20:40:22.000Z
|
2021-07-06T00:23:45.000Z
|
Sources/engine/vulkangfx/private/Device.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 32
|
2020-07-11T15:51:13.000Z
|
2021-06-07T10:25:07.000Z
|
Sources/engine/vulkangfx/private/Device.cpp
|
Zino2201/ZinoEngine
|
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
|
[
"MIT"
] | 3
|
2019-12-19T17:04:04.000Z
|
2021-05-17T01:49:59.000Z
|
#include "Device.h"
#include <set>
#include "Queue.h"
#include "VulkanBackend.h"
namespace ze::gfx::vulkan
{
Device::Device(const vk::PhysicalDevice& in_phys_device) :
physical_device(in_phys_device)
{
/** Get queue family indices */
{
std::vector<vk::QueueFamilyProperties> queue_families = physical_device.getQueueFamilyProperties();
/** Present queue use gfx queue by default */
int i = 0;
for (const vk::QueueFamilyProperties& queue_family : queue_families)
{
if (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)
{
queue_family_indices.gfx = i;
}
if (queue_family_indices.is_complete())
break;
i++;
}
}
/** Queue create infos */
std::vector<vk::DeviceQueueCreateInfo> queue_create_infos;
{
std::set<uint32_t> unique_queue_families =
{
queue_family_indices.gfx.value()
};
float priority = 1.f;
for (uint32_t family : unique_queue_families)
{
queue_create_infos.emplace_back(
vk::DeviceQueueCreateFlags(),
family,
1,
&priority);
}
}
vk::DeviceCreateInfo device_create_infos(
vk::DeviceCreateFlags(),
static_cast<uint32_t>(queue_create_infos.size()),
queue_create_infos.data(),
enable_validation_layers ? static_cast<uint32_t>(validation_layers.size()) : 0,
enable_validation_layers ? validation_layers.data() : 0,
static_cast<uint32_t>(required_device_extensions.size()),
required_device_extensions.data());
auto [result, handle] = physical_device.createDeviceUnique(device_create_infos);
if (result != vk::Result::eSuccess)
ze::logger::error("Failed to create logical device: {}", vk::to_string(result));
device = std::move(handle);
/** Create allocator */
{
VmaAllocatorCreateInfo alloc_create_info = {};
alloc_create_info.device = *device;
alloc_create_info.physicalDevice = physical_device;
vk::Result result = static_cast<vk::Result>(vmaCreateAllocator(&alloc_create_info, &allocator.allocator));
if(result != vk::Result::eSuccess)
ze::logger::error("Failed to create allocator: {}", vk::to_string(result));
}
}
Device::~Device() = default;
void Device::create_queues()
{
/** Create queues */
gfx_queue = get_backend().queue_create(queue_family_indices.gfx.value(), 0);
present_queue = gfx_queue;
}
}
| 26.75
| 108
| 0.721851
|
Zino2201
|
dce41568e4034733e0af04c7610f35da93f2bdee
| 335
|
cpp
|
C++
|
_includes/leet162/leet162.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
_includes/leet162/leet162.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | 8
|
2019-12-19T04:46:05.000Z
|
2022-02-26T03:45:22.000Z
|
_includes/leet162/leet162.cpp
|
mingdaz/leetcode
|
64f2e5ad0f0446d307e23e33a480bad5c9e51517
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size()==1) return 0;
int n = nums.size();
if(nums[0]>nums[1]) return 0;
if(nums[n-1]>nums[n-2]) return n-1;
for(int i=1;i<n-1;i++){
while(nums[i]>nums[i-1]) i++;
return i-1;
}
}
};
| 23.928571
| 44
| 0.471642
|
mingdaz
|
dce470ebca5be3782233b543b7f9cc5ed1d2d438
| 49,427
|
cpp
|
C++
|
Samples/Win7Samples/multimedia/mediafoundation/topoedit/tedutil/PropertyView.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8
|
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/multimedia/mediafoundation/topoedit/tedutil/PropertyView.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/multimedia/mediafoundation/topoedit/tedutil/PropertyView.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2
|
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "stdafx.h"
#include "propertyview.h"
#include <assert.h>
#include "commctrl.h"
#include "wmcontainer.h"
#include "atlconv.h"
#include "nserror.h"
KeyStringTypeTriplet CPropertyInfo::ms_AttributeKeyStrings[] = {
{ MF_TOPONODE_CONNECT_METHOD, L"MF_TOPONODE_CONNECT_METHOD", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_DECODER, L"MF_TOPONODE_DECODER", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_DECRYPTOR, L"MF_TOPONODE_DECRYPTOR", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_DISCARDABLE, L"MF_TOPONODE_DISCARDABLE", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_ERROR_MAJORTYPE, L"MF_TOPONODE_ERROR_MAJORTYPE", VT_CLSID, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_ERROR_SUBTYPE, L"MF_TOPONODE_ERROR_SUBTYPE", VT_CLSID, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_ERRORCODE, L"MF_TOPONODE_ERRORCODE", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_LOCKED, L"MF_TOPONODE_LOCKED", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_MARKIN_HERE, L"MF_TOPONODE_MARKIN_HERE", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_MARKOUT_HERE, L"MF_TOPONODE_MARKOUT_HERE", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_MEDIASTART, L"MF_TOPONODE_MEDIASTART", VT_UI8, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_MEDIASTOP, L"MF_TOPONODE_MEDIASTOP", VT_UI8, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_PRESENTATION_DESCRIPTOR, L"MF_TOPONODE_PRESENTATION_DESCRIPTOR", VT_UNKNOWN, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_SEQUENCE_ELEMENTID, L"MF_TOPONODE_SEQUENCE_ELEMENTID", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_SOURCE, L"MF_TOPONODE_SOURCE", VT_UNKNOWN, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_STREAM_DESCRIPTOR, L"MF_TOPONODE_STREAM_DESCRIPTOR", VT_UNKNOWN, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_WORKQUEUE_ID, L"MF_TOPONODE_WORKQUEUE_ID", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_WORKQUEUE_MMCSS_CLASS, L"MF_TOPONODE_WORKQUEUE_MMCSS_CLASS", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_WORKQUEUE_MMCSS_TASKID, L"MF_TOPONODE_WORKQUEUE_MMCSS_TASKID", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_D3DAWARE, L"MF_TOPONODE_D3DAWARE", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_DRAIN, L"MF_TOPONODE_DRAIN", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_FLUSH, L"MF_TOPONODE_FLUSH", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_TRANSFORM_OBJECTID, L"MF_TOPONODE_TRANSFORM_OBJECTID", VT_CLSID, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_DISABLE_PREROLL, L"MF_TOPONODE_DISABLE_PREROLL", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, L"MF_TOPONODE_NOSHUTDOWN_ON_REMOVE", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_RATELESS, L"MF_TOPONODE_RATELESS", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_STREAMID, L"MF_TOPONODE_STREAMID", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_TOPONODE_PRIMARYOUTPUT, L"MF_TOPONODE_PRIMARYOUTPUT", VT_UI4, TED_ATTRIBUTE_CATEGORY_TOPONODE },
{ MF_MT_ALL_SAMPLES_INDEPENDENT, L"MF_MT_ALL_SAMPLES_INDEPENDENT", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AM_FORMAT_TYPE, L"MF_MT_AM_FORMAT_TYPE", VT_CLSID, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_COMPRESSED, L"MF_MT_COMPRESSED", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_FIXED_SIZE_SAMPLES, L"MF_MT_FIXED_SIZE_SAMPLES", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MAJOR_TYPE, L"MF_MT_MAJOR_TYPE", VT_CLSID, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_SAMPLE_SIZE, L"MF_MT_SAMPLE_SIZE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_SUBTYPE, L"MF_MT_SUBTYPE", VT_CLSID, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_USER_DATA, L"MF_MT_USER_DATA", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_WRAPPED_TYPE, L"MF_MT_WRAPPED_TYPE", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_AVG_BYTES_PER_SECOND, L"MF_MT_AUDIO_AVG_BYTES_PER_SECOND", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_BITS_PER_SAMPLE, L"MF_MT_AUDIO_BITS_PER_SAMPLE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_BLOCK_ALIGNMENT, L"MF_MT_AUDIO_BLOCK_ALIGNMENT", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_CHANNEL_MASK, L"MF_MT_AUDIO_CHANNEL_MASK", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_FLOAT_SAMPLES_PER_SECOND, L"MF_MT_AUDIO_FLOAT_SAMPLES_PER_SECOND", VT_R8, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_FOLDDOWN_MATRIX, L"MF_MT_AUDIO_FOLDDOWN_MATRIX", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_NUM_CHANNELS, L"MF_MT_AUDIO_NUM_CHANNELS", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_PREFER_WAVEFORMATEX, L"MF_MT_AUDIO_PREFER_WAVEFORMATEX", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_SAMPLES_PER_BLOCK, L"MF_MT_AUDIO_SAMPLES_PER_BLOCK", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_SAMPLES_PER_SECOND, L"MF_MT_AUDIO_SAMPLES_PER_SECOND", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_VALID_BITS_PER_SAMPLE, L"MF_MT_AUDIO_VALID_BITS_PER_SAMPLE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AVG_BIT_ERROR_RATE, L"MF_MT_AVG_BIT_ERROR_RATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AVG_BITRATE, L"MF_MT_AVG_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_CUSTOM_VIDEO_PRIMARIES, L"MF_MT_CUSTOM_VIDEO_PRIMARIES", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_DEFAULT_STRIDE, L"MF_MT_DEFAULT_STRIDE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_DRM_FLAGS, L"MF_MT_DRM_FLAGS", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_FRAME_RATE, L"MF_MT_FRAME_RATE", VT_UI8, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_FRAME_SIZE, L"MF_MT_FRAME_SIZE", VT_UI8, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_GEOMETRIC_APERTURE, L"MF_MT_GEOMETRIC_APERTURE", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_INTERLACE_MODE, L"MF_MT_INTERLACE_MODE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MAX_KEYFRAME_SPACING, L"MF_MT_MAX_KEYFRAME_SPACING", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MINIMUM_DISPLAY_APERTURE, L"MF_MT_MINIMUM_DISPLAY_APERTURE", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MPEG_SEQUENCE_HEADER, L"MF_MT_MPEG_SEQUENCE_HEADER", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MPEG_START_TIME_CODE, L"MF_MT_MPEG_START_TIME_CODE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MPEG2_FLAGS, L"MF_MT_MPEG2_FLAGS", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MPEG2_LEVEL, L"MF_MT_MPEG2_LEVEL", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_MPEG2_PROFILE, L"MF_MT_MPEG2_PROFILE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_PAD_CONTROL_FLAGS, L"MF_MT_PAD_CONTROL_FLAGS", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_PALETTE, L"MF_MT_PALETTE", (VT_VECTOR | VT_UI1), TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_PAN_SCAN_APERTURE, L"MF_MT_PAN_SCAN_APERTURE", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_PAN_SCAN_ENABLED, L"MF_MT_PAN_SCAN_ENABLED", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_PIXEL_ASPECT_RATIO, L"MF_MT_PIXEL_ASPECT_RATIO", VT_UI8, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_SOURCE_CONTENT_HINT, L"MF_MT_SOURCE_CONTENT_HINT", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_TRANSFER_FUNCTION, L"MF_MT_TRANSFER_FUNCTION", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_VIDEO_CHROMA_SITING, L"MF_MT_VIDEO_CHROMA_SITING", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_VIDEO_LIGHTING, L"MF_MT_VIDEO_LIGHTING", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_VIDEO_NOMINAL_RANGE, L"MF_MT_VIDEO_NOMINAL_RANGE", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_VIDEO_PRIMARIES, L"MF_MT_VIDEO_PRIMARIES", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_YUV_MATRIX, L"MF_MT_YUV_MATRIX", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_WMADRC_PEAKREF, L"MF_MT_AUDIO_WMADRC_PEAKREF", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_MT_AUDIO_WMADRC_AVGREF, L"MF_MT_AUDIO_WMADRC_AVGREF", VT_UI4, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_SD_LANGUAGE, L"MF_SD_LANGUAGE", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_PROTECTED, L"MF_SD_PROTECTED", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_SAMI_LANGUAGE, L"MF_SD_SAMI_LANGUAGE", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_EXTSTRMPROP_AVG_BUFFERSIZE, L"MF_SD_ASF_EXTSTRMPROP_AVG_BUFFERSIZE", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_EXTSTRMPROP_AVG_DATA_BITRATE, L"MF_SD_ASF_EXTSTRMPROP_AVG_DATA_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_EXTSTRMPROP_LANGUAGE_ID_INDEX, L"MF_SD_ASF_EXTSTRMPROP_LANGUAGE_ID_INDEX", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_EXTSTRMPROP_MAX_BUFFERSIZE, L"MF_SD_ASF_EXTSTRMPROP_MAX_BUFFERSIZE", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_EXTSTRMPROP_MAX_DATA_BITRATE, L"MF_SD_ASF_EXTSTRMPROP_MAX_DATA_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_METADATA_DEVICE_CONFORMANCE_TEMPLATE, L"MF_SD_ASF_METADATA_DEVICE_CONFORMANCE_TEMPLATE", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_SD_ASF_STREAMBITRATES_BITRATE, L"MF_SD_ASF_STREAMBITRATES_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_STREAMDESCRIPTOR },
{ MF_ASFSTREAMCONFIG_LEAKYBUCKET1, L"MF_ASFSTREAMCONFIG_LEAKYBUCKET1", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_ASFSTREAMCONFIG_LEAKYBUCKET2, L"MF_ASFSTREAMCONFIG_LEAKYBUCKET2", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_MEDIATYPE },
{ MF_PD_APP_CONTEXT, L"MF_PD_APP_CONTEXT", VT_UNKNOWN, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_AUDIO_ENCODING_BITRATE, L"MF_PD_AUDIO_ENCODING_BITRATE ", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_DURATION, L"MF_PD_DURATION", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_LAST_MODIFIED_TIME, L"MF_PD_LAST_MODIFIED_TIME", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_MIME_TYPE, L"MF_PD_MIME_TYPE", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_PMPHOST_CONTEXT, L"MF_PD_PMPHOST_CONTEXT", VT_UNKNOWN, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_SAMI_STYLELIST, L"MF_PD_SAMI_STYLELIST", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_TOTAL_FILE_SIZE, L"MF_PD_TOTAL_FILE_SIZE", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_VIDEO_ENCODING_BITRATE, L"MF_PD_VIDEO_ENCODING_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CODECLIST, L"MF_PD_ASF_CODECLIST", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CONTENTENCRYPTION_KEYID, L"MF_PD_ASF_CONTENTENCRYPTION_KEYID", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CONTENTENCRYPTION_LICENSE_URL, L"MF_PD_ASF_CONTENTENCRYPTION_LICENSE_URL", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CONTENTENCRYPTION_SECRET_DATA, L"MF_PD_ASF_CONTENTENCRYPTION_SECRET_DATA", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CONTENTENCRYPTION_TYPE, L"MF_PD_ASF_CONTENTENCRYPTION_TYPE", VT_LPWSTR, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_CONTENTENCRYPTIONEX_ENCRYPTION_DATA, L"MF_PD_ASF_CONTENTENCRYPTIONEX_ENCRYPTION_DATA", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_DATA_LENGTH, L"MF_PD_ASF_DATA_LENGTH", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_DATA_START_OFFSET, L"MF_PD_ASF_DATA_START_OFFSET", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_CREATION_TIME, L"MF_PD_ASF_FILEPROPERTIES_CREATION_TIME", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_FILE_ID, L"MF_PD_ASF_FILEPROPERTIES_FILE_ID", VT_CLSID, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_FLAGS, L"MF_PD_ASF_FILEPROPERTIES_FLAGS", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_MAX_BITRATE, L"MF_PD_ASF_FILEPROPERTIES_MAX_BITRATE", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_MAX_PACKET_SIZE, L"MF_PD_ASF_FILEPROPERTIES_MAX_PACKET_SIZE", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_MIN_PACKET_SIZE, L"MF_PD_ASF_FILEPROPERTIES_MIN_PACKET_SIZE", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_PACKETS, L"MF_PD_ASF_FILEPROPERTIES_PACKETS", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_PLAY_DURATION, L"MF_PD_ASF_FILEPROPERTIES_PLAY_DURATION", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_PREROLL, L"MF_PD_ASF_FILEPROPERTIES_PREROLL", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_FILEPROPERTIES_SEND_DURATION, L"MF_PD_ASF_FILEPROPERTIES_SEND_DURATION", VT_UI8, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_INFO_HAS_AUDIO, L"MF_PD_ASF_INFO_HAS_AUDIO", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_INFO_HAS_NON_AUDIO_VIDEO, L"MF_PD_ASF_INFO_HAS_NON_AUDIO_VIDEO", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_INFO_HAS_VIDEO, L"MF_PD_ASF_INFO_HAS_VIDEO", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_LANGLIST, L"MF_PD_ASF_LANGLIST", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_MARKER, L"MF_PD_ASF_MARKER", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_METADATA_IS_VBR, L"MF_PD_ASF_METADATA_IS_VBR", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_METADATA_LEAKY_BUCKET_PAIRS, L"MF_PD_ASF_METADATA_LEAKY_BUCKET_PAIRS", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_METADATA_V8_BUFFERAVERAGE, L"MF_PD_ASF_METADATA_V8_BUFFERAVERAGE", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_METADATA_V8_VBRPEAK, L"MF_PD_ASF_METADATA_V8_VBRPEAK", VT_UI4, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR },
{ MF_PD_ASF_SCRIPT, L"MF_PD_ASF_SCRIPT", VT_VECTOR | VT_UI1, TED_ATTRIBUTE_CATEGORY_PRESENTATIONDESCRIPTOR }
};
#define AttributeKeyStringsLength sizeof(CPropertyInfo::ms_AttributeKeyStrings) / sizeof(KeyStringTypeTriplet)
KeyStringPair CPropertyInfo::ms_AttributeValueStrings[] = {
{ MFMediaType_Audio, L"MFMediaType_Audio" },
{ MFMediaType_Video, L"MFMediaType_Video" },
{ MFMediaType_Protected, L"MFMediaType_Protected" },
{ MFMediaType_SAMI, L"MFMediaType_SAMI" },
{ MFMediaType_Script, L"MFMediaType_Script" },
{ MFMediaType_Image, L"MFMediaType_Image" },
{ MFMediaType_HTML, L"MFMediaType_HTML" },
{ MFMediaType_Binary, L"MFMediaType_Binary" },
{ MFMediaType_FileTransfer, L"MFMediaType_FileTransfer" },
{ MFAudioFormat_Dolby_AC3_SPDIF, L"MFAudioFormat_Dolby_AC3_SPDIF" },
{ MFAudioFormat_DRM, L"MFAudioFormat_DRM" },
{ MFAudioFormat_DTS, L"MFAudioFormat_DTS" },
{ MFAudioFormat_Float, L"MFAudioFormat_Float" },
{ MFAudioFormat_MP3, L"MFAudioFormat_MP3" },
{ MFAudioFormat_MPEG, L"MFAudioFormat_MPEG" },
{ MFAudioFormat_MSP1, L"MFAudioFormat_MSP1" },
{ MFAudioFormat_PCM, L"MFAudioFormat_PCM" },
{ MFAudioFormat_WMASPDIF, L"MFAudioFormat_WMASPDIF" },
{ MFAudioFormat_WMAudio_Lossless, L"MFAudioFormat_WMAudio_Lossless" },
{ MFAudioFormat_WMAudioV8, L"MFAudioFormat_WMAudioV8" },
{ MFAudioFormat_WMAudioV9, L"MFAudioFormat_WMAudioV9" },
{ MFVideoFormat_ARGB32, L"MFVideoFormat_ARGB32" },
{ MFVideoFormat_RGB24, L"MFVideoFormat_RGB24" },
{ MFVideoFormat_RGB32, L"MFVideoFormat_RGB32" },
{ MFVideoFormat_RGB555, L"MFVideoFormat_RGB555" },
{ MFVideoFormat_RGB565, L"MFVideoFormat_RGB565" },
{ MFVideoFormat_AI44, L"MFVideoFormat_AI44" },
{ MFVideoFormat_AYUV, L"MFVideoFormat_AYUV" },
{ MFVideoFormat_NV11, L"MFVideoFormat_NV11" },
{ MFVideoFormat_NV12, L"MFVideoFormat_NV12" },
{ MFVideoFormat_P010, L"MFVideoFormat_P010" },
{ MFVideoFormat_P016, L"MFVideoFormat_P016" },
{ MFVideoFormat_P210, L"MFVideoFormat_P210" },
{ MFVideoFormat_P216, L"MFVideoFormat_P216" },
{ MFVideoFormat_UYVY, L"MFVideoFormat_UYVY" },
{ MFVideoFormat_v210, L"MFVideoFormat_v210" },
{ MFVideoFormat_v410, L"MFVideoFormat_v410" },
{ MFVideoFormat_Y210, L"MFVideoFormat_Y210" },
{ MFVideoFormat_Y216, L"MFVideoFormat_Y216" },
{ MFVideoFormat_Y410, L"MFVideoFormat_Y410" },
{ MFVideoFormat_Y416, L"MFVideoFormat_Y416" },
{ MFVideoFormat_YUY2, L"MFVideoFormat_YUY2" },
{ MFVideoFormat_YV12, L"MFVideoFormat_YV12" },
{ MFVideoFormat_DV25, L"MFVideoFormat_DV25" },
{ MFVideoFormat_DV50, L"MFVideoFormat_DV50" },
{ MFVideoFormat_DVH1, L"MFVideoFormat_DVH1" },
{ MFVideoFormat_DVSD, L"MFVideoFormat_DVSD" },
{ MFVideoFormat_DVSL, L"MFVideoFormat_DVSL" },
{ MFVideoFormat_MP43, L"MFVideoFormat_MP43" },
{ MFVideoFormat_MP4S, L"MFVideoFormat_MP4S" },
{ MFVideoFormat_MPEG2, L"MFVideoFormat_MPEG2" },
{ MFVideoFormat_MPG1, L"MFVideoFormat_MPG1" },
{ MFVideoFormat_MSS1, L"MFVideoFormat_MSS1" },
{ MFVideoFormat_MSS2, L"MFVideoFormat_MSS2" },
{ MFVideoFormat_WMV1, L"MFVideoFormat_WMV1" },
{ MFVideoFormat_WMV2, L"MFVideoFormat_WMV2" },
{ MFVideoFormat_WMV3, L"MFVideoFormat_WMV3" }
};
#define AttributeValueStringsLength sizeof(CPropertyInfo::ms_AttributeValueStrings) / sizeof(KeyStringPair)
DWORD TEDGetAttributeListLength()
{
return AttributeKeyStringsLength;
}
LPCWSTR TEDGetAttributeName(DWORD dwIndex)
{
return CPropertyInfo::ms_AttributeKeyStrings[dwIndex].m_str;
}
GUID TEDGetAttributeGUID(DWORD dwIndex)
{
return CPropertyInfo::ms_AttributeKeyStrings[dwIndex].m_key;
}
VARTYPE TEDGetAttributeType(DWORD dwIndex)
{
return CPropertyInfo::ms_AttributeKeyStrings[dwIndex].m_vt;
}
TED_ATTRIBUTE_CATEGORY TEDGetAttributeCategory(DWORD dwIndex)
{
return CPropertyInfo::ms_AttributeKeyStrings[dwIndex].m_category;
}
BOOL ConvertStringToSystemTime(const CAtlString& strValue, LPSYSTEMTIME pSystemTime)
{
int iCharLoc = strValue.Find('/');
if(-1 == iCharLoc) return FALSE;
pSystemTime->wMonth = (WORD) _wtoi( strValue.Left(iCharLoc) );
int iLastLoc = iCharLoc + 1;
iCharLoc = strValue.Find('/', iLastLoc);
if(-1 == iCharLoc) return FALSE;
pSystemTime->wDay = (WORD) _wtoi( strValue.Mid(iLastLoc, iCharLoc - iLastLoc) );
iLastLoc = iCharLoc + 1;
iCharLoc = strValue.Find(' ', iLastLoc);
if(-1 == iCharLoc) return FALSE;
pSystemTime->wYear = (WORD) _wtoi( strValue.Mid(iLastLoc, iCharLoc - iLastLoc) );
iLastLoc = iCharLoc + 1;
iCharLoc = strValue.Find(':', iLastLoc);
if(-1 == iCharLoc) return FALSE;
pSystemTime->wHour = (WORD) _wtoi( strValue.Mid(iLastLoc, iCharLoc - iLastLoc) );
iLastLoc = iCharLoc + 1;
iCharLoc = strValue.Find(':', iLastLoc);
if(-1 == iCharLoc) return FALSE;
pSystemTime->wMinute = (WORD) _wtoi( strValue.Mid(iLastLoc, iCharLoc - iLastLoc) );
pSystemTime->wSecond = (WORD) _wtoi( strValue.Mid(iLastLoc) );
return TRUE;
}
/*********************************\
* CPropertyInfo *
\*********************************/
CPropertyInfo::CPropertyInfo()
: m_cRef(0)
{
}
CPropertyInfo::~CPropertyInfo()
{
}
HRESULT CPropertyInfo::QueryInterface(REFIID riid, void** ppInterface)
{
if(NULL == ppInterface)
{
return E_POINTER;
}
if(riid == IID_IUnknown || riid == IID_ITedPropertyInfo)
{
ITedPropertyInfo* pPropertyInfo = this;
*ppInterface = pPropertyInfo;
AddRef();
return S_OK;
}
*ppInterface = NULL;
return E_NOINTERFACE;
}
ULONG CPropertyInfo::AddRef()
{
ULONG cRef = InterlockedIncrement(&m_cRef);
return cRef;
}
ULONG CPropertyInfo::Release()
{
ULONG cRef = InterlockedDecrement(&m_cRef);
if(cRef == 0)
{
delete this;
}
return cRef;
}
void CPropertyInfo::ConvertKeyToString(GUID key, /* out */ CAtlStringW& strName)
{
USES_CONVERSION;
bool found = false;
for(DWORD i = 0; i < AttributeKeyStringsLength; i++)
{
if(ms_AttributeKeyStrings[i].m_key == key)
{
strName = ms_AttributeKeyStrings[i].m_str;
found = true;
break;
}
}
if(!found)
{
LPOLESTR strClsid = NULL;
StringFromCLSID(key, &strClsid);
strName = OLE2W(strClsid);
CoTaskMemFree(strClsid);
}
}
void CPropertyInfo::ConvertPropertyValueToString(GUID key, PROPVARIANT propVal, /* out */ CAtlStringW& strValue)
{
USES_CONVERSION;
switch(propVal.vt)
{
case VT_I1:
strValue.Format(L"%d", propVal.cVal);
break;
case VT_UI1:
strValue.Format(L"%d", propVal.bVal);
break;
case VT_I2:
strValue.Format(L"%d", propVal.iVal);
break;
case VT_UI2:
strValue.Format(L"%d", propVal.uiVal);
break;
case VT_I4:
strValue.Format(L"%d", propVal.lVal);
break;
case VT_UI4:
if(MF_TOPONODE_ERRORCODE == key)
{
strValue.Format(L"%x", propVal.ulVal);
}
else
{
strValue.Format(L"%d", propVal.ulVal);
}
break;
case VT_UI8:
if(MF_MT_FRAME_RATE == key ||MF_MT_PIXEL_ASPECT_RATIO == key || MF_MT_FRAME_SIZE == key)
{
UINT32 numerator, denominator;
denominator = propVal.uhVal.LowPart;
numerator = propVal.uhVal.HighPart;
strValue.Format(L"N: %d D: %d", numerator, denominator);
}
else
{
strValue.Format(L"%ld", propVal.uhVal.QuadPart);
}
break;
case VT_INT:
strValue.Format(L"%d", propVal.intVal);
break;
case VT_UINT:
strValue.Format(L"%d", propVal.uintVal);
break;
case VT_R4:
strValue.Format(L"%f", propVal.fltVal);
break;
case VT_R8:
strValue.Format(L"%f", propVal.dblVal);
break;
case VT_BOOL:
if(VARIANT_TRUE == propVal.boolVal)
{
strValue = L"True";
}
else
{
strValue = L"False";
}
break;
case VT_LPSTR:
strValue = CA2W(propVal.pszVal);
break;
case VT_LPWSTR:
strValue = propVal.pwszVal;
break;
case VT_UNKNOWN:
if(NULL == propVal.punkVal)
{
strValue = L"NULL IUnknown";
}
else
{
strValue = L"IUnknown";
}
break;
case VT_CLSID:
{
bool found = false;
if(propVal.puuid != NULL)
{
for(DWORD i = 0; i < AttributeValueStringsLength; i++)
{
if(ms_AttributeValueStrings[i].m_key == *(propVal.puuid) )
{
strValue = ms_AttributeValueStrings[i].m_str;
found = true;
break;
}
}
if(!found)
{
LPOLESTR strClsid = NULL;
StringFromCLSID(*propVal.puuid, &strClsid);
strValue = OLE2W(strClsid);
CoTaskMemFree(strClsid);
}
}
else
{
strValue = L"{00000000-0000-0000-0000-000000000000}";
}
break;
}
case VT_VECTOR | VT_UI1:
if(MF_PD_ASF_FILEPROPERTIES_CREATION_TIME == key || MF_PD_LAST_MODIFIED_TIME == key)
{
PFILETIME pFileTime;
SYSTEMTIME SystemTime;
pFileTime = (PFILETIME) propVal.caub.pElems;
if(FileTimeToSystemTime(pFileTime, &SystemTime))
{
SYSTEMTIME LocalTime;
if(SystemTimeToTzSpecificLocalTime(NULL /* current active timezone */, &SystemTime, &LocalTime))
{
strValue.Format(L"%d/%d/%d %d:%d:%d", LocalTime.wMonth, LocalTime.wDay,
LocalTime.wYear, LocalTime.wHour, LocalTime.wMinute, LocalTime.wSecond);
}
}
}
else
{
CAtlString strTemp;
for(DWORD i = 0; i < propVal.caub.cElems; i++)
{
strValue.AppendFormat(L"%2.2x%s", propVal.caub.pElems[i], (i == propVal.caub.cElems - 1) ? "" : " ");
}
}
break;
}
}
void CPropertyInfo::ConvertStringToKey(CAtlStringW strName, /* out */ GUID& key)
{
USES_CONVERSION;
bool found = false;
for(DWORD i = 0; i < AttributeKeyStringsLength; i++)
{
if(ms_AttributeKeyStrings[i].m_str == strName)
{
key = ms_AttributeKeyStrings[i].m_key;
found = true;
break;
}
}
if(!found)
{
LPOLESTR strClsid = W2OLE(strName.GetBuffer());
CLSIDFromString(strClsid, &key);
}
}
void CPropertyInfo::ConvertStringToPropertyValue(GUID key, CAtlStringW strValue, VARTYPE vt, /* out */ PROPVARIANT& propVal)
{
USES_CONVERSION;
propVal.vt = vt;
switch(vt)
{
case VT_I1:
propVal.cVal = (CHAR) _wtoi(strValue);
break;
case VT_UI1:
propVal.bVal =(UCHAR) _wtoi(strValue);
break;
case VT_I2:
propVal.iVal = (SHORT) _wtoi(strValue);
break;
case VT_UI2:
propVal.uiVal = (USHORT) _wtoi(strValue);
break;
case VT_I4:
propVal.lVal = _wtoi(strValue);
break;
case VT_UI4:
propVal.ulVal = (ULONG) _wtoi64(strValue);
break;
case VT_UI8:
{
if(strValue.GetLength() > 0 && strValue.GetAt(0) == 'N')
{
UINT32 numerator, denominator;
int charLoc = strValue.Find(' ', 4);
numerator = (UINT32) _wtoi64(strValue.Mid(3, charLoc - 3));
denominator = (UINT32) _wtoi64(strValue.Mid(charLoc + 5));
propVal.uhVal.LowPart = denominator;
propVal.uhVal.HighPart = numerator;
}
else
{
propVal.uhVal.QuadPart = _wtoi64(strValue);
}
break;
}
case VT_INT:
propVal.intVal = _wtoi(strValue);
break;
case VT_UINT:
propVal.uintVal = (UINT) _wtoi64(strValue);
break;
case VT_R4:
propVal.fltVal = (FLOAT) _wtof(strValue);
break;
case VT_R8:
propVal.dblVal = _wtof(strValue);
break;
case VT_BOOL:
if(strValue == L"True")
{
propVal.boolVal = VARIANT_TRUE;
}
else
{
propVal.boolVal = VARIANT_FALSE;
}
break;
case VT_LPSTR:
propVal.pszVal = (LPSTR) CoTaskMemAlloc(sizeof(CHAR) * (strValue.GetLength() + 1));
strcpy_s(propVal.pszVal, strValue.GetLength() + 1, CW2A(strValue.GetBuffer()));
break;
case VT_LPWSTR:
propVal.pwszVal = (LPWSTR) CoTaskMemAlloc(sizeof(WCHAR) * (strValue.GetLength() + 1));
wcscpy_s(propVal.pwszVal, strValue.GetLength() + 1, strValue.GetBuffer());
break;
case VT_CLSID:
{
propVal.puuid = (GUID*) CoTaskMemAlloc(sizeof(GUID));
bool found = false;
for(DWORD i = 0; i < AttributeValueStringsLength; i++)
{
if(ms_AttributeValueStrings[i].m_str == strValue )
{
*(propVal.puuid) = ms_AttributeValueStrings[i].m_key;
found = true;
break;
}
}
if(!found)
{
CLSIDFromString(W2OLE(strValue.GetBuffer()), propVal.puuid);
}
break;
}
case VT_VECTOR | VT_UI1:
{
if(MF_PD_ASF_FILEPROPERTIES_CREATION_TIME == key || MF_PD_LAST_MODIFIED_TIME == key)
{
FILETIME FileTime;
SYSTEMTIME SystemTime;
ZeroMemory(&SystemTime, sizeof(SYSTEMTIME));
ConvertStringToSystemTime(strValue, &SystemTime);
SystemTimeToFileTime(&SystemTime, &FileTime);
propVal.caub.pElems = (BYTE*) CoTaskMemAlloc(sizeof(FileTime));
CopyMemory(propVal.pbVal, (BYTE*) &FileTime, sizeof(FileTime));
propVal.caub.cElems = sizeof(FileTime);
}
break;
}
}
}
/*********************************\
* CNodePropertyInfo *
\ *********************************/
CNodePropertyInfo::CNodePropertyInfo(CComPtr<IMFTopologyNode> spNode)
: m_spNode(spNode)
{
HRESULT hr = S_OK;
CComPtr<IPropertyStore> spPropStore;
hr = spNode->QueryInterface(IID_IPropertyStore, (void**) &m_spNodePropertyStore);
if(E_NOINTERFACE == hr)
{
CComPtr<IUnknown> spUnk;
hr = spNode->GetObject(&spUnk);
if(SUCCEEDED(hr) && spUnk != NULL)
{
spUnk->QueryInterface(IID_IPropertyStore, (void**) &m_spNodePropertyStore);
}
}
spNode->QueryInterface(IID_IMFAttributes, (void**) &m_spNodeAttributes);
}
CNodePropertyInfo::~CNodePropertyInfo()
{
}
HRESULT CNodePropertyInfo::GetPropertyInfoName(__out LPWSTR* szName, __out TED_ATTRIBUTE_CATEGORY* pCategory)
{
CAtlString str(L"Node Attributes");
size_t AllocLen = (str.GetLength() + 1) * sizeof(WCHAR);
*szName = (LPWSTR) CoTaskMemAlloc(AllocLen);
if(NULL == *szName)
{
return E_OUTOFMEMORY;
}
wcscpy_s(*szName, str.GetLength() + 1, str.GetString());
*pCategory = TED_ATTRIBUTE_CATEGORY_TOPONODE;
return S_OK;
}
HRESULT CNodePropertyInfo::GetPropertyCount(DWORD* pdwCount)
{
HRESULT hr = S_OK;
if(NULL == pdwCount)
{
IFC(E_POINTER);
}
if(NULL != m_spNodeAttributes)
{
IFC( m_spNodeAttributes->GetCount((UINT32*) pdwCount) );
}
else if(NULL != m_spNodePropertyStore)
{
IFC( m_spNodePropertyStore->GetCount(pdwCount) );
}
else
{
*pdwCount = 0;
}
Cleanup:
return hr;
}
HRESULT CNodePropertyInfo::GetProperty(DWORD dwIndex, __out LPWSTR* strName, __out LPWSTR* strValue)
{
HRESULT hr = S_OK;
CAtlStringW strNameTemp, strValueTemp;
if(NULL == strName || NULL == strValue)
{
return E_POINTER;
}
*strName = NULL;
*strValue = NULL;
if(NULL != m_spNodeAttributes)
{
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spNodeAttributes->GetItemByIndex(dwIndex, &key, &propVal) );
ConvertKeyToString(key, strNameTemp);
ConvertPropertyValueToString(key, propVal, strValueTemp);
PropVariantClear(&propVal);
}
else if(NULL != m_spNodePropertyStore)
{
PROPERTYKEY propKey;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spNodePropertyStore->GetAt(dwIndex, &propKey) );
IFC( m_spNodePropertyStore->GetValue(propKey, &propVal) );
ConvertKeyToString(propKey.fmtid, strNameTemp);
ConvertPropertyValueToString(propKey.fmtid, propVal, strValueTemp);
PropVariantClear(&propVal);
}
else
{
hr = E_INVALIDARG;
}
*strName = (LPWSTR) CoTaskMemAlloc((strNameTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strName) IFC( E_OUTOFMEMORY );
wcscpy_s(*strName, strNameTemp.GetLength() + 1, strNameTemp.GetBuffer());
*strValue = (LPWSTR) CoTaskMemAlloc((strValueTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strValue) IFC( E_OUTOFMEMORY );
wcscpy_s(*strValue, strValueTemp.GetLength() + 1, strValueTemp.GetBuffer());
Cleanup:
if(FAILED(hr))
{
CoTaskMemFree(*strName);
CoTaskMemFree(*strValue);
}
return hr;
}
HRESULT CNodePropertyInfo::GetPropertyType(DWORD dwIndex, __out VARTYPE* vt)
{
HRESULT hr = S_OK;
if(NULL == vt)
{
IFC( E_POINTER );
}
if(NULL != m_spNodeAttributes)
{
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spNodeAttributes->GetItemByIndex(dwIndex, &key, &propVal) );
*vt = propVal.vt;
PropVariantClear(&propVal);
}
else if(NULL != m_spNodePropertyStore)
{
PROPERTYKEY propKey;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spNodePropertyStore->GetAt(dwIndex, &propKey) );
IFC( m_spNodePropertyStore->GetValue(propKey, &propVal) );
*vt = propVal.vt;
PropVariantClear(&propVal);
}
Cleanup:
return hr;
}
HRESULT CNodePropertyInfo::SetProperty(DWORD dwIndex, __in LPCWSTR strName, VARTYPE vt, __in LPCWSTR strValue)
{
HRESULT hr = S_OK;
PROPVARIANT propVal;
PropVariantInit(&propVal);
GUID key;
ConvertStringToKey(strName, key);
ConvertStringToPropertyValue(key, strValue, vt, propVal);
if(NULL != m_spNodeAttributes)
{
IFC( m_spNodeAttributes->SetItem(key, propVal) );
}
else
{
PROPERTYKEY propKey;
propKey.fmtid = key;
propKey.pid = PID_FIRST_USABLE;
IFC( m_spNodePropertyStore->SetValue(propKey, propVal) );
}
Cleanup:
PropVariantClear(&propVal);
return hr;
}
/*********************************\
* CConnectionPropertyInfo *
\ *********************************/
CConnectionPropertyInfo::CConnectionPropertyInfo(CComPtr<IMFMediaType> spUpstreamType, CComPtr<IMFMediaType> spDownstreamType)
: m_spUpstreamType(spUpstreamType)
, m_spDownstreamType(spDownstreamType)
{
}
CConnectionPropertyInfo::~CConnectionPropertyInfo()
{
}
HRESULT CConnectionPropertyInfo::GetPropertyInfoName(__out LPWSTR* szName, __out TED_ATTRIBUTE_CATEGORY* pCategory)
{
CAtlString str(L"Media Types");
size_t AllocLen = (str.GetLength() + 1) * sizeof(WCHAR);
*szName = (LPWSTR) CoTaskMemAlloc(AllocLen);
if(NULL == *szName)
{
return E_OUTOFMEMORY;
}
wcscpy_s(*szName, str.GetLength() + 1, str.GetString());
*pCategory = TED_ATTRIBUTE_CATEGORY_MEDIATYPE;
return S_OK;
}
HRESULT CConnectionPropertyInfo::GetPropertyCount(DWORD* pdwCount)
{
HRESULT hr = S_OK;
if(NULL == pdwCount)
{
return E_POINTER;
}
UINT32 unUpstreamCount;
UINT32 unDownstreamCount;
if(m_spUpstreamType)
{
IFC( m_spUpstreamType->GetCount(&unUpstreamCount) );
}
else
{
unUpstreamCount = 1;
}
if(m_spDownstreamType)
{
IFC( m_spDownstreamType->GetCount(&unDownstreamCount) );
}
else
{
unDownstreamCount = 1;
}
*pdwCount = DWORD( unUpstreamCount + unDownstreamCount + 3);
Cleanup:
return hr;
}
HRESULT CConnectionPropertyInfo::GetProperty(DWORD dwIndex, __out LPWSTR* strName, __out LPWSTR* strValue)
{
HRESULT hr = S_OK;
if(NULL == strName || NULL == strValue)
{
return E_POINTER;
}
UINT32 unUpstreamCount;
CAtlStringW strNameTemp, strValueTemp;
*strName = NULL;
*strValue = NULL;
if(m_spUpstreamType)
{
IFC( m_spUpstreamType->GetCount(&unUpstreamCount) );
}
else
{
unUpstreamCount = 1;
}
if(unUpstreamCount + 1 > dwIndex)
{
if(0 == dwIndex)
{
strNameTemp = L"Upstream Media Type";
}
else
{
if(!m_spUpstreamType)
{
strNameTemp = L"None";
}
else
{
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spUpstreamType->GetItemByIndex(dwIndex - 1, &key, &propVal) );
ConvertKeyToString(key, strNameTemp);
ConvertPropertyValueToString(key, propVal, strValueTemp);
PropVariantClear(&propVal);
}
}
}
else if(unUpstreamCount + 1 == dwIndex)
{
strNameTemp = L"";
}
else if(unUpstreamCount + 2 == dwIndex)
{
strNameTemp = L"Downstream Media Type";
}
else
{
if(!m_spDownstreamType)
{
strNameTemp = L"None";
}
else
{
DWORD realIndex = dwIndex - unUpstreamCount - 3;
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spDownstreamType->GetItemByIndex(realIndex, &key, &propVal) );
ConvertKeyToString(key, strNameTemp);
ConvertPropertyValueToString(key, propVal, strValueTemp);
PropVariantClear(&propVal);
}
}
*strName = (LPWSTR) CoTaskMemAlloc((strNameTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strName) IFC( E_OUTOFMEMORY );
wcscpy_s(*strName, strNameTemp.GetLength() + 1, strNameTemp.GetBuffer());
*strValue = (LPWSTR) CoTaskMemAlloc((strValueTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strValue) IFC( E_OUTOFMEMORY );
wcscpy_s(*strValue, strValueTemp.GetLength() + 1, strValueTemp.GetBuffer());
Cleanup:
if(FAILED(hr))
{
CoTaskMemFree(*strName);
CoTaskMemFree(*strValue);
}
return hr;
}
HRESULT CConnectionPropertyInfo::GetPropertyType(DWORD dwIndex, __out VARTYPE* vt)
{
HRESULT hr = S_OK;
UINT32 unUpstreamCount;
if(NULL == vt)
{
IFC( E_POINTER );
}
if(m_spUpstreamType)
{
IFC( m_spUpstreamType->GetCount(&unUpstreamCount) );
}
else
{
unUpstreamCount = 1;
}
if(unUpstreamCount + 1 > dwIndex)
{
if(0 == dwIndex)
{
*vt = VT_EMPTY;
}
else
{
if(!m_spUpstreamType)
{
*vt = VT_EMPTY;
}
else
{
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spUpstreamType->GetItemByIndex(dwIndex - 1, &key, &propVal) );
*vt = propVal.vt;
PropVariantClear(&propVal);
}
}
}
else if(unUpstreamCount + 1 == dwIndex)
{
*vt = VT_EMPTY;
}
else if(unUpstreamCount + 2 == dwIndex)
{
*vt = VT_EMPTY;
}
else
{
if(!m_spDownstreamType)
{
*vt = VT_EMPTY;
}
else
{
DWORD realIndex = dwIndex - unUpstreamCount - 3;
GUID key;
PROPVARIANT propVal;
PropVariantInit(&propVal);
IFC( m_spDownstreamType->GetItemByIndex(realIndex, &key, &propVal) );
*vt = propVal.vt;
PropVariantClear(&propVal);
}
}
Cleanup:
return hr;
}
HRESULT CConnectionPropertyInfo::SetProperty(DWORD dwIndex, __in LPCWSTR strName, VARTYPE vt, __in LPCWSTR strValue)
{
HRESULT hr = S_OK;
UINT32 unUpstreamCount;
PROPVARIANT propVal;
PropVariantInit(&propVal);
GUID key;
ConvertStringToKey(strName, key);
ConvertStringToPropertyValue(key, strValue, vt, propVal);
IFC( m_spUpstreamType->GetCount(&unUpstreamCount) );
if(dwIndex <= unUpstreamCount + 1)
{
IFC( m_spUpstreamType->SetItem(key, propVal) );
}
else
{
IFC( m_spDownstreamType->SetItem(key, propVal) );
}
Cleanup:
PropVariantClear(&propVal);
return hr;
}
/*********************************\
* CAttributesPropertyInfo *
\ *********************************/
CAttributesPropertyInfo::CAttributesPropertyInfo(CComPtr<IMFAttributes> spAttributes, CAtlString strName, TED_ATTRIBUTE_CATEGORY Category)
: m_spAttributes(spAttributes)
, m_strName(strName)
, m_Category(Category)
{
}
CAttributesPropertyInfo::~CAttributesPropertyInfo()
{
}
HRESULT CAttributesPropertyInfo::GetPropertyInfoName(__out LPWSTR* szName, __out TED_ATTRIBUTE_CATEGORY* pCategory)
{
size_t AllocLen = (m_strName.GetLength() + 1) * sizeof(WCHAR);
*szName = (LPWSTR) CoTaskMemAlloc(AllocLen);
if(NULL == *szName)
{
return E_OUTOFMEMORY;
}
wcscpy_s(*szName, m_strName.GetLength() + 1, m_strName.GetString());
*pCategory = m_Category;
return S_OK;
}
HRESULT CAttributesPropertyInfo::GetPropertyCount(DWORD* pdwCount)
{
HRESULT hr = S_OK;
if(NULL == pdwCount)
{
return E_POINTER;
}
IFC( m_spAttributes->GetCount((UINT32*) pdwCount) );
Cleanup:
return hr;
}
HRESULT CAttributesPropertyInfo::GetProperty(DWORD dwIndex, __out LPWSTR* strName, __out LPWSTR* strValue)
{
HRESULT hr = S_OK;
CAtlStringW strNameTemp, strValueTemp;
GUID key;
PROPVARIANT var;
PropVariantInit(&var);
*strName = NULL;
*strValue = NULL;
IFC( m_spAttributes->GetItemByIndex(dwIndex, &key, &var) );
ConvertKeyToString(key, strNameTemp);
ConvertPropertyValueToString(key, var, strValueTemp);
*strName = (LPWSTR) CoTaskMemAlloc((strNameTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strName) IFC( E_OUTOFMEMORY );
wcscpy_s(*strName, strNameTemp.GetLength() + 1, strNameTemp.GetBuffer());
*strValue = (LPWSTR) CoTaskMemAlloc((strValueTemp.GetLength() + 1) * sizeof(WCHAR));
if(!*strValue) IFC( E_OUTOFMEMORY );
wcscpy_s(*strValue, strValueTemp.GetLength() + 1, strValueTemp.GetBuffer());
Cleanup:
if(FAILED(hr))
{
CoTaskMemFree(*strName);
CoTaskMemFree(*strValue);
}
PropVariantClear(&var);
return hr;
}
HRESULT CAttributesPropertyInfo::GetPropertyType(DWORD dwIndex, __out VARTYPE* vt)
{
HRESULT hr = S_OK;
if(NULL == vt)
{
return E_POINTER;
}
GUID key;
PROPVARIANT var;
PropVariantInit(&var);
IFC( m_spAttributes->GetItemByIndex(dwIndex, &key, &var) );
*vt = var.vt;
Cleanup:
PropVariantClear(&var);
return hr;
}
HRESULT CAttributesPropertyInfo::SetProperty(DWORD dwIndex, __in LPCWSTR strName, VARTYPE vt, __in LPCWSTR strValue)
{
HRESULT hr = S_OK;
GUID key;
PROPVARIANT var;
PropVariantInit(&var);
ConvertStringToKey(strName, key);
ConvertStringToPropertyValue(key, strValue, vt, var);
IFC( m_spAttributes->SetItem(key, var) );
Cleanup:
PropVariantClear(&var);
return hr;
}
/*********************************\
* COTAPropertyInfo *
\ *********************************/
COTAPropertyInfo::COTAPropertyInfo(CComPtr<IMFOutputTrustAuthority>* arrOTA, DWORD cOTACount)
: m_arrOTA(arrOTA)
, m_cOTACount(cOTACount)
{
}
COTAPropertyInfo::~COTAPropertyInfo()
{
delete[] m_arrOTA;
}
HRESULT COTAPropertyInfo::GetPropertyInfoName(__out LPWSTR* szName, __out TED_ATTRIBUTE_CATEGORY* pCategory)
{
CAtlString str(L"OTA Attributes");
size_t AllocLen = (str.GetLength() + 1) * sizeof(WCHAR);
*szName = (LPWSTR) CoTaskMemAlloc(AllocLen);
if(NULL == *szName)
{
return E_OUTOFMEMORY;
}
wcscpy_s(*szName, str.GetLength() + 1, str.GetString());
*pCategory = TED_ATTRIBUTE_CATEGORY_OTA;
return S_OK;
}
HRESULT COTAPropertyInfo::GetPropertyCount(DWORD* pdwCount)
{
if(NULL == pdwCount)
{
return E_POINTER;
}
*pdwCount = m_cOTACount + 1;
return S_OK;
}
HRESULT COTAPropertyInfo::GetProperty(DWORD dwIndex, __out LPWSTR* strName, __out LPWSTR* strValue)
{
HRESULT hr = S_OK;
if(NULL == strName || NULL == strValue)
{
return E_POINTER;
}
if(m_cOTACount + 1 <= dwIndex)
{
return E_INVALIDARG;
}
*strName = NULL;
*strValue = NULL;
if(0 == dwIndex)
{
*strName = (LPWSTR) CoTaskMemAlloc(25 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 25, L"Output Trust Authorities");
}
else
{
MFPOLICYMANAGER_ACTION action;
IFC( m_arrOTA[dwIndex - 1]->GetAction(&action) );
switch(action)
{
case PEACTION_NO:
*strName = (LPWSTR) CoTaskMemAlloc(12 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 12, L"PEACTION_NO");
break;
case PEACTION_PLAY:
*strName = (LPWSTR) CoTaskMemAlloc(14 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 14, L"PEACTION_PLAY");
break;
case PEACTION_COPY:
*strName = (LPWSTR) CoTaskMemAlloc(14 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 14, L"PEACTION_COPY");
break;
case PEACTION_EXPORT:
*strName = (LPWSTR) CoTaskMemAlloc(16 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 16, L"PEACTION_EXPORT");
break;
case PEACTION_EXTRACT:
*strName = (LPWSTR) CoTaskMemAlloc(17 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 17, L"PEACTION_EXTRACT");
break;
case PEACTION_LAST:
*strName = (LPWSTR) CoTaskMemAlloc(14 * sizeof(WCHAR));
CHECK_ALLOC(*strName);
wcscpy_s(*strName, 14, L"PEACTION_LAST");
break;
}
}
*strValue = (LPWSTR) CoTaskMemAlloc(1 * sizeof(WCHAR) );
CHECK_ALLOC(*strValue);
*strValue[0] = 0;
Cleanup:
if(FAILED(hr))
{
CoTaskMemFree(*strName);
CoTaskMemFree(*strValue);
}
return hr;
}
HRESULT COTAPropertyInfo::GetPropertyType(DWORD dwIndex, __out VARTYPE* vt)
{
if(NULL == vt)
{
return E_POINTER;
}
if(m_cOTACount + 1 <= dwIndex)
{
return E_INVALIDARG;
}
*vt = VT_EMPTY;
return S_OK;
}
HRESULT COTAPropertyInfo::SetProperty(DWORD dwIndex, __in LPCWSTR strName, VARTYPE vt, __in LPCWSTR strValue)
{
return E_NOTIMPL;
}
| 35.584593
| 172
| 0.638194
|
windows-development
|
dce698bc29562a04b19df7cb68f758544c555697
| 371
|
cpp
|
C++
|
C++/First Steps in Coding - Basics of C++/While Loops/Max Number.cpp
|
EduardV777/Softuni-Python-Exercises
|
79db667028aea7dfecb3dbbd834c752180c50f44
|
[
"Unlicense"
] | null | null | null |
C++/First Steps in Coding - Basics of C++/While Loops/Max Number.cpp
|
EduardV777/Softuni-Python-Exercises
|
79db667028aea7dfecb3dbbd834c752180c50f44
|
[
"Unlicense"
] | null | null | null |
C++/First Steps in Coding - Basics of C++/While Loops/Max Number.cpp
|
EduardV777/Softuni-Python-Exercises
|
79db667028aea7dfecb3dbbd834c752180c50f44
|
[
"Unlicense"
] | null | null | null |
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
int maxNum, k=0;
while (true) {
string currNum;
cin >> currNum;
if (currNum=="Stop"){
cout << maxNum;
break;
}
else {
int number = stoi(currNum);
if (k == 0) {
maxNum = number;
k++;
}
if (maxNum < number) {
maxNum = number;
}
}
}
}
| 14.269231
| 30
| 0.549865
|
EduardV777
|
dce6f145b7343fc30d6edb7f743b3ae53efc872a
| 21,745
|
hpp
|
C++
|
viennadata/storage.hpp
|
viennadata/viennadata-dev
|
4c64fa8e131dcc6d2574b5b9456d8c8d4456b1aa
|
[
"MIT"
] | 1
|
2015-09-13T03:51:41.000Z
|
2015-09-13T03:51:41.000Z
|
viennadata/storage.hpp
|
viennadata/viennadata-dev
|
4c64fa8e131dcc6d2574b5b9456d8c8d4456b1aa
|
[
"MIT"
] | null | null | null |
viennadata/storage.hpp
|
viennadata/viennadata-dev
|
4c64fa8e131dcc6d2574b5b9456d8c8d4456b1aa
|
[
"MIT"
] | null | null | null |
#ifndef VIENNADATA_STORAGE_HPP
#define VIENNADATA_STORAGE_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaData - The Vienna Data Library
-----------------
Authors: Florian Rudolf rudolf@iue.tuwien.ac.at
Karl Rupp rupp@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <map>
#include "viennadata/forwards.hpp"
#include "viennadata/container_map.hpp"
namespace viennadata
{
/** @brief The central storage class. Can be configured with container configuration and runtime type information
*
* Holds a std::map<runtime_key_type, container_map_base> which maps the combination <element_type/tag, key_type, value_type> to the container_map
* Additionally holds three maps for <element_type>, <element_type, key_type>, <element_type, value_type> for supporting operation on more than one data value
* (e.g. erase<all, all>(element))
*
* @tparam cont
*/
template<typename WrappedContainerConfig /* see forwards.hpp for default argument */,
typename RuntimeTypeInformation /* see forwards.hpp for default argument */>
class storage
{
public:
typedef RuntimeTypeInformation runtime_type_information;
typedef typename WrappedContainerConfig::type container_config;
typedef typename RuntimeTypeInformation::runtime_key_type runtime_key_type;
typedef std::map<runtime_key_type, container_map_base*> container_map_map_type;
typedef std::map<runtime_key_type, std::vector<base_dynamic_container_map_accessor*> > dynamic_key_to_container_accessor_map;
storage() {}
storage(runtime_type_information const & rtti_) : rtti(rtti_) {}
/** @brief Resets the storage, takes care of dynamically allocated objects */
void clear()
{
for (typename container_map_map_type::iterator it = container_maps.begin();
it != container_maps.end();
++it)
delete it->second;
// only one out of
// element_type_to_container_map_accessor_map,
// element_and_key_type_to_container_map_accessor_map, or
// element_and_value_type_to_container_map_accessor_map
// has to be deleted
for (typename dynamic_key_to_container_accessor_map::iterator it = element_type_to_container_map_accessor_map.begin();
it != element_type_to_container_map_accessor_map.end();
++it)
{
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin();
jt != it->second.end();
++jt)
delete *jt;
}
container_maps.clear();
element_type_to_container_map_accessor_map.clear();
element_and_key_type_to_container_map_accessor_map.clear();
element_and_value_type_to_container_map_accessor_map.clear();
}
~storage() { clear(); }
private:
/** @brief Base method for querying a container map based on a combination of <key_type, value_type, element_type/tag>
*
* Method is const but maps are all mutable
* if container_map is not available it is created
* maps for <element_tag>, <element_tag, key_type>, <element_tag, value_type> are updated
*/
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
container_map<
KeyType,
typename result_of::container_from_config<
container_config,
viennameta::static_pair<typename result_of::element_tag<ElementTypeOrTag>::type,
viennameta::static_pair<KeyType, ValueType> >
>::type,
typename result_of::access_tag_from_config<
container_config,
viennameta::static_pair<typename result_of::element_tag<ElementTypeOrTag>::type,
viennameta::static_pair<KeyType, ValueType> >
>::type
> &
get_container_map_impl() const
{
typedef typename result_of::element_tag<ElementTypeOrTag>::type element_tag;
typedef viennameta::static_pair<element_tag, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
typedef container_map<KeyType, container_type, access_tag> container_map_type;
runtime_key_type runtime_key = rtti.template key< static_key_type >();
typename container_map_map_type::iterator it = container_maps.find(runtime_key);
if (it == container_maps.end())
{
container_map_type * container_map = new container_map_type();
container_maps.insert(std::make_pair(runtime_key, static_cast<container_map_base*>(container_map)));
base_dynamic_container_map_accessor * container_map_accessor =
new dynamic_container_map_accessor<container_map_type, element_tag>(*container_map);
element_type_to_container_map_accessor_map[rtti.template key<element_tag>()].
push_back(container_map_accessor);
element_and_key_type_to_container_map_accessor_map[rtti.template key< viennameta::static_pair<element_tag, KeyType> >()].
push_back(container_map_accessor);
element_and_value_type_to_container_map_accessor_map[rtti.template key< viennameta::static_pair<element_tag, ValueType> >()].
push_back(container_map_accessor);
return *container_map;
}
else
return *static_cast<container_map_type*>(it->second);
}
/** @brief Query a container by using a key and get_container_map
*
* Method is const but maps are all mutable
*/
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
typename result_of::container_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type &
get_container_impl(KeyType const & key) const
{
return get_container_map_impl<KeyType, ValueType, ElementTypeOrTag>().get(key);
}
public:
/** @brief get_container_map public interface, using private implementation */
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
container_map<
KeyType,
typename result_of::container_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type,
typename result_of::access_tag_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type
> &
get_container_map()
{
return get_container_map_impl<KeyType, ValueType, ElementTypeOrTag>();
}
/** @brief get_container_map public interface, using private implementation; const version -> returning const reference */
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
container_map<
KeyType,
typename result_of::container_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type,
typename result_of::access_tag_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type
> const &
get_container_map() const
{
return get_container_map_impl<KeyType, ValueType, ElementTypeOrTag>();
}
/** @brief get_container public interface, using private implementation */
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
typename result_of::container_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type &
get_container(KeyType const & key)
{
return get_container_impl<KeyType, ValueType, ElementTypeOrTag>(key);
}
/** @brief get_container public interface, using private implementation; const version -> returning const reference */
template<typename KeyType, typename ValueType, typename ElementTypeOrTag>
typename result_of::container_from_config<
container_config,
viennameta::static_pair<ElementTypeOrTag, viennameta::static_pair<KeyType, ValueType> >
>::type const &
get_container(KeyType const & key) const
{
return get_container_impl<KeyType, ValueType, ElementTypeOrTag>(key);
}
/** @brief Returns value for <key_type, value_type, element_type> with specific key and element */
template<typename KeyType, typename ValueType, typename ElementType>
ValueType & lookup(KeyType const & key, ElementType const & element)
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
return container_access<container_type, ElementType, access_tag>::lookup(
get_container_map<KeyType, ValueType, ElementType>().get(key), element);
}
/** @brief Returns value for <key_type, value_type, element_type> with specific key and element; const version */
template<typename KeyType, typename ValueType, typename ElementType>
ValueType const & lookup(KeyType const & key, ElementType const & element) const
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
return container_access<container_type, ElementType, access_tag>::lookup(
get_container_map<KeyType, ValueType, ElementType>().get(key), element);
}
/** @brief Query the availability of a value for <key_type, value_type, element_type> with specific key and element; returns NULL if not found */
template<typename KeyType, typename ValueType, typename ElementType>
ValueType * find(KeyType const & key, ElementType const & element)
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
return container_access<container_type, ElementType, access_tag>::find(
get_container_map<KeyType, ValueType, ElementType>().get(key), element);
}
/** @brief Query the availability of a value for <key_type, value_type, element_type> with specific key and element; returns NULL if not found; const version */
template<typename KeyType, typename ValueType, typename ElementType>
ValueType const * find(KeyType const & key, ElementType const & element) const
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
return container_access<container_type, ElementType, access_tag>::find(
get_container_map<KeyType, ValueType, ElementType>().get(key), element);
}
/** @brief Erases the value for <key_type, value_type, element_type> with specific key and element */
template<typename KeyType, typename ValueType, typename ElementType>
void erase(KeyType const & key, ElementType const & element)
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
container_access<container_type, ElementType, access_tag>::erase(
get_container_map<KeyType, ValueType, ElementType>().get(key), element);
}
/** @brief Erases all values the specific element */
template<typename ElementType>
void erase_all_data_from_element(ElementType const & element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_type_to_container_map_accessor_map.find(rtti.template key<ElementType>());
if (it == element_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_element(element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->erase_all(dynamic_element);
}
/** @brief Erases all values for specific element with a specific key_type */
template<typename KeyType, typename ElementType>
void erase_all_data_from_element_with_key(ElementType const & element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_key_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType,KeyType> >());
if (it == element_and_key_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_element(element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->erase_all(dynamic_element);
}
/** @brief Erases all values for specific element with a specific key_type and key */
template<typename KeyType, typename ElementType>
void erase_all_data_from_element_with_key(KeyType const & key, ElementType const & element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_key_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType,KeyType> >());
if (it == element_and_key_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_element(element);
dynamic_type_wrapper<KeyType> dynamic_key(key);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->erase(dynamic_key, dynamic_element);
}
/** @brief erases all values for specific element with a specific value_type */
template<typename ValueType, typename ElementType>
void erase_all_data_from_element_with_value_type(ElementType const & element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_value_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType, ValueType> >());
if (it == element_and_value_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_element(element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->erase_all(dynamic_element);
}
/** @brief copy value for <key_type, value_type, element_type> with specific key and element to another element */
template<typename KeyType, typename ValueType, typename ElementType>
void copy(KeyType const & key, ElementType const & src_element, ElementType const & dst_element)
{
typedef viennameta::static_pair<ElementType, viennameta::static_pair<KeyType, ValueType> > static_key_type;
typedef typename result_of::container_from_config< container_config, static_key_type >::type container_type;
typedef typename result_of::access_tag_from_config< container_config, static_key_type >::type access_tag;
return container_access<container_type, ElementType, access_tag>::copy(
get_container_map<KeyType, ValueType, ElementType>().get(key), src_element, dst_element);
}
/** @brief copy all values the specific element to another element */
template<typename ElementType>
void copy_all_data_from_element(ElementType const & src_element, ElementType const & dst_element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_type_to_container_map_accessor_map.find(rtti.template key<ElementType>());
if (it == element_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_src_element(src_element);
dynamic_type_wrapper<ElementType> dynamic_dst_element(dst_element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->copy_all(dynamic_src_element, dynamic_dst_element);
}
/** @brief copy all values for specific element with a specific key_type to another element */
template<typename KeyType, typename ElementType>
void copy_all_data_from_element_with_key(ElementType const & src_element, ElementType const & dst_element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_key_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType,KeyType> >());
if (it == element_and_key_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_src_element(src_element);
dynamic_type_wrapper<ElementType> dynamic_dst_element(dst_element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->copy_all(dynamic_src_element, dynamic_dst_element);
}
/** @brief copy all values for specific element with a specific key_type and key to another element */
template<typename KeyType, typename ElementType>
void copy_all_data_from_element_with_key(KeyType const & key, ElementType const & src_element, ElementType const & dst_element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_key_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType,KeyType> >());
if (it == element_and_key_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_src_element(src_element);
dynamic_type_wrapper<ElementType> dynamic_dst_element(dst_element);
dynamic_type_wrapper<KeyType> dynamic_key(key);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->copy(dynamic_key, dynamic_src_element, dynamic_dst_element);
}
/** @brief erases all values for specific element with a specific value_type */
template<typename ValueType, typename ElementType>
void copy_all_data_from_element_with_value_type(ElementType const & src_element, ElementType const & dst_element)
{
typename dynamic_key_to_container_accessor_map::iterator it =
element_and_value_type_to_container_map_accessor_map.find(rtti.template key< viennameta::static_pair<ElementType, ValueType> >());
if (it == element_and_value_type_to_container_map_accessor_map.end()) return;
dynamic_type_wrapper<ElementType> dynamic_src_element(src_element);
dynamic_type_wrapper<ElementType> dynamic_dst_element(dst_element);
for (std::vector<base_dynamic_container_map_accessor*>::iterator jt = it->second.begin(); jt != it->second.end(); ++jt)
(*jt)->copy_all(dynamic_src_element, dynamic_dst_element);
}
private:
runtime_type_information rtti;
mutable container_map_map_type container_maps;
mutable dynamic_key_to_container_accessor_map element_type_to_container_map_accessor_map;
mutable dynamic_key_to_container_accessor_map element_and_key_type_to_container_map_accessor_map;
mutable dynamic_key_to_container_accessor_map element_and_value_type_to_container_map_accessor_map;
};
} // namespace viennadata
#endif
| 50.925059
| 164
| 0.699333
|
viennadata
|
dce6f68eda4cb1f4187d74f94f049975a08e1050
| 518
|
cpp
|
C++
|
DirectUI/Dispatcher.cpp
|
oven425/DirectUI
|
00bc0f018a045cbe1709e893ed10a37e2fe1e4e4
|
[
"MIT"
] | 2
|
2021-01-14T00:54:58.000Z
|
2021-01-14T00:55:01.000Z
|
DirectUI/Dispatcher.cpp
|
oven425/DirectUI
|
00bc0f018a045cbe1709e893ed10a37e2fe1e4e4
|
[
"MIT"
] | null | null | null |
DirectUI/Dispatcher.cpp
|
oven425/DirectUI
|
00bc0f018a045cbe1709e893ed10a37e2fe1e4e4
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Dispatcher.h"
using namespace DirectUI;
using namespace Threading;
Dispatcher::Dispatcher()
{
//this->m_hTimerQueue = ::CreateTimerQueue();
//::CreateTimerQueueTimer(&this->m_hTimeUI, this->m_hTimerQueue, &Dispatcher::UITimer, this, 10000, 0, 0);
this->m_Pool = thread(&Dispatcher::Polling, this);
}
void Dispatcher::Polling()
{
while (true)
{
this_thread::sleep_for(chrono::milliseconds(1));
}
}
//void Dispatcher::UITimer(PVOID lpParam, BOOLEAN TimerOrWaitFired)
//{
//
//}
| 19.185185
| 107
| 0.710425
|
oven425
|
dce8c11b63f254f1c21fdf6289ab97f4a0d67afa
| 10,522
|
cpp
|
C++
|
examples/49_SimpleTessellation/SimpleTessellationDemo.cpp
|
zsb534923374/VulkanDemos
|
3bda2a8f29cfb69ffdb1bed5a53ffa1c4a2c1dc5
|
[
"MIT"
] | 1
|
2019-10-12T15:07:38.000Z
|
2019-10-12T15:07:38.000Z
|
examples/49_SimpleTessellation/SimpleTessellationDemo.cpp
|
Guangehhhh/VulkanDemos
|
d3b9cc113aa3657689a0e7828892fb754f73361f
|
[
"MIT"
] | null | null | null |
examples/49_SimpleTessellation/SimpleTessellationDemo.cpp
|
Guangehhhh/VulkanDemos
|
d3b9cc113aa3657689a0e7828892fb754f73361f
|
[
"MIT"
] | null | null | null |
#include "Common/Common.h"
#include "Common/Log.h"
#include "Demo/DVKCommon.h"
#include "Math/Vector4.h"
#include "Math/Matrix4x4.h"
#include <vector>
class SimpleTessellationDemo : public DemoBase
{
public:
SimpleTessellationDemo(int32 width, int32 height, const char* title, const std::vector<std::string>& cmdLine)
: DemoBase(width, height, title, cmdLine)
{
}
virtual ~SimpleTessellationDemo()
{
}
virtual bool PreInit() override
{
return true;
}
virtual bool Init() override
{
DemoBase::Setup();
DemoBase::Prepare();
CreateGUI();
InitParmas();
LoadAssets();
m_Ready = true;
return true;
}
virtual void Exist() override
{
DemoBase::Release();
DestroyAssets();
DestroyGUI();
}
virtual void Loop(float time, float delta) override
{
if (!m_Ready) {
return;
}
Draw(time, delta);
}
private:
struct ModelViewProjectionBlock
{
Matrix4x4 model;
Matrix4x4 view;
Matrix4x4 proj;
};
struct TessParamBlock
{
Vector4 levelOuter;
Vector4 levelInner;
};
void Draw(float time, float delta)
{
int32 bufferIndex = DemoBase::AcquireBackbufferIndex();
UpdateFPS(time, delta);
bool hovered = UpdateUI(time, delta);
if (!hovered) {
m_ViewCamera.Update(time, delta);
}
SetupCommandBuffers(bufferIndex);
DemoBase::Present(bufferIndex);
}
bool UpdateUI(float time, float delta)
{
m_GUI->StartFrame();
{
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(0, 0), ImGuiSetCond_FirstUseEver);
ImGui::Begin("SimpleTessellationDemo", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
float level = m_VulkanDevice->GetLimits().maxTessellationGenerationLevel;
ImGui::Separator();
ImGui::SliderFloat2("LevelInner:", (float*)&(m_TessParam.levelInner), 0.0f, level);
ImGui::Separator();
ImGui::SliderFloat4("LevelOuter:", (float*)&(m_TessParam.levelOuter), 0.0f, level);
ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / m_LastFPS, m_LastFPS);
ImGui::End();
}
bool hovered = ImGui::IsAnyWindowHovered() || ImGui::IsAnyItemHovered() || ImGui::IsRootWindowOrAnyChildHovered();
m_GUI->EndFrame();
m_GUI->Update();
return hovered;
}
void LoadAssets()
{
vk_demo::DVKCommandBuffer* cmdBuffer = vk_demo::DVKCommandBuffer::Create(m_VulkanDevice, m_CommandPool);
m_PatchTriangle = vk_demo::DVKModel::Create(
m_VulkanDevice,
cmdBuffer,
{
-10, 10, 0.0f,
10, 10, 0.0f,
10, -10, 0.0f,
-10, -10, 0.0f
},
{ 0, 1, 2, 0, 2, 3 },
{ VertexAttribute::VA_Position }
);
m_PatchQuat = vk_demo::DVKModel::Create(
m_VulkanDevice,
cmdBuffer,
{
-10, 10, 0.0f,
10, 10, 0.0f,
10, -10, 0.0f,
-10, -10, 0.0f
},
{ 0, 1, 2, 3 },
{ VertexAttribute::VA_Position }
);
m_PatchIso = vk_demo::DVKModel::Create(
m_VulkanDevice,
cmdBuffer,
{
-10, 10, 0.0f,
10, 10, 0.0f,
10, -10, 0.0f,
-10, -10, 0.0f
},
{ 0, 1, 2, 3 },
{ VertexAttribute::VA_Position }
);
m_ShaderTri = vk_demo::DVKShader::Create(
m_VulkanDevice,
true,
"assets/shaders/49_SimpleTessellation/Simple.vert.spv",
"assets/shaders/49_SimpleTessellation/Simple.frag.spv",
nullptr,
nullptr,
"assets/shaders/49_SimpleTessellation/SimpleTri.tesc.spv",
"assets/shaders/49_SimpleTessellation/SimpleTri.tese.spv"
);
m_MaterialTri = vk_demo::DVKMaterial::Create(
m_VulkanDevice,
m_RenderPass,
m_PipelineCache,
m_ShaderTri
);
m_MaterialTri->pipelineInfo.rasterizationState.cullMode = VK_CULL_MODE_NONE;
m_MaterialTri->pipelineInfo.rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
m_MaterialTri->pipelineInfo.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
m_MaterialTri->pipelineInfo.tessellationState.patchControlPoints = 3;
m_MaterialTri->PreparePipeline();
m_ShaderQuad = vk_demo::DVKShader::Create(
m_VulkanDevice,
true,
"assets/shaders/49_SimpleTessellation/Simple.vert.spv",
"assets/shaders/49_SimpleTessellation/Simple.frag.spv",
nullptr,
nullptr,
"assets/shaders/49_SimpleTessellation/SimpleQuad.tesc.spv",
"assets/shaders/49_SimpleTessellation/SimpleQuad.tese.spv"
);
m_MaterialQuat = vk_demo::DVKMaterial::Create(
m_VulkanDevice,
m_RenderPass,
m_PipelineCache,
m_ShaderQuad
);
m_MaterialQuat->pipelineInfo.rasterizationState.cullMode = VK_CULL_MODE_NONE;
m_MaterialQuat->pipelineInfo.rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
m_MaterialQuat->pipelineInfo.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
m_MaterialQuat->pipelineInfo.tessellationState.patchControlPoints = 4;
m_MaterialQuat->PreparePipeline();
m_ShaderIso = vk_demo::DVKShader::Create(
m_VulkanDevice,
true,
"assets/shaders/49_SimpleTessellation/Simple.vert.spv",
"assets/shaders/49_SimpleTessellation/Simple.frag.spv",
nullptr,
nullptr,
"assets/shaders/49_SimpleTessellation/SimpleIso.tesc.spv",
"assets/shaders/49_SimpleTessellation/SimpleIso.tese.spv"
);
m_MaterialIso = vk_demo::DVKMaterial::Create(
m_VulkanDevice,
m_RenderPass,
m_PipelineCache,
m_ShaderIso
);
m_MaterialIso->pipelineInfo.rasterizationState.cullMode = VK_CULL_MODE_NONE;
m_MaterialIso->pipelineInfo.rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
m_MaterialIso->pipelineInfo.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
m_MaterialIso->pipelineInfo.tessellationState.patchControlPoints = 2;
m_MaterialIso->PreparePipeline();
delete cmdBuffer;
}
void DestroyAssets()
{
delete m_PatchTriangle;
delete m_PatchQuat;
delete m_PatchIso;
delete m_ShaderTri;
delete m_ShaderQuad;
delete m_ShaderIso;
delete m_MaterialTri;
delete m_MaterialQuat;
delete m_MaterialIso;
}
void DrawModel(VkCommandBuffer commandBuffer, vk_demo::DVKModel* model, vk_demo::DVKMaterial* material)
{
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipeline());
material->BeginFrame();
for (int32 i = 0; i < model->meshes.size(); ++i)
{
m_MVPParam.model = model->meshes[i]->linkNode->GetGlobalMatrix();
m_MVPParam.view = m_ViewCamera.GetView();
m_MVPParam.proj = m_ViewCamera.GetProjection();
material->BeginObject();
material->SetLocalUniform("tessParam", &m_TessParam, sizeof(TessParamBlock));
material->SetLocalUniform("uboMVP", &m_MVPParam, sizeof(ModelViewProjectionBlock));
material->EndObject();
material->BindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, i);
model->meshes[i]->BindDrawCmd(commandBuffer);
}
material->EndFrame();
}
void SetupCommandBuffers(int32 backBufferIndex)
{
float hh = m_FrameHeight * 0.5f;
float hw = m_FrameWidth * 0.5f;
VkViewport viewport = {};
viewport.x = 0;
viewport.y = 0;
viewport.width = hw;
viewport.height = -(float)hh; // flip y axis
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.extent.width = hw;
scissor.extent.height = hh;
scissor.offset.x = 0;
scissor.offset.y = 0;
VkCommandBuffer commandBuffer = m_CommandBuffers[backBufferIndex];
VkCommandBufferBeginInfo cmdBeginInfo;
ZeroVulkanStruct(cmdBeginInfo, VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO);
VERIFYVULKANRESULT(vkBeginCommandBuffer(commandBuffer, &cmdBeginInfo));
VkClearValue clearValues[2];
clearValues[0].color = { { 0.2f, 0.2f, 0.2f, 1.0f } };
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBeginInfo;
ZeroVulkanStruct(renderPassBeginInfo, VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO);
renderPassBeginInfo.renderPass = m_RenderPass;
renderPassBeginInfo.framebuffer = m_FrameBuffers[backBufferIndex];
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = m_FrameWidth;
renderPassBeginInfo.renderArea.extent.height = m_FrameHeight;
vkCmdBeginRenderPass(commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
{
viewport.y = hh;
viewport.x = hw;
scissor.offset.x = hw;
scissor.offset.y = 0;
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
DrawModel(commandBuffer, m_PatchTriangle, m_MaterialTri);
}
{
viewport.y = hh + hh;
viewport.x = 0;
scissor.offset.x = 0;
scissor.offset.y = hh;
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
DrawModel(commandBuffer, m_PatchQuat, m_MaterialQuat);
}
{
viewport.y = hh + hh;
viewport.x = hw;
scissor.offset.x = hw;
scissor.offset.y = hh;
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
DrawModel(commandBuffer, m_PatchIso, m_MaterialIso);
}
m_GUI->BindDrawCmd(commandBuffer, m_RenderPass);
vkCmdEndRenderPass(commandBuffer);
VERIFYVULKANRESULT(vkEndCommandBuffer(commandBuffer));
}
void InitParmas()
{
m_TessParam.levelInner.Set(1, 1, 1, 1);
m_TessParam.levelOuter.Set(2, 2, 2, 2);
m_ViewCamera.SetPosition(0, 0, -50.0f);
m_ViewCamera.LookAt(0, 0, 0);
m_ViewCamera.Perspective(PI / 4, (float)GetWidth(), (float)GetHeight(), 1.0f, 1500.0f);
}
void CreateGUI()
{
m_GUI = new ImageGUIContext();
m_GUI->Init("assets/fonts/Ubuntu-Regular.ttf");
}
void DestroyGUI()
{
m_GUI->Destroy();
delete m_GUI;
}
private:
bool m_Ready = false;
vk_demo::DVKModel* m_PatchTriangle = nullptr;
vk_demo::DVKModel* m_PatchQuat = nullptr;
vk_demo::DVKModel* m_PatchIso = nullptr;
vk_demo::DVKShader* m_ShaderTri = nullptr;
vk_demo::DVKShader* m_ShaderQuad = nullptr;
vk_demo::DVKShader* m_ShaderIso = nullptr;
vk_demo::DVKMaterial* m_MaterialTri = nullptr;
vk_demo::DVKMaterial* m_MaterialQuat = nullptr;
vk_demo::DVKMaterial* m_MaterialIso = nullptr;
vk_demo::DVKCamera m_ViewCamera;
ModelViewProjectionBlock m_MVPParam;
TessParamBlock m_TessParam;
ImageGUIContext* m_GUI = nullptr;
};
std::shared_ptr<AppModuleBase> CreateAppMode(const std::vector<std::string>& cmdLine)
{
return std::make_shared<SimpleTessellationDemo>(1400, 900, "SimpleTessellationDemo", cmdLine);
}
| 26.370927
| 140
| 0.715358
|
zsb534923374
|
dceb2f7e8901d4355e71a2291388fac0b1ca53cd
| 30,141
|
cc
|
C++
|
util/makeMapSectioned.cc
|
MartinezTorres/Edelweiss
|
ef7eeaa1b8262e85f708c672fbb3310a6912be0c
|
[
"MIT"
] | 2
|
2021-01-20T13:12:31.000Z
|
2021-02-24T17:00:36.000Z
|
util/makeMapSectioned.cc
|
MartinezTorres/Edelweiss
|
ef7eeaa1b8262e85f708c672fbb3310a6912be0c
|
[
"MIT"
] | 1
|
2021-04-07T20:19:37.000Z
|
2021-04-07T20:19:37.000Z
|
util/makeMapSectioned.cc
|
MartinezTorres/Edelweiss
|
ef7eeaa1b8262e85f708c672fbb3310a6912be0c
|
[
"MIT"
] | 1
|
2021-02-24T17:00:43.000Z
|
2021-02-24T17:00:43.000Z
|
////////////////////////////////////////////////////////////////////////
// Build MSX1 palette
//
// Manuel Martinez (salutte@gmail.com)
//
// FLAGS: -std=gnu++14 -g `pkg-config opencv --cflags --libs` -Ofast -lpthread -fopenmp -lgomp -Wno-format-nonliteral
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#include <map>
#include <thread>
#include <chrono>
#include <functional>
using namespace std::chrono_literals;
struct Colorspace {
std::array<float, 256> TsRGB2lin;
std::array<uint8_t,4096> Tlin2sRGB;
Colorspace() {
for (size_t i=0; i<256; i++) {
double srgb = (i+0.5)/255.999;
double lin = 0;
if (srgb <= 0.0405) {
lin = srgb/12.92;
} else {
lin = std::pow((srgb+0.055)/(1.055),2.4);
}
TsRGB2lin[i]=lin;
}
for (size_t i=0; i<4096; i++) {
double lin = (i+0.5)/4095.999;
double srgb = 0;
if (lin <= 0.0031308) {
srgb = lin*12.92;
} else {
srgb = 1.055*std::pow(lin,1/2.4)-0.055;
}
Tlin2sRGB[i]=srgb*255.999999999;
}
}
cv::Vec3f sRGB2Lin(cv::Vec3b a) const {
return {
TsRGB2lin[a[0]],
TsRGB2lin[a[1]],
TsRGB2lin[a[2]]
};
}
cv::Vec3b lin2sRGB(cv::Vec3f a) const {
auto cap = [](float f){
int i = std::round(f*4095.999+0.5);
return std::min(std::max(i,0),4095);
};
return {
Tlin2sRGB[cap(a[0])],
Tlin2sRGB[cap(a[1])],
Tlin2sRGB[cap(a[2])],
};
}
cv::Mat3f sRGB2Lin(cv::Mat3b a) const {
cv::Mat3f ret(a.rows, a.cols);
for (int i=0; i<a.rows; i++)
for (int j=0; j<a.cols; j++)
ret(i,j) = sRGB2Lin(a(i,j));
return ret;
}
cv::Mat3b lin2sRGB(cv::Mat3f a) const {
cv::Mat3b ret(a.rows, a.cols);
for (int i=0; i<a.rows; i++)
for (int j=0; j<a.cols; j++)
ret(i,j) = lin2sRGB(a(i,j));
return ret;
}
static float Y(cv::Vec3b a) {
return a[0]*0.2126 + a[1]*0.7152 + a[2]*0.0722;
}
static float perceptualCompare(cv::Vec3b rgb1, cv::Vec3b rgb2) {
const int YR = 19595, YG = 38470, YB = 7471, CB_R = -11059, CB_G = -21709, CB_B = 32767, CR_R = 32767, CR_G = -27439, CR_B = -5329;
cv::Vec3b ycc1, ycc2;
{
const int r = rgb1[0], g = rgb1[1], b = rgb1[2];
ycc1[0] = (r * YR + g * YG + b * YB + 32767) >> 16;
ycc1[1] = 128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16);
ycc1[2] = 128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16);
}
{
const int r = rgb2[0], g = rgb2[1], b = rgb2[2];
ycc2[0] = (r * YR + g * YG + b * YB + 32767) >> 16;
ycc2[1] = 128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16);
ycc2[2] = 128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16);
}
float Ydiff = 1.f * std::pow(std::abs(ycc1[0]-ycc2[0]), 1);
float C1diff = 1.f * std::pow(std::abs(ycc1[1]-ycc2[1]), 1);
float C2diff = 1.f * std::pow(std::abs(ycc1[2]-ycc2[2]), 1);
return Ydiff + C1diff + C2diff;
}
static float perceptualDifference(cv::Vec3f rgb1_, cv::Vec3f rgb2_) {
auto f = [](cv::Vec3f c) {
cv::Vec3f yuv;
yuv[0] = 0.21*c[0]+0.72*c[1]+0.07*c[2];
yuv[1] = -0.10*c[0]-0.34*c[1]+0.46*c[2];
yuv[2] = 0.62*c[0]-0.56*c[1]-0.06*c[2];
return yuv;
};
cv::Vec3f yuv1 = f(rgb1_), yuv2 = f(rgb2_);
float Ydiff = 1.f * std::pow(std::abs(yuv1[0]-yuv2[0]), 1);
float Udiff = 1.f * std::pow(std::abs(yuv1[1]-yuv2[1]), 1);
float Vdiff = 1.f * std::pow(std::abs(yuv1[2]-yuv2[2]), 1);
return Ydiff + Udiff + Vdiff;
}
};
static Colorspace CS;
struct Tpalette {
std::map<std::string, std::vector<cv::Vec3b>> allColors = { // Note, those are RGB
{ "HW-MSX", {//https://paulwratt.github.io/programmers-palettes/HW-MSX/HW-MSX-palettes.html
{ 0, 0, 0}, // transparent
{ 1, 1, 1}, // black
{ 62, 184, 73}, // medium green
{ 116, 208, 125}, // light green
{ 89, 85, 224}, // dark blue
{ 128, 118, 241}, // light blue
{ 185, 94, 81}, // dark red
{ 101, 219, 239}, // cyan
{ 219, 101, 89}, // medium red
{ 255, 137, 125}, // light red
{ 204, 195, 94}, // dark yellow
{ 222, 208, 135}, // light yellow
{ 58, 162, 65}, // dark green
{ 183, 102, 181}, // magenta
{ 204, 204, 204}, // gray
{ 255, 255, 255} // white
} },
{ "Toshiba Palette", {
{ 0, 0, 0 }, // transparent,
{ 0, 0, 0 }, // black,
{ 102, 204, 102 }, // medium green,
{ 136, 238, 136 }, // light green,
{ 68, 68, 221 }, // dark blue,
{ 119, 119, 255 }, // light blue,
{ 187, 85, 85 }, // dark red,
{ 119, 221, 221 }, // cyan,
{ 221, 102, 102 }, // medium red,
{ 255, 119, 119 }, // light red,
{ 204, 204, 85 }, // dark yellow,
{ 238, 238, 136 }, // light yellow,
{ 85, 170, 85 }, // dark green,
{ 187, 85, 187 }, // magenta,
{ 204, 204, 204 }, // gray,
{ 238, 238, 238 } // white,
} },
{ "TMS9918A (NTSC)", {
{ 0, 0, 0 }, // transparent,
{ 0, 0, 0 }, // black,
{ 71, 183, 62 }, // medium green,
{ 124, 208, 108 }, // light green,
{ 99, 91, 169 }, // dark blue,
{ 127, 113, 255 }, // light blue,
{ 183, 98, 73 }, // dark red,
{ 92, 199, 239 }, // cyan,
{ 217, 107, 72 }, // medium red,
{ 253, 142, 108 }, // light red,
{ 195, 206, 66 }, // dark yellow,
{ 211, 219, 117 }, // light yellow,
{ 61, 160, 47 }, // dark green,
{ 183, 99, 199 }, // magenta,
{ 205, 205, 205 }, // gray,
{ 255, 255, 255 } // white,
} },
{ "TMS9929A (PAL)", {
{ 0, 0, 0 }, // transparent,
{ 0, 0, 0 }, // black,
{ 81, 202, 92 }, // medium green,
{ 133, 223, 141 }, // light green,
{ 108, 103, 240 }, // dark blue,
{ 146, 137, 255 }, // light blue,
{ 213, 100, 113 }, // dark red,
{ 102, 219, 239 }, // cyan,
{ 231, 118, 131 }, // medium red,
{ 255, 152, 164 }, // light red,
{ 215, 207, 97 }, // dark yellow,
{ 230, 222, 112 }, // light yellow,
{ 74, 177, 81 }, // dark green,
{ 200, 121, 200 }, // magenta,
{ 205, 205, 205 }, // gray,
{ 255, 255, 255 } // white,
} },
{ "TMS9929A (PAL, alternate GAMMA)", {
{ 0, 0, 0 }, // transparent,
{ 0, 0, 0 }, // black,
{ 72, 178, 81 }, // medium green,
{ 117, 196, 125 }, // light green,
{ 95, 91, 212 }, // dark blue,
{ 129, 121, 224 }, // light blue,
{ 187, 89, 99 }, // dark red,
{ 90, 193, 210 }, // cyan,
{ 203, 104, 115 }, // medium red,
{ 224, 134, 145 }, // light red,
{ 189, 182, 86 }, // dark yellow,
{ 203, 196, 99 }, // light yellow,
{ 66, 156, 72 }, // dark green,
{ 176, 108, 175 }, // magenta,
{ 180, 180, 180 }, // gray,
{ 255, 255, 255 } // white,
} }
};
typedef std::pair<std::array<cv::Vec3b, 4>, std::array<size_t, 2>> Palette4;
std::vector<Palette4> allPalettes;
cv::Mat3b colorMatrix;
// Tpalette(std::string name = "HW-MSX") {
Tpalette(std::string name = "TMS9918A (NTSC)") {
auto colors = allColors.find(name)->second;
colorMatrix = cv::Mat3b(14,14);
for (size_t j=1; j<colors.size(); j++)
for (size_t k=1; k<colors.size(); k++)
colorMatrix((j>8?j-2:j-1),(k>8?k-2:k-1)) = CS.lin2sRGB((CS.sRGB2Lin(colors[j]) + CS.sRGB2Lin(colors[k]))*0.5);
std::vector<Palette4> tentativePalettes;
//for (size_t i=1; i<colors.size(); i++) { // I is the background color, which is common to both tiles.
size_t i = 1; { //On a better though, let's fix the background to black so we can perfilate everything.
for (size_t j=1; j<colors.size(); j++) { // J is the first foreground color
if (j==i) continue;
if (j==8) continue;
for (size_t k=j; k<colors.size(); k++) { // K is the second foreground color
if (k==i) continue;
if (k==8) continue;
Palette4 p4 = { {
colors[i],
CS.lin2sRGB((CS.sRGB2Lin(colors[i]) + CS.sRGB2Lin(colors[j]))*0.5),
CS.lin2sRGB((CS.sRGB2Lin(colors[i]) + CS.sRGB2Lin(colors[k]))*0.5),
CS.lin2sRGB((CS.sRGB2Lin(colors[j]) + CS.sRGB2Lin(colors[k]))*0.5),
}, {j, k} };
if (j==k) {
// allPalettes.push_back(p4);
} else {
tentativePalettes.push_back(p4);
}
}
}
}
std::random_shuffle(tentativePalettes.begin(), tentativePalettes.end());
for (auto &tp : tentativePalettes) {
auto &t = tp.first;
float minD = 1e10;
for (auto &pp : allPalettes) {
auto &p = pp.first;
float d = 0.f;
auto perceptualCompare = Colorspace::perceptualCompare;
d += std::min(std::min(std::min(perceptualCompare(t[0],p[0]), perceptualCompare(t[0],p[1])), perceptualCompare(t[0],p[2])), perceptualCompare(t[0],p[3]));
d += std::min(std::min(std::min(perceptualCompare(t[1],p[0]), perceptualCompare(t[1],p[1])), perceptualCompare(t[1],p[2])), perceptualCompare(t[1],p[3]));
d += std::min(std::min(std::min(perceptualCompare(t[2],p[0]), perceptualCompare(t[2],p[1])), perceptualCompare(t[2],p[2])), perceptualCompare(t[2],p[3]));
d += std::min(std::min(std::min(perceptualCompare(t[3],p[0]), perceptualCompare(t[3],p[1])), perceptualCompare(t[3],p[2])), perceptualCompare(t[3],p[3]));
minD = std::min(minD, d);
}
//std::cout << minD << std::endl;
if (minD>75)
allPalettes.push_back(tp);
}
std::sort(allPalettes.begin(), allPalettes.end(), [](const Palette4 &a, const Palette4 &b){
if (a.second[0]!=b.second[0]) return a.second[0]<b.second[0];
return a.second[1]<b.second[1];
});
}
struct Tile { std::array<uint8_t,8> pattern, color; };
std::array<Tile ,2> findBestPatterns(cv::Mat3b bgr, bool forceDebug=false) const {
cv::Mat3b rgb = bgr.clone();
for (auto &c : rgb) std::swap(c[0], c[2]);
cv::Mat3b debugImg(8,32);
rgb.copyTo(debugImg(cv::Rect(24,0,8,8)));
bool showDebug = false;
std::array<Tile ,2> ret;
for (size_t line = 0; line<8; line++) {
uint8_t colorA=0, colorB=0;
double best = 1e10;
for (int i=1; i<colorMatrix.rows; i++) {
for (int j=i; j<colorMatrix.cols; j++) {
double cost = 0;
for (size_t k=0; k<8; k++) {
cost += pow(
std::min( Colorspace::perceptualCompare(colorMatrix(0,0), rgb(line,k)),
std::min( Colorspace::perceptualCompare(colorMatrix(0,j), rgb(line,k)),
std::min( Colorspace::perceptualCompare(colorMatrix(i,0), rgb(line,k)),
1.01f*Colorspace::perceptualCompare(colorMatrix(i,j), rgb(line,k))))),2);
}
if (i != j) cost += 1;
if (cost<best) {
best = cost;
colorA = i;
colorB = j;
std::cerr << int(colorA) << " " << int(colorB) << " " << cost << std::endl;
}
}
}
if (line%2) std::swap(colorA, colorB);
std::cerr << int(colorA) << " " << int(colorB) << " " << std::endl;
ret[0].pattern[line] = 0;
ret[1].pattern[line] = 0;
for (size_t k=0; k<8; k++) {
uint pA = 0, pB = 0;
double best = Colorspace::perceptualCompare(colorMatrix(0,0), rgb(line,k));
double c;
if ( (c = Colorspace::perceptualCompare(colorMatrix(colorA,0), rgb(line,k))) < best) {
best = c; pA = 1; pB = 0;
}
if ( (c = Colorspace::perceptualCompare(colorMatrix(0,colorB), rgb(line,k)))*1.01 < best) {
best = c; pA = 0; pB = 1;
}
if ( (c = Colorspace::perceptualCompare(colorMatrix(colorA,colorB), rgb(line,k)))*1.02 < best) {
best = c; pA = 1; pB = 1;
}
if (colorA==colorB and (k+line)%2 == 1)
std::swap(pA, pB);
ret[0].pattern[line] = (ret[0].pattern[line]<<1) + pA;
ret[1].pattern[line] = (ret[1].pattern[line]<<1) + pB;
debugImg(line,0*8+k) = colorMatrix(pA*colorA,0);
debugImg(line,1*8+k) = colorMatrix(0,pB*colorB);
debugImg(line,2*8+k) = colorMatrix(pA*colorA,pB*colorB);
}
ret[0].color[line] = (colorA>6?colorA+2:colorA+1)<<4;
ret[1].color[line] = (colorB>6?colorB+2:colorB+1)<<4;
if (best > 50) {
std::cerr << line << ": " << best << std::endl;
showDebug = true;
}
}
if (showDebug or forceDebug) {
cv::Mat3b debug2;
cv::resize(debugImg,debug2,cv::Size(0,0), 10, 10,cv::INTER_NEAREST);
for (auto &c : debug2) std::swap(c[0], c[2]);
cv::imshow("debug", debug2);
cv::waitKey(10);
if (forceDebug) cv::waitKey(0);
}
return ret;
}
};
int main(int argc, const char *argv[]) {
Tpalette P;
char msg[100];
// a map has:
// original map, and any number of altered maps. Traversability is independent of mapping (as are objects).
// animations will be handled at the tile level.
if (argc<4) { std::cerr << "usage: makeMap name standardTiles map0 {map1} {map2} {map3}" << std::endl; exit(-1); }
// A section is a 32x8 piece of the map. A section has its own storage of tiles8. It also stores tiles8 of contiguous areas (i.e., a 2x2 section area)
// Tile8 map: 64x16 (1Kb)
// Animated tiles: 4x4x32 (0.5Kb)
// We are doing it right: traversability, triggers and spawns.
struct Section {
struct Map {
cv::Mat3b img;
cv::Mat1b map16;
};
std::vector<Map> maps;
struct Tile16 {
cv::Mat3b img;
cv::Matx< int, 2, 2 > idx;
size_t count;
};
std::vector<Tile16> tiles16;
struct Tile8 {
cv::Mat3b img;
std::array<Tpalette::Tile ,2> msx1_interlaced;
size_t count;
};
std::vector<Tile8> tiles8;
};
// Load image corresponding to animated tiles
struct Tile8 {
cv::Mat3b img;
std::array<Tpalette::Tile ,2> msx1_interlaced;
size_t count;
};
std::vector<Tile8> tiles8;
std::vector<std::vector<Tile8>> animatedTiles;
{
cv::Mat3b img = cv::imread(argv[2]);
if (img.rows % 8) { std::cerr << "animated tiles not multiple of 8" << std::endl; exit(-1); }
if (img.cols != 32) { std::cerr << "animated tiles not 4 tiles wide" << std::endl; exit(-1); }
for (int i=0; i+7<img.rows; i+=8) {
std::vector<Tile8> at;
for (int j=0; j+7<img.cols; j+=8) {
Tile8 tile8;
tile8.img = img(cv::Rect(j,i,8,8)).clone();
tile8.msx1_interlaced = P.findBestPatterns(tile8.img, true);
tile8.count = 1;
at.push_back(tile8);
}
animatedTiles.push_back(at);
tiles8.push_back(at.front());
}
}
// Process all Maps, find all unique 16x16 tiles.
{
for (int i=3; i<argc; i++) {
maps.push_back(Map());
Map &map = maps.front();
map.img = cv::imread(argv[i]);
if (maps.size() and map.img.size() != maps.front().img.size()) { std::cerr << "inconsistnt map size" << std::endl; exit(-1); }
if (map.img.rows % 16) { std::cerr << "map size not multiple of 16" << std::endl; exit(-1); }
if (map.img.cols % 16) { std::cerr << "map size not multiple of 16" << std::endl; exit(-1); }
map.map16 = cv::Mat1b(map.img.rows/16, map.img.cols/16);
for (int i=0; i+15<map.img.rows; i+=16) {
for (int j=0; j+15<map.img.cols; j+=16) {
cv::Mat3b tile = map.img(cv::Rect(j,i,16,16));
bool found = false;
for (uint k=0; not found and k<tiles16.size(); k++) {
auto &t = tiles16[k].img;
double n = cv::norm(tile-t) + cv::norm(t-tile);
if (n<1) {
tiles16[k].img.copyTo(tile);
tiles16[k].count++;
map.map16(i/16,j/16) = k;
found = true;
}
}
if (not found) {
map.map16(i/16,j/16) = tiles16.size();
Tile16 tile16;
tile16.img = tile.clone();
tile16.count = 1;
tiles16.push_back(tile16);
}
}
}
}
std::cout << "Found " << tiles16.size() << " unique 16x16 tiles." << std::endl;
if (tiles16.size()>256) { std::cerr << "Too many unique 16x16 tiles." << std::endl; exit(-1); }
}
// Find all unique 8x8 tiles.
{
for (auto &tile16 : tiles16) {
for (int i=0; i+7<tile16.img.rows; i+=8) {
for (int j=0; j+7<tile16.img.cols; j+=8) {
cv::Mat3b tile = tile16.img(cv::Rect(j,i,8,8));
bool found = false;
for (uint k=0; not found and k<tiles8.size(); k++) {
auto &t = tiles8[k].img;
double n = cv::norm(tile-t) + cv::norm(t-tile);
if (n<1) {
tiles8[k].img.copyTo(tile);
tiles8[k].count++;
tile16.idx(i/8,j/8) = k;
found = true;
}
}
if (not found) {
tile16.idx(i/8,j/8) = tiles8.size();
Tile8 tile8;
tile8.img = tile.clone();
tile8.msx1_interlaced = P.findBestPatterns(tile8.img);
tile8.count = 1;
tiles8.push_back(tile8);
}
}
}
}
std::cout << "Found " << tiles8.size() << " unique 8x8 tiles." << std::endl;
if (tiles8.size()>256) { std::cerr << "Too many unique 8x8 tiles." << std::endl; exit(-1); }
}
// Check that no more than 96 tiles are in use simultaneously within a 32 x 8 window
{
int score = 0;
cv::Mat1d histMap(2*maps.front().map16.rows, 2*maps.front().map16.cols, 0.);
int t8Rows = 2*maps.front().map16.rows;
int t8Cols = 2*maps.front().map16.cols;
static constexpr const struct { int width = 32+1, height = 8+1; } window;
for (int i=0; i+window.height-1 < t8Rows; i++) {
for (int j=0; j+window.width-1 < t8Cols; j++) {
std::map<std::pair<size_t,size_t>, int> uniqueTiles;
for (size_t m = 0; m<maps.size(); m++) {
for (int ii=0; ii<window.height; ii++) {
for (int jj=0; jj<window.width; jj++) {
int tile16Idx = maps[m].map16((i+ii)/2,(j+jj)/2);
auto &tile16 = tiles16[tile16Idx];
size_t tile8Idx = tile16.idx((i+ii)%2,(j+jj)%2);
if (tile8Idx<animatedTiles.size()) continue;
uniqueTiles[{m,tile8Idx}]++;
}
}
}
if (uniqueTiles.size()>64) { std::cerr << uniqueTiles.size() << " unique 8x8 tiles at: (" << i << ", " << j << ")" << std::endl; }
if (uniqueTiles.size()>96) { std::cerr << "Too many unique 8x8 tiles at: (" << i << ", " << j << ")" << std::endl; exit(-1); }
score = std::max(score,int(uniqueTiles.size()));
for (int ii=0; ii<window.height; ii++) {
for (int jj=0; jj<window.width; jj++) {
histMap(i+ii,j+jj) = std::max(histMap(i+ii,j+jj), double(uniqueTiles.size()));
}
}
}
}
if (score>64) {
cv::Mat3b heatMap(histMap.rows, histMap.cols, cv::Vec3b(0,0,0));
for (int i=0; i<histMap.rows; i++) {
for (int j=0; j<histMap.cols; j++) {
if (histMap(i,j)<64) {
heatMap(i,j)=cv::Vec3b(0,255,0);
} else if (histMap(i,j)<88) {
heatMap(i,j)=cv::Vec3b(0,255,255);
} else if (histMap(i,j)<96) {
heatMap(i,j)=cv::Vec3b(0,128,255);
} else {
heatMap(i,j)=cv::Vec3b(0,0,255);
}
}
}
cv::resize(heatMap, heatMap, cv::Size(), 8, 8, cv::INTER_LINEAR);
cv::imwrite("heatmap.png", heatMap);
cv::imshow("heatmap.png", heatMap);
cv::waitKey(0);
}
}
std::string MAP_NAME = argv[1];
uint NUM_ANIMATED_TILES = animatedTiles.size();
uint NUM_ANIMATED_FRAMES = (animatedTiles.size()?animatedTiles.front().size():0);
uint NUM_MAPS = maps.size();
uint MAP16_Y = maps.front().map16.rows;
uint MAP16_X = maps.front().map16.cols;
// Prepare external header
{
std::ofstream header(MAP_NAME+".h");
header << "#pragma once" << std::endl;
header << "#define MAP_NAME " << MAP_NAME << std::endl;
header << "#include <map/interface.h>" << std::endl;
header << "#undef MAP_NAME" << std::endl;
}
// Spawn Implementation
{
std::ofstream src(MAP_NAME+".c");
src << "#include <map/interface.h>" << std::endl;
src << "#define MAP_NAME " << MAP_NAME << std::endl;
src << "#define NUM_ANIMATED_TILES " << NUM_ANIMATED_TILES << std::endl;
src << "#define NUM_ANIMATED_FRAMES " << NUM_ANIMATED_FRAMES << std::endl;
src << "#define NUM_MAPS " << NUM_MAPS << std::endl;
src << "#define MAP16_Y " << MAP16_Y << std::endl;
src << "#define MAP16_X " << MAP16_X << std::endl;
src << "#define MAP_ANIMATED " << (MAP_NAME + std::string("_animated")) << std::endl;
src << "USING_MODULE(" << (MAP_NAME + std::string("_animated")) << ", PAGE_C);" << std::endl;
src << "extern const uint8_t " << (MAP_NAME + std::string("_animated")) << "[" << NUM_ANIMATED_TILES << "][" <<NUM_ANIMATED_FRAMES << "][2][16];" << std::endl;
src << "#define MAP_MAP16 " << (MAP_NAME + "_map" + char('0'+0) + "_map16") << std::endl;
for (size_t m=0; m<maps.size(); m++) {
src << "#define MAP" << char('0'+m) << "_MAP16 " << (MAP_NAME + "_map" + char('0'+m) + "_map16") << std::endl;
src << "USING_MODULE(" << (MAP_NAME + "_map" + char('0'+m) + "_map16") << ", PAGE_D);" << std::endl;
src << "extern const uint8_t " << (MAP_NAME + "_map" + char('0'+m) + "_map16") << "[" << MAP16_Y << "]["<< MAP16_X << "];" << std::endl;
}
src << "#define MAP_TILES16 " << (MAP_NAME + "_tiles16") << std::endl;
src << "USING_MODULE(" << (MAP_NAME + "_tiles16") << ", PAGE_C);" << std::endl;
src << "extern const uint8_t " << (MAP_NAME + "_tiles16") << "[256][2][2];" << std::endl;
src << "#define MAP_TILES8 " << (MAP_NAME + "_tiles8") << std::endl;
src << "USING_MODULE(" << (MAP_NAME + "_tiles8") << ", PAGE_C);" << std::endl;
src << "extern const uint8_t " << (MAP_NAME + "_tiles8") << "[256][2][16];" << std::endl;
src << "#include <map/implementation.h>" << std::endl;
}
// Spawn Animated Tiles
{
std::ofstream ofs(MAP_NAME + std::string("_animated") + ".c");
ofs << "#include <stdint.h>" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + std::string("_animated")) << "[" << NUM_ANIMATED_TILES << "][" <<NUM_ANIMATED_FRAMES << "][2][16];" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + std::string("_animated")) << "[" << NUM_ANIMATED_TILES << "][" <<NUM_ANIMATED_FRAMES << "][2][16] = {" << std::endl;
for (auto &animatedTile : animatedTiles) { ofs << "{";
for (auto &tile : animatedTile) { ofs << "{";
auto p = tile.msx1_interlaced;
ofs << "{";
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[0].pattern[j]); ofs << msg; }
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[1].pattern[j]); ofs << msg; }
ofs << "}," << std::endl;
ofs << " {";
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[0].color[j]); ofs << msg; }
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[1].color[j]); ofs << msg; }
ofs << "}";
ofs << "}," << std::endl << " "; }
ofs << "}," << std::endl; }
ofs << "};" << std::endl;
}
// Spawn Maps
{
for (size_t m=0; m<maps.size(); m++) {
{
auto &map16 = maps[m].map16;
std::ofstream ofs(MAP_NAME + "_map" + char('0'+m) + "_map16" + ".c");
ofs << "#include <stdint.h>" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_map" + char('0'+m) + "_map16") << "[" << MAP16_Y << "]["<< MAP16_X << "];" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_map" + char('0'+m) + "_map16") << "[" << MAP16_Y << "]["<< MAP16_X << "] = {" << std::endl;
for (int i=0; i<map16.rows; i++) {
ofs << "{";
for (int j=0; j<map16.cols; j++) {
if (j and (j%16==0)) ofs << std::endl << " ";
sprintf(msg,"0x%02X,", map16(i,j)); ofs << msg;
}
ofs << "}," << std::endl;
}
ofs << "};" << std::endl;
}
}
}
// Spawn tile16
{
std::ofstream ofs(MAP_NAME + "_tiles16" + ".c");
ofs << "#include <stdint.h>" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_tiles16") << "[256][2][2];" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_tiles16") << "[256][2][2] = {" << std::endl;
for (size_t i=0; i<tiles16.size(); i++) {
if (i and (i%4==0)) ofs << std::endl;
sprintf(msg,"{ { 0x%04X, 0x%04X}, { 0x%04X, 0x%04X} }, ", tiles16[i].idx(0,0), tiles16[i].idx(0,1), tiles16[i].idx(1,0), tiles16[i].idx(1,1));
ofs << msg;
}
ofs << "};" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_tiles16_filler") << "[7*1024] = { 0 };" << std::endl;
}
// Spawn tile8
{
std::ofstream ofs(MAP_NAME + "_tiles8" + ".c");
ofs << "#include <stdint.h>" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_tiles8") << "[256][2][16];" << std::endl;
ofs << "const uint8_t " << (MAP_NAME + "_tiles8") << "[256][2][16] = {" << std::endl;
for (auto &tile8 : tiles8) { ofs << "{";
auto p = tile8.msx1_interlaced;
ofs << "{";
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[0].pattern[j]); ofs << msg; }
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[1].pattern[j]); ofs << msg; }
ofs << "}," << std::endl;
ofs << " {";
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[0].color[j]); ofs << msg; }
for (int j=0; j<8; j++) { sprintf(msg,"0x%02X,", p[1].color[j]); ofs << msg; }
ofs << "}";
ofs << "}," << std::endl; }
ofs << "};" << std::endl;
}
}
| 39.555118
| 170
| 0.438605
|
MartinezTorres
|
dcece1ecc68c0dcea13dbd246f3977a328a8f631
| 4,874
|
cpp
|
C++
|
offline_compiler/utilities/windows/seh_exception.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | 3
|
2019-09-20T23:26:36.000Z
|
2019-10-03T17:44:12.000Z
|
offline_compiler/utilities/windows/seh_exception.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | 1
|
2019-09-17T08:06:24.000Z
|
2019-09-17T08:06:24.000Z
|
offline_compiler/utilities/windows/seh_exception.cpp
|
cwang64/compute-runtime
|
440520ffdc5807574f0abfbf64b3790d1c0547e4
|
[
"MIT"
] | 3
|
2019-05-16T07:22:51.000Z
|
2019-11-11T03:05:32.000Z
|
/*
* Copyright (C) 2018-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "seh_exception.h"
#include "runtime/os_interface/os_library.h"
#include <memory>
#include <string>
#pragma warning(push)
#pragma warning(disable : 4091)
#include <dbghelp.h>
#pragma warning(pop)
#include <windows.h>
#include <excpt.h>
#include <psapi.h>
using namespace std;
string SehException::getExceptionDescription(unsigned int code) {
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
return "Access violation";
case EXCEPTION_DATATYPE_MISALIGNMENT:
return "Datatype misalignement";
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
case EXCEPTION_INT_DIVIDE_BY_ZERO:
return "Divide by zero";
case EXCEPTION_STACK_OVERFLOW:
return "Stack overflow";
default:
break;
}
return "Unknown";
}
int SehException::filter(unsigned int code, struct _EXCEPTION_POINTERS *ep) {
printf("EXCEPTION: %s\n", SehException::getExceptionDescription(code).c_str());
if (code != EXCEPTION_STACK_OVERFLOW) {
string callstack;
SehException::getCallStack(code, ep, callstack);
printf("Callstack:\n\n%s", callstack.c_str());
}
return EXCEPTION_EXECUTE_HANDLER;
}
void SehException::getCallStack(unsigned int code, struct _EXCEPTION_POINTERS *ep, string &stack) {
DWORD machine = 0;
HANDLE hProcess = GetCurrentProcess();
HANDLE hThread = GetCurrentThread();
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) {
machine = IMAGE_FILE_MACHINE_I386;
} else if (systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
machine = IMAGE_FILE_MACHINE_AMD64;
} else {
stack = "invalid processor arch";
return;
}
stack.clear();
BOOL result = SymInitialize(hProcess, NULL, TRUE);
if (result == FALSE) {
return;
}
STACKFRAME64 stackFrame;
memset(&stackFrame, 0, sizeof(STACKFRAME64));
const int nameSize = 255;
char buffer[sizeof(IMAGEHLP_SYMBOL64) + (nameSize + 1) * sizeof(char)];
IMAGEHLP_SYMBOL64 *symbol = reinterpret_cast<IMAGEHLP_SYMBOL64 *>(buffer);
symbol->MaxNameLength = nameSize;
DWORD displacement = 0;
DWORD64 displacement64 = 0;
unique_ptr<NEO::OsLibrary> psApiLib(NEO::OsLibrary::load("psapi.dll"));
auto getMappedFileName = reinterpret_cast<getMappedFileNameFunction>(psApiLib->getProcAddress("GetMappedFileNameA"));
size_t callstackCounter = 0;
const size_t maxCallstackDepth = 1000;
#ifdef _WIN64
stackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
stackFrame.AddrStack.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
#else
stackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
stackFrame.AddrStack.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
#endif
while (callstackCounter < maxCallstackDepth) {
symbol->Name[255] = '\0';
if (!StackWalk64(machine, hProcess, hThread, &stackFrame, ep->ContextRecord, nullptr, SymFunctionTableAccess64, SymGetModuleBase64, 0)) {
break;
}
if (stackFrame.AddrFrame.Offset == 0) {
break;
}
string lineInCode;
string module;
string symbolName;
DWORD64 address = stackFrame.AddrPC.Offset;
IMAGEHLP_LINE64 imageLine;
imageLine.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (SymGetLineFromAddr64(hProcess, address, &displacement, &imageLine)) {
lineInCode = imageLine.FileName;
char filename[MAX_PATH + 1];
filename[MAX_PATH] = '\0';
if (getMappedFileName(hProcess, reinterpret_cast<LPVOID>(imageLine.Address), filename, MAX_PATH)) {
module = filename;
}
}
if (SymGetSymFromAddr64(hProcess, address, &displacement64, symbol)) {
symbolName = symbol->Name;
}
addLineToCallstack(stack, callstackCounter, module, lineInCode, symbolName);
callstackCounter++;
}
}
void SehException::addLineToCallstack(std::string &callstack, size_t counter, std::string &module, std::string &line, std::string &symbol) {
callstack += "[";
callstack += to_string(counter);
callstack += "]: ";
if (module.size()) {
callstack += "Module:";
callstack += module + "\n\t";
}
if (line.size()) {
callstack += line + ":";
}
callstack += symbol + "\n";
}
| 29.185629
| 145
| 0.669881
|
cwang64
|
dceea8de8f2da38e8984527c0ff0a1d17fc9356a
| 2,088
|
cpp
|
C++
|
full_code/Input Combos/Motor2D/ctEntities.cpp
|
Wilhelman/Input-Combos
|
9aeb5621c0148318caf7cfbc31972856d149587e
|
[
"MIT"
] | null | null | null |
full_code/Input Combos/Motor2D/ctEntities.cpp
|
Wilhelman/Input-Combos
|
9aeb5621c0148318caf7cfbc31972856d149587e
|
[
"MIT"
] | null | null | null |
full_code/Input Combos/Motor2D/ctEntities.cpp
|
Wilhelman/Input-Combos
|
9aeb5621c0148318caf7cfbc31972856d149587e
|
[
"MIT"
] | null | null | null |
#include "ctApp.h"
#include "ctRender.h"
#include "ctEntities.h"
#include "ctTextures.h"
#include "Entity.h"
#include "ctAudio.h"
#include "ctWindow.h"
#include "ctLog.h"
#include "ctFadeToBlack.h"
#include "Player.h"
ctEntities::ctEntities()
{
name = "entities";
}
// Destructor
ctEntities::~ctEntities()
{
LOG("Unloading entities spritesheet");
App->tex->UnLoad(entity_sprites);
}
bool ctEntities::Awake(pugi::xml_node& config)
{
LOG("Loading Entities from config file");
bool ret = true;
spritesheetName = config.child("spritesheetSource").attribute("name").as_string();
return ret;
}
bool ctEntities::Start()
{
bool ret = true;
entity_sprites = App->tex->Load(spritesheetName.data());
if (entity_sprites == NULL) {
LOG("Error loading entities spritesheet!!");
ret = false;
}
if (!ret)
return false;
return ret;
}
bool ctEntities::PreUpdate()
{
for (int i = 0; i < entities.capacity(); i++) {
if (entities[i]->to_destroy) {
delete(entities[i]);
entities[i] = nullptr;
entities.erase(entities.cbegin() + i);
entities.shrink_to_fit();
}
}
return true;
}
// Called before render is available
bool ctEntities::Update(float dt)
{
for (int i = 0; i < entities.capacity(); i++)
if (entities.at(i) != nullptr) entities[i]->Update(dt);
for (int i = 0; i < entities.capacity(); i++)
if (entities.at(i) != nullptr) entities[i]->Draw(entity_sprites);
return true;
}
// Called before quitting
bool ctEntities::CleanUp()
{
LOG("Freeing all enemies");
App->tex->UnLoad(entity_sprites);
return true;
}
bool ctEntities::SpawnEntity(int x, int y, EntityType type)
{
// find room for the new entity
bool ret = false;
switch (type)
{
case EntityType::PLAYER: {
Player* player = new Player(x, y, PLAYER);
entities.push_back(player);
ret = true;
break;
}
default:
break;
}
return ret;
}
Player* ctEntities::GetPlayer() const {
for (uint i = 0; i < entities.capacity(); ++i)
{
if (entities.at(i) != nullptr)
{
if (entities[i]->type == PLAYER)
return (Player*)entities[i];
}
}
return nullptr;
}
| 16.704
| 83
| 0.660441
|
Wilhelman
|
fd5f0ef43bf1e26a62d1702c83614711a8de2b9c
| 1,069
|
cpp
|
C++
|
vtools/Sample/src/Application.cpp
|
SergeyStrukov/CCore-3-xx
|
820507e78f8aa35ca05761e00e060c8f64c59af5
|
[
"BSL-1.0"
] | 8
|
2017-12-21T07:00:16.000Z
|
2020-04-02T09:05:55.000Z
|
vtools/Sample/src/Application.cpp
|
SergeyStrukov/CCore-3-xx
|
820507e78f8aa35ca05761e00e060c8f64c59af5
|
[
"BSL-1.0"
] | null | null | null |
vtools/Sample/src/Application.cpp
|
SergeyStrukov/CCore-3-xx
|
820507e78f8aa35ca05761e00e060c8f64c59af5
|
[
"BSL-1.0"
] | 1
|
2020-03-30T09:54:18.000Z
|
2020-03-30T09:54:18.000Z
|
/* Application.cpp */
//----------------------------------------------------------------------------------------
//
// Project: Sample 1.00
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2017 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <inc/Application.h>
namespace App {
/* struct AppPreferenceBag */
void AppPreferenceBag::bindItems(ConfigItemBind &binder)
{
binder.group("Common"_str);
binder.item("title"_str,title);
binder.group("Menu"_str);
binder.item("File"_str,menu_File);
binder.item("Options"_str,menu_Options);
binder.item("New"_str,menu_New);
binder.item("Open"_str,menu_Open);
binder.item("Save"_str,menu_Save);
binder.item("SaveAs"_str,menu_SaveAs);
binder.item("Exit"_str,menu_Exit);
binder.item("Global"_str,menu_Global);
binder.item("App"_str,menu_App);
}
} // namespace App
| 25.452381
| 90
| 0.565014
|
SergeyStrukov
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.