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
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
21d677c56deb7822da554788ffea2a4b46844ef7
4,985
cpp
C++
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
33
2015-12-16T15:32:22.000Z
2022-03-21T05:09:40.000Z
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
3
2016-06-08T09:53:44.000Z
2020-10-26T11:27:23.000Z
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
10
2016-01-27T10:30:01.000Z
2022-03-21T05:08:27.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2015, Daichi Yoshikawa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Daichi Yoshikawa nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Daichi Yoshikawa * *********************************************************************/ #include <iostream> #include "ahl_robot/utils/math.hpp" namespace ahl_robot { namespace math { void computeEr(const Eigen::Quaternion<double>& q, Eigen::MatrixXd& Er) { Er.resize(4, 3); Er << -q.x(), -q.y(), -q.z(), q.w(), q.z(), -q.y(), -q.z(), q.w(), q.x(), q.y(), -q.x(), q.w(); Er = 0.5 * Er; } void calculateInverseTransformationMatrix(const Eigen::Matrix4d& src, Eigen::Matrix4d& dst) { dst = Eigen::Matrix4d::Identity(); Eigen::Matrix3d R_trans = src.block(0, 0, 3, 3).transpose(); dst.block(0, 0, 3, 3) = R_trans; dst.block(0, 3, 3, 1) = -R_trans * src.block(0, 3, 3, 1); } void rpyToRotationMatrix(const std::vector<double>& rpy, Eigen::Matrix3d& mat) { double sin_a = sin(rpy[2]); double cos_a = cos(rpy[2]); double sin_b = sin(rpy[1]); double cos_b = cos(rpy[1]); double sin_g = sin(rpy[0]); double cos_g = cos(rpy[0]); mat.coeffRef(0, 0) = cos_a * cos_b; mat.coeffRef(0, 1) = cos_a * sin_b * sin_g - sin_a * cos_g; mat.coeffRef(0, 2) = cos_a * sin_b * cos_g + sin_a * sin_g; mat.coeffRef(1, 0) = sin_a * cos_b; mat.coeffRef(1, 1) = sin_a * sin_b * sin_g + cos_a * cos_g; mat.coeffRef(1, 2) = sin_a * sin_b * cos_g - cos_a * sin_g; mat.coeffRef(2, 0) = -sin_b; mat.coeffRef(2, 1) = cos_b * sin_g; mat.coeffRef(2, 2) = cos_b * cos_g; } void rpyToRotationMatrix(const Eigen::Vector3d& rpy, Eigen::Matrix3d& mat) { double sin_a = sin(rpy.coeff(2)); double cos_a = cos(rpy.coeff(2)); double sin_b = sin(rpy.coeff(1)); double cos_b = cos(rpy.coeff(1)); double sin_g = sin(rpy.coeff(0)); double cos_g = cos(rpy.coeff(0)); mat.coeffRef(0, 0) = cos_a * cos_b; mat.coeffRef(0, 1) = cos_a * sin_b * sin_g - sin_a * cos_g; mat.coeffRef(0, 2) = cos_a * sin_b * cos_g + sin_a * sin_g; mat.coeffRef(1, 0) = sin_a * cos_b; mat.coeffRef(1, 1) = sin_a * sin_b * sin_g + cos_a * cos_g; mat.coeffRef(1, 2) = sin_a * sin_b * cos_g - cos_a * sin_g; mat.coeffRef(2, 0) = -sin_b; mat.coeffRef(2, 1) = cos_b * sin_g; mat.coeffRef(2, 2) = cos_b * cos_g; } void rpyToQuaternion(const Eigen::Vector3d& rpy, Eigen::Quaternion<double>& q) { double a = rpy.coeff(0); double b = rpy.coeff(1); double g = rpy.coeff(2); double sin_b_half = sin(0.5 * b); double cos_b_half = cos(0.5 * b); double diff_a_g_half = 0.5 * (a - g); double sum_a_g_half = 0.5 * (a + g); q.x() = sin_b_half * cos(diff_a_g_half); q.y() = sin_b_half * sin(diff_a_g_half); q.z() = cos_b_half * sin(sum_a_g_half); q.w() = cos_b_half * cos(sum_a_g_half); } void xyzrpyToTransformationMatrix(const Eigen::Vector3d& xyz, const Eigen::Vector3d& rpy, Eigen::Matrix4d& T) { T = Eigen::Matrix4d::Identity(); Eigen::Matrix3d R; rpyToRotationMatrix(rpy, R); T.block(0, 0, 3, 3) = R; T.block(0, 3, 3, 1) = xyz; } } // namespace math } // namespace ahl_robot
38.053435
113
0.608425
21dcf21fc5692fa094e45e1ac901bd23ca517dbe
146
cpp
C++
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
#include "mpch.h" #include "Line.hpp" namespace ml { Line::Line(Vec2f a, Vec2f b) { transform.setPoint(a, 0); transform.setPoint(b, 1); } }
16.222222
31
0.650685
21e7e4c022bf5ddcc7dc9dfefcdc89b2686c2df5
332
cpp
C++
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
void CMyODListBox::OnLButtonDown(UINT nFlags, CPoint point) { BOOL bOutside = TRUE; UINT uItem = ItemFromPoint(point, bOutside); if (!bOutside) { // Set the anchor to be the middle item. SetAnchorIndex(uItem); ASSERT((UINT)GetAnchorIndex() == uItem); } CListBox::OnLButtonDown(nFlags, point); }
23.714286
59
0.662651
21e857cd750b4772a92043e4d352ae467ee5893d
28,999
cpp
C++
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cws/v20180312/CwsClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Cws::V20180312; using namespace TencentCloud::Cws::V20180312::Model; using namespace std; namespace { const string VERSION = "2018-03-12"; const string ENDPOINT = "cws.tencentcloudapi.com"; } CwsClient::CwsClient(const Credential &credential, const string &region) : CwsClient(credential, region, ClientProfile()) { } CwsClient::CwsClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } CwsClient::CreateMonitorsOutcome CwsClient::CreateMonitors(const CreateMonitorsRequest &request) { auto outcome = MakeRequest(request, "CreateMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateMonitorsResponse rsp = CreateMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateMonitorsOutcome(rsp); else return CreateMonitorsOutcome(o.GetError()); } else { return CreateMonitorsOutcome(outcome.GetError()); } } void CwsClient::CreateMonitorsAsync(const CreateMonitorsRequest& request, const CreateMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateMonitorsOutcomeCallable CwsClient::CreateMonitorsCallable(const CreateMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<CreateMonitorsOutcome()>>( [this, request]() { return this->CreateMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateSitesOutcome CwsClient::CreateSites(const CreateSitesRequest &request) { auto outcome = MakeRequest(request, "CreateSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateSitesResponse rsp = CreateSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateSitesOutcome(rsp); else return CreateSitesOutcome(o.GetError()); } else { return CreateSitesOutcome(outcome.GetError()); } } void CwsClient::CreateSitesAsync(const CreateSitesRequest& request, const CreateSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateSitesOutcomeCallable CwsClient::CreateSitesCallable(const CreateSitesRequest &request) { auto task = std::make_shared<std::packaged_task<CreateSitesOutcome()>>( [this, request]() { return this->CreateSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateSitesScansOutcome CwsClient::CreateSitesScans(const CreateSitesScansRequest &request) { auto outcome = MakeRequest(request, "CreateSitesScans"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateSitesScansResponse rsp = CreateSitesScansResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateSitesScansOutcome(rsp); else return CreateSitesScansOutcome(o.GetError()); } else { return CreateSitesScansOutcome(outcome.GetError()); } } void CwsClient::CreateSitesScansAsync(const CreateSitesScansRequest& request, const CreateSitesScansAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateSitesScans(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateSitesScansOutcomeCallable CwsClient::CreateSitesScansCallable(const CreateSitesScansRequest &request) { auto task = std::make_shared<std::packaged_task<CreateSitesScansOutcome()>>( [this, request]() { return this->CreateSitesScans(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateVulsMisinformationOutcome CwsClient::CreateVulsMisinformation(const CreateVulsMisinformationRequest &request) { auto outcome = MakeRequest(request, "CreateVulsMisinformation"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateVulsMisinformationResponse rsp = CreateVulsMisinformationResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateVulsMisinformationOutcome(rsp); else return CreateVulsMisinformationOutcome(o.GetError()); } else { return CreateVulsMisinformationOutcome(outcome.GetError()); } } void CwsClient::CreateVulsMisinformationAsync(const CreateVulsMisinformationRequest& request, const CreateVulsMisinformationAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateVulsMisinformation(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateVulsMisinformationOutcomeCallable CwsClient::CreateVulsMisinformationCallable(const CreateVulsMisinformationRequest &request) { auto task = std::make_shared<std::packaged_task<CreateVulsMisinformationOutcome()>>( [this, request]() { return this->CreateVulsMisinformation(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateVulsReportOutcome CwsClient::CreateVulsReport(const CreateVulsReportRequest &request) { auto outcome = MakeRequest(request, "CreateVulsReport"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateVulsReportResponse rsp = CreateVulsReportResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateVulsReportOutcome(rsp); else return CreateVulsReportOutcome(o.GetError()); } else { return CreateVulsReportOutcome(outcome.GetError()); } } void CwsClient::CreateVulsReportAsync(const CreateVulsReportRequest& request, const CreateVulsReportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateVulsReport(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateVulsReportOutcomeCallable CwsClient::CreateVulsReportCallable(const CreateVulsReportRequest &request) { auto task = std::make_shared<std::packaged_task<CreateVulsReportOutcome()>>( [this, request]() { return this->CreateVulsReport(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DeleteMonitorsOutcome CwsClient::DeleteMonitors(const DeleteMonitorsRequest &request) { auto outcome = MakeRequest(request, "DeleteMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteMonitorsResponse rsp = DeleteMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteMonitorsOutcome(rsp); else return DeleteMonitorsOutcome(o.GetError()); } else { return DeleteMonitorsOutcome(outcome.GetError()); } } void CwsClient::DeleteMonitorsAsync(const DeleteMonitorsRequest& request, const DeleteMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DeleteMonitorsOutcomeCallable CwsClient::DeleteMonitorsCallable(const DeleteMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteMonitorsOutcome()>>( [this, request]() { return this->DeleteMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DeleteSitesOutcome CwsClient::DeleteSites(const DeleteSitesRequest &request) { auto outcome = MakeRequest(request, "DeleteSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteSitesResponse rsp = DeleteSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteSitesOutcome(rsp); else return DeleteSitesOutcome(o.GetError()); } else { return DeleteSitesOutcome(outcome.GetError()); } } void CwsClient::DeleteSitesAsync(const DeleteSitesRequest& request, const DeleteSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DeleteSitesOutcomeCallable CwsClient::DeleteSitesCallable(const DeleteSitesRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteSitesOutcome()>>( [this, request]() { return this->DeleteSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeConfigOutcome CwsClient::DescribeConfig(const DescribeConfigRequest &request) { auto outcome = MakeRequest(request, "DescribeConfig"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeConfigResponse rsp = DescribeConfigResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeConfigOutcome(rsp); else return DescribeConfigOutcome(o.GetError()); } else { return DescribeConfigOutcome(outcome.GetError()); } } void CwsClient::DescribeConfigAsync(const DescribeConfigRequest& request, const DescribeConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeConfig(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeConfigOutcomeCallable CwsClient::DescribeConfigCallable(const DescribeConfigRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeConfigOutcome()>>( [this, request]() { return this->DescribeConfig(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeMonitorsOutcome CwsClient::DescribeMonitors(const DescribeMonitorsRequest &request) { auto outcome = MakeRequest(request, "DescribeMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeMonitorsResponse rsp = DescribeMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeMonitorsOutcome(rsp); else return DescribeMonitorsOutcome(o.GetError()); } else { return DescribeMonitorsOutcome(outcome.GetError()); } } void CwsClient::DescribeMonitorsAsync(const DescribeMonitorsRequest& request, const DescribeMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeMonitorsOutcomeCallable CwsClient::DescribeMonitorsCallable(const DescribeMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeMonitorsOutcome()>>( [this, request]() { return this->DescribeMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSiteQuotaOutcome CwsClient::DescribeSiteQuota(const DescribeSiteQuotaRequest &request) { auto outcome = MakeRequest(request, "DescribeSiteQuota"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSiteQuotaResponse rsp = DescribeSiteQuotaResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSiteQuotaOutcome(rsp); else return DescribeSiteQuotaOutcome(o.GetError()); } else { return DescribeSiteQuotaOutcome(outcome.GetError()); } } void CwsClient::DescribeSiteQuotaAsync(const DescribeSiteQuotaRequest& request, const DescribeSiteQuotaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSiteQuota(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSiteQuotaOutcomeCallable CwsClient::DescribeSiteQuotaCallable(const DescribeSiteQuotaRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSiteQuotaOutcome()>>( [this, request]() { return this->DescribeSiteQuota(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSitesOutcome CwsClient::DescribeSites(const DescribeSitesRequest &request) { auto outcome = MakeRequest(request, "DescribeSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSitesResponse rsp = DescribeSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSitesOutcome(rsp); else return DescribeSitesOutcome(o.GetError()); } else { return DescribeSitesOutcome(outcome.GetError()); } } void CwsClient::DescribeSitesAsync(const DescribeSitesRequest& request, const DescribeSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSitesOutcomeCallable CwsClient::DescribeSitesCallable(const DescribeSitesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSitesOutcome()>>( [this, request]() { return this->DescribeSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSitesVerificationOutcome CwsClient::DescribeSitesVerification(const DescribeSitesVerificationRequest &request) { auto outcome = MakeRequest(request, "DescribeSitesVerification"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSitesVerificationResponse rsp = DescribeSitesVerificationResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSitesVerificationOutcome(rsp); else return DescribeSitesVerificationOutcome(o.GetError()); } else { return DescribeSitesVerificationOutcome(outcome.GetError()); } } void CwsClient::DescribeSitesVerificationAsync(const DescribeSitesVerificationRequest& request, const DescribeSitesVerificationAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSitesVerification(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSitesVerificationOutcomeCallable CwsClient::DescribeSitesVerificationCallable(const DescribeSitesVerificationRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSitesVerificationOutcome()>>( [this, request]() { return this->DescribeSitesVerification(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsOutcome CwsClient::DescribeVuls(const DescribeVulsRequest &request) { auto outcome = MakeRequest(request, "DescribeVuls"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsResponse rsp = DescribeVulsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsOutcome(rsp); else return DescribeVulsOutcome(o.GetError()); } else { return DescribeVulsOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsAsync(const DescribeVulsRequest& request, const DescribeVulsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVuls(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsOutcomeCallable CwsClient::DescribeVulsCallable(const DescribeVulsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsOutcome()>>( [this, request]() { return this->DescribeVuls(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsNumberOutcome CwsClient::DescribeVulsNumber(const DescribeVulsNumberRequest &request) { auto outcome = MakeRequest(request, "DescribeVulsNumber"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsNumberResponse rsp = DescribeVulsNumberResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsNumberOutcome(rsp); else return DescribeVulsNumberOutcome(o.GetError()); } else { return DescribeVulsNumberOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsNumberAsync(const DescribeVulsNumberRequest& request, const DescribeVulsNumberAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVulsNumber(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsNumberOutcomeCallable CwsClient::DescribeVulsNumberCallable(const DescribeVulsNumberRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsNumberOutcome()>>( [this, request]() { return this->DescribeVulsNumber(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsNumberTimelineOutcome CwsClient::DescribeVulsNumberTimeline(const DescribeVulsNumberTimelineRequest &request) { auto outcome = MakeRequest(request, "DescribeVulsNumberTimeline"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsNumberTimelineResponse rsp = DescribeVulsNumberTimelineResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsNumberTimelineOutcome(rsp); else return DescribeVulsNumberTimelineOutcome(o.GetError()); } else { return DescribeVulsNumberTimelineOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsNumberTimelineAsync(const DescribeVulsNumberTimelineRequest& request, const DescribeVulsNumberTimelineAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVulsNumberTimeline(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsNumberTimelineOutcomeCallable CwsClient::DescribeVulsNumberTimelineCallable(const DescribeVulsNumberTimelineRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsNumberTimelineOutcome()>>( [this, request]() { return this->DescribeVulsNumberTimeline(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifyConfigAttributeOutcome CwsClient::ModifyConfigAttribute(const ModifyConfigAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifyConfigAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyConfigAttributeResponse rsp = ModifyConfigAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyConfigAttributeOutcome(rsp); else return ModifyConfigAttributeOutcome(o.GetError()); } else { return ModifyConfigAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifyConfigAttributeAsync(const ModifyConfigAttributeRequest& request, const ModifyConfigAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyConfigAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifyConfigAttributeOutcomeCallable CwsClient::ModifyConfigAttributeCallable(const ModifyConfigAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyConfigAttributeOutcome()>>( [this, request]() { return this->ModifyConfigAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifyMonitorAttributeOutcome CwsClient::ModifyMonitorAttribute(const ModifyMonitorAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifyMonitorAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyMonitorAttributeResponse rsp = ModifyMonitorAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyMonitorAttributeOutcome(rsp); else return ModifyMonitorAttributeOutcome(o.GetError()); } else { return ModifyMonitorAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifyMonitorAttributeAsync(const ModifyMonitorAttributeRequest& request, const ModifyMonitorAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyMonitorAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifyMonitorAttributeOutcomeCallable CwsClient::ModifyMonitorAttributeCallable(const ModifyMonitorAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyMonitorAttributeOutcome()>>( [this, request]() { return this->ModifyMonitorAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifySiteAttributeOutcome CwsClient::ModifySiteAttribute(const ModifySiteAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifySiteAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifySiteAttributeResponse rsp = ModifySiteAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifySiteAttributeOutcome(rsp); else return ModifySiteAttributeOutcome(o.GetError()); } else { return ModifySiteAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifySiteAttributeAsync(const ModifySiteAttributeRequest& request, const ModifySiteAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifySiteAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifySiteAttributeOutcomeCallable CwsClient::ModifySiteAttributeCallable(const ModifySiteAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifySiteAttributeOutcome()>>( [this, request]() { return this->ModifySiteAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::VerifySitesOutcome CwsClient::VerifySites(const VerifySitesRequest &request) { auto outcome = MakeRequest(request, "VerifySites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); VerifySitesResponse rsp = VerifySitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return VerifySitesOutcome(rsp); else return VerifySitesOutcome(o.GetError()); } else { return VerifySitesOutcome(outcome.GetError()); } } void CwsClient::VerifySitesAsync(const VerifySitesRequest& request, const VerifySitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->VerifySites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::VerifySitesOutcomeCallable CwsClient::VerifySitesCallable(const VerifySitesRequest &request) { auto task = std::make_shared<std::packaged_task<VerifySitesOutcome()>>( [this, request]() { return this->VerifySites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
33.719767
210
0.683851
21e9d91ffbb9f9ccc18cf739ab91c534075e5f63
422
cpp
C++
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int temp = n; int count = 0; map<int, int> mp; while (n != 0) { int a = sqrt(n); int b = temp - pow(a, 2); mp[a] = b; n--; } for (auto &pr : mp) { if (pr.first + pow(pr.second, 2) == m) { count++; } if (pr.second + pow(pr.first, 2) == m && (pr.second == 0 || pr.first == 0)) { count++; } } cout << count; }
16.88
79
0.481043
21e9ecdbe50ce01fc0c3a82d9ea330a09897dad5
14,755
cpp
C++
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
10
2015-03-12T20:20:34.000Z
2021-02-03T08:07:31.000Z
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
3
2015-07-04T23:50:43.000Z
2016-08-01T09:19:52.000Z
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
6
2015-11-28T16:18:26.000Z
2020-03-29T17:14:56.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "T3D/components/physics/rigidBodyComponent.h" #include "core/util/safeDelete.h" #include "console/consoleTypes.h" #include "console/consoleObject.h" #include "core/stream/bitStream.h" #include "console/engineAPI.h" #include "sim/netConnection.h" #include "T3D/physics/physicsBody.h" #include "T3D/physics/physicsPlugin.h" #include "T3D/physics/physicsWorld.h" #include "T3D/physics/physicsCollision.h" #include "T3D/components/collision/collisionComponent.h" bool RigidBodyComponent::smNoCorrections = false; bool RigidBodyComponent::smNoSmoothing = false; ////////////////////////////////////////////////////////////////////////// // Constructor/Destructor ////////////////////////////////////////////////////////////////////////// RigidBodyComponent::RigidBodyComponent() : Component() { mMass = 20; mDynamicFriction = 1; mStaticFriction = 0.1f; mRestitution = 10; mLinearDamping = 0; mAngularDamping = 0; mLinearSleepThreshold = 1; mAngularSleepThreshold = 1; mWaterDampingScale = 0.1f; mBuoyancyDensity = 1; mSimType = SimType_ServerOnly; mPhysicsRep = NULL; mResetPos = MatrixF::Identity; mOwnerColComponent = NULL; mFriendlyName = "RigidBody(Component)"; } RigidBodyComponent::~RigidBodyComponent() { } IMPLEMENT_CO_NETOBJECT_V1(RigidBodyComponent); bool RigidBodyComponent::onAdd() { if(! Parent::onAdd()) return false; return true; } void RigidBodyComponent::onRemove() { Parent::onRemove(); } void RigidBodyComponent::initPersistFields() { Parent::initPersistFields(); } //This is mostly a catch for situations where the behavior is re-added to the object and the like and we may need to force an update to the behavior void RigidBodyComponent::onComponentAdd() { Parent::onComponentAdd(); if (isServerObject()) { storeRestorePos(); PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset); } CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>(); if (colComp) { colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics); updatePhysics(colComp->getCollisionData()); } else updatePhysics(); } void RigidBodyComponent::onComponentRemove() { Parent::onComponentRemove(); if (isServerObject()) { PhysicsPlugin::getPhysicsResetSignal().remove(this, &RigidBodyComponent::_onPhysicsReset); } CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>(); if (colComp) { colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics); } SAFE_DELETE(mPhysicsRep); } void RigidBodyComponent::componentAddedToOwner(Component *comp) { CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp); if (colComp) { colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics); updatePhysics(colComp->getCollisionData()); } } void RigidBodyComponent::componentRemovedFromOwner(Component *comp) { //test if this is a shape component! CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp); if (colComp) { colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics); updatePhysics(); } } void RigidBodyComponent::ownerTransformSet(MatrixF *mat) { if (mPhysicsRep) mPhysicsRep->setTransform(mOwner->getTransform()); } void RigidBodyComponent::updatePhysics(PhysicsCollision* collision) { SAFE_DELETE(mPhysicsRep); if (!PHYSICSMGR) return; mWorld = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client"); if (!collision) return; mPhysicsRep = PHYSICSMGR->createBody(); mPhysicsRep->init(collision, mMass, 0, mOwner, mWorld); mPhysicsRep->setMaterial(mRestitution, mDynamicFriction, mStaticFriction); mPhysicsRep->setDamping(mLinearDamping, mAngularDamping); mPhysicsRep->setSleepThreshold(mLinearSleepThreshold, mAngularSleepThreshold); mPhysicsRep->setTransform(mOwner->getTransform()); // The reset position is the transform on the server // at creation time... its not used on the client. if (isServerObject()) { storeRestorePos(); PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset); } } U32 RigidBodyComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream) { U32 retMask = Parent::packUpdate(con, mask, stream); if (stream->writeFlag(mask & StateMask)) { // This will encode the position relative to the control // object position. // // This will compress the position to as little as 6.25 // bytes if the position is within about 30 meters of the // control object. // // Worst case its a full 12 bytes + 2 bits if the position // is more than 500 meters from the control object. // stream->writeCompressedPoint(mState.position); // Use only 3.5 bytes to send the orientation. stream->writeQuat(mState.orientation, 9); // If the server object has been set to sleep then // we don't need to send any velocity. if (!stream->writeFlag(mState.sleeping)) { // This gives me ~0.015f resolution in velocity magnitude // while only costing me 1 bit of the velocity is zero length, // <5 bytes in normal cases, and <8 bytes if the velocity is // greater than 1000. AssertWarn(mState.linVelocity.len() < 1000.0f, "PhysicsShape::packUpdate - The linVelocity is out of range!"); stream->writeVector(mState.linVelocity, 1000.0f, 16, 9); // For angular velocity we get < 0.01f resolution in magnitude // with the most common case being under 4 bytes. AssertWarn(mState.angVelocity.len() < 10.0f, "PhysicsShape::packUpdate - The angVelocity is out of range!"); stream->writeVector(mState.angVelocity, 10.0f, 10, 9); } } return retMask; } void RigidBodyComponent::unpackUpdate(NetConnection *con, BitStream *stream) { Parent::unpackUpdate(con, stream); if (stream->readFlag()) // StateMask { PhysicsState state; // Read the encoded and compressed position... commonly only 6.25 bytes. stream->readCompressedPoint(&state.position); // Read the compressed quaternion... 3.5 bytes. stream->readQuat(&state.orientation, 9); state.sleeping = stream->readFlag(); if (!state.sleeping) { stream->readVector(&state.linVelocity, 1000.0f, 16, 9); stream->readVector(&state.angVelocity, 10.0f, 10, 9); } if (!smNoCorrections && mPhysicsRep && mPhysicsRep->isDynamic()) { // Set the new state on the physics object immediately. mPhysicsRep->applyCorrection(state.getTransform()); mPhysicsRep->setSleeping(state.sleeping); if (!state.sleeping) { mPhysicsRep->setLinVelocity(state.linVelocity); mPhysicsRep->setAngVelocity(state.angVelocity); } mPhysicsRep->getState(&mState); } // If there is no physics object then just set the // new state... the tick will take care of the // interpolation and extrapolation. if (!mPhysicsRep || !mPhysicsRep->isDynamic()) mState = state; } } void RigidBodyComponent::processTick() { Parent::processTick(); if (!mPhysicsRep || !PHYSICSMGR) return; // Note that unlike TSStatic, the serverside PhysicsShape does not // need to play the ambient animation because even if the animation were // to move collision shapes it would not affect the physx representation. PROFILE_START(RigidBodyComponent_ProcessTick); if (!mPhysicsRep->isDynamic()) return; // SINGLE PLAYER HACK!!!! if (PHYSICSMGR->isSinglePlayer() && isClientObject() && getServerObject()) { RigidBodyComponent *servObj = (RigidBodyComponent*)getServerObject(); mOwner->setTransform(servObj->mState.getTransform()); mRenderState[0] = servObj->mRenderState[0]; mRenderState[1] = servObj->mRenderState[1]; return; } // Store the last render state. mRenderState[0] = mRenderState[1]; // If the last render state doesn't match the last simulation // state then we got a correction and need to Point3F errorDelta = mRenderState[1].position - mState.position; const bool doSmoothing = !errorDelta.isZero() && !smNoSmoothing; const bool wasSleeping = mState.sleeping; // Get the new physics state. mPhysicsRep->getState(&mState); updateContainerForces(); // Smooth the correction back into the render state. mRenderState[1] = mState; if (doSmoothing) { F32 correction = mClampF(errorDelta.len() / 20.0f, 0.1f, 0.9f); mRenderState[1].position.interpolate(mState.position, mRenderState[0].position, correction); mRenderState[1].orientation.interpolate(mState.orientation, mRenderState[0].orientation, correction); } //Check if any collisions occured findContact(); // If we haven't been sleeping then update our transform // and set ourselves as dirty for the next client update. if (!wasSleeping || !mState.sleeping) { // Set the transform on the parent so that // the physics object isn't moved. mOwner->setTransform(mState.getTransform()); // If we're doing server simulation then we need // to send the client a state update. if (isServerObject() && mPhysicsRep && !smNoCorrections && !PHYSICSMGR->isSinglePlayer() // SINGLE PLAYER HACK!!!! ) setMaskBits(StateMask); } PROFILE_END(); } void RigidBodyComponent::findContact() { SceneObject *contactObject = NULL; VectorF *contactNormal = new VectorF(0, 0, 0); Vector<SceneObject*> overlapObjects; mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects); if (!overlapObjects.empty()) { //fire our signal that the physics sim said collisions happened onPhysicsCollision.trigger(*contactNormal, overlapObjects); } } void RigidBodyComponent::_onPhysicsReset(PhysicsResetEvent reset) { if (reset == PhysicsResetEvent_Store) mResetPos = mOwner->getTransform(); else if (reset == PhysicsResetEvent_Restore) { mOwner->setTransform(mResetPos); } } void RigidBodyComponent::storeRestorePos() { mResetPos = mOwner->getTransform(); } void RigidBodyComponent::applyImpulse(const Point3F &pos, const VectorF &vec) { if (mPhysicsRep && mPhysicsRep->isDynamic()) mPhysicsRep->applyImpulse(pos, vec); } void RigidBodyComponent::applyRadialImpulse(const Point3F &origin, F32 radius, F32 magnitude) { if (!mPhysicsRep || !mPhysicsRep->isDynamic()) return; // TODO: Find a better approximation of the // force vector using the object box. VectorF force = mOwner->getWorldBox().getCenter() - origin; F32 dist = force.magnitudeSafe(); force.normalize(); if (dist == 0.0f) force *= magnitude; else force *= mClampF(radius / dist, 0.0f, 1.0f) * magnitude; mPhysicsRep->applyImpulse(origin, force); // TODO: There is no simple way to really sync this sort of an // event with the client. // // The best is to send the current physics snapshot, calculate the // time difference from when this event occured and the time when the // client recieves it, and then extrapolate where it should be. // // Even then its impossible to be absolutely sure its synced. // // Bottom line... you shouldn't use physics over the network like this. // } void RigidBodyComponent::updateContainerForces() { PROFILE_SCOPE(RigidBodyComponent_updateContainerForces); // If we're not simulating don't update forces. PhysicsWorld *world = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client"); if (!world || !world->isEnabled()) return; ContainerQueryInfo info; info.box = mOwner->getWorldBox(); info.mass = mMass; // Find and retreive physics info from intersecting WaterObject(s) mOwner->getContainer()->findObjects(mOwner->getWorldBox(), WaterObjectType | PhysicalZoneObjectType, findRouter, &info); // Calculate buoyancy and drag F32 angDrag = mAngularDamping; F32 linDrag = mLinearDamping; F32 buoyancy = 0.0f; Point3F cmass = mPhysicsRep->getCMassPosition(); F32 density = mBuoyancyDensity; if (density > 0.0f) { if (info.waterCoverage > 0.0f) { F32 waterDragScale = info.waterViscosity * mWaterDampingScale; F32 powCoverage = mPow(info.waterCoverage, 0.25f); angDrag = mLerp(angDrag, angDrag * waterDragScale, powCoverage); linDrag = mLerp(linDrag, linDrag * waterDragScale, powCoverage); } buoyancy = (info.waterDensity / density) * mPow(info.waterCoverage, 2.0f); // A little hackery to prevent oscillation // Based on this blog post: // (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html) // JCF: disabled! Point3F buoyancyForce = buoyancy * -world->getGravity() * TickSec * mMass; mPhysicsRep->applyImpulse(cmass, buoyancyForce); } // Update the dampening as the container might have changed. mPhysicsRep->setDamping(linDrag, angDrag); // Apply physical zone forces. if (!info.appliedForce.isZero()) mPhysicsRep->applyImpulse(cmass, info.appliedForce); }
31.595289
148
0.681261
21ebcb1f72aa97b78ff6c8488fef39137fd25562
4,265
cpp
C++
Random-integer-generator/Random_integer_generatorDlg.cpp
MCjiaozi/Random-integer-generator
8bbd7c662d44556045dba7e848029252982032e2
[ "MIT" ]
null
null
null
Random-integer-generator/Random_integer_generatorDlg.cpp
MCjiaozi/Random-integer-generator
8bbd7c662d44556045dba7e848029252982032e2
[ "MIT" ]
null
null
null
Random-integer-generator/Random_integer_generatorDlg.cpp
MCjiaozi/Random-integer-generator
8bbd7c662d44556045dba7e848029252982032e2
[ "MIT" ]
null
null
null
 // Random_integer_generatorDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "Random_integer_generator.h" #include "Random_integer_generatorDlg.h" #include "afxdialogex.h" #include "MA.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CRandom_integer_generatorDlg 对话框 CRandom_integer_generatorDlg::CRandom_integer_generatorDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_Random_integer_generator_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1); } void CRandom_integer_generatorDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CRandom_integer_generatorDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDOK, &CRandom_integer_generatorDlg::OnBnClickedOk) // ON_WM_MOUSEMOVE() ON_WM_NCHITTEST() ON_BN_CLICKED(IDC_BTN_OPENM, &CRandom_integer_generatorDlg::OnBnClickedBtnOpenm) END_MESSAGE_MAP() // CRandom_integer_generatorDlg 消息处理程序 BOOL CRandom_integer_generatorDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 HICON icon; icon = AfxGetApp()->LoadIcon(IDI_ICON1); SetIcon(icon, TRUE); // 设置大图标 SetIcon(icon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 CRect rectDlg; HDC desktopDc = ::GetDC(NULL); int s = GetDeviceCaps(desktopDc, VERTRES); double sk = GetDeviceCaps(desktopDc, LOGPIXELSY) / static_cast<double>(96); GetWindowRect(rectDlg);//x,y为对话框左上角的坐标 w,h为对话框的宽高 SetWindowPos(NULL, 0, int(s-120*sk), rectDlg.Width(), rectDlg.Height(), NULL); CString con = AfxGetApp()->m_lpCmdLine; if (con != _T("-silence")) { MA* pOneDlgObj = new MA; if (pOneDlgObj) { BOOL ret = pOneDlgObj->Create(IDD_DIALOG_MAIN, GetDesktopWindow()); } pOneDlgObj->ShowWindow(SW_SHOW); } return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CRandom_integer_generatorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CRandom_integer_generatorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CRandom_integer_generatorDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CRandom_integer_generatorDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 CDialogEx::OnOK(); } LRESULT CRandom_integer_generatorDlg::OnNcHitTest(CPoint point) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CRect rc; GetClientRect(&rc); ClientToScreen(&rc); return rc.PtInRect(point) ? HTCAPTION : CDialog::OnNcHitTest(point); } void CRandom_integer_generatorDlg::OnBnClickedBtnOpenm() { // TODO: 在此添加控件通知处理程序代码 MA* pOneDlgObj = new MA; if (pOneDlgObj) { BOOL ret = pOneDlgObj->Create(IDD_DIALOG_MAIN, GetDesktopWindow()); } pOneDlgObj->ShowWindow(SW_SHOW); }
20.603865
86
0.736928
21ed3f17619794aef95953a386f528f7ea2f97a7
1,335
cpp
C++
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
1
2018-10-30T10:02:11.000Z
2018-10-30T10:02:11.000Z
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
null
null
null
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> using namespace std; template<class It> void printByIt(It begin, It end); template<class It> void printByIt(It begin, It end) { for (It curr = begin; curr != end; ++curr) { cout << *curr << " "; } cout << endl; } void sink(vector<int>& a, int k, int N) { int child = 2 * (k+1) - 1; while (child <= N) { if (child < N && a[child] < a[child+1]) { child++; } if (a[k] >= a[child]) { break; } swap(a[k], a[child]); k = child; child = 2 *(k+1) - 1; } } void heap_sort(vector<int>& a) { int N = a.size() - 1; for (int k = N/2; k >= 0; --k) { sink(a, k, N); } while (N > 0) { swap(a[0], a[N--]); sink(a, 0, N); } } int main() { //vector<int> unorder = {5, 4, 3, 4, 1, 4, 2}; //vector<int> unorder = { 2, 4, 3, 1}; //vector<int> unorder = {5, 4, 9, 4, 7, 4, 2}; //vector<int> unorder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //vector<int> unorder = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; //vector<int> unorder = { 3, 2, 1}; vector<int> unorder; cout << "before order: "; printByIt(unorder.begin(), unorder.end()); heap_sort(unorder); cout << "after order: "; printByIt(unorder.begin(), unorder.end()); }
22.25
60
0.468914
21ee74d06c68e18c398f9bb4c9583345361f9456
60
hpp
C++
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/home/support/nonterminal/locals.hpp>
30
59
0.816667
21f009619fb86e73eede2854736e9fb710b9ac1d
15,993
cpp
C++
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from portal.djinni #include "NativeOsIo.hpp" // my header #include "Marshal.hpp" #include "NativeBinaryResult.hpp" #include "NativeBoolResult.hpp" #include "NativeCancellationToken.hpp" #include "NativeFileType.hpp" #include "NativeHeader.hpp" #include "NativeHttpProgressResult.hpp" #include "NativeHttpResult.hpp" #include "NativeHttpVerb.hpp" #include "NativeLogType.hpp" #include "NativeLongResult.hpp" #include "NativeStringResult.hpp" #include "NativeStringsResult.hpp" #include "NativeVoidResult.hpp" namespace djinni_generated { NativeOsIo::NativeOsIo() : ::djinni::JniInterface<::ai::OsIo, NativeOsIo>() {} NativeOsIo::~NativeOsIo() = default; NativeOsIo::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { } NativeOsIo::JavaProxy::~JavaProxy() = default; void NativeOsIo::JavaProxy::log(::ai::LogType c_type, int32_t c_line, const std::string & c_file, const std::string & c_message) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_log, ::djinni::get(::djinni_generated::NativeLogType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_line)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_message))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::log_lines(::ai::LogType c_type, int32_t c_line, const std::string & c_file, const std::vector<std::string> & c_messages) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_logLines, ::djinni::get(::djinni_generated::NativeLogType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_line)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_messages))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_readall(const std::string & c_path, const std::shared_ptr<::ai::BinaryResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileReadall, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeBinaryResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_writeall(const std::string & c_path, const std::vector<uint8_t> & c_content, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWriteall, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni::Binary::fromCpp(jniEnv, c_content)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_writeall_safely(const std::string & c_path, const std::vector<uint8_t> & c_content, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWriteallSafely, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni::Binary::fromCpp(jniEnv, c_content)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_write_password(const std::string & c_username, const std::string & c_password, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWritePassword, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_password)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_read_password(const std::string & c_username, const std::shared_ptr<::ai::StringResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileReadPassword, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni_generated::NativeStringResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_size(const std::string & c_path, const std::shared_ptr<::ai::LongResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileSize, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeLongResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } bool NativeOsIo::JavaProxy::file_thumbnail(const std::string & c_path, ::ai::FileType c_type, const std::shared_ptr<::ai::BinaryResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_fileThumbnail, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeFileType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni_generated::NativeBinaryResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::Bool::toCpp(jniEnv, jret); } void NativeOsIo::JavaProxy::copy_file(const std::string & c_current_path, const std::string & c_new_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_copyFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_current_path)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_new_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::make_path(const std::string & c_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_makePath, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::rename_file(const std::string & c_current_path, const std::string & c_new_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_renameFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_current_path)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_new_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_request(::ai::HttpVerb c_verb, const std::string & c_url, const std::vector<::ai::Header> & c_headers, const std::string & c_body, const std::shared_ptr<::ai::HttpResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpRequest, ::djinni::get(::djinni_generated::NativeHttpVerb::fromCpp(jniEnv, c_verb)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_body)), ::djinni::get(::djinni_generated::NativeHttpResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_upload_file(::ai::HttpVerb c_verb, const std::string & c_url, const std::string & c_file_path, const std::vector<::ai::Header> & c_headers, const std::shared_ptr<::ai::HttpProgressResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpUploadFile, ::djinni::get(::djinni_generated::NativeHttpVerb::fromCpp(jniEnv, c_verb)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file_path)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni_generated::NativeHttpProgressResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_download_file(const std::string & c_url, const std::string & c_file_path, const std::vector<::ai::Header> & c_headers, int64_t c_size, const std::string & c_md5, const std::shared_ptr<::ai::HttpProgressResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpDownloadFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file_path)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni::I64::fromCpp(jniEnv, c_size)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_md5)), ::djinni::get(::djinni_generated::NativeHttpProgressResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } void NativeOsIo::JavaProxy::wait(int32_t c_millis, const std::shared_ptr<::ai::VoidResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_wait, ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_millis)), ::djinni::get(::djinni_generated::NativeVoidResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_expand_directories(const std::vector<std::string> & c_paths, const std::shared_ptr<::ai::StringsResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileExpandDirectories, ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_paths)), ::djinni::get(::djinni_generated::NativeStringsResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_copy_hierarchy(const std::string & c_dest_root_path, const std::vector<std::string> & c_dest_relative_paths, const std::vector<std::string> & c_src_paths) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileCopyHierarchy, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_dest_root_path)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_dest_relative_paths)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_src_paths))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_clear_cache(const std::string & c_username, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileClearCache, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } } // namespace djinni_generated
70.144737
292
0.640718
21f1d8be0a830d3e3a426259d4832472feff02c5
2,354
cc
C++
lite/kernels/host/sequence_unpad_compute.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/kernels/host/sequence_unpad_compute.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/kernels/host/sequence_unpad_compute.cc
yingshengBD/Paddle-Lite
eea59b66f61bb2acad471010c9526eeec43a15ca
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/host/sequence_unpad_compute.h" namespace paddle { namespace lite { namespace kernels {} // namespace kernels } // namespace lite } // namespace paddle using SequenceUnpadFloat32 = paddle::lite::kernels::host::SequenceUnpadCompute<float>; REGISTER_LITE_KERNEL( sequence_unpad, kHost, kFloat, kAny, SequenceUnpadFloat32, float32) .BindInput("X", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kAny))}) .BindInput("Length", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kAny))}) .Finalize(); using SequenceUnpadInt64 = paddle::lite::kernels::host::SequenceUnpadCompute<int64_t>; REGISTER_LITE_KERNEL( sequence_unpad, kHost, kFloat, kAny, SequenceUnpadInt64, int64) .BindInput("X", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindInput("Length", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .Finalize();
40.586207
75
0.56712
21f5c9bd775815a5e340b8446a0d8ec77a9db745
3,236
hxx
C++
opencascade/VrmlData_Box.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/VrmlData_Box.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/VrmlData_Box.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 2006-05-25 // Created by: Alexander GRIGORIEV // Copyright (c) 2006-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef VrmlData_Box_HeaderFile #define VrmlData_Box_HeaderFile #include <VrmlData_Geometry.hxx> #include <gp_XYZ.hxx> /** * Inplementation of the Box node. * This node is defined by Size vector, assumong that the box center is located * in (0., 0., 0.) and that each corner is 0.5*|Size| distance from the center. */ class VrmlData_Box : public VrmlData_Geometry { public: // ---------- PUBLIC METHODS ---------- /** * Empty constructor */ inline VrmlData_Box () : mySize (2., 2., 2.) {} /** * Constructor */ inline VrmlData_Box (const VrmlData_Scene& theScene, const char * theName, const Standard_Real sizeX = 2., const Standard_Real sizeY = 2., const Standard_Real sizeZ = 2.) : VrmlData_Geometry (theScene, theName), mySize (sizeX, sizeY, sizeZ) {} /** * Query the Box size */ inline const gp_XYZ& Size () const { return mySize; } /** * Set the Box Size */ inline void SetSize (const gp_XYZ& theSize) { mySize = theSize; SetModified(); } /** * Query the primitive topology. This method returns a Null shape if there * is an internal error during the primitive creation (zero radius, etc.) */ Standard_EXPORT virtual const Handle(TopoDS_TShape)& TShape () Standard_OVERRIDE; /** * Create a copy of this node. * If the parameter is null, a new copied node is created. Otherwise new node * is not created, but rather the given one is modified. */ Standard_EXPORT virtual Handle(VrmlData_Node) Clone (const Handle(VrmlData_Node)& theOther)const Standard_OVERRIDE; /** * Fill the Node internal data from the given input stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Read (VrmlData_InBuffer& theBuffer) Standard_OVERRIDE; /** * Write the Node to output stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Write (const char * thePrefix) const Standard_OVERRIDE; private: // ---------- PRIVATE FIELDS ---------- gp_XYZ mySize; public: // Declaration of CASCADE RTTI DEFINE_STANDARD_RTTI_INLINE(VrmlData_Box,VrmlData_Geometry) }; // Definition of HANDLE object using Standard_DefineHandle.hxx DEFINE_STANDARD_HANDLE (VrmlData_Box, VrmlData_Geometry) #endif
31.115385
95
0.64555
21f88e293e61d25342f8ab1972bd6644b2b65b9d
904
cpp
C++
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll=long long; void solve() { int k,q; cin >> k >> q; vector<ll> d(k); for (auto& x: d) { cin >> x; } while (q--) { ll n,x,m; cin >> n >> x >> m; n--; x %= m; ll sum = 0; for (auto& x: d) { sum += x%m; } // a_n ll z = x + (n/k) * sum; { ll r = n%k; for (int i = 0; i < r; i++) { z += d[i]%m; } } // #>, cross ll res = z / m; // #=, for (int i = 0; i < k; i++) { if (d[i]%m == 0 && i < n) { res += 1 + (n-i-1) / k; } } res = n - res; cout << res << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
18.08
41
0.301991
21fb53a330953c1ce3974576a63b90ad5df83880
4,214
hpp
C++
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
15
2015-09-02T13:25:55.000Z
2021-04-23T04:02:19.000Z
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
1
2015-11-18T03:50:18.000Z
2016-06-16T08:34:01.000Z
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
4
2016-05-20T18:57:27.000Z
2019-03-17T09:18:13.000Z
#pragma once /// \file node_neighbors.hpp #include <ndtree/algorithm/node_location.hpp> #include <ndtree/algorithm/node_or_parent_at.hpp> #include <ndtree/algorithm/shift_location.hpp> #include <ndtree/concepts.hpp> #include <ndtree/location/default.hpp> #include <ndtree/relations/neighbor.hpp> #include <ndtree/types.hpp> #include <ndtree/utility/static_const.hpp> #include <ndtree/utility/stack_vector.hpp> namespace ndtree { inline namespace v1 { // struct node_neighbors_fn { /// Finds neighbors of node at location \p loc across the Manifold /// (appends them to a push_back-able container) template <typename Manifold, typename Tree, typename Loc, typename PushBackableContainer, CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Manifold positions, Tree const& t, Loc&& loc, PushBackableContainer& s) const noexcept -> void { static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), ""); // For all same level neighbor positions for (auto&& sl_pos : positions()) { auto neighbor = node_or_parent_at(t, shift_location(loc, positions[sl_pos])); if (!neighbor.idx) { continue; } NDTREE_ASSERT((neighbor.level == loc.level()) || (neighbor.level == (loc.level() - 1)), "found neighbor must either be at the same level or at the " "parent level"); // if the neighbor found is a leaf node we are done // note: it is either at the same or parent level of the node // (doesn't matter which case it is, it is the correct neighbor) if (t.is_leaf(neighbor.idx)) { s.push_back(neighbor.idx); } else { // if it has children we add the children sharing a face with the node for (auto&& cp : Manifold{}.children_sharing_face(sl_pos)) { s.push_back(t.child(neighbor.idx, cp)); } } } } /// Finds neighbors of node at location \p loc across the Manifold /// /// \returns stack allocated vector containing the neighbors template <typename Manifold, typename Tree, typename Loc, int max_no_neighbors = Manifold::no_child_level_neighbors(), CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Manifold, Tree const& t, Loc&& loc) const noexcept -> stack_vector<node_idx, max_no_neighbors> { static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), ""); stack_vector<node_idx, max_no_neighbors> neighbors; (*this)(Manifold{}, t, loc, neighbors); return neighbors; } /// Finds set of unique neighbors of node at location \p loc across all /// manifolds /// /// \param t [in] tree. /// \param loc [in] location (location of the node). /// \returns stack allocated vector containing the unique set of neighbors /// template <typename Tree, typename Loc, int nd = Tree::dimension(), CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Tree const& t, Loc&& loc) const noexcept -> stack_vector<node_idx, max_no_neighbors(nd)> { stack_vector<node_idx, max_no_neighbors(nd)> neighbors; // For each surface manifold append the neighbors using manifold_rng = meta::as_list<meta::integer_range<int, 1, nd + 1>>; meta::for_each(manifold_rng{}, [&](auto m_) { using manifold = manifold_neighbors<nd, decltype(m_){}>; (*this)(manifold{}, t, loc, neighbors); }); // sort them and remove dupplicates ranges::sort(neighbors); neighbors.erase(ranges::unique(neighbors), end(neighbors)); return neighbors; } /// Finds set of unique neighbors of node \p n across all manifolds /// /// \param t [in] tree. /// \param n [in] node index. /// \returns stack allocated vector containing the unique set of neighbors /// template <typename Tree, typename Loc = location::default_location<Tree::dimension()>, CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Tree const& t, node_idx n, Loc l = Loc{}) const noexcept { return (*this)(t, node_location(t, n, l)); } }; namespace { constexpr auto&& node_neighbors = static_const<node_neighbors_fn>::value; } // namespace } // namespace v1 } // namespace ndtree
38.66055
80
0.665638
21fc31b255d35e447e5963d78bc5cd3c7c4300c2
750
cpp
C++
C++/test/algorithm/number_theory/primorial_of_prime.cpp
Shubham230198/Algos
9a07f372e3571be931acbaa384de32c35b9814a9
[ "MIT" ]
4
2019-10-22T18:03:45.000Z
2019-10-23T17:27:54.000Z
C++/test/algorithm/number_theory/primorial_of_prime.cpp
Shubham230198/Algos
9a07f372e3571be931acbaa384de32c35b9814a9
[ "MIT" ]
null
null
null
C++/test/algorithm/number_theory/primorial_of_prime.cpp
Shubham230198/Algos
9a07f372e3571be931acbaa384de32c35b9814a9
[ "MIT" ]
null
null
null
#include "third_party/catch.hpp" #include "algorithm/number_theory/primorial_of_prime.hpp" TEST_CASE("Normal cases","[primorial_of_prime]") { REQUIRE(primorial_of_prime(2) == 2); REQUIRE(primorial_of_prime(5) == 30); REQUIRE(primorial_of_prime(11) == 2310); REQUIRE(primorial_of_prime(13) == 30030); REQUIRE(primorial_of_prime(23) == 223092870); REQUIRE(primorial_of_prime(29) == 6469693230); REQUIRE(primorial_of_prime(37) == 7420738134810); REQUIRE(primorial_of_prime(43) == 13082761331670030); REQUIRE(primorial_of_prime(47) == 614889782588491410); } TEST_CASE("Overflow cases","[primorial_of_prime]") { REQUIRE(primorial_of_prime(53) == -1); REQUIRE(primorial_of_prime(88) == -1); }
39.473684
59
0.706667
21fd4bc267f14b60f09e459e847e00fd01369c86
995
cpp
C++
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
4
2020-12-29T09:27:10.000Z
2022-02-12T14:20:23.000Z
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-27T06:15:28.000Z
2021-11-27T06:15:28.000Z
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-17T21:42:57.000Z
2021-11-17T21:42:57.000Z
/* Move all negative numbers to beginning and positive to end with constant extra space Input: -12, 11, -13, -5, 6, -7, 5, -3, -6 Output: -12 -13 -5 -7 -3 -6 11 6 5 https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/ */ #include<iostream> using namespace std; int main() { int n; cin>>n; int arr[n]; for(int i=0; i<n; i++){ cin>>arr[i]; } //two pointer approach int left = 0, right = n-1; while(left <= right){ if(arr[left] < 0 && arr[right] < 0) left++; else if(arr[left] > 0 && arr[right] < 0){ swap(arr[left], arr[right]); left++; right--; } else if(arr[left] > 0 && arr[right] > 0){ right--; } else if(arr[left] < 0 && arr[right] > 0){ left++; right--; } } //display the array for(int i=0; i<n; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
21.170213
96
0.491457
21fece503f73452353bb3fdc2d5faf6d4d5d2db7
29,388
cpp
C++
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //***************************************************************************** //***************************************************************************** #include "stdpch.h" #include "richedit.h" #include "commctrl.h" #include "resource.h" #include "corpolicy.h" #include "corperm.h" #include "corhlpr.h" #include "winwrap.h" #include "acuihelp.h" #include "acui.h" //+--------------------------------------------------------------------------- // // Function: ACUISetArrowCursorSubclass // // Synopsis: subclass routine for setting the arrow cursor. This can be // set on multiline edit routines used in the dialog UIs for // the default Authenticode provider // // Arguments: [hwnd] -- window handle // [uMsg] -- message id // [wParam] -- parameter 1 // [lParam] -- parameter 2 // // Returns: TRUE if message handled, FALSE otherwise // // Notes: // //---------------------------------------------------------------------------- LRESULT CALLBACK ACUISetArrowCursorSubclass ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { //HDC hdc; WNDPROC wndproc; //PAINTSTRUCT ps; wndproc = (WNDPROC)WszGetWindowLong(hwnd, GWLP_USERDATA); switch ( uMsg ) { case WM_SETCURSOR: SetCursor(WszLoadCursor(NULL, IDC_ARROW)); return( TRUE ); break; case WM_CHAR: if ( wParam != (WPARAM)' ' ) { break; } case WM_LBUTTONDOWN: return(TRUE); case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: return( TRUE ); break; case EM_SETSEL: return( TRUE ); break; case WM_PAINT: WszCallWindowProc(wndproc, hwnd, uMsg, wParam, lParam); if ( hwnd == GetFocus() ) { DrawFocusRectangle(hwnd, NULL); } return( TRUE ); break; case WM_SETFOCUS: InvalidateRect(hwnd, NULL, FALSE); UpdateWindow(hwnd); SetCursor(WszLoadCursor(NULL, IDC_ARROW)); return( TRUE ); case WM_KILLFOCUS: InvalidateRect(hwnd, NULL, TRUE); UpdateWindow(hwnd); return( TRUE ); } return(WszCallWindowProc(wndproc, hwnd, uMsg, wParam, lParam)); } //+--------------------------------------------------------------------------- // // Function: RebaseControlVertical // // Synopsis: Take the window control, if it has to be resized for text, do // so. Reposition it adjusted for delta pos and return any // height difference for the text resizing // // Arguments: [hwndDlg] -- host dialog // [hwnd] -- control // [hwndNext] -- next control // [fResizeForText] -- resize for text flag // [deltavpos] -- delta vertical position // [oline] -- original number of lines // [minsep] -- minimum separator // [pdeltaheight] -- delta in control height // // Returns: (none) // // Notes: // //---------------------------------------------------------------------------- VOID RebaseControlVertical ( HWND hwndDlg, HWND hwnd, HWND hwndNext, BOOL fResizeForText, int deltavpos, int oline, int minsep, int* pdeltaheight ) { int x = 0; int y = 0; int odn = 0; int orig_w; RECT rect; RECT rectNext; RECT rectDlg; TEXTMETRIC tm={0}; // // Set the delta height to zero for now. If we resize the text // a new one will be calculated // *pdeltaheight = 0; // // Get the control window rectangle // GetWindowRect(hwnd, &rect); GetWindowRect(hwndNext, &rectNext); odn = rectNext.top - rect.bottom; orig_w = rect.right - rect.left; MapWindowPoints(NULL, hwndDlg, (LPPOINT) &rect, 2); // // If we have to resize the control due to text, find out what font // is being used and the number of lines of text. From that we'll // calculate what the new height for the control is and set it up // if ( fResizeForText == TRUE ) { HDC hdc; HFONT hfont; HFONT hfontOld; int cline; int h; int w; int dh; int lineHeight; // // Get the metrics of the current control font // hdc = GetDC(hwnd); if (hdc == NULL) { hdc = GetDC(NULL); if (hdc == NULL) { return; } } hfont = (HFONT)WszSendMessage(hwnd, WM_GETFONT, 0, 0); if ( hfont == NULL ) { hfont = (HFONT)WszSendMessage(hwndDlg, WM_GETFONT, 0, 0); } hfontOld = (HFONT)SelectObject(hdc, hfont); if(!GetTextMetrics(hdc, &tm)) { tm.tmHeight=32; //hopefully GetRichEditControlLineHeight will replace it. // If not - we have to take a guess because we can't fail RebaseControlVertical tm.tmMaxCharWidth=16; // doesn't matter that much but should be bigger than 0 }; lineHeight = GetRichEditControlLineHeight(hwnd); if (lineHeight == 0) { lineHeight = tm.tmHeight; } // // Set the minimum separation value // if ( minsep == 0 ) { minsep = lineHeight; } // // Calculate the width and the new height needed // cline = (int)WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0); h = cline * lineHeight; w = GetEditControlMaxLineWidth(hwnd, hdc, cline); w += 3; // a little bump to make sure string will fit if (w > orig_w) { w = orig_w; } SelectObject(hdc, hfontOld); ReleaseDC(hwnd, hdc); // // Calculate an addition to height by checking how much space was // left when there were the original # of lines and making sure that // that amount is still left when we do any adjustments // h += ( ( rect.bottom - rect.top ) - ( oline * lineHeight ) ); dh = h - ( rect.bottom - rect.top ); // // If the current height is too small, adjust for it, otherwise // leave the current height and just adjust for the width // if ( dh > 0 ) { SetWindowPos(hwnd, NULL, 0, 0, w, h, SWP_NOZORDER | SWP_NOMOVE); } else { SetWindowPos( hwnd, NULL, 0, 0, w, ( rect.bottom - rect.top ), SWP_NOZORDER | SWP_NOMOVE ); } if ( cline < WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ) { AdjustEditControlWidthToLineCount(hwnd, cline, &tm); } } // // If we have to use deltavpos then calculate the X and the new Y // and set the window position appropriately // if ( deltavpos != 0 ) { GetWindowRect(hwndDlg, &rectDlg); MapWindowPoints(NULL, hwndDlg, (LPPOINT) &rectDlg, 2); x = rect.left - rectDlg.left - GetSystemMetrics(SM_CXEDGE); y = rect.top - rectDlg.top - GetSystemMetrics(SM_CYCAPTION) + deltavpos; SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } // // Get the window rect for the next control and see what the distance // is between the current control and it. With that we must now // adjust our deltaheight, if the distance to the next control is less // than a line height then make it a line height, otherwise just let it // be // if ( hwndNext != NULL ) { int dn; GetWindowRect(hwnd, &rect); GetWindowRect(hwndNext, &rectNext); dn = rectNext.top - rect.bottom; if ( odn > minsep ) { if ( dn < minsep ) { *pdeltaheight = minsep - dn; } } else { if ( dn < odn ) { *pdeltaheight = odn - dn; } } } } int GetRichEditControlLineHeight(HWND hwnd) { RECT rect; POINT pointInFirstRow; POINT pointInSecondRow; int secondLineCharIndex; int i; RECT originalRect; GetWindowRect(hwnd, &originalRect); // // HACK ALERT, believe it or not there is no way to get the height of the current // font in the edit control, so get the position a character in the first row and the position // of a character in the second row, and do the subtraction to get the // height of the font // WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInFirstRow, (LPARAM) 0); // // HACK ON TOP OF HACK ALERT, // since there may not be a second row in the edit box, keep reducing the width // by half until the first row falls over into the second row, then get the position // of the first char in the second row and finally reset the edit box size back to // it's original size // secondLineCharIndex = (int)WszSendMessage(hwnd, EM_LINEINDEX, (WPARAM) 1, (LPARAM) 0); if (secondLineCharIndex == -1) { for (i=0; i<20; i++) { GetWindowRect(hwnd, &rect); SetWindowPos( hwnd, NULL, 0, 0, (rect.right-rect.left)/2, rect.bottom-rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); secondLineCharIndex = (int)WszSendMessage(hwnd, EM_LINEINDEX, (WPARAM) 1, (LPARAM) 0); if (secondLineCharIndex != -1) { break; } } if (secondLineCharIndex == -1) { // if we failed after twenty tries just reset the control to its original size // and get the heck outa here!! SetWindowPos(hwnd, NULL, 0, 0, originalRect.right-originalRect.left, originalRect.bottom-originalRect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); return 0; } WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInSecondRow, (LPARAM) secondLineCharIndex); SetWindowPos(hwnd, NULL, 0, 0, originalRect.right-originalRect.left, originalRect.bottom-originalRect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } else { WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInSecondRow, (LPARAM) secondLineCharIndex); } return (pointInSecondRow.y - pointInFirstRow.y); } //+--------------------------------------------------------------------------- // // Function: FormatACUIResourceString // // Synopsis: formats a string given a resource id and message arguments // // Arguments: [StringResourceId] -- resource id // [aMessageArgument] -- message arguments // [ppszFormatted] -- formatted string goes here // // Returns: S_OK if successful, any valid HRESULT otherwise // //---------------------------------------------------------------------------- HRESULT FormatACUIResourceString (HINSTANCE hResources, UINT StringResourceId, DWORD_PTR* aMessageArgument, LPWSTR* ppszFormatted) { HRESULT hr = S_OK; WCHAR sz[MAX_LOADSTRING_BUFFER]; LPVOID pvMsg; pvMsg = NULL; sz[0] = NULL; // // Load the string resource and format the message with that string and // the message arguments // if (StringResourceId != 0) { if ( WszLoadString(hResources, StringResourceId, sz, MAX_LOADSTRING_BUFFER) == 0 ) { return(HRESULT_FROM_WIN32(GetLastError())); } if ( WszFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, sz, 0, 0, (LPWSTR)&pvMsg, 0, (va_list *)aMessageArgument) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { if ( WszFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, (char *)aMessageArgument[0], 0, 0, (LPWSTR)&pvMsg, 0, (va_list *)&aMessageArgument[1]) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if (pvMsg) { *ppszFormatted = new WCHAR[wcslen((WCHAR *)pvMsg) + 1]; if (*ppszFormatted) { wcscpy(*ppszFormatted, (WCHAR *)pvMsg); } LocalFree(pvMsg); } return( hr ); } //+--------------------------------------------------------------------------- // // Function: CalculateControlVerticalDistance // // Synopsis: calculates the vertical distance from the bottom of Control1 // to the top of Control2 // // Arguments: [hwnd] -- parent dialog // [Control1] -- first control // [Control2] -- second control // // Returns: the distance in pixels // // Notes: assumes control1 is above control2 // //---------------------------------------------------------------------------- int CalculateControlVerticalDistance (HWND hwnd, UINT Control1, UINT Control2) { RECT rect1; RECT rect2; GetWindowRect(GetDlgItem(hwnd, Control1), &rect1); GetWindowRect(GetDlgItem(hwnd, Control2), &rect2); return( rect2.top - rect1.bottom ); } //+--------------------------------------------------------------------------- // // Function: CalculateControlVerticalDistanceFromDlgBottom // // Synopsis: calculates the distance from the bottom of the control to // the bottom of the dialog // // Arguments: [hwnd] -- dialog // [Control] -- control // // Returns: the distance in pixels // // Notes: // //---------------------------------------------------------------------------- int CalculateControlVerticalDistanceFromDlgBottom (HWND hwnd, UINT Control) { RECT rect; RECT rectControl; GetClientRect(hwnd, &rect); GetWindowRect(GetDlgItem(hwnd, Control), &rectControl); return( rect.bottom - rectControl.bottom ); } //+--------------------------------------------------------------------------- // // Function: ACUICenterWindow // // Synopsis: centers the given window // // Arguments: [hWndToCenter] -- window handle // // Returns: (none) // // Notes: This code was stolen from ATL and hacked upon madly :-) // //---------------------------------------------------------------------------- VOID ACUICenterWindow (HWND hWndToCenter) { HWND hWndCenter; // determine owner window to center against DWORD dwStyle = (DWORD) WszGetWindowLong(hWndToCenter, GWL_STYLE); if(dwStyle & WS_CHILD) hWndCenter = ::GetParent(hWndToCenter); else hWndCenter = ::GetWindow(hWndToCenter, GW_OWNER); if (hWndCenter == NULL) { return; } // get coordinates of the window relative to its parent RECT rcDlg; ::GetWindowRect(hWndToCenter, &rcDlg); RECT rcArea; RECT rcCenter; HWND hWndParent; if(!(dwStyle & WS_CHILD)) { // don't center against invisible or minimized windows if(hWndCenter != NULL) { DWORD dwStyle2 = (DWORD) WszGetWindowLong(hWndCenter, GWL_STYLE); if(!(dwStyle2 & WS_VISIBLE) || (dwStyle2 & WS_MINIMIZE)) hWndCenter = NULL; } // center within screen coordinates WszSystemParametersInfo(SPI_GETWORKAREA, NULL, &rcArea, NULL); if(hWndCenter == NULL) rcCenter = rcArea; else ::GetWindowRect(hWndCenter, &rcCenter); } else { // center within parent client coordinates hWndParent = ::GetParent(hWndToCenter); ::GetClientRect(hWndParent, &rcArea); ::GetClientRect(hWndCenter, &rcCenter); ::MapWindowPoints(hWndCenter, hWndParent, (POINT*)&rcCenter, 2); } int DlgWidth = rcDlg.right - rcDlg.left; int DlgHeight = rcDlg.bottom - rcDlg.top; // find dialog's upper left based on rcCenter int xLeft = (rcCenter.left + rcCenter.right) / 2 - DlgWidth / 2; int yTop = (rcCenter.top + rcCenter.bottom) / 2 - DlgHeight / 2; // if the dialog is outside the screen, move it inside if(xLeft < rcArea.left) xLeft = rcArea.left; else if(xLeft + DlgWidth > rcArea.right) xLeft = rcArea.right - DlgWidth; if(yTop < rcArea.top) yTop = rcArea.top; else if(yTop + DlgHeight > rcArea.bottom) yTop = rcArea.bottom - DlgHeight; // map screen coordinates to child coordinates ::SetWindowPos( hWndToCenter, HWND_TOPMOST, xLeft, yTop, -1, -1, SWP_NOSIZE | SWP_NOACTIVATE ); } //+--------------------------------------------------------------------------- // // Function: ACUIViewHTMLHelpTopic // // Synopsis: html help viewer // // Arguments: [hwnd] -- caller window // [pszTopic] -- topic // // Returns: (none) // // Notes: // //---------------------------------------------------------------------------- VOID ACUIViewHTMLHelpTopic (HWND hwnd, LPSTR pszTopic) { // HtmlHelpA( // hwnd, // "%SYSTEMROOT%\\help\\iexplore.chm>large_context", // HH_DISPLAY_TOPIC, // (DWORD)pszTopic // ); } //+--------------------------------------------------------------------------- // // Function: GetEditControlMaxLineWidth // // Synopsis: gets the maximum line width of the edit control // //---------------------------------------------------------------------------- int GetEditControlMaxLineWidth (HWND hwndEdit, HDC hdc, int cline) { int index; int line; int charwidth; int maxwidth = 0; CHAR szMaxBuffer[1024]; WCHAR wsz[1024]; TEXTRANGEA tr; SIZE size; tr.lpstrText = szMaxBuffer; for ( line = 0; line < cline; line++ ) { index = (int)WszSendMessage(hwndEdit, EM_LINEINDEX, (WPARAM)line, 0); charwidth = (int)WszSendMessage(hwndEdit, EM_LINELENGTH, (WPARAM)index, 0); tr.chrg.cpMin = index; tr.chrg.cpMax = index + charwidth; WszSendMessage(hwndEdit, EM_GETTEXTRANGE, 0, (LPARAM)&tr); wsz[0] = NULL; MultiByteToWideChar(0, 0, (const char *)tr.lpstrText, -1, &wsz[0], 1024); if (wsz[0]) { GetTextExtentPoint32W(hdc, &wsz[0], charwidth, &size); if ( size.cx > maxwidth ) { maxwidth = size.cx; } } } return( maxwidth ); } //+--------------------------------------------------------------------------- // // Function: DrawFocusRectangle // // Synopsis: draws the focus rectangle for the edit control // //---------------------------------------------------------------------------- void DrawFocusRectangle (HWND hwnd, HDC hdc) { RECT rect; //PAINTSTRUCT ps; BOOL fReleaseDC = FALSE; if ( hdc == NULL ) { hdc = GetDC(hwnd); if ( hdc == NULL ) { return; } fReleaseDC = TRUE; } GetClientRect(hwnd, &rect); DrawFocusRect(hdc, &rect); if ( fReleaseDC == TRUE ) { ReleaseDC(hwnd, hdc); } } //+--------------------------------------------------------------------------- // // Function: GetHotKeyCharPositionFromString // // Synopsis: gets the character position for the hotkey, zero means // no-hotkey // //---------------------------------------------------------------------------- int GetHotKeyCharPositionFromString (LPWSTR pwszText) { LPWSTR psz = pwszText; while ( ( psz = wcschr(psz, L'&') ) != NULL ) { psz++; if ( *psz != L'&' ) { break; } } if ( psz == NULL ) { return( 0 ); } return (int)(( psz - pwszText ) ); } //+--------------------------------------------------------------------------- // // Function: GetHotKeyCharPosition // // Synopsis: gets the character position for the hotkey, zero means // no-hotkey // //---------------------------------------------------------------------------- int GetHotKeyCharPosition (HWND hwnd) { int nPos = 0; WCHAR szText[MAX_LOADSTRING_BUFFER] = L""; if (WszGetWindowText(hwnd, szText, MAX_LOADSTRING_BUFFER)) { nPos = GetHotKeyCharPositionFromString(szText); } return nPos; } //+--------------------------------------------------------------------------- // // Function: FormatHotKeyOnEditControl // // Synopsis: formats the hot key on an edit control by making it underlined // //---------------------------------------------------------------------------- VOID FormatHotKeyOnEditControl (HWND hwnd, int hkcharpos) { CHARRANGE cr; CHARFORMAT cf; assert( hkcharpos != 0 ); cr.cpMin = hkcharpos - 1; cr.cpMax = hkcharpos; WszSendMessage(hwnd, EM_EXSETSEL, 0, (LPARAM)&cr); memset(&cf, 0, sizeof(CHARFORMAT)); cf.cbSize = sizeof(CHARFORMAT); cf.dwMask = CFM_UNDERLINE; cf.dwEffects |= CFM_UNDERLINE; WszSendMessage(hwnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); cr.cpMin = -1; cr.cpMax = 0; WszSendMessage(hwnd, EM_EXSETSEL, 0, (LPARAM)&cr); } //+--------------------------------------------------------------------------- // // Function: AdjustEditControlWidthToLineCount // // Synopsis: adjust edit control width to the given line count // //---------------------------------------------------------------------------- void AdjustEditControlWidthToLineCount(HWND hwnd, int cline, TEXTMETRIC* ptm) { RECT rect; int w; int h; GetWindowRect(hwnd, &rect); h = rect.bottom - rect.top; w = rect.right - rect.left; while ( cline < WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ) { w += ptm->tmMaxCharWidth?ptm->tmMaxCharWidth:16; SetWindowPos(hwnd, NULL, 0, 0, w, h, SWP_NOZORDER | SWP_NOMOVE); printf( "Line count adjusted to = %d\n", (DWORD) WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ); } } DWORD CryptUISetRicheditTextW(HWND hwndDlg, UINT id, LPCWSTR pwsz) { EDITSTREAM editStream; STREAMIN_HELPER_STRUCT helpStruct; SetRicheditIMFOption(GetDlgItem(hwndDlg, id)); // // setup the edit stream struct since it is the same no matter what // editStream.dwCookie = (DWORD_PTR) &helpStruct; editStream.dwError = 0; editStream.pfnCallback = SetRicheditTextWCallback; if (!GetRichEdit2Exists() || !fRichedit20Usable(GetDlgItem(hwndDlg, id))) { WszSetDlgItemText(hwndDlg, id, pwsz); return 0; } helpStruct.pwsz = pwsz; helpStruct.byteoffset = 0; helpStruct.fStreamIn = TRUE; SendDlgItemMessageA(hwndDlg, id, EM_STREAMIN, SF_TEXT | SF_UNICODE, (LPARAM) &editStream); return editStream.dwError; } void SetRicheditIMFOption(HWND hWndRichEdit) { DWORD dwOptions; if (GetRichEdit2Exists() && fRichedit20Usable(hWndRichEdit)) { dwOptions = (DWORD)SendMessageA(hWndRichEdit, EM_GETLANGOPTIONS, 0, 0); dwOptions |= IMF_UIFONTS; SendMessageA(hWndRichEdit, EM_SETLANGOPTIONS, 0, dwOptions); } } DWORD CALLBACK SetRicheditTextWCallback( DWORD_PTR dwCookie, // application-defined value LPBYTE pbBuff, // pointer to a buffer LONG cb, // number of bytes to read or write LONG *pcb // pointer to number of bytes transferred ) { STREAMIN_HELPER_STRUCT *pHelpStruct = (STREAMIN_HELPER_STRUCT *) dwCookie; LONG lRemain = ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); if (pHelpStruct->fStreamIn) { // // The whole string can be copied first time // if ((cb >= (LONG) (wcslen(pHelpStruct->pwsz) * sizeof(WCHAR))) && (pHelpStruct->byteoffset == 0)) { memcpy(pbBuff, pHelpStruct->pwsz, wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)); *pcb = wcslen(pHelpStruct->pwsz) * sizeof(WCHAR); pHelpStruct->byteoffset = *pcb; } // // The whole string has been copied, so terminate the streamin callbacks // by setting the num bytes copied to 0 // else if (((LONG)(wcslen(pHelpStruct->pwsz) * sizeof(WCHAR))) <= pHelpStruct->byteoffset) { *pcb = 0; } // // The rest of the string will fit in this buffer // else if (cb >= (LONG) ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset)) { memcpy( pbBuff, ((BYTE *)pHelpStruct->pwsz) + pHelpStruct->byteoffset, ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset)); *pcb = ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); pHelpStruct->byteoffset += ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); } // // copy as much as possible // else { memcpy( pbBuff, ((BYTE *)pHelpStruct->pwsz) + pHelpStruct->byteoffset, cb); *pcb = cb; pHelpStruct->byteoffset += cb; } } else { // // This is the EM_STREAMOUT which is only used during the testing of // the richedit2.0 functionality. (we know our buffer is 32 bytes) // if (cb <= 32) { memcpy(pHelpStruct->psz, pbBuff, cb); } *pcb = cb; } return 0; } static BOOL fRichedit20UsableCheckMade = FALSE; static BOOL fRichedit20UsableVar = FALSE; BOOL fRichedit20Usable(HWND hwndEdit) { EDITSTREAM editStream; STREAMIN_HELPER_STRUCT helpStruct; LPWSTR pwsz = L"Test String"; LPSTR pwszCompare = "Test String"; char compareBuf[32]; if (fRichedit20UsableCheckMade) { return (fRichedit20UsableVar); } // // setup the edit stream struct since it is the same no matter what // editStream.dwCookie = (DWORD_PTR) &helpStruct; editStream.dwError = 0; editStream.pfnCallback = SetRicheditTextWCallback; helpStruct.pwsz = pwsz; helpStruct.byteoffset = 0; helpStruct.fStreamIn = TRUE; SendMessageA(hwndEdit, EM_SETSEL, 0, -1); SendMessageA(hwndEdit, EM_STREAMIN, SF_TEXT | SF_UNICODE | SFF_SELECTION, (LPARAM) &editStream); memset(&(compareBuf[0]), 0, 32 * sizeof(char)); helpStruct.psz = compareBuf; helpStruct.fStreamIn = FALSE; SendMessageA(hwndEdit, EM_STREAMOUT, SF_TEXT, (LPARAM) &editStream); fRichedit20UsableVar = (strcmp(pwszCompare, compareBuf) == 0); fRichedit20UsableCheckMade = TRUE; SetWindowTextA(hwndEdit, ""); return (fRichedit20UsableVar); }
28.811765
115
0.500272
1d019fde0e400dd85407182f3575e568a42677b0
1,127
cpp
C++
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
HeadClot/ue4-rts
53499c49942aada835b121c89419aaa0be624cbd
[ "MIT" ]
617
2017-04-16T13:34:20.000Z
2022-03-31T23:43:47.000Z
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
freezernick/ue4-rts
14ac47ce07d920c01c999f78996791c75de8ff8a
[ "MIT" ]
178
2017-04-05T19:30:21.000Z
2022-03-11T05:44:03.000Z
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
freezernick/ue4-rts
14ac47ce07d920c01c999f78996791c75de8ff8a
[ "MIT" ]
147
2017-06-27T08:35:09.000Z
2022-03-28T03:06:17.000Z
#include "Libraries/RTSConstructionLibrary.h" #include "Construction/RTSBuilderComponent.h" int32 URTSConstructionLibrary::GetConstructableBuildingIndex(AActor* Builder, TSubclassOf<AActor> BuildingClass) { if (!IsValid(Builder)) { return INDEX_NONE; } URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>(); if (!IsValid(BuilderComponent)) { return INDEX_NONE; } return BuilderComponent->GetConstructibleBuildingClasses().IndexOfByKey(BuildingClass); } TSubclassOf<AActor> URTSConstructionLibrary::GetConstructableBuildingClass(AActor* Builder, int32 BuildingIndex) { if (!IsValid(Builder)) { return nullptr; } URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>(); if (!IsValid(BuilderComponent)) { return nullptr; } TArray<TSubclassOf<AActor>> ConstructableBuildings = BuilderComponent->GetConstructibleBuildingClasses(); return ConstructableBuildings.IsValidIndex(BuildingIndex) ? ConstructableBuildings[BuildingIndex] : nullptr; }
28.175
112
0.753327
1d01d78a62b4b0e4ac4e5254e1866e2051263ade
710
hpp
C++
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
#ifndef DNSPERF_QUERY_PROCESSOR_HPP #define DNSPERF_QUERY_PROCESSOR_HPP #include <string> #include <cstdint> #include "query_result.hpp" /** * Interface of processor which is responsible for making a query. */ struct query_processor { query_processor() = default; query_processor(const query_processor & other) = default; query_processor( query_processor && other) = default; query_processor & operator=(const query_processor & other) = default; query_processor & operator=( query_processor && other) = default; virtual ~query_processor() = default; virtual query_result process(const std::string & url) const = 0; }; #endif //DNSPERF_QUERY_PROCESSOR_HPP
25.357143
73
0.725352
1d0af241a2faaa6acd1f66644a479013f931bef4
868
cpp
C++
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #include "ThreadLockData.h" #include "Mutex.h" #include "MutexBase.h" namespace BOI { MutexBase::MutexBase() : m_mutexId(0), m_lockData() { } void MutexBase::Attach(Mutex* pMutex) { pMutex->m_pBase = this; pMutex->m_pMutex = &m_mutexes[m_mutexId]; m_mutexId = (m_mutexId + 1) % BOI_MUTEXBASE_MAX_QMUTEXES; } ThreadLockData* MutexBase::GetData() { ThreadLockData* pThreadLockData = m_lockData.localData(); if (pThreadLockData == NULL) { pThreadLockData = new ThreadLockData; m_lockData.setLocalData(pThreadLockData); } return pThreadLockData; } } // namespace BOI
18.869565
63
0.686636
1d0bd93afc7c766106a533846cefcae4e2fd40c8
3,426
cc
C++
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
17
2019-12-11T14:26:21.000Z
2022-01-30T03:41:40.000Z
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
8
2019-12-13T14:45:32.000Z
2022-02-14T16:22:30.000Z
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
2
2020-07-29T08:47:50.000Z
2021-12-13T10:38:39.000Z
// Copyright 2019 Magazino GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 <iostream> #include <memory> #include <thread> #include "ros/ros.h" #include "tf_service/buffer_server.h" #include "boost/program_options.hpp" namespace po = boost::program_options; int main(int argc, char** argv) { int num_threads = 0; po::options_description desc("Options"); // clang-format off desc.add_options() ("help", "show usage") ("num_threads", po::value<int>(&num_threads)->default_value(0), "Number of handler threads. 0 means number of CPU cores.") ("cache_time", po::value<double>(), "Buffer cache time of the underlying TF buffer in seconds.") ("max_timeout", po::value<double>(), "Requests with lookup timeouts (seconds) above this will be blocked.") ("frames_service", "Advertise the tf2_frames service.") ("debug", "Advertise the tf2_frames service (same as --frames_service).") ("add_legacy_server", "If set, also run a tf2_ros::BufferServer.") ("legacy_server_namespace", po::value<std::string>(), "Use a separate namespace for the legacy action server.") ; // clang-format on po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); } catch (const po::error& exception) { std::cerr << exception.what() << std::endl; return EXIT_FAILURE; } po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return EXIT_FAILURE; } ros::init(argc, argv, "tf_service"); // boost::po overflows unsigned int for negative values passed to argv, // so we use a signed one and check manually. if (num_threads < 0) { ROS_ERROR("The number of threads can't be negative."); return EXIT_FAILURE; } else if (num_threads == 0) { ROS_INFO_STREAM("--num_threads unspecified / zero, using available cores."); num_threads = std::thread::hardware_concurrency(); } tf_service::ServerOptions options; if (vm.count("cache_time")) options.cache_time = ros::Duration(vm["cache_time"].as<double>()); if (vm.count("max_timeout")) options.max_timeout = ros::Duration(vm["max_timeout"].as<double>()); options.debug = vm.count("frames_service") || vm.count("debug"); options.add_legacy_server = vm.count("add_legacy_server"); options.legacy_server_namespace = vm.count("legacy_server_namespace") ? vm["legacy_server_namespace"].as<std::string>() : ros::this_node::getName(); ROS_INFO_STREAM("Starting server with " << num_threads << " handler threads"); ROS_INFO_STREAM_COND(options.add_legacy_server, "Also starting a legacy tf2::BufferServer in namespace " << options.legacy_server_namespace); tf_service::Server server(options); ros::AsyncSpinner spinner(num_threads); spinner.start(); ros::waitForShutdown(); spinner.stop(); return EXIT_SUCCESS; }
36.063158
80
0.686223
1d0c60396f941b1a20a0ef08295b70ee6329743d
5,333
cpp
C++
libraries/GTU/Flight.cpp
ugurkanates/GTURocketTeam
09c65cd0c0a16549eb05b647f8af632604b063a5
[ "MIT" ]
7
2018-10-18T18:41:52.000Z
2021-04-28T20:46:44.000Z
libraries/GTU/Flight.cpp
ugurkanates/GTURocketTeam
09c65cd0c0a16549eb05b647f8af632604b063a5
[ "MIT" ]
null
null
null
libraries/GTU/Flight.cpp
ugurkanates/GTURocketTeam
09c65cd0c0a16549eb05b647f8af632604b063a5
[ "MIT" ]
null
null
null
/* * Flight.cpp * * Created on: Sep 9, 2018 * Ugurkan Ates & Mustafa Sehriyar Main software for Avianoic system inside Rocket This software initialize sensors,controls flight,when to open chutes(2 chute) and tracks GPS data to find rocket after launch */ #include <Flight.h> Flight::Flight(): rocketState(JustStarted) { } void Flight::init(){ /* Rocket has states indicating what position it is currently Main loop behaves according to state changes */ rocketState = JustStarted; basePresure = 0 ; previousAltitude = 0; pendingApogee = false; apogeeCountdownStart = 0; safetyApogeeCountdownStart = 0; freeFallAltitudeInRange = 0; //my sensor() ? pinMode(FIRST_FIRE_GND, OUTPUT); pinMode(SECOND_FIRE_GND, OUTPUT); digitalWrite(FIRST_FIRE_GND, LOW); digitalWrite(SECOND_FIRE_GND, LOW); if(mySensor.Initialize()){ rocketState = Standby; } else { rocketState = StartUpError; } pendingApogee = false; delay(1000); // SENSORLER kendine gelsin -> sensors cooldown } //Serial.begin(9600); /*1 //Serial.begin(9600); delay(1000); // SENSORLER kendine gelsin -> sensors cooldown if(mySensor.Initialize()){ rocketState = Standby; Serial.println("ee"); } else { //rocketState = StartUpError; } Serial.println("er1");//Serial.println("error"); pendingApogee = false; Serial.println("er2");//Serial.println("error"); */ Flight::~Flight() { // TODO Auto-generated destructor stub } //main loop is here void Flight::koop(){ //mySensor.heartBeat(); float acc = 0; float alt = 0; /*if(!mySensor.getAcceleration(acc)){ Serial.println("CA");//Serial.println("error"); return; } if(!mySensor.getAltitude(alt)){ Serial.println("CB");//Serial.println("error"); return; } */ Serial.println("Accelemator DATA "); mySensor.getAcceleration(acc); Serial.println("Altitude DATA "); mySensor.getAltitude(alt); Serial.println("GPS DATA "); mySensor.getGpsLocation(); switch(rocketState) { case StartUpError: StartupErrorF(); // ac kapa -> yap break; case Standby: StandbyF(acc); break; case RiseWithMotor: RiseWithMotorF(acc); break; case RiseAfterMotorStops: //expect apogee RiseAfterMotorStopsF(acc, alt); break; case Drogue: DrogueF(alt); break; case Landing: LandingF(); break; default: break; } previousAltitude = alt; } // MAIN SETUP - ARDUINO void Flight::fireFirst(){ pinMode(FIRST_FIRE_GND, INPUT); pinMode(FIRST_FIRE_VCC, OUTPUT); digitalWrite(FIRST_FIRE_VCC, LOW); delay(FIRE_DURATION); //fitil patlama ms pinMode(FIRST_FIRE_GND, INPUT); pinMode(FIRST_FIRE_VCC, INPUT); apogeeCountdownStart = 0; safetyApogeeCountdownStart = 0; pendingApogee = false; rocketState = Drogue; } void Flight::fireSecond(){ pinMode(SECOND_FIRE_GND, INPUT); pinMode(SECOND_FIRE_VCC, OUTPUT); digitalWrite(SECOND_FIRE_VCC, LOW); delay(FIRE_DURATION); pinMode(SECOND_FIRE_GND, INPUT); pinMode(SECOND_FIRE_VCC, INPUT); rocketState = Landing; } void Flight::LandingF(){ Serial.print(mySensor.getGpsLocation()); } int Flight::isInFreeFall(float altitude) { if(previousAltitude - altitude > FREE_FALL_ALTITUDE_DELTA) { freeFallAltitudeInRange++; } return (freeFallAltitudeInRange >= FREE_FALL_ALTITUDE_LIMIT); } void Flight::DrogueF(float alt){ if(isInFreeFall(alt)) { fireFirst(); fireSecond(); } if (alt < SECOND_FIRE_ALTITUDE) { fireSecond(); } } void Flight::RiseAfterMotorStopsF(float acc, float alt){ if(pendingApogee) { if(previousAltitude - alt > APOGEE_ALTITUDE_DELTA) { fireFirst(); } } // If the apogee countdown is finished, fire it // It has 4 SECURITY CHECK TO OPEN PARACHUTES //one is time check others based on accelatrion sensor //if its lower than 2.94 it will try to open parachutes surely //it lower than 1.47 it will lower the time requires for it //if its lower than 0.5 it will try to fire parachute immediately // this security checks done for ensuring even if Arduino get sensor data slowly it will fire chutes int apogeeCountdownCheck = checkApogeeCountdowns(); if(apogeeCountdownCheck > 0) { fireFirst(); return; } if(acc< 0.5){ fireFirst(); return; } if(acc < 1.47) { //APOGEE_IDEAL 9.8 CARP pendingApogee = true; if(apogeeCountdownStart == 0) { apogeeCountdownStart = millis(); } return; } if(acc < 2.94) { if(safetyApogeeCountdownStart == 0) { safetyApogeeCountdownStart = millis(); } return; } } void Flight::RiseWithMotorF(float acceleration){ if(acceleration <= 7.35) { //COAST_ACCELERATION G ile carpildidegistirdim rocketState = RiseAfterMotorStops; return; } } void Flight::StandbyF(float acceleration){ // G ile carpildi 9.8 if(acceleration >= 12.25) { //Boost acceleration rocketState = RiseWithMotor; return; } // 7.35 < x 12.25 arası standby if(acceleration <= 7.35) { //COAST_ACCELERATION rocketState = RiseAfterMotorStops; return; } } void Flight::StartupErrorF(){ digitalWrite(13, HIGH); while(true){ delay(1000); } } bool Flight::checkApogeeCountdowns(){ if(apogeeCountdownStart > 0 && abs(apogeeCountdownStart - millis()) >= APOGEE_COUNTDOWN) { return true; } if(safetyApogeeCountdownStart > 0 && abs(safetyApogeeCountdownStart -millis()) >= SAFETY_APOGEE_COUNTDOWN) { return true; } return false; }
18.844523
109
0.705794
1d0ebd650e004eb8f4e81f6a905b6b1723f5f9f7
63,741
cpp
C++
src/plugin/kernel/src/AFCKernelModule.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
168
2016-08-18T07:24:48.000Z
2018-02-06T06:40:45.000Z
src/plugin/kernel/src/AFCKernelModule.cpp
Mu-L/ARK
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
11
2019-05-27T12:26:02.000Z
2021-05-12T02:45:16.000Z
src/plugin/kernel/src/AFCKernelModule.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
51
2016-09-01T10:17:38.000Z
2018-02-06T10:45:25.000Z
/* * This source file is part of ARK * For the latest info, see https://github.com/ArkNX * * Copyright (c) 2013-2020 ArkNX 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 "base/AFDefine.hpp" #include "kernel/include/AFCKernelModule.hpp" #include "kernel/include/AFCEntity.hpp" #include "kernel/include/AFCTable.hpp" #include "kernel/include/AFCDataList.hpp" #include "kernel/include/AFCContainer.hpp" namespace ark { AFCKernelModule::AFCKernelModule() { inner_nodes_.AddElement(AFEntityMetaBaseEntity::config_id(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::class_name(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_id(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_inst_id(), ARK_NEW int32_t(0)); } AFCKernelModule::~AFCKernelModule() { objects_.clear(); } bool AFCKernelModule::Init() { delete_list_.clear(); m_pMapModule = FindModule<AFIMapModule>(); m_pClassModule = FindModule<AFIClassMetaModule>(); m_pConfigModule = FindModule<AFIConfigModule>(); m_pGUIDModule = FindModule<AFIGUIDModule>(); auto container_func = std::bind(&AFCKernelModule::OnContainerCallBack, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); AddCommonContainerCallBack(std::move(container_func), 999999); // after other callbacks being done AddSyncCallBack(); return true; } bool AFCKernelModule::Update() { cur_exec_object_ = NULL_GUID; if (!delete_list_.empty()) { for (auto it : delete_list_) { DestroyEntity(it); } delete_list_.clear(); } for (auto& iter : objects_) { auto pEntity = iter.second; if (pEntity == nullptr) { continue; } pEntity->Update(); } AFClassCallBackManager::OnDelaySync(); return true; } bool AFCKernelModule::PreShut() { return DestroyAll(); } bool AFCKernelModule::CopyData(std::shared_ptr<AFIEntity> pEntity, std::shared_ptr<AFIStaticEntity> pStaticEntity) { if (pEntity == nullptr || nullptr == pStaticEntity) { return false; } // static node manager must be not empty auto pStaticNodeManager = GetNodeManager(pStaticEntity); if (pStaticNodeManager == nullptr || pStaticNodeManager->IsEmpty()) { return false; } // node manager must be empty auto pNodeManager = GetNodeManager(pEntity); if (pNodeManager == nullptr || !pNodeManager->IsEmpty()) { return false; } // copy data auto& data_list = pStaticNodeManager->GetDataList(); for (auto& iter : data_list) { auto pData = iter.second; pNodeManager->CreateData(pData); } return true; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const guid_t& self, const int map_id, const int map_instance_id, const std::string& class_name, const ID_TYPE config_id, const AFIDataList& args) { guid_t object_id = self; auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } if (!pMapInfo->ExistInstance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr; if (config_id > 0) { auto pStaticEntity = GetStaticEntity(config_id); if (nullptr == pStaticEntity) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } if (pStaticEntity->GetClassName() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } } // check args num size_t arg_count = args.GetCount(); if (arg_count % 2 != 0) { ARK_LOG_ERROR("Args count is wrong, count = {}", arg_count); return nullptr; } if (object_id == NULL_GUID) { object_id = m_pGUIDModule->CreateGUID(); } // Check if the entity exists if (GetEntity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } std::shared_ptr<AFIEntity> pEntity = std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, args); objects_.insert(object_id, pEntity); if (class_name == AFEntityMetaPlayer::self_name()) { pMapInfo->AddEntityToInstance(map_instance_id, object_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have //{ //} CopyData(pEntity, pStaticEntity); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); // original args here DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pEntity; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateContainerEntity( const guid_t& self, const uint32_t container_index, const std::string& class_name, const ID_TYPE config_id) { auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("There is no object, object = {}", self); return nullptr; } auto pContainer = pEntity->FindContainer(container_index); if (pContainer == nullptr) { ARK_LOG_ERROR("There is no container, container = {}", container_index); return nullptr; } auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr; if (config_id > 0) { auto pStaticEntity = GetStaticEntity(config_id); if (nullptr == pStaticEntity) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } if (pStaticEntity->GetClassName() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } } auto map_id = pEntity->GetMapID(); auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } auto map_instance_id = pEntity->GetMapEntityID(); if (!pMapInfo->ExistInstance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } guid_t object_id = m_pGUIDModule->CreateGUID(); // Check if the entity exists if (GetEntity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } std::shared_ptr<AFIEntity> pContainerEntity = std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, AFCDataList()); objects_.insert(object_id, pContainerEntity); CopyData(pContainerEntity, pStaticEntity); pContainer->Place(pContainerEntity); AFCDataList args; DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pContainerEntity; } std::shared_ptr<AFIStaticEntity> AFCKernelModule::GetStaticEntity(const ID_TYPE config_id) { return m_pConfigModule->FindStaticEntity(config_id); } std::shared_ptr<AFIEntity> AFCKernelModule::GetEntity(const guid_t& self) { return objects_.find_value(self); } bool AFCKernelModule::DestroyAll() { for (auto& iter : objects_) { auto& pEntity = iter.second; if (pEntity->GetParentContainer() != nullptr) { continue; } delete_list_.push_back(iter.second->GetID()); } // run another frame Update(); return true; } bool AFCKernelModule::DestroyEntity(const guid_t& self) { if (self == cur_exec_object_ && self != NULL_GUID) { return DestroySelf(self); } auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID); return false; } auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer) { // use container to destroy its entity return pParentContainer->Destroy(self); } else { return InnerDestroyEntity(pEntity); } } bool AFCKernelModule::DestroySelf(const guid_t& self) { delete_list_.push_back(self); return true; } bool AFCKernelModule::InnerDestroyEntity(std::shared_ptr<AFIEntity> pEntity) { if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID); return false; } auto& self = pEntity->GetID(); int32_t map_id = pEntity->GetMapID(); int32_t inst_id = pEntity->GetMapEntityID(); std::shared_ptr<AFMapInfo> pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo != nullptr) { const std::string& class_name = pEntity->GetClassName(); pMapInfo->RemoveEntityFromInstance( inst_id, self, ((class_name == AFEntityMetaPlayer::self_name()) ? true : false)); DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_PRE_DESTROY, AFCDataList()); DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_DESTROY, AFCDataList()); return objects_.erase(self); } else { ARK_LOG_ERROR("Cannot find this map, object_id={} map={} inst={}", self, map_id, inst_id); return false; } } bool AFCKernelModule::AddEventCallBack(const guid_t& self, const int nEventID, EVENT_PROCESS_FUNCTOR&& cb) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pEventManager = GetEventManager(pEntity); ARK_ASSERT_RET_VAL(pEventManager != nullptr, false); return pEventManager->AddEventCallBack(nEventID, std::move(cb)); } bool AFCKernelModule::AddClassCallBack(const std::string& class_name, CLASS_EVENT_FUNCTOR&& cb, const int32_t prio) { return m_pClassModule->AddClassCallBack(class_name, std::move(cb), prio); } bool AFCKernelModule::AddNodeCallBack( const std::string& class_name, const std::string& name, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto index = pClassMeta->GetIndex(name); if (index == 0) { return false; } AddNodeCallBack(class_name, index, std::move(cb), prio); return true; } bool AFCKernelModule::AddTableCallBack( const std::string& class_name, const std::string& name, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto index = pClassMeta->GetIndex(name); if (index == 0) { return false; } AddTableCallBack(class_name, index, std::move(cb), prio); return true; } bool AFCKernelModule::AddNodeCallBack( const std::string& class_name, const uint32_t index, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pDataMeta = pClassMeta->FindDataMeta(index); ARK_ASSERT_RET_VAL(pDataMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddDataCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddTableCallBack( const std::string& class_name, const uint32_t index, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pTableMeta = pClassMeta->FindTableMeta(index); ARK_ASSERT_RET_VAL(pTableMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddTableCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddContainerCallBack( const std::string& class_name, const uint32_t index, CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pContainerMeta = pClassMeta->FindContainerMeta(index); ARK_ASSERT_RET_VAL(pContainerMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddContainerCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddCommonContainerCallBack(CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(AFEntityMetaPlayer::self_name()); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto& meta_list = pClassMeta->GetContainerMetaList(); for (auto& iter : meta_list) { auto pMeta = iter.second; if (!pMeta) { continue; } AddContainerCallBack(AFEntityMetaPlayer::self_name(), pMeta->GetIndex(), std::move(cb), prio); } return true; } bool AFCKernelModule::AddCommonClassEvent(CLASS_EVENT_FUNCTOR&& cb, const int32_t prio) { auto& class_meta_list = m_pClassModule->GetMetaList(); for (auto& iter : class_meta_list) { auto pClassMeta = iter.second; if (nullptr == pClassMeta) { continue; } AddClassCallBack(iter.first, std::move(cb), prio); } return true; } bool AFCKernelModule::AddLeaveSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddLeaveSceneEvent(std::move(cb), prio); } bool AFCKernelModule::AddEnterSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddEnterSceneEvent(std::move(cb), prio); } bool AFCKernelModule::AddMoveEvent(const std::string& class_name, MOVE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddMoveEvent(std::move(cb), prio); } void AFCKernelModule::AddSyncCallBack() { // node sync call back auto node_func = std::bind(&AFCKernelModule::OnSyncNode, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(node_func)); AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(node_func)); // table sync call back auto table_func = std::bind(&AFCKernelModule::OnSyncTable, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(table_func)); AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(table_func)); // container sync call back auto container_func = std::bind(&AFCKernelModule::OnSyncContainer, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6); AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(container_func)); AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(container_func)); // data delay call back auto delay_func = std::bind( &AFCKernelModule::OnDelaySyncData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(delay_func)); AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(delay_func)); // send msg functor auto view_func = std::bind(&AFCKernelModule::SendToView, this, std::placeholders::_1, std::placeholders::_2); sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_VIEW, std::forward<SYNC_FUNCTOR>(view_func))); auto self_func = std::bind(&AFCKernelModule::SendToSelf, this, std::placeholders::_1, std::placeholders::_2); sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_SELF, std::forward<SYNC_FUNCTOR>(self_func))); } int AFCKernelModule::OnSyncNode( const guid_t& self, const uint32_t index, const ArkDataMask mask_value, const AFIData& data) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync node failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } if (!NodeToPBData(index, data, pb_entity)) { ARK_LOG_ERROR("node to pb failed, self={}, index={}", self, index); return -1; } pb_data.set_id(entity_id); if (SendSyncMsg(entity_id, mask_value, pb_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}, index={}", entity_id, index); return -1; } return 0; } int AFCKernelModule::OnSyncTable( const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data) { ArkTableOpType op_type = static_cast<ArkTableOpType>(event.op_type_); switch (op_type) { case ArkTableOpType::TABLE_ADD: { OnSyncTableAdd(self, event, mask_value); } break; case ArkTableOpType::TABLE_DELETE: { OnSyncTableDelete(self, event, mask_value); } break; case ArkTableOpType::TABLE_SWAP: // do not have yet break; case ArkTableOpType::TABLE_UPDATE: { OnSyncTableUpdate(self, event, mask_value, data); } break; case ArkTableOpType::TABLE_COVERAGE: // will do something break; default: break; } return 0; } int AFCKernelModule::OnSyncContainer(const guid_t& self, const uint32_t index, const ArkDataMask mask, const ArkContainerOpType op_type, uint32_t src_index, uint32_t dest_index) { switch (op_type) { case ArkContainerOpType::OP_PLACE: { OnSyncContainerPlace(self, index, mask, src_index); } break; case ArkContainerOpType::OP_REMOVE: { OnSyncContainerRemove(self, index, mask, src_index); } break; case ArkContainerOpType::OP_DESTROY: { OnSyncContainerDestroy(self, index, mask, src_index); } break; case ArkContainerOpType::OP_SWAP: { OnSyncContainerSwap(self, index, mask, src_index, dest_index); } break; default: break; } return 0; } int AFCKernelModule::OnDelaySyncData(const guid_t& self, const ArkDataMask mask_value, const AFDelaySyncData& data) { if (data.node_list_.size() == 0 && data.table_list_.size() == 0) { return 0; } // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync delay data failed entity do no exist, self={}", self); return -1; } AFMsg::pb_delay_entity pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync delay data failed container entity do no exist, self={}", self); return -1; } } // node to pb for (auto& iter : data.node_list_) { auto pNode = iter; if (!NodeToPBData(pNode, pb_entity)) { continue; } } // table to pb for (auto& iter : data.table_list_) { auto table_index = iter.first; auto& table = iter.second; DelayTableToPB(table, table_index, pb_data, *pb_entity); } // container to pb for (auto& iter : data.container_list_) { auto container_index = iter.first; auto& container = iter.second; DelayContainerToPB(pEntity, container, container_index, pb_data); } pb_data.set_id(entity_id); if (SendSyncMsg(entity_id, mask_value, pb_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}", self); return -1; } return 0; } int AFCKernelModule::OnSyncTableAdd(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } auto pTable = pEntity->FindTable(event.table_index_); if (nullptr == pTable) { ARK_LOG_ERROR("sync table failed table do no exist, self={}, table={}", self, event.table_name_); return -1; } auto pRow = pTable->FindRow(event.row_); if (nullptr == pRow) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_entity_table_add pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; if (!RowToPBData(pRow, event.row_, &pb_row)) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); pb_data.set_id(entity_id); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncTableDelete(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity_table_delete pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncTableUpdate( const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity_table_update pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; if (!NodeToPBData(event.data_index_, data, &pb_row)) { ARK_LOG_ERROR( "sync table failed table node do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); pb_data.set_id(entity_id); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncContainerPlace( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } auto pContainer = pEntity->FindContainer(index); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed container do no exist, self={}, container={}", self, index); return -1; } auto pContainerEntity = pContainer->Find(src_index); if (pContainerEntity == nullptr) { ARK_LOG_ERROR("sync container failed container entity do no exist, self={}, container={}, entity={}", self, index, src_index); return -1; } if (pContainerEntity->IsSent()) { AFMsg::pb_container_place pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); pb_data.set_entity_id(pContainerEntity->GetID()); SendSyncMsg(self, mask, pb_data); } else { AFMsg::pb_container_create pb_data; if (!EntityToPBData(pContainerEntity, pb_data.mutable_data())) { ARK_LOG_ERROR("sync container failed container entity to pb failed, self={}, container={}, entity={}", self, index, src_index); return -1; } pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); } return 0; } int AFCKernelModule::OnSyncContainerRemove( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_remove pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); return 0; } int AFCKernelModule::OnSyncContainerDestroy( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_destroy pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); return 0; } int AFCKernelModule::OnSyncContainerSwap( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index, uint32_t dest_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_swap pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_src_index(src_index); pb_data.set_dest_index(dest_index); SendSyncMsg(self, mask, pb_data); return 0; } bool AFCKernelModule::DelayTableToPB( const AFDelaySyncTable& table, const uint32_t index, AFMsg::pb_delay_entity& data, AFMsg::pb_entity_data& pb_entity) { AFMsg::pb_table pb_table; AFMsg::delay_clear_row clear_row_list; for (auto& iter : table.row_list_) { AFMsg::pb_entity_data pb_row; auto row_index = iter.first; auto& row_data = iter.second; for (auto& iter_row : row_data.node_list_) { auto pNode = iter_row; if (NodeToPBData(pNode, &pb_row)) { pb_table.mutable_datas_value()->insert({row_index, pb_row}); } } if (row_data.need_clear_) { clear_row_list.add_row_list(row_index); } } if (table.need_clear_) { data.add_clear_tables(index); } if (clear_row_list.row_list_size() > 0) { data.mutable_clear_rows()->insert({index, clear_row_list}); } pb_entity.mutable_datas_table()->insert({index, pb_table}); return true; } bool AFCKernelModule::DelayContainerToPB(std::shared_ptr<AFIEntity> pEntity, const AFDelaySyncContainer& container, const uint32_t index, AFMsg::pb_delay_entity& data) { AFMsg::delay_container pb_delay_container; AFMsg::pb_container pb_conatiner; for (auto& iter : container.index_list_) { auto entity_index = iter; auto pContaier = pEntity->FindContainer(index); if (pContaier == nullptr) { continue; } auto pContainerEntity = pContaier->Find(entity_index); if (pContainerEntity == nullptr) { pb_delay_container.mutable_entity_list()->insert({entity_index, NULL_GUID}); } else if (pEntity->IsSent()) { pb_delay_container.mutable_entity_list()->insert({entity_index, pContainerEntity->GetID()}); } else { AFMsg::pb_entity pb_container_entity; if (!EntityToPBData(pContainerEntity, &pb_container_entity)) { continue; } pb_conatiner.mutable_datas_value()->insert({entity_index, pb_container_entity}); } } if (pb_conatiner.datas_value_size() > 0) { data.mutable_data()->mutable_datas_container()->insert({index, pb_conatiner}); } data.mutable_container_entity()->insert({index, pb_delay_container}); AFMsg::delay_container pb_destroy_entity; for (auto& iter : container.destroy_list_) { auto entity_index = iter; pb_destroy_entity.mutable_entity_list()->insert({entity_index, NULL_GUID}); } data.mutable_destroy_entity()->insert({index, pb_destroy_entity}); return true; } bool AFCKernelModule::TryAddContainerPBEntity(std::shared_ptr<AFIContainer> pContainer, const guid_t& self, AFMsg::pb_entity_data& pb_entity_data, guid_t& parent_id, AFMsg::pb_entity_data*& pb_container_entity) { parent_id = pContainer->GetParentID(); auto pParentEntity = GetEntity(parent_id); if (pParentEntity == nullptr) { ARK_LOG_ERROR("parent entity do no exist, parent={}", parent_id); return false; } auto self_index = pContainer->Find(self); if (self_index == 0) { ARK_LOG_ERROR("entity is not in container, self={}", self); return false; } AFMsg::pb_container pb_container; auto result_container = pb_entity_data.mutable_datas_container()->insert({pContainer->GetIndex(), pb_container}); if (!result_container.second) { ARK_LOG_ERROR("entity insert container failed, self={} container index = {}", self, pContainer->GetIndex()); return false; } auto& container = result_container.first->second; AFMsg::pb_entity pb_entity; auto result_entity = container.mutable_datas_value()->insert({self_index, pb_entity}); if (!result_entity.second) { ARK_LOG_ERROR("container insert entity failed, self={} container index = {}", self, pContainer->GetIndex()); return false; } auto& entity = result_entity.first->second; pb_container_entity = entity.mutable_data(); return true; } int AFCKernelModule::SendSyncMsg(const guid_t& self, const ArkDataMask mask_value, const google::protobuf::Message& msg) { auto iter = sync_functors.find(mask_value); if (iter == sync_functors.end()) { return -1; } iter->second(self, msg); return 0; } int AFCKernelModule::SendToView(const guid_t& self, const google::protobuf::Message& msg) { auto pEntity = GetEntity(self); if (nullptr == pEntity) { return -1; } auto map_id = pEntity->GetMapID(); auto inst_id = pEntity->GetMapEntityID(); AFCDataList map_inst_entity_list; m_pMapModule->GetInstEntityList(map_id, inst_id, map_inst_entity_list); for (size_t i = 0; i < map_inst_entity_list.GetCount(); i++) { auto pViewEntity = GetEntity(map_inst_entity_list.Int64(i)); if (pViewEntity == nullptr) { continue; } const std::string& strObjClassName = pViewEntity->GetClassName(); if (AFEntityMetaPlayer::self_name() == strObjClassName) { SendToSelf(pViewEntity->GetID(), msg); } } return 0; } int AFCKernelModule::SendToSelf(const guid_t& self, const google::protobuf::Message& msg) { //SendMsgPBToGate(AFMsg::EGMI_ACK_NODE_DATA, entity, ident); return 0; } bool AFCKernelModule::DoEvent( const guid_t& self, const std::string& class_name, ArkEntityEvent class_event, const AFIDataList& args) { return m_pClassModule->DoClassEvent(self, class_name, class_event, args); } bool AFCKernelModule::DoEvent(const guid_t& self, const int event_id, const AFIDataList& args) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pEventManager = GetEventManager(pEntity); ARK_ASSERT_RET_VAL(pEventManager != nullptr, false); return pEventManager->DoEvent(event_id, args); } bool AFCKernelModule::Exist(const guid_t& self) { return (objects_.find_value(self) != nullptr); } bool AFCKernelModule::LogSelfInfo(const guid_t& id) { return false; } int AFCKernelModule::LogObjectData(const guid_t& guid) { auto entity = GetEntity(guid); if (entity == nullptr) { return -1; } auto pNodeManager = GetNodeManager(entity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, -1); auto pTableManager = GetTableManager(entity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, -1); auto& node_list = pNodeManager->GetDataList(); for (auto& iter : node_list) { auto pData = iter.second; if (!pData) { continue; } ARK_LOG_TRACE("Player[{}] Node[{}] Value[{}]", guid, pData->GetName(), pData->ToString()); } auto& table_list = pTableManager->GetTableList(); for (auto& iter : table_list) { auto pTable = iter.second; if (!pTable) { continue; } for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { auto pRowNodeManager = GetNodeManager(pRow); if (!pRowNodeManager) { continue; } auto& row_data_list = pRowNodeManager->GetDataList(); for (auto& iter_row : row_data_list) { auto pNode = iter_row.second; if (!pNode) { continue; } ARK_LOG_TRACE("Player[{}] Table[{}] Row[{}] Col[{}] Value[{}]", guid, pTable->GetName(), pRow->GetRow(), pNode->GetName(), pNode->ToString()); } } } return 0; } bool AFCKernelModule::LogInfo(const guid_t& id) { std::shared_ptr<AFIEntity> pEntity = GetEntity(id); if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find entity, id = {}", id); return false; } if (m_pMapModule->IsInMapInstance(id)) { int map_id = pEntity->GetMapID(); ARK_LOG_INFO("----------child object list-------- , id = {} mapid = {}", id, map_id); AFCDataList entity_list; int online_count = m_pMapModule->GetMapOnlineList(map_id, entity_list); for (int i = 0; i < online_count; ++i) { guid_t target_entity_id = entity_list.Int64(i); ARK_LOG_INFO("id = {} mapid = {}", target_entity_id, map_id); } } else { ARK_LOG_INFO("---------print object start--------, id = {}", id); ARK_LOG_INFO("---------print object end--------, id = {}", id); } return true; } //--------------entity to pb db data------------------ bool AFCKernelModule::EntityToDBData(const guid_t& self, AFMsg::pb_db_entity& pb_data) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); return EntityToDBData(pEntity, pb_data); } bool AFCKernelModule::EntityToDBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_db_entity& pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pNodeManager = GetNodeManager(pEntity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false); auto pTableManager = GetTableManager(pEntity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, false); auto pContainerManager = GetContainerManager(pEntity); ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false); pb_data.set_id(pEntity->GetID()); pb_data.set_config_id(pEntity->GetConfigID()); pb_data.set_map_id(pEntity->GetMapID()); pb_data.set_map_inst_id(pEntity->GetMapEntityID()); pb_data.set_class_name(pEntity->GetClassName()); // node to db auto& node_list = pNodeManager->GetDataList(); for (auto& iter : node_list) { auto pNode = iter.second; if (!pNode) { continue; } if (!pNode->HaveMask(ArkDataMask::PF_SAVE)) { continue; } NodeToDBData(pNode, *pb_data.mutable_data()); } // table to db auto& table_list = pTableManager->GetTableList(); for (auto& iter : table_list) { auto pTable = iter.second; if (!pTable) { continue; } if (!pTable->HaveMask(ArkDataMask::PF_SAVE)) { continue; } AFMsg::pb_db_table pb_table; if (!TableToDBData(pTable, pb_table)) { continue; } pb_data.mutable_data()->mutable_datas_table()->insert({pTable->GetName(), pb_table}); } // container to db auto& container_list = pContainerManager->GetContainerList(); for (auto& iter : container_list) { auto pContainer = iter.second; if (!pContainer) { continue; } AFMsg::pb_db_container pb_container; for (auto index = pContainer->First(); index > 0; index = pContainer->Next()) { auto pSubEntity = pContainer->Find(index); if (!pSubEntity) { continue; } AFMsg::pb_db_entity pb_container_entity; if (!EntityToDBData(pSubEntity, pb_container_entity)) { continue; } pb_container.mutable_datas_value()->insert({index, pb_container_entity}); } if (pb_container.datas_value_size() > 0) { pb_data.mutable_data()->mutable_datas_entity()->insert({pContainer->GetName(), pb_container}); } } return true; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const AFMsg::pb_db_entity& pb_data) { auto entity_id = pb_data.id(); auto pEntity = GetEntity(entity_id); if (pEntity != nullptr) { ARK_LOG_ERROR("entity already exists, object = {}", entity_id); return nullptr; } const std::string& class_name = pb_data.class_name(); auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } auto map_id = pb_data.map_id(); auto map_inst_id = pb_data.map_inst_id(); auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } auto pCEntity = std::make_shared<AFCEntity>(pClassMeta, entity_id, NULL_INT, map_id, map_inst_id, AFCDataList()); pEntity = std::static_pointer_cast<AFIEntity>(pCEntity); objects_.insert(entity_id, pEntity); if (class_name == AFEntityMetaPlayer::self_name()) { pMapInfo->AddEntityToInstance(map_inst_id, entity_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have //{ //} // init data auto& pb_db_entity_data = pb_data.data(); // node data auto pNodeManager = pCEntity->GetNodeManager(); if (nullptr != pNodeManager) { DBDataToNode(pNodeManager, pb_db_entity_data); } // table data auto pTableManager = pCEntity->GetTableManager(); if (nullptr != pTableManager) { for (auto& iter : pb_db_entity_data.datas_table()) { DBDataToTable(pEntity, iter.first, iter.second); } } // container data for (auto& iter : pb_db_entity_data.datas_entity()) { DBDataToContainer(pEntity, iter.first, iter.second); } // todo : add new event? AFCDataList args; DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pEntity; } bool AFCKernelModule::SendCustomMessage(const guid_t& target, const uint32_t msg_id, const AFIDataList& args) { ARK_ASSERT_RET_VAL(Exist(target) && msg_id > 0, false); AFMsg::pb_custom_message custom_message; custom_message.set_message_id(msg_id); size_t count = args.GetCount(); for (size_t i = 0; i < count; i++) { auto data_type = args.GetType(i); switch (data_type) { case ark::ArkDataType::DT_BOOLEAN: custom_message.add_data_list()->set_bool_value(args.Bool(i)); break; case ark::ArkDataType::DT_INT32: custom_message.add_data_list()->set_int_value(args.Int(i)); break; case ark::ArkDataType::DT_UINT32: custom_message.add_data_list()->set_uint_value(args.UInt(i)); break; case ark::ArkDataType::DT_INT64: custom_message.add_data_list()->set_int64_value(args.Int64(i)); break; case ark::ArkDataType::DT_UINT64: custom_message.add_data_list()->set_uint64_value(args.UInt64(i)); break; case ark::ArkDataType::DT_FLOAT: custom_message.add_data_list()->set_float_value(args.Float(i)); break; case ark::ArkDataType::DT_DOUBLE: custom_message.add_data_list()->set_double_value(args.Double(i)); break; case ark::ArkDataType::DT_STRING: custom_message.add_data_list()->set_str_value(args.String(i)); break; default: break; } } // send message return true; } // pb table to entity table bool AFCKernelModule::DBDataToTable( std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_table& pb_table) { auto pTable = pEntity->FindTable(name); ARK_ASSERT_RET_VAL(pTable != nullptr, false); auto pCTable = dynamic_cast<AFCTable*>(pTable); ARK_ASSERT_RET_VAL(pCTable != nullptr, false); for (auto& iter : pb_table.datas_value()) { auto row_index = iter.first; if (row_index == NULL_INT) { continue; } auto& pb_db_entity_data = iter.second; auto pRow = pCTable->CreateRow(row_index, AFCDataList()); if (pRow == nullptr) { continue; } auto pNodeManager = GetNodeManager(pRow); if (pNodeManager == nullptr) { continue; } DBDataToNode(pNodeManager, pb_db_entity_data); } return true; } bool AFCKernelModule::DBDataToContainer( std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_container& pb_data) { auto pContainer = pEntity->FindContainer(name); if (nullptr == pContainer) { return false; } auto pCContainer = std::dynamic_pointer_cast<AFCContainer>(pContainer); if (nullptr == pCContainer) { return false; } for (auto& iter : pb_data.datas_value()) { auto pContainerEntity = CreateEntity(iter.second); if (nullptr == pContainerEntity) { continue; } pCContainer->InitEntityList(iter.first, pContainerEntity); } return true; } int AFCKernelModule::OnContainerCallBack(const guid_t& self, const uint32_t index, const ArkContainerOpType op_type, const uint32_t src_index, const uint32_t dest_index) { if (op_type == ArkContainerOpType::OP_DESTROY) { // destroy entity auto pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, 0); auto pContainer = pEntity->FindContainer(index); ARK_ASSERT_RET_VAL(pContainer != nullptr, 0); auto pContainerEntity = pContainer->Find(src_index); ARK_ASSERT_RET_VAL(pContainerEntity != nullptr, 0); InnerDestroyEntity(pContainerEntity); } return 0; } bool AFCKernelModule::DBDataToNode( std::shared_ptr<AFNodeManager> pNodeManager, const AFMsg::pb_db_entity_data& pb_db_entity_data) { //bool data for (auto& iter : pb_db_entity_data.datas_bool()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetBool(iter.second); } //int32 data for (auto& iter : pb_db_entity_data.datas_int32()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetInt32(iter.second); } //uint32 data for (auto& iter : pb_db_entity_data.datas_uint32()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetUInt32(iter.second); } //int64 data for (auto& iter : pb_db_entity_data.datas_int64()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetInt64(iter.second); } //uint64 data for (auto& iter : pb_db_entity_data.datas_uint64()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetUInt64(iter.second); } //float data for (auto& iter : pb_db_entity_data.datas_float()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetFloat(iter.second); } //double data for (auto& iter : pb_db_entity_data.datas_double()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetDouble(iter.second); } //string data for (auto& iter : pb_db_entity_data.datas_string()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetString(iter.second); } return true; } //----------------------------- bool AFCKernelModule::NodeToDBData(AFINode* pNode, AFMsg::pb_db_entity_data& pb_data) { ARK_ASSERT_RET_VAL(pNode != nullptr, false); auto& name = pNode->GetName(); switch (pNode->GetType()) { case ArkDataType::DT_BOOLEAN: pb_data.mutable_datas_bool()->insert({name, pNode->GetBool()}); break; case ArkDataType::DT_INT32: pb_data.mutable_datas_int32()->insert({name, pNode->GetInt32()}); break; case ArkDataType::DT_UINT32: pb_data.mutable_datas_uint32()->insert({name, pNode->GetUInt32()}); break; case ArkDataType::DT_INT64: pb_data.mutable_datas_int64()->insert({name, pNode->GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data.mutable_datas_uint64()->insert({name, pNode->GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data.mutable_datas_float()->insert({name, pNode->GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data.mutable_datas_double()->insert({name, pNode->GetDouble()}); break; case ArkDataType::DT_STRING: pb_data.mutable_datas_string()->insert({name, pNode->GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::TableToDBData(AFITable* pTable, AFMsg::pb_db_table& pb_data) { ARK_ASSERT_RET_VAL(pTable != nullptr, false); for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { auto pNodeManager = GetNodeManager(pRow); if (!pNodeManager) { continue; } AFMsg::pb_db_entity_data row_data; auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { NodeToDBData(iter.second, row_data); } pb_data.mutable_datas_value()->insert({pRow->GetRow(), row_data}); } return true; } //----------entity to pb client data--------------- bool AFCKernelModule::NodeToPBData(AFINode* pNode, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(pNode != nullptr && pb_data != nullptr, false); auto index = pNode->GetIndex(); switch (pNode->GetType()) { case ArkDataType::DT_BOOLEAN: pb_data->mutable_datas_bool()->insert({index, pNode->GetBool()}); break; case ArkDataType::DT_INT32: pb_data->mutable_datas_int32()->insert({index, pNode->GetInt32()}); break; case ArkDataType::DT_UINT32: pb_data->mutable_datas_uint32()->insert({index, pNode->GetUInt32()}); break; case ArkDataType::DT_INT64: pb_data->mutable_datas_int64()->insert({index, pNode->GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data->mutable_datas_uint64()->insert({index, pNode->GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data->mutable_datas_float()->insert({index, pNode->GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data->mutable_datas_double()->insert({index, pNode->GetDouble()}); break; case ArkDataType::DT_STRING: pb_data->mutable_datas_string()->insert({index, pNode->GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::NodeToPBData(const uint32_t index, const AFIData& data, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(index > 0 && pb_data != nullptr, false); switch (data.GetType()) { case ArkDataType::DT_BOOLEAN: pb_data->mutable_datas_bool()->insert({index, data.GetBool()}); break; case ArkDataType::DT_INT32: pb_data->mutable_datas_int32()->insert({index, data.GetInt()}); break; case ArkDataType::DT_UINT32: pb_data->mutable_datas_uint32()->insert({index, data.GetUInt()}); break; case ArkDataType::DT_INT64: pb_data->mutable_datas_int64()->insert({index, data.GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data->mutable_datas_uint64()->insert({index, data.GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data->mutable_datas_float()->insert({index, data.GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data->mutable_datas_double()->insert({index, data.GetDouble()}); break; case ArkDataType::DT_STRING: pb_data->mutable_datas_string()->insert({index, data.GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::TableToPBData(AFITable* pTable, const uint32_t index, AFMsg::pb_table* pb_data) { ARK_ASSERT_RET_VAL(pTable != nullptr && index > 0 && pb_data != nullptr, false); for (AFIRow* pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { AFMsg::pb_entity_data row_data; if (!RowToPBData(pRow, pRow->GetRow(), &row_data)) { continue; } pb_data->mutable_datas_value()->insert({index, row_data}); } return true; } bool AFCKernelModule::ContainerToPBData(std::shared_ptr<AFIContainer> pContainer, AFMsg::pb_container* pb_data) { ARK_ASSERT_RET_VAL(pContainer != nullptr && pb_data != nullptr, false); for (auto index = pContainer->First(); index > 0; index = pContainer->Next()) { auto pEntity = pContainer->Find(index); if (nullptr == pEntity) { continue; } AFMsg::pb_entity pb_entity; if (!EntityToPBData(pEntity, &pb_entity)) { continue; } pb_data->mutable_datas_value()->insert({index, pb_entity}); } return true; } bool AFCKernelModule::RowToPBData(AFIRow* pRow, const uint32_t index, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(pRow != nullptr && index > 0 && pb_data != nullptr, false); auto pNodeManager = GetNodeManager(pRow); if (!pNodeManager) { return false; } auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { NodeToPBData(iter.second, pb_data); } return true; } bool AFCKernelModule::TableRowDataToPBData( const uint32_t index, uint32_t row, const uint32_t col, const AFIData& data, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(index > 0 && row > 0 && col > 0 && pb_data != nullptr, false); AFMsg::pb_entity_data row_data; if (!NodeToPBData(col, data, &row_data)) { return false; } AFMsg::pb_table table_data; table_data.mutable_datas_value()->insert({row, row_data}); pb_data->mutable_datas_table()->insert({index, table_data}); return true; } bool AFCKernelModule::EntityToPBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity* pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); pb_data->set_id(pEntity->GetID()); EntityNodeToPBData(pEntity, pb_data->mutable_data()); EntityTableToPBData(pEntity, pb_data->mutable_data()); EntityContainerToPBData(pEntity, pb_data->mutable_data()); return true; } bool AFCKernelModule::EntityToPBDataByMask( std::shared_ptr<AFIEntity> pEntity, ArkMaskType mask, AFMsg::pb_entity* pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); pb_data->set_id(pEntity->GetID()); EntityNodeToPBData(pEntity, pb_data->mutable_data(), mask); EntityTableToPBData(pEntity, pb_data->mutable_data(), mask); EntityContainerToPBData(pEntity, pb_data->mutable_data(), mask); return true; } bool AFCKernelModule::EntityContainerToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pContainerManager = GetContainerManager(pEntity); ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false); auto& container_list = pContainerManager->GetContainerList(); for (auto& iter : container_list) { auto pContainer = iter.second; if (!pContainer) { continue; } if (!mask.none()) { auto result = (pContainer->GetMask() & mask); if (!result.any()) { continue; } } AFMsg::pb_container pb_container; if (!ContainerToPBData(pContainer, &pb_container)) { continue; } pb_data->mutable_datas_container()->insert({iter.first, pb_container}); } return true; } //node all to pb data bool AFCKernelModule::EntityNodeToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pNodeManager = GetNodeManager(pEntity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false); auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { auto pNode = iter.second; if (!pNode) { continue; } if (!mask.none()) { auto result = (pNode->GetMask() & mask); if (!result.any()) { continue; } } NodeToPBData(pNode, pb_data); } return true; } bool AFCKernelModule::EntityTableToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pTableManager = GetTableManager(pEntity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, false); auto& data_list = pTableManager->GetTableList(); for (auto& iter : data_list) { auto pTable = iter.second; if (!pTable) { continue; } if (!mask.none()) { auto result = (pTable->GetMask() & mask); if (!result.any()) { continue; } } const auto index = pTable->GetIndex(); AFMsg::pb_table table_data; if (!TableToPBData(pTable, index, &table_data)) { continue; } pb_data->mutable_datas_table()->insert({index, table_data}); } return true; } // -----------get entity manager-------------- std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIStaticEntity> pStaticEntity) const { if (pStaticEntity == nullptr) { return nullptr; } auto pCStaticEntity = std::dynamic_pointer_cast<AFCStaticEntity>(pStaticEntity); if (pCStaticEntity == nullptr) { return nullptr; } return pCStaticEntity->GetNodeManager(); } std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetNodeManager(); } std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(AFIRow* pRow) const { if (pRow == nullptr) { return nullptr; } auto pCRow = dynamic_cast<AFCRow*>(pRow); if (pCRow == nullptr) { return nullptr; } return pCRow->GetNodeManager(); } std::shared_ptr<AFTableManager> AFCKernelModule::GetTableManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetTableManager(); } std::shared_ptr<AFIContainerManager> AFCKernelModule::GetContainerManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetContainerManager(); } std::shared_ptr<AFIEventManager> AFCKernelModule::GetEventManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetEventManager(); } } // namespace ark
28.725101
120
0.643259
1d10590f67240a9e3501b73e806bb57d339aeb08
574
cpp
C++
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
1
2017-08-30T05:59:47.000Z
2017-08-30T05:59:47.000Z
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
null
null
null
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Name : OpenToolTest.cpp // Author : // Version : // Copyright : // Description : Hello World in C++, Ansi-style //============================================================================ #include "Server.h" #include "Timer.h" #include <unistd.h> #include <iostream> using namespace std; int main() { bool listening = true; cout << "This is a Test." << endl; Server Test_Server(12000); while(listening) { sleep(1); //Test.Available(); } return 0; }
17.393939
78
0.439024
1d117be860a84dc612994f2ead8819ad6300b505
6,885
cpp
C++
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
1
2020-04-16T15:10:20.000Z
2020-04-16T15:10:20.000Z
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
null
null
null
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
null
null
null
#include "pgf/cli.hpp" #include "pgf/util.hpp" #include <cassert> namespace pgf { CommandOptionValue::CommandOptionValue(const CommandOptionValueType& type) : type(type) { switch (type) { case CommandOptionValueType::Int: data = 0; break; case CommandOptionValueType::String: data = std::string(); break; case CommandOptionValueType::Bool: default: data = false; break; } } void CommandOptions::AddOption(const std::string& name, char shortName, const CommandOptionValueType& type) { m_options.push_back(CommandOptionName{ name, shortName }); m_values.push_back(CommandOptionValue{ type }); } std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(const std::string& name) { if (name.empty()) return m_values.end(); unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.name == name) break; ++index; } return m_values.begin() + index; } std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(const std::string& name) const { if (name.empty()) return m_values.end(); unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index++]; if (opt.name == name) break; } return m_values.begin() + index; } std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(char name) { unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.shortName == name) break; ++index; } return m_values.begin() + index; } std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(char name) const { unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.shortName == name) break; ++index; } return m_values.begin() + index; } bool CommandOptions::HasOption(const std::string& name) { return std::find_if( m_options.begin(), m_options.end(), [&name](const CommandOptionName& opt) { return opt.name == name; } ) != m_options.end(); } bool CommandOptions::HasOption(char name) { return std::find_if( m_options.begin(), m_options.end(), [&name](const CommandOptionName& opt) { return opt.shortName == name; } ) != m_options.end(); } void CommandOptions::SetOptionValue(const std::string& name, bool value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::Bool) return; optValue->data = value; } void CommandOptions::SetOptionValue(const std::string& name, int value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::Int) return; optValue->data = value; } void CommandOptions::SetOptionValue(const std::string& name, const std::string& value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::String) return; optValue->data = value; } void CommandOptions::ProcessArguments(std::vector<std::string>& args) { for (unsigned int i = 0; i < args.size(); ++i) { std::string arg = args[i]; if (util::StartsWith(arg, "--")) { arg = util::ToLower(arg.substr(2)); if (!HasOption(arg)) { continue; } auto optValue = this->FindOptionValue(arg); if (optValue == m_values.end()) continue; switch (optValue->type) { case CommandOptionValueType::String: if (i + 1 < args.size()) { optValue->data = args[i + 1]; args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Int: if (i + 1 < args.size()) { optValue->data = std::stoi(args[i + 1]); args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Bool: default: optValue->data = true; break; } args.erase(args.begin() + (i--)); } else if (util::StartsWith(arg, "-")) { arg = util::ToLower(arg.substr(1)); for (char c : arg) { if (!HasOption(c)) continue; auto optValue = this->FindOptionValue(c); if (optValue == m_values.end()) continue; switch (optValue->type) { case CommandOptionValueType::String: if (i + 1 < args.size()) { optValue->data = args[i + 1]; args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Int: if (i + 1 < args.size()) { optValue->data = std::stoi(args[i + 1]); args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Bool: default: optValue->data = true; break; } } args.erase(args.begin() + (i--)); } } } }
28.6875
114
0.444735
1d12265999bf15a69bf71cd08842c9fa6a5943cb
4,741
cpp
C++
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
3
2019-04-08T19:17:51.000Z
2019-05-21T01:01:29.000Z
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
1
2019-04-30T23:39:06.000Z
2019-07-27T00:07:20.000Z
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
1
2019-02-28T09:22:18.000Z
2019-02-28T09:22:18.000Z
/** * Copyright 2020 Colin Doig. Distributed under the MIT license. */ #include <wx/wx.h> #include <wx/dcclient.h> #include <wx/dcmemory.h> #include <wx/file.h> #include <wx/sizer.h> #include <wx/mstream.h> #include <wx/stdpaths.h> #include <wx/stattext.h> #include <wx/wfstream.h> #include <wx/url.h> #include <curl/curl.h> #include <iomanip> #include <iostream> #include <sstream> #include <greentop/ExchangeApi.h> #include "dialog/PriceHistory.h" #include "Util.h" namespace greenthumb { namespace dialog { size_t writeToStream(char* buffer, size_t size, size_t nitems, wxMemoryOutputStream* stream) { size_t realwrote = size * nitems; stream->Write(buffer, realwrote); return realwrote; } PriceHistory::PriceHistory(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &pos, const wxSize &size, long style, const wxString &name) : wxDialog(parent, id, title, pos, size, style, name) { int borderWidth = 10; int borderFlags = wxTOP | wxRIGHT | wxLEFT; wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); wxFlexGridSizer* gridSizer = new wxFlexGridSizer(2, borderWidth, borderWidth); wxStaticText* bettingOnLabel = new wxStaticText(this, wxID_ANY, "Betting on:"); gridSizer->Add(bettingOnLabel); bettingOn = new wxStaticText(this, wxID_ANY, ""); gridSizer->Add(bettingOn); wxStaticText* lastPriceTradedLabel = new wxStaticText(this, wxID_ANY, "Last price matched:"); gridSizer->Add(lastPriceTradedLabel); lastPriceTraded = new wxStaticText(this, wxID_ANY, ""); gridSizer->Add(lastPriceTraded); vbox->Add(gridSizer, 0, borderFlags, borderWidth); chartPanel = new ImagePanel( this, wxID_ANY, wxDefaultPosition, wxSize(CHART_WIDTH, CHART_HEIGHT), wxSUNKEN_BORDER ); vbox->Add(chartPanel, 0, borderFlags, borderWidth); wxSizer* buttonSizer = CreateButtonSizer(wxCLOSE); if (buttonSizer) { vbox->Add(buttonSizer, 0, wxTOP | wxBOTTOM | wxALIGN_RIGHT, borderWidth); } SetSizer(vbox); vbox->Fit(this); Bind(wxEVT_BUTTON, &PriceHistory::OnClose, this, wxID_CLOSE); } void PriceHistory::SetLastPriceTraded(const double lastPriceTraded) { if (lastPriceTraded > 0) { std::ostringstream lastPriceStream; lastPriceStream << std::fixed << std::setprecision(2) << lastPriceTraded; wxString label((lastPriceStream.str()).c_str(), wxConvUTF8); this->lastPriceTraded->SetLabel(label); } } void PriceHistory::SetRunner(const entity::Market& market, const greentop::sport::Runner& runner) { if (market.HasRunner(runner.getSelectionId())) { greentop::sport::RunnerCatalog rc = market.GetRunner(runner.getSelectionId()); std::string runnerName = rc.getRunnerName(); if (runner.getHandicap().isValid()) { runnerName = runnerName + " " + wxString::Format(wxT("%.1f"), runner.getHandicap().getValue()); } bettingOn->SetLabel( GetSelectionName(market.GetMarketCatalogue(), rc, runner.getHandicap()) ); } LoadChart(market, runner); } void PriceHistory::LoadChart( const entity::Market& market, const greentop::sport::Runner& runner ) { wxString marketId(market.GetMarketCatalogue().getMarketId().substr(2)); std::ostringstream oStream; oStream << runner.getSelectionId().getValue(); wxString selectionId = oStream.str(); wxString handicap = "0"; greentop::Optional<double> optionalHandicap = runner.getHandicap(); if (optionalHandicap.isValid()) { std::ostringstream handicapStream; handicapStream << optionalHandicap.getValue(); handicap = handicapStream.str(); } wxString chartUrl = "https://xtsd.betfair.com/LoadRunnerInfoChartAction/?marketId=" + market.GetMarketCatalogue().getMarketId().substr(2) + "&selectionId=" + selectionId + "&handicap=" + handicap; curl_global_init(CURL_GLOBAL_DEFAULT); CURL* curl = curl_easy_init(); if (curl) { wxMemoryOutputStream out; curl_easy_setopt(curl, CURLOPT_URL, static_cast<const char*>(chartUrl.c_str())); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToStream); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out); CURLcode res = curl_easy_perform(curl); if (res == CURLE_OK) { wxMemoryInputStream in(out); wxImage image(in, wxBITMAP_TYPE_JPEG); wxBitmap chart = wxBitmap(image); chartPanel->SetBitmap(chart); } curl_easy_cleanup(curl); } curl_global_cleanup(); } void PriceHistory::OnClose(wxCommandEvent& event) { EndModal(wxID_OK); } } }
31.606667
99
0.674119
1d131892aa907fe7c6c9b8a43c537b45deac968d
382
hpp
C++
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#ifndef LOCIC_SUPPORT_HASHER_HPP #define LOCIC_SUPPORT_HASHER_HPP #include <cstddef> #include <locic/Support/Hash.hpp> namespace locic{ class Hasher { public: Hasher(); void addValue(size_t value); template <typename T> void add(const T& object) { addValue(hashObject<T>(object)); } size_t get() const; private: size_t seed_; }; } #endif
12.322581
35
0.675393
1d14c8e3d86aa27baf03d1b5648d2047ed72ea52
3,198
hpp
C++
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
31
2020-11-23T17:26:36.000Z
2022-03-07T09:46:20.000Z
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
6
2021-04-29T17:47:31.000Z
2022-02-24T17:10:00.000Z
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
11
2021-02-12T12:16:05.000Z
2022-02-10T11:18:47.000Z
// MIT License // // Copyright (c) 2021 Clyde McQueen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_ #define ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_ #include <QBoxLayout> #include <QWidget> #include "orca_topside/video_pipeline.hpp" QT_BEGIN_NAMESPACE class QLabel; QT_END_NAMESPACE namespace orca_topside { class TeleopNode; class TopsideLayout; class TopsideWidget : public QWidget { Q_OBJECT public: explicit TopsideWidget(std::shared_ptr<TeleopNode> node, QWidget *parent = nullptr); void about_to_quit(); void set_armed(bool armed); void set_hold(bool enabled); void set_tilt(int tilt); void set_depth(double target, double actual); void set_lights(int lights); void set_status(uint32_t status, double voltage); void set_trim_x(double v); void set_trim_y(double v); void set_trim_z(double v); void set_trim_yaw(double v); static void update_pipeline(const std::shared_ptr<VideoPipeline> & pipeline, QLabel *label, const char *prefix); void update_pipeline_f() { update_pipeline(video_pipeline_f_, pipeline_f_label_, "F"); } void update_pipeline_l() { update_pipeline(video_pipeline_l_, pipeline_l_label_, "L"); } void update_pipeline_r() { update_pipeline(video_pipeline_r_, pipeline_r_label_, "R"); } protected: void closeEvent(QCloseEvent *event) override; void keyPressEvent(QKeyEvent *event) override; private slots: void update_fps(); private: std::shared_ptr<TeleopNode> node_; std::shared_ptr<VideoPipeline> video_pipeline_f_; std::shared_ptr<VideoPipeline> video_pipeline_l_; std::shared_ptr<VideoPipeline> video_pipeline_r_; GstWidget *gst_widget_f_; GstWidget *gst_widget_l_; GstWidget *gst_widget_r_; TopsideLayout *cam_layout_; QLabel *armed_label_; QLabel *hold_label_; QLabel *depth_label_; QLabel *lights_label_; QLabel *pipeline_f_label_; QLabel *pipeline_l_label_; QLabel *pipeline_r_label_; QLabel *status_label_; QLabel *tilt_label_; QLabel *trim_x_label_; QLabel *trim_y_label_; QLabel *trim_z_label_; QLabel *trim_yaw_label_; }; } // namespace orca_topside #endif // ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_
30.169811
93
0.772358
1d1a805f6372f1eca7b7c40773034606e218253a
8,602
cpp
C++
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
#pragma once #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cmath> #include <Windows.h> #include "Camara.h" #include "objLoader.h" #include "player.h" #include "Luz.h" #include "hud.h" #include "mundo.h" #include "colisiones.h" #include <conio.h> #include <stdlib.h> #include <al\al.h> #include <al\alc.h> #include "sound.h" //#include <al\alu.h> //#include <al\alut.h> using namespace std; void Display(); void Reshape(int w, int h); void Keyboard(unsigned char key, int x, int y); void KeyboardUp(unsigned char key, int x, int y); void MueveRaton(int x, int y); void PulsaRaton(int button, int state, int x, int y); void Timer(int value); void Idle(); void Iniciar(); void Malla(); void update(int value); void updatePlayer(int value); void chase(int value); bool endGame = false; bool g_key[256] = {false}; bool g_shift_down = false; bool g_fps_mode = true; int g_viewport_width = 1240; int g_viewport_height = 720; int bang_g_viewport_width = 1240; int bang_g_viewport_height = 720; bool g_mouse_left_down = false; bool g_mouse_right_down = false; // Movement settings const float velMov = 0.1; const float g_rotation_speed = M_PI / 180 * 0.1; const float velAc = 0.0075; const float velDec = -0.0025; //Player Player *player; objloader *cargador; GLuint suelo; int caja; int test; //Light Luz *luz; GLfloat LuzPos[] = { 0.0f, 200.0f, 0.0f, 1.0f }; GLfloat SpotDir[] = { 0.0f, -200.0f, 0.0f }; //World Mundo *mundo; int dificultad = 1; vector<Ball*> _ranas; vector<Box*> _cajas; float _timeUntilUpdate = 0; float _timeUntilUpdatePlayer = 0; //Frogs int chaseNum = 0; //Sound sound *audio; //HUD char msg[50]; char datosHud[50]; int bangCounter = 0; char *bang; char bang1[10] = "BANG!!"; char bang2[10] = "PIUM!!"; char bang3[10] = "PUM!!"; char bang4[10] = "PAYUM!!"; /* */ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1240, 720); glutCreateWindow("Global Strike: Counter Offensive"); glutIgnoreKeyRepeat(1); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutMouseFunc(PulsaRaton); glutMotionFunc(MueveRaton); glutPassiveMotionFunc(MueveRaton); glutKeyboardFunc(Keyboard); glutKeyboardUpFunc(KeyboardUp); glutIdleFunc(Idle); Iniciar(); glutTimerFunc(TIMER_MS, update, 0); glutTimerFunc(TIMER_MS, updatePlayer, 0); glutTimerFunc(3000, chase, chaseNum); glutTimerFunc(1, Timer, 0); glutMainLoop(); return 0; } void Iniciar(){ audio = new sound; GLfloat Ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat Diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f }; GLfloat SpecRef[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat Specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; printf("\n\n*_*_*_*_*_*_*_*_*_*_*_*_WELCOME TO FROGZ_*_*_*_*_*_*_*_*_*_*_*_*\n\n"); printf("Inserte dificultad:\n\n\tTest: 0\n\n\tFacil: 1\n\n\tNormalillo: 2\n\n\tRanas Astronautas: 3\n"); do{ scanf(" %d", &dificultad); } while (dificultad != 1 && dificultad != 2 && dificultad != 0 && dificultad != 3); mundo = new Mundo(audio,dificultad); player = new Player(mundo,audio); glEnable(GL_TEXTURE_2D); glEnable(GL_SMOOTH); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_NORMALIZE); // Ilumination luz = new Luz(); glutSetCursor(GLUT_CURSOR_NONE); } void Reshape(int w, int h) { g_viewport_width = w; g_viewport_height = h; glViewport(0, 0, (GLsizei)w, (GLsizei)h); //set the viewport to the current window specifications glMatrixMode(GL_PROJECTION); //set the matrix to projection glLoadIdentity(); gluPerspective(60, (GLfloat)w / (GLfloat)h, 0.1, 100.0); //set the perspective (angle of sight, width, height, ,depth) glMatrixMode(GL_MODELVIEW); //set the matrix back to model } void Keyboard(unsigned char key, int x, int y) { if (key == 27) { exit(0); } if (key == 'p') { g_fps_mode = !g_fps_mode; if (g_fps_mode) { glutSetCursor(GLUT_CURSOR_NONE); glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2); } else { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); } } if (glutGetModifiers() == GLUT_ACTIVE_SHIFT) { g_shift_down = true; } else { g_shift_down = false; } if (key == 'r' || key == 'R'){ player->Recargar(); } g_key[key] = true; } void KeyboardUp(unsigned char key, int x, int y) { g_key[key] = false; } void Timer(int value) { if (g_fps_mode) { if (g_key['w'] || g_key['W']) { player->Acelerar(velAc); } else if (g_key['s'] || g_key['S']) { player->Acelerar(-velAc); } else if (!g_key['w'] && !g_key['W'] && !g_key['s'] && !g_key['S']){ player->Decelerar(velDec); } if (g_key['a'] || g_key['A']) { player->AcelerarHorizontal(velAc); } else if (g_key['d'] || g_key['D']) { player->AcelerarHorizontal(-velAc); } else if (!g_key['a'] && !g_key['A'] && !g_key['d'] && !g_key['D']){ player->DecelerarHorizontal(velDec); } } glutTimerFunc(1, Timer, 0); } void Idle() { Display(); } void PulsaRaton(int button, int state, int x, int y) { if (state == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { if (g_fps_mode){ g_mouse_left_down = true; player->Disparo(); bangCounter = 40; switch (rand() % 4){ case 0: bang = bang1; break; case 1: bang = bang2; break; case 2: bang = bang3; break; case 3: bang = bang4; break; } bang_g_viewport_width = (rand() % (g_viewport_width - 200)) + 100; bang_g_viewport_height = (rand() % (g_viewport_height - 100)) + 50; } } else if (button == GLUT_RIGHT_BUTTON) { g_mouse_right_down = true; } } else if (state == GLUT_UP) { if (button == GLUT_LEFT_BUTTON) { g_mouse_left_down = false; } else if (button == GLUT_RIGHT_BUTTON) { g_mouse_right_down = false; } } } void MueveRaton(int x, int y) { static bool just_warped = false; if (just_warped) { just_warped = false; return; } if (g_fps_mode) { int dx = x - g_viewport_width / 2; int dy = y - g_viewport_height / 2; if (dx) { player->RotarHorizontal(g_rotation_speed*dx); } if (dy) { player->RotarVertical(g_rotation_speed*dy); } glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2); just_warped = true; } } void Display(void) { glClearColor(0.0, 0.0, 0.0, 1.0); //clear the screen to black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear the color buffer and the depth buffer glMatrixMode(GL_PROJECTION); //set the matrix to projection glLoadIdentity(); gluPerspective(60, (GLfloat)g_viewport_width / (GLfloat)g_viewport_height, 0.1, 200.0); //set the perspective (angle of sight, width, height, ,depth) glMatrixMode(GL_MODELVIEW); //set the matrix back to model glLoadIdentity(); if (endGame){ mundo->end(); exit(0); } //Camera Position player->Refresh(g_fps_mode); //Light luz->refresh(LuzPos,SpotDir); //World mundo->dibujarMundoEstatico(); mundo->dibujarMundoDinamico(); //Weapon if (g_fps_mode){ player->dibujaArma(); } else{ player->dibujarModelo(); } //HUD sprintf(msg, "Ranas restantes: [%d]", mundo->getRanas().size()); sprintf(datosHud,"Vida: [%d] Balas: [%d]",player->getVida(),player->getBalas()); hud(msg, g_viewport_width, g_viewport_height,5,20); hud(datosHud, g_viewport_width, g_viewport_height, g_viewport_width -400 , g_viewport_height-20); if (player->getBalas() > 0){ if (bangCounter > 0){ bangCounter--; hudBang(bang, g_viewport_width, g_viewport_height, bang_g_viewport_width, bang_g_viewport_height); } } if ((mundo->getRanas().size() <= 0 && dificultad!=0) || player->getVida()<= 0){ fin(g_viewport_width, g_viewport_height); Sleep(500); endGame = true; } glutSwapBuffers(); //swap the buffers } void update(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); _cajas = mundo->getCajas(); advance(_ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer, mundo,(dificultad!=3)); glutPostRedisplay(); } glutTimerFunc(TIMER_MS, update, 0); } void updatePlayer(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); _cajas = mundo->getCajas(); advancePlayer(player->hitball, player, _ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer); glutPostRedisplay(); } glutTimerFunc(1, updatePlayer, 0); } void chase(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); chasePlayer(player->hitball, player, _ranas, chaseNum); chaseNum++; if (chaseNum >= numRanas){ chaseNum = 0; } glutPostRedisplay(); } glutTimerFunc(500, chase, 0); }
19.461538
150
0.666008
1d1ab64d64cd8ee156fcc81a16222fc301597264
3,121
cpp
C++
SphereWeights/SphereWeightsMain.cpp
papagiannakis/viper
2f25416385b0cf42c60e19ff787fe4a6a4c26223
[ "Apache-2.0" ]
847
2019-07-29T15:21:02.000Z
2022-03-26T16:28:55.000Z
SphereWeights/SphereWeightsMain.cpp
Open-AGI/viper
2f25416385b0cf42c60e19ff787fe4a6a4c26223
[ "Apache-2.0" ]
17
2020-04-08T16:41:11.000Z
2021-11-18T09:39:20.000Z
SphereWeights/SphereWeightsMain.cpp
Open-AGI/viper
2f25416385b0cf42c60e19ff787fe4a6a4c26223
[ "Apache-2.0" ]
100
2019-12-27T10:18:24.000Z
2022-03-26T16:30:40.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 // // https://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 "SphereWeights.h" #include <fstream> #include <iostream> #include <thread> #include "Viper_json.h" using namespace OpenGP; using Vec2i = Eigen::Vector2i; using Vec3i = Eigen::Vector3i; using Vec4i = Eigen::Vector4i; int main(int argc, char **argv) { std::clog << "Starting SphereWeights:" << std::endl; std::istream *stream_ptr = &std::cin; std::ifstream file_stream; if (argc > 1) { file_stream = std::ifstream(argv[1]); stream_ptr = &file_stream; } std::istream &in_stream = *stream_ptr; std::string input, line; while (std::getline(in_stream, line)) { input += line + "\n"; } rapidjson::Document j; j.Parse(input.c_str()); auto verts = viper::from_json<std::vector<Vec3>>(j["vertices"]); auto tris = viper::from_json<std::vector<Vec3i>>(j["triangles"]); auto spheres = viper::from_json<std::vector<Vec4>>(j["spheres"]); auto pills = viper::from_json<std::vector<Vec2i>>(j["pills"]); SurfaceMesh mesh; SphereMesh smesh; for (auto vert : verts) { mesh.add_vertex(vert); } for (auto tri : tris) { using V = SurfaceMesh::Vertex; mesh.add_triangle(V(tri[0]), V(tri[1]), V(tri[2])); } for (auto sphere : spheres) { smesh.add_vertex(sphere); } for (auto pill : pills) { using V = SphereMesh::Vertex; smesh.add_edge(V(pill[0]), V(pill[1])); } calc_weights(smesh, mesh); auto &weights = mesh.get_vertex_property<std::vector<float>>("v:skinweight").vector(); auto &bone_ids = mesh.get_vertex_property<std::vector<int>>("v:boneid").vector(); { rapidjson::MemoryPoolAllocator<> alloc; rapidjson::Document j(&alloc); j.SetObject(); rapidjson::Document::AllocatorType &allocator = j.GetAllocator(); rapidjson::Value weights_array(rapidjson::kArrayType); for (auto &w : weights) { weights_array.PushBack(viper::to_json(w, allocator), allocator); } j.AddMember("weights", weights_array, allocator); rapidjson::Value ids_array(rapidjson::kArrayType); for (auto &i : bone_ids) { ids_array.PushBack(viper::to_json(i, allocator), allocator); } j.AddMember("bone_ids", ids_array, allocator); rapidjson::StringBuffer strbuf; strbuf.Clear(); rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); j.Accept(writer); std::cout << strbuf.GetString() << std::endl; } return 0; }
29.168224
78
0.63281
1d1e65eb821351186e10c0160fe1b1419c21d2bc
3,786
cpp
C++
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct MCMF { using F = int; const static F INF = 0x3f3f3f3f; // using F = long long; const static F INF = 0x3f3f3f3f3f3f3f3f; struct Edge { int v, bro; F cap, cost; Edge() {} Edge(int _v, int _bro, F _cap, F _cost) : v(_v), bro(_bro), cap(_cap), cost(_cost) {} }; vector<Edge> e; vector<int> pos, pre; vector<F> dis; vector<bool> trk; int n, s, t, m; MCMF(int _n, int _s, int _t) : n(_n), s(_s), t(_t), m(0) { pos.assign(n, -1); pre.resize(n); dis.resize(n); trk.resize(n); e.reserve(4e5); } void add(int u, int v, F cap = INF, F cost = 0) { assert(u < n && v < n); e.emplace_back(v, pos[u], cap, cost); pos[u] = m++; e.emplace_back(u, pos[v], 0, -cost); pos[v] = m++; } bool spfa() { queue<int> q; fill(pre.begin(), pre.end(), -1); fill(dis.begin(), dis.end(), INF); fill(trk.begin(), trk.end(), false); dis[s] = 0; trk[s] = true; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); trk[u] = false; for (int i = pos[u]; i != -1; i = e[i].bro){ int v = e[i].v; if (e[i].cap > 0 && dis[v] > dis[u] + e[i].cost){ dis[v] = dis[u] + e[i].cost; pre[v] = i; if (!trk[v]){ trk[v] = true; q.push(v); } } } } return pre[t] != -1; } pair<F,F> mcmf() { F flow = 0, cost = 0; while (spfa()) { // (dijkstra()) { // don't need max-flow, but min cost. require each push at least -COST if (dis[t] >= 0) break; F f = INF; for (int i = pre[t]; i != -1; i = pre[e[i^1].v]) f = min(f, e[i].cap); for (int i = pre[t]; i != -1; i = pre[e[i^1].v]){ e[i].cap -= f; e[i^1].cap += f; cost += e[i].cost * f; } flow += f; } return {flow, cost}; } }; void solve() { int n1,n2,m,r,b; cin >> n1 >> n2 >> m >> r >> b; string s1,s2; cin >> s1 >> s2; int S = n1+n2, T = S + 1; MCMF g(T+1, S, T); for (int _ = 0; _ < m; _++) { int x,y; cin >> x >> y; x--;y--; y+=n1; g.add(x, y, 1, r); g.add(y, x, 1, b); } int cnt = 0; const int CAP = 2*m; const int COST = 100005; for (int i = 0; i < n1; i++) { if (s1[i] == 'R') { g.add(S, i, 1, -COST); g.add(S, i, CAP); cnt++; } else if (s1[i] == 'B') { g.add(i, T, 1, -COST); g.add(i, T, CAP); cnt++; } else { g.add(S, i, CAP); g.add(i, T, CAP); } } for (int i = 0; i < n2; i++) { int k = i + n1; if (s2[i] == 'B') { g.add(S, k, 1, -COST); g.add(S, k, CAP); cnt++; } else if (s2[i] == 'R') { g.add(k, T, 1, -COST); g.add(k, T, CAP); cnt++; } else { g.add(S, k, CAP); g.add(k, T, CAP); } } int flow,cost; tie(flow,cost) = g.mcmf(); cost += cnt * COST; if (cost >= COST) { cout << -1; return; } cout << cost << "\n"; for (int i = 0; i < m; i++) { if (g.e[i*4 + 1].cap) { cout << 'R'; } else if (g.e[i*4 + 3].cap) { cout << 'B'; } else { cout << 'U'; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
26.851064
93
0.368727
1d20c2d41c5beddc32aea4e0a322fc051891a8da
2,800
cpp
C++
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SoundSubmixGraph/SoundSubmixGraphNode.h" #include "Sound/SoundSubmix.h" #include "SoundSubmixGraph/SoundSubmixGraphSchema.h" #include "SoundSubmixGraph/SoundSubmixGraph.h" #define LOCTEXT_NAMESPACE "SoundSubmixGraphNode" USoundSubmixGraphNode::USoundSubmixGraphNode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , ChildPin(NULL) , ParentPin(NULL) { } bool USoundSubmixGraphNode::CheckRepresentsSoundSubmix() { if (!SoundSubmix) { return false; } for (int32 ChildIndex = 0; ChildIndex < ChildPin->LinkedTo.Num(); ChildIndex++) { USoundSubmixGraphNode* ChildNode = CastChecked<USoundSubmixGraphNode>(ChildPin->LinkedTo[ChildIndex]->GetOwningNode()); if (!SoundSubmix->ChildSubmixes.Contains(ChildNode->SoundSubmix)) { return false; } } for (int32 ChildIndex = 0; ChildIndex < SoundSubmix->ChildSubmixes.Num(); ChildIndex++) { bool bFoundChild = false; for (int32 NodeChildIndex = 0; NodeChildIndex < ChildPin->LinkedTo.Num(); NodeChildIndex++) { USoundSubmixGraphNode* ChildNode = CastChecked<USoundSubmixGraphNode>(ChildPin->LinkedTo[NodeChildIndex]->GetOwningNode()); if (ChildNode->SoundSubmix == SoundSubmix->ChildSubmixes[ChildIndex]) { bFoundChild = true; break; } } if (!bFoundChild) { return false; } } return true; } FLinearColor USoundSubmixGraphNode::GetNodeTitleColor() const { return Super::GetNodeTitleColor(); } void USoundSubmixGraphNode::AllocateDefaultPins() { check(Pins.Num() == 0); ChildPin = CreatePin(EGPD_Output, TEXT("SoundSubmix"), FString(), nullptr, LOCTEXT("SoundSubmixChildren", "Children").ToString()); ParentPin = CreatePin(EGPD_Input, TEXT("SoundSubmix"), FString(), nullptr, FString()); } void USoundSubmixGraphNode::AutowireNewNode(UEdGraphPin* FromPin) { if (FromPin) { const USoundSubmixGraphSchema* Schema = CastChecked<USoundSubmixGraphSchema>(GetSchema()); if (FromPin->Direction == EGPD_Input) { Schema->TryCreateConnection(FromPin, ChildPin); } else { Schema->TryCreateConnection(FromPin, ParentPin); } } } bool USoundSubmixGraphNode::CanCreateUnderSpecifiedSchema(const UEdGraphSchema* Schema) const { return Schema->IsA(USoundSubmixGraphSchema::StaticClass()); } FText USoundSubmixGraphNode::GetNodeTitle(ENodeTitleType::Type TitleType) const { if (SoundSubmix) { return FText::FromString(SoundSubmix->GetName()); } else { return Super::GetNodeTitle(TitleType); } } bool USoundSubmixGraphNode::CanUserDeleteNode() const { USoundSubmixGraph* SoundSubmixGraph = CastChecked<USoundSubmixGraph>(GetGraph()); // Cannot remove the root node from the graph return SoundSubmix != SoundSubmixGraph->GetRootSoundSubmix(); } #undef LOCTEXT_NAMESPACE
25.225225
131
0.756071
1d22dee0f995a9780c5640ceacf6fdbcb0c4d5bf
5,048
cpp
C++
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ecm/v20190719/model/PeakBase.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ecm::V20190719::Model; using namespace std; PeakBase::PeakBase() : m_peakCpuNumHasBeenSet(false), m_peakMemoryNumHasBeenSet(false), m_peakStorageNumHasBeenSet(false), m_recordTimeHasBeenSet(false) { } CoreInternalOutcome PeakBase::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("PeakCpuNum") && !value["PeakCpuNum"].IsNull()) { if (!value["PeakCpuNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakCpuNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakCpuNum = value["PeakCpuNum"].GetInt64(); m_peakCpuNumHasBeenSet = true; } if (value.HasMember("PeakMemoryNum") && !value["PeakMemoryNum"].IsNull()) { if (!value["PeakMemoryNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakMemoryNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakMemoryNum = value["PeakMemoryNum"].GetInt64(); m_peakMemoryNumHasBeenSet = true; } if (value.HasMember("PeakStorageNum") && !value["PeakStorageNum"].IsNull()) { if (!value["PeakStorageNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakStorageNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakStorageNum = value["PeakStorageNum"].GetInt64(); m_peakStorageNumHasBeenSet = true; } if (value.HasMember("RecordTime") && !value["RecordTime"].IsNull()) { if (!value["RecordTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `PeakBase.RecordTime` IsString=false incorrectly").SetRequestId(requestId)); } m_recordTime = string(value["RecordTime"].GetString()); m_recordTimeHasBeenSet = true; } return CoreInternalOutcome(true); } void PeakBase::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_peakCpuNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakCpuNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakCpuNum, allocator); } if (m_peakMemoryNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakMemoryNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakMemoryNum, allocator); } if (m_peakStorageNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakStorageNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakStorageNum, allocator); } if (m_recordTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RecordTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_recordTime.c_str(), allocator).Move(), allocator); } } int64_t PeakBase::GetPeakCpuNum() const { return m_peakCpuNum; } void PeakBase::SetPeakCpuNum(const int64_t& _peakCpuNum) { m_peakCpuNum = _peakCpuNum; m_peakCpuNumHasBeenSet = true; } bool PeakBase::PeakCpuNumHasBeenSet() const { return m_peakCpuNumHasBeenSet; } int64_t PeakBase::GetPeakMemoryNum() const { return m_peakMemoryNum; } void PeakBase::SetPeakMemoryNum(const int64_t& _peakMemoryNum) { m_peakMemoryNum = _peakMemoryNum; m_peakMemoryNumHasBeenSet = true; } bool PeakBase::PeakMemoryNumHasBeenSet() const { return m_peakMemoryNumHasBeenSet; } int64_t PeakBase::GetPeakStorageNum() const { return m_peakStorageNum; } void PeakBase::SetPeakStorageNum(const int64_t& _peakStorageNum) { m_peakStorageNum = _peakStorageNum; m_peakStorageNumHasBeenSet = true; } bool PeakBase::PeakStorageNumHasBeenSet() const { return m_peakStorageNumHasBeenSet; } string PeakBase::GetRecordTime() const { return m_recordTime; } void PeakBase::SetRecordTime(const string& _recordTime) { m_recordTime = _recordTime; m_recordTimeHasBeenSet = true; } bool PeakBase::RecordTimeHasBeenSet() const { return m_recordTimeHasBeenSet; }
27.736264
140
0.695721
918f20f50d64eb3cfc21d7e7cd53b8b6c2a70df5
6,728
cc
C++
src/ShaderCompiler/Private/MetalCompiler.cc
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/ShaderCompiler/Private/MetalCompiler.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/ShaderCompiler/Private/MetalCompiler.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include <Kaleido3D.h> #include "MetalCompiler.h" #include <Core/Utils/MD5.h> #include <Core/Os.h> #include "GLSLangUtils.h" #include "SPIRVCrossUtils.h" #define METAL_BIN_DIR_MACOS "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/usr/bin/" #define METAL_BIN_DIR_IOS "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/usr/bin/" #define METAL_COMPILE_TMP "/.metaltmp/" #define COMPILE_OPTION "-arch air64 -emit-llvm -c" #include <string.h> using namespace std; namespace k3d { NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR); MetalCompiler::MetalCompiler() { sInitializeGlSlang(); } MetalCompiler::~MetalCompiler() { sFinializeGlSlang(); } NGFXShaderCompileResult MetalCompiler::Compile(String const& src, NGFXShaderDesc const& inOp, NGFXShaderBundle& bundle) { if (inOp.Format == NGFX_SHADER_FORMAT_TEXT) { if (inOp.Lang == NGFX_SHADER_LANG_METALSL) { if (m_IsMac) { } else // iOS { } } else // process hlsl or glsl { bool canConvertToMetalSL = false; switch (inOp.Lang) { case NGFX_SHADER_LANG_ESSL: case NGFX_SHADER_LANG_GLSL: case NGFX_SHADER_LANG_HLSL: case NGFX_SHADER_LANG_VKGLSL: canConvertToMetalSL = true; break; default: break; } if (canConvertToMetalSL) { EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); switch (inOp.Lang) { case NGFX_SHADER_LANG_ESSL: case NGFX_SHADER_LANG_GLSL: case NGFX_SHADER_LANG_VKGLSL: break; case NGFX_SHADER_LANG_HLSL: messages = (EShMessages)(EShMsgVulkanRules | EShMsgSpvRules | EShMsgReadHlsl); break; default: break; } glslang::TProgram& program = *new glslang::TProgram; TBuiltInResource Resources; initResources(Resources); const char* shaderStrings[1]; EShLanguage stage = findLanguage(inOp.Stage); glslang::TShader* shader = new glslang::TShader(stage); shaderStrings[0] = src.CStr(); shader->setStrings(shaderStrings, 1); shader->setEntryPoint(inOp.EntryFunction.CStr()); if (!shader->parse(&Resources, 100, false, messages)) { puts(shader->getInfoLog()); puts(shader->getInfoDebugLog()); return NGFX_SHADER_COMPILE_FAILED; } program.addShader(shader); if (!program.link(messages)) { puts(program.getInfoLog()); puts(program.getInfoDebugLog()); return NGFX_SHADER_COMPILE_FAILED; } vector<unsigned int> spirv; GlslangToSpv(*program.getIntermediate(stage), spirv); if (program.buildReflection()) { ExtractAttributeData(program, bundle.Attributes); ExtractUniformData(inOp.Stage, program, bundle.BindingTable); } else { return NGFX_SHADER_COMPILE_FAILED; } uint32 bufferLoc = 0; vector<spirv_cross::MSLVertexAttr> vertAttrs; for (auto& attr : bundle.Attributes) { spirv_cross::MSLVertexAttr vAttrib; vAttrib.location = attr.VarLocation; vAttrib.msl_buffer = attr.VarBindingPoint; vertAttrs.push_back(vAttrib); bufferLoc = attr.VarBindingPoint; } vector<spirv_cross::MSLResourceBinding> resBindings; for (auto& binding : bundle.BindingTable.Bindings) { if (binding.VarType == NGFX_SHADER_BIND_BLOCK) { bufferLoc ++; spirv_cross::MSLResourceBinding resBind; resBind.stage = rhiShaderStageToSpvModel(binding.VarStage); resBind.desc_set = 0; resBind.binding = binding.VarNumber; resBind.msl_buffer = bufferLoc; resBindings.push_back(resBind); } } auto metalc = make_unique<spirv_cross::CompilerMSL>(spirv); spirv_cross::CompilerMSL::Options config; config.flip_vert_y = false; config.entry_point_name = inOp.EntryFunction.CStr(); auto result = metalc->compile(config, &vertAttrs, &resBindings); if (m_IsMac) { auto ret = mtlCompile(result, bundle.RawData); if (ret == NGFX_SHADER_COMPILE_FAILED) return ret; bundle.Desc = inOp; bundle.Desc.Format = NGFX_SHADER_FORMAT_BYTE_CODE; bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL; } else { bundle.RawData = {result.c_str()}; bundle.Desc = inOp; bundle.Desc.Format = NGFX_SHADER_FORMAT_TEXT; bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL; } } } } else { if (inOp.Lang == NGFX_SHADER_LANG_METALSL) { } else { } } return NGFX_SHADER_COMPILE_OK; } const char* MetalCompiler::GetVersion() { return "Metal"; } NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR) { #if K3DPLATFORM_OS_MAC MD5 md5(source); auto name = md5.toString(); auto intermediate = string(".") + METAL_COMPILE_TMP; Os::Path::MakeDir(intermediate.c_str()); auto tmpSh = intermediate + name + ".metal"; auto tmpAr = intermediate + name + ".air"; auto tmpLib = intermediate + name + ".metallib"; Os::File shSrcFile(tmpSh.c_str()); shSrcFile.Open(IOWrite); shSrcFile.Write(source.data(), source.size()); shSrcFile.Close(); auto mcc = string(METAL_BIN_DIR_MACOS) + "metal"; auto mlink = string(METAL_BIN_DIR_MACOS) + "metallib"; auto ccmd = mcc + " -arch air64 -c -o " + tmpAr + " " + tmpSh; auto ret = system(ccmd.c_str()); if(ret) { return NGFX_SHADER_COMPILE_FAILED; } auto lcmd = mlink + " -split-module -o " + tmpLib + " " + tmpAr; ret = system(lcmd.c_str()); if(ret) { return NGFX_SHADER_COMPILE_FAILED; } Os::MemMapFile bcFile; bcFile.Open(tmpLib.c_str(), IORead); metalIR = { bcFile.FileData(), (size_t)bcFile.GetSize() }; bcFile.Close(); //Os::Remove(intermediate.c_str()); #endif return NGFX_SHADER_COMPILE_OK; } }
31.586854
121
0.582194
9194384a31c83f2f72a2087ad9b27858c9062688
582
cpp
C++
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
1
2016-11-18T02:34:18.000Z
2016-11-18T02:34:18.000Z
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
null
null
null
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
null
null
null
// Copyright Oliver Kowalke 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "boost/fiber/barrier.hpp" #include <boost/assert.hpp> namespace boost { namespace fibers { bool barrier::wait() { mutex::scoped_lock lk( mtx_); bool cycle( cycle_); if ( 0 == --current_) { cycle_ = ! cycle_; current_ = initial_; cond_.notify_all(); return true; } else { while ( cycle == cycle_) cond_.wait( lk); } return false; } }}
16.628571
61
0.651203
919a463419264750d166d11f2fcd75703cf8ae1f
32,321
cpp
C++
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
10
2021-08-20T05:49:10.000Z
2022-01-07T13:00:20.000Z
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
null
null
null
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
4
2021-09-11T12:08:01.000Z
2022-02-09T00:16:19.000Z
/** XR Vessel add-ons for OpenOrbiter Space Flight Simulator Copyright (C) 2006-2021 Douglas Beachy This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Email: mailto:doug.beachy@outlook.com Web: https://www.alteaaerospace.com **/ //------------------------------------------------------------------------- // ParserTreeNode.cpp : implementation of ParserTreeNode class; maintains state // for a given node in our parser tree. //------------------------------------------------------------------------- #include <windows.h> #include <limits> #include "ParserTreeNode.h" // so numeric_limits<T> min, max will compile #undef min #undef max /* Here is an example of how a simple parser tree might look: ParserTreeNode(nullptr) // root node / \ (Set) \ / (Config) (Engine) / \ / / \ (MainBoth, MainLeft, MainRight, (AttitudeHold) (AirspeedHold) Retro...,Hover..., Scram...) / \ / / \ / / \ / (Pitch, AOA) (#targetAirspeed -- this is a leaf node) / / / / (ThrottleLevel, (#targetX #targetBank -- leaf node) GimbalX, GimbayY, ...) / / (#doubleValue) or (#boolValue) */ // Constructor // csNodeText = "Set", "MainLeft", etc. If null, denotes the root node of the tree. Will be cloned internally. // nodeGroup = arbitrary group ID that groups like nodes together when constructing help strings // pNodeData = arbitrary data assigned to this node that is for use by the caller as he sees fit. May be null, although this is normally only null for top-level nodes. // Typically, however, this will be data that will be used later by the LeafHandler of this node or one of its children. This is clone internally. // pCallback = handler that executes for leaf nodes; should be null for non-leaf nodes. This is not cloned internally. ParserTreeNode::ParserTreeNode(const char *pNodeText, const int nodeGroup, const NodeData *pNodeData, LeafHandler *pCallback) : m_nodeGroup(nodeGroup), m_pLeafHandler(pCallback), m_pParentNode(nullptr) { m_pCSNodeText = ((pNodeText != nullptr) ? new CString(pNodeText) : nullptr); // clone it m_pNodeData = ((pNodeData != nullptr) ? pNodeData->Clone() : nullptr); // deep-clone it } // Destructor ParserTreeNode::~ParserTreeNode() { // recursively free all our child nodes for (unsigned int i=0; i < m_children.size(); i++) delete m_children[i]; // free our node text and NodeDAta that we created via cloning in the constructor delete m_pCSNodeText; delete m_pNodeData; } // Add a child node to this node void ParserTreeNode::AddChild(ParserTreeNode *pChildNode) { _ASSERTE(pChildNode != nullptr); pChildNode->SetParentNode(this); // we are the parent m_children.push_back(pChildNode); } // NOTE: for parsing purposes, all string comparisons are case-insensitive. // Parse the command and set csCommand to a full auto-completed string if possible. // Some examples: // S -> returns "Set" // s m -> returns "Set MainBoth" // -> (again) "Set MainLeft" // // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // direction: true = tab direction forward, false = tab direction backward // Returns true if we autocompleted all commands in csCommand bool ParserTreeNode::AutoComplete(CString &csCommand, AUTOCOMPLETION_STATE *pACState, const bool direction) const { csCommand = csCommand.Trim(); if (csCommand.IsEmpty()) return false; // nothing to complete // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments const int autocompletedTokenCount = AutoComplete(argv, 0, pACState, direction); // now reconstruct the full string from the auto-completed pieces csCommand.Empty(); for (unsigned int i=0; i < argv.size(); i++) { if (i > 0) csCommand += " "; csCommand += argv[i]; } const bool autoCompletedAll = (autocompletedTokenCount == argv.size()); // if we autocompleted all tokens successfully, append a trailing space if (autoCompletedAll) csCommand += " "; return autoCompletedAll; } // Recursive method to auto-complete all commands in argv. // argv = arguments to be autocompleted // startingIndex = 0-based index at which to start parsing // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // direction: true = tab direction forward, false = tab direction backward // Returns # of nodes auto-completed (may be zero) int ParserTreeNode::AutoComplete(vector<CString> &argv, const int startingIndex, AUTOCOMPLETION_STATE *pACState, const bool direction) const { _ASSERTE(startingIndex >= 0); _ASSERTE(startingIndex < static_cast<int>(argv.size())); _ASSERTE(pACState != nullptr); int autocompletedTokens = 0; // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; // By design, only track autocompletion state for the *last* token on the line; otherwise we would // overwrite the command following the one we would autocomplete. AUTOCOMPLETION_STATE *pActiveACState = ((startingIndex == (argv.size()-1)) ? pACState : nullptr); const int nextArgIndex = startingIndex + 1; ParserTreeNode *pMatchingChild = FindChildForToken(csToken, pActiveACState, direction); if (pMatchingChild != nullptr) { // Note: by design, we count a token as autocompleted if even if was already complete autocompletedTokens++; argv[startingIndex] = *pMatchingChild->GetNodeText(); // change argv entry to completed token; e.g., "Set", "Main", etc. if (nextArgIndex < static_cast<int>(argv.size())) // any more arguments to parse? { // now let's recurse down to the next level and try to autocomplete the next level down autocompletedTokens += pMatchingChild->AutoComplete(argv, nextArgIndex, pACState, direction); // propagate the ACState that was passed in } } else // no matching child { // let's see if we're a leaf node AND this is the last token on the line (i.e., the first leaf node parameter) if ((m_pLeafHandler != nullptr) && (nextArgIndex == static_cast<int>(argv.size()))) { // this is leaf node parameter #1, so let's see if there are any autocompletion tokens available for it const char **pFirstParamTokens = m_pLeafHandler->GetFirstParamAutocompletionTokens(this); // may be nullptr // let's try to find a unique match const char *pAutocompletedToken = AutocompleteToken(argv[startingIndex], pACState, direction, pFirstParamTokens); if (pAutocompletedToken != nullptr) { autocompletedTokens++; argv[startingIndex] = pAutocompletedToken; // change argv entry to completed token // since this is the last token on the line, there is nothing else to parse: fall through and return } } } return autocompletedTokens; } // Parse the command until either the entire command is parsed (and executed via its leaf handler) // or we locate a syntax or value error. // // Returns true on success, false on error // pCommand = command to be parsed // statusOut = output buffer for result text bool ParserTreeNode::Parse(const char *pCommand, CString &statusOut) const { CString csCommand = CString(pCommand).Trim(); if (csCommand.IsEmpty()) { statusOut = "command is empty."; return false; } // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments and execute the command CString commandStatus; bool success = Parse(argv, 0, commandStatus); statusOut.Format("Command: [%s]\r\n", csCommand); statusOut += (success ? "" : "Error: ") + commandStatus; return success; } // Recursive method that will parse the command and recurse down to our child nodes until we execute the // command or locate a syntax error. // // argv = arguments to be parsed // startingIndex = 0-based index at which to start parsing; NOTE: may be beyond end of argv if this is a leaf node that takes no arguments // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // Returns true on success, false on error bool ParserTreeNode::Parse(vector<CString> &argv, const int startingIndex, CString &statusOut) const { _ASSERTE(startingIndex >= 0); // do not validate argv against startingIndex here: may be beyond end of argv if this is a leaf node that takes no arguments statusOut.Empty(); bool retVal = false; // assume failure // if this is a leaf node, invoke the leafHandler execute the action for this node if (m_pLeafHandler != nullptr) { _ASSERTE(m_children.size() == 0); // leaf nodes must not have any children // build vector of remaining arguments vector<CString> remainingArgv; for (int i=startingIndex; i < static_cast<int>(argv.size()); i++) remainingArgv.push_back(argv[i]); // invoke the leaf handler to execute this command retVal = m_pLeafHandler->Execute(this, remainingArgv, statusOut); } else // not a leaf node, so let's keep recursing down... { const int nextArgIndex = startingIndex + 1; if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse? { // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; ParserTreeNode *pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot) if (pMatchingChild != nullptr) { // command token is valid const int nextArgIndex = startingIndex + 1; // Note: there may not be any more arguments to parse here; e.g., for leaf nodes that take no arguments. // Therefore, we always recurse down to the next level and attempt to parse/execute it. retVal = pMatchingChild->Parse(argv, nextArgIndex, statusOut); } else // unknown command { statusOut.Format("Invalid command token: [%s]", csToken); // fall through and return false } } else // no more arguments, but this is not a leaf node { statusOut = "Required token missing; options are: "; AppendChildNodeNames(statusOut); // fall through and return false } } return retVal; } // Sets argsOut to a list of bracket-grouped available arguments for the supplied command. // Returns the level for which the available arguments pertain. // For example: // "" -> (returns 1), argsOut = [Set, Config, ...] // Set -> (returns 2), argsOut = [MainBoth, MainLeft, ...] // Set foo -> (returns 2), argsOut = [MainBoth, MainLeft, ...] (foo is invalid, but the user can still correct 'foo' to be one of the valid options) // Set MainBoth -> (returns 3), argsOut = [ThrottleLevel, GimbalX, GimbalY, ...] // "foo" -> (returns 1), argsOut = [Set, Config, ...] (foo is an invalid command) int ParserTreeNode::GetAvailableArgumentsForCommand(const char *pCommand, vector<CString> &argsOut) const { CString csCommand = CString(pCommand).Trim(); // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments argsOut.clear(); // reset int argLevel = GetAvailableArgumentsForCommand(argv, 0, argsOut); return argLevel; } // Recursively parse the supplied command and populate argsOut with bracket-grouped, valid arguments for this command. // argv = arguments to parse // startingIndex = index into argv to parse; also denotes our recursion level (0...n) // argsOut = will be populated with valid arguments for this command // Returns the level for which the arguments in argsOut pertain. int ParserTreeNode::GetAvailableArgumentsForCommand(vector<CString> &argv, const int startingIndex, vector<CString> &argsOut) const { _ASSERTE(startingIndex >= 0); int retVal; // if this is a leaf node, we have reached the end of the chain, so show the leaf handler's help text if (m_pLeafHandler != nullptr) { _ASSERTE(m_children.size() == 0); // leaf nodes must not have any children CString csHelp; m_pLeafHandler->GetArgumentHelp(this, csHelp); argsOut.push_back("[" + csHelp + "]"); // e.g., "[<double> (range -1.0 - 1.0)]" retVal = startingIndex; // startingIndex also matches our recursion level } else // not a leaf node, so let's keep recursing down... { ParserTreeNode *pMatchingChild = nullptr; if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse? { // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot) } const int nextArgIndex = startingIndex + 1; if (pMatchingChild != nullptr) { // command token is valid, so let's recurse down to the next level (keep parsing) const int nextArgIndex = startingIndex + 1; retVal = pMatchingChild->GetAvailableArgumentsForCommand(argv, nextArgIndex, argsOut); // recurse down } else { // No child node found and this is NOT a leaf node, so we have invalid tokens at this level. // Therefore, we return a list of this level's child nodes (available options), grouped in brackets [ ... ]. int currentNodeGroup; for (unsigned int i=0; i < m_children.size(); i++) { const ParserTreeNode *pChild = m_children[i]; _ASSERTE(pChild != nullptr); CString nodeText = *m_children[i]->GetNodeText(); // enclose a given group of commands in brackets for clarity if (i == 0) { currentNodeGroup = pChild->GetNodeGroup(); // first node at this level, so its group is the active group now nodeText = " [" + nodeText; // first group start } else if (pChild->GetNodeGroup() != currentNodeGroup) { // new group coming, so append closing "]" to previous command text and prepend " [" to this command text currentNodeGroup = pChild->GetNodeGroup(); // this is the new active group argsOut.back() += "]"; nodeText = " [" + nodeText; } argsOut.push_back(nodeText); } argsOut.back() += "]"; // last group end retVal = startingIndex; } } _ASSERTE(argsOut.size() > 0); return retVal; } // appends csOut with formatted names for all our child nodes void ParserTreeNode::AppendChildNodeNames(CString &csOut) const { for (unsigned int i=0; i < m_children.size(); i++) { if (i > 0) csOut += ", "; csOut += *m_children[i]->GetNodeText(); // e.g., "Set", "MainBoth", etc. } } // static factory method that creates a new autocompletion state; it is the caller's responsibility to eventually free this ParserTreeNode::AUTOCOMPLETION_STATE *ParserTreeNode::AllocateNewAutocompletionState() { AUTOCOMPLETION_STATE *pNew = reinterpret_cast<AUTOCOMPLETION_STATE *>(new ParserTreeNode::AutocompletionState()); ResetAutocompletionState(pNew); return pNew; } // static utility method to reset the autcompletion state to a new command void ParserTreeNode::ResetAutocompletionState(AUTOCOMPLETION_STATE *pACState) { AutocompletionState *ptr = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type ptr->significantCharacters = 0; ptr->tokenCandidateIndex = 0; } // Examine our child nodes and try to locate a case-insensitive match for the supplied token. // acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line) // direction: true = tab direction forward, false = tab direction backward // Returns node on a match or nullptr if no match found OR if more than one match found. ParserTreeNode *ParserTreeNode::FindChildForToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction) const { if (csToken.IsEmpty()) return nullptr; // sanity check // NOTE: do not modify this object's state *except* for the last token on the command line AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type // assume no autocompletionstate int significantCharacters = csToken.GetLength(); int tokenCandidateIndex = 0; if (pActiveACState != nullptr) { // we may be stepping through the possible candidates significantCharacters = pActiveACState->significantCharacters; if (significantCharacters <= 0) { // we were reset, so test all characters in the token significantCharacters = csToken.GetLength(); } tokenCandidateIndex = pActiveACState->tokenCandidateIndex; } _ASSERTE(significantCharacters <= csToken.GetLength()); // step through each of our child nodes and build a list of all case-insensitive matches vector<ParserTreeNode *> matchingNodes; for (unsigned int i=0; i < m_children.size(); i++) { ParserTreeNode *pCandidate = m_children[i]; const CString csNodeTextPrefix = pCandidate->GetNodeText()->Left(significantCharacters); const CString csTokenPrefix = csToken.Left(significantCharacters); if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0) matchingNodes.push_back(pCandidate); // we have a match } // decide which matching node to use ParserTreeNode *pRetVal = nullptr; const int matchingNodeCount = static_cast<int>(matchingNodes.size()); if (matchingNodeCount > 0) { _ASSERTE(tokenCandidateIndex >= 0); _ASSERTE(tokenCandidateIndex < matchingNodeCount); if (pActiveACState == nullptr) // not stepping through multiple tokens? { // must have exactly *one* match or we cannot autocomplete this token pRetVal = ((matchingNodeCount == 1) ? matchingNodes.front() : nullptr); } else // we're stepping through multiple tokens (always on the last token on the line) { pRetVal = matchingNodes[tokenCandidateIndex]; // update our AutocompletionState for next time pActiveACState->significantCharacters = significantCharacters; if (direction) // forward? { if (++pActiveACState->tokenCandidateIndex >= matchingNodeCount) pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning } else // backward { if (--pActiveACState->tokenCandidateIndex < 0) pActiveACState->tokenCandidateIndex = (matchingNodeCount - 1); // wrap around to end } } } return pRetVal; } // Try to autocomplete the supplied token using the supplied list of valid token values. // (This method is similar to 'FindChildForToken' above.) // // acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line) // direction: true = tab direction forward, false = tab direction backward // pValidTokenValues: may be nullptr. Otherwise, points to a nullptr-terminated array of valid token values. // Returns autocompleted token on a match or nullptr if pValidTokenValues is nullptr OR no match found OR if more than one match found. const char *ParserTreeNode::AutocompleteToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction, const char **pValidTokenValues) const { if (pValidTokenValues == nullptr) return nullptr; // no autocompletion possible if (csToken.IsEmpty()) return nullptr; // sanity check // NOTE: do not modify this object's state *except* for the last token on the command line AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type // assume no autocompletionstate int significantCharacters = csToken.GetLength(); int tokenCandidateIndex = 0; if (pActiveACState != nullptr) { // we may be stepping through the possible candidates significantCharacters = pActiveACState->significantCharacters; if (significantCharacters <= 0) { // we were reset, so test all characters in the token significantCharacters = csToken.GetLength(); } tokenCandidateIndex = pActiveACState->tokenCandidateIndex; } _ASSERTE(significantCharacters <= csToken.GetLength()); // step through each of our valid tokens and build a list of all case-insensitive matches vector<const char *> matchingTokens; for (const char **ppValidToken = pValidTokenValues; *ppValidToken != nullptr; ppValidToken++) { CString candidate = *ppValidToken; // valid token (a possible match) const CString csNodeTextPrefix = candidate.Left(significantCharacters); const CString csTokenPrefix = csToken.Left(significantCharacters); if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0) matchingTokens.push_back(*ppValidToken); // we have a match } // decide which matching node to use const char *pRetVal = nullptr; const int matchingTokenCount = static_cast<int>(matchingTokens.size()); if (matchingTokenCount > 0) { _ASSERTE(tokenCandidateIndex >= 0); _ASSERTE(tokenCandidateIndex < matchingTokenCount); if (pActiveACState == nullptr) // not stepping through multiple tokens? { // must have exactly *one* match or we cannot autocomplete this token pRetVal = ((matchingTokenCount == 1) ? matchingTokens.front() : nullptr); } else // we're stepping through multiple tokens (always on the last token on the line) { pRetVal = matchingTokens[tokenCandidateIndex]; // update our AutocompletionState for next time pActiveACState->significantCharacters = significantCharacters; if (direction) // forward? { if (++pActiveACState->tokenCandidateIndex >= matchingTokenCount) pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning } else // backward { if (--pActiveACState->tokenCandidateIndex < 0) pActiveACState->tokenCandidateIndex = (matchingTokenCount - 1); // wrap around to end } } } return pRetVal; } // static utility method that will parse a given command string into space-delimited tokens // argv = contains parse-delmited tokens; NOTE: it is the caller's responsibility to free the CString objects // added to the vector. // Returns: # of valid (i.e., non-empty) tokens parsed; i.e., argv.size() int ParserTreeNode::ParseToSpaceDelimitedTokens(const char *pCommand, vector<CString> &argv) { CString csCommand(pCommand); int tokenIndex = 0; while (tokenIndex >= 0) { CString token = csCommand.Tokenize(" ", tokenIndex); if (!token.IsEmpty()) { argv.push_back(token.Trim()); // whack any other non-printables } } return static_cast<int>(argv.size()); } // // LeafHandler static utility methods // // Parse a validated double from the supplied string. // // Parameters: // pStr = string to be parsed // dblOut = will be set to parsed value, regardless of whether it is in range // min = minimum valid value, inclusive // max = maximum valid value, inclusive // pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails // // Returns: true if value parsed successfully and is in range, false otherwise. bool ParserTreeNode::LeafHandler::ParseValidatedDouble(const char *pStr, double &dblOut, const double min, const double max, CString *pCSErrorMsgOut) { bool parseSuccessful = ParseDouble(pStr, dblOut); bool inRange = ((dblOut >= min) && (dblOut <= max)); if (pCSErrorMsgOut != nullptr) { if (!parseSuccessful) { pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr); } else // parse successful { if (!inRange) { if ((min != numeric_limits<double>::min()) && (max != numeric_limits<double>::max())) { // normal limits defined pCSErrorMsgOut->Format("Value out-of-range (%.4lf); valid range is %.4lf - %.4lf.", dblOut, min, max); } else if (min == numeric_limits<double>::min()) { // upper limit, but no lower limit pCSErrorMsgOut->Format("Value too large (%.4lf); must be <= %.4lf.", dblOut, max); } else // must be max == numeric_limits<double>::max() { // lower limit, but no upper limit pCSErrorMsgOut->Format("Value too small (%.4lf); must be >= %.4lf.", dblOut, min); } } } } return inRange; } // Parse a validated boolean from the supplied string. // // Parameters: // pStr = string to be parsed; for success, must be one of "true", "on", "false", or "off" (case-insensitive) // boolOut = will be set to parsed value, regardless of whether it is valid // pCSErrorMsgOut = if non-null, will be set to error reason if parse fails // // Returns: true if value parsed is valid, false otherwise bool ParserTreeNode::LeafHandler::ParseValidatedBool(const char *pStr, bool &boolOut, CString *pCSErrorMsgOut) { bool success = ParseBool(pStr, boolOut); if ((pCSErrorMsgOut != nullptr) && (!success)) pCSErrorMsgOut->Format("Invalid boolean value (%s); valid options are 'true', 'on', 'false', or 'off' (case-insensitive).", pStr); return success; } // Parse a validated integer from the supplied string. // // Parameters: // pStr = string to be parsed // intOut = will be set to parsed value, regardless of whether it is in range // min = minimum valid value, inclusive // max = maximum valid value, inclusive // pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails // // Returns: true if value parsed successfully and is in range, false otherwise. bool ParserTreeNode::LeafHandler::ParseValidatedInt(const char *pStr, int &intOut, const int min, const int max, CString *pCSErrorMsgOut) { bool parseSuccessful = ParseInt(pStr, intOut); bool inRange = (parseSuccessful && (intOut >= min) && (intOut <= max)); if (pCSErrorMsgOut != nullptr) { if (!parseSuccessful) pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr); else if (!inRange) // value parsed successfully, but is it out-of-range? pCSErrorMsgOut->Format("Value out-of-range (%d); valid range is %d - %d.", intOut, min, max); } return inRange; } // Parse a double from the supplied string; returns true on success, false on error. // On success, dblOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string). bool ParserTreeNode::LeafHandler::ParseDouble(const char *pStr, double &dblOut) { _ASSERTE(pStr != nullptr); // we use sscanf_s instead of atof here because it has error handling return (sscanf_s(pStr, "%lf", &dblOut) == 1); } // Parse a boolean from the supplied string; returns true on success, false on error. // pStr: should be one of "true", "on", "false", or "off" (case-insensitive). // On success, boolOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string). bool ParserTreeNode::LeafHandler::ParseBool(const char *pStr, bool &boolOut) { _ASSERTE(pStr != nullptr); bool success = false; if (!_stricmp(pStr, "true") || !_stricmp(pStr, "on")) { boolOut = success = true; } else if (!_stricmp(pStr, "false") || !_stricmp(pStr, "off")) { boolOut = false; success = true; } // else fall through and return false return success; } // Parse an integer from the supplied string; returns true on success, false on error. // On success, intOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string) bool ParserTreeNode::LeafHandler::ParseInt(const char *pStr, int &intOut) { _ASSERTE(pStr != nullptr); // we use sscanf_s instead of atof here because it has error handling return (sscanf_s(pStr, "%d", &intOut) == 1); } // Recursively build a tree of all command help text appended to csOut. // indent = indent for this line in csOut. void ParserTreeNode::BuildCommandHelpTree(int recursionLevel, CString &csOut) { // build indent string CString csIndent; for (int i=0; i < recursionLevel; i++) csIndent += " "; csOut += csIndent; // indent this line // add our command text const CString *pNodeText = GetNodeText(); if (pNodeText != nullptr) { csOut += *pNodeText; csOut += " "; } // if we're a leaf node, see if we have any help text if (m_pLeafHandler != nullptr) { CString csLeafHelp; m_pLeafHandler->GetArgumentHelp(this, csLeafHelp); csOut += csLeafHelp; // add the leaf node text, too } // terminate this line if (csOut.GetLength() > 0) // prevent extra root node newline and indent { csOut += "\r\n"; recursionLevel++; } // recurse down to all our children for (unsigned i=0; i < m_children.size(); i++) m_children[i]->BuildCommandHelpTree(recursionLevel, csOut); if (m_children.size() > 0) // not a leaf node? csOut += "\r\n"; // add separator line }
42.696169
189
0.643173
919d7d690b95402d371b19dc25e50af043a8fb21
2,188
cpp
C++
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
13
2018-06-12T11:42:19.000Z
2021-12-28T00:57:46.000Z
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
2
2018-05-10T13:32:02.000Z
2018-05-12T18:32:53.000Z
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
7
2020-01-06T07:07:19.000Z
2021-12-06T15:43:00.000Z
#include <memory> #include <sys/time.h> #define GLFW_INCLUDE_GLU #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include "constants.hpp" #include "Scene.hpp" #include "Simulator.hpp" #include "MACGrid.hpp" int main() { if (glfwInit() == GLFW_FALSE) { fprintf(stderr, "Initialization failed!\n"); } if (OFFSCREEN_MODE) { glfwWindowHint(GLFW_VISIBLE, 0); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow *window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, WIN_TITLE, NULL, NULL); if (window == NULL) { fprintf(stderr, "Window creation failed!"); glfwTerminate(); } glfwMakeContextCurrent(window); glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); } // set background color glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glLineWidth(1.2f); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); double time = 0.0; int step = 1; std::shared_ptr<MACGrid> grids = std::make_shared<MACGrid>(); std::unique_ptr<Simulator> simulator = std::make_unique<Simulator>(grids, time); std::unique_ptr<Scene> scene = std::make_unique<Scene>(grids); printf("\n*** SIMULATION START ***\n"); struct timeval s, e; // scene->writeData(); while (glfwWindowShouldClose(window) == GL_FALSE && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { printf("\n=== STEP %d ===\n", step); time += DT; gettimeofday(&s, NULL); simulator->update(); scene->update(); // scene->writeData(); scene->render(); gettimeofday(&e, NULL); printf("time = %lf\n", (e.tv_sec - s.tv_sec) + (e.tv_usec - s.tv_usec) * 1.0E-6); ++step; if (time >= FINISH_TIME) { break; } glfwSwapBuffers(window); glfwPollEvents(); } printf("\n*** SIMULATION END ***\n"); glfwTerminate(); return 0; }
25.149425
106
0.59415
91a7b84e71b83bb1d8f1f43442cbe90a3dafe442
1,143
cpp
C++
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
#include "SDL.h" #include <SDL2/SDL_image.h> #include "graphics.h" #include "globals.h" /* * Graphics class implementation. * Holds all information dealing with game graphics. */ Graphics::Graphics(){ SDL_CreateWindowAndRenderer(globals::SCREEN_WIDTH, globals::SCREEN_HEIGHT, 0, &this->_window, &this->_renderer); SDL_SetWindowTitle(this->_window, "Hong"); } Graphics::~Graphics(){ SDL_DestroyWindow(this->_window); SDL_DestroyRenderer(this->_renderer); } SDL_Surface* Graphics::loadImage( const std::string &filePath ){ if ( this->_spriteSheets.count(filePath) == 0 ){ /* * the file from this path hasn't been loaded yet. */ this->_spriteSheets[filePath] = IMG_Load(filePath.c_str()); } return _spriteSheets[filePath]; } void Graphics::blitSurface( SDL_Texture* texture, SDL_Rect* sourceRectangle, SDL_Rect* destinationRectangle ) { SDL_RenderCopy( this->_renderer, texture, sourceRectangle, destinationRectangle ); } void Graphics::flip(){ SDL_RenderPresent(this->_renderer); } void Graphics::clear(){ SDL_RenderClear(this->_renderer); } SDL_Renderer* Graphics::getRenderer() const { return this->_renderer; }
22.86
113
0.741907
91a8b666f9cf365fc0a1b889422c3d8fac1755d8
3,809
cpp
C++
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CLOUDCOMPARE # //# # //# 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; version 2 or later of the License. # //# # //# 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. # //# # //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) # //# # //########################################################################## #include "ccColorGradientDlg.h" //Local #include "ccQtHelpers.h" //Qt #include <QColorDialog> //system #include <assert.h> //persistent parameters static QColor s_firstColor(Qt::black); static QColor s_secondColor(Qt::white); static ccColorGradientDlg::GradientType s_lastType(ccColorGradientDlg::Default); static double s_lastFreq = 5.0; ccColorGradientDlg::ccColorGradientDlg(QWidget* parent) : QDialog(parent, Qt::Tool) , Ui::ColorGradientDialog() { setupUi(this); connect(firstColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeFirstColor); connect(secondColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeSecondColor); //restore previous parameters ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor); ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor); setType(s_lastType); bandingFreqSpinBox->setValue(s_lastFreq); } unsigned char ccColorGradientDlg::getDimension() const { return static_cast<unsigned char>(directionComboBox->currentIndex()); } void ccColorGradientDlg::setType(ccColorGradientDlg::GradientType type) { switch(type) { case Default: defaultRampRadioButton->setChecked(true); break; case TwoColors: customRampRadioButton->setChecked(true); break; case Banding: bandingRadioButton->setChecked(true); break; default: assert(false); } } ccColorGradientDlg::GradientType ccColorGradientDlg::getType() const { //ugly hack: we use 's_lastType' here as the type is only requested //when the dialog is accepted if (customRampRadioButton->isChecked()) s_lastType = TwoColors; else if (bandingRadioButton->isChecked()) s_lastType = Banding; else s_lastType = Default; return s_lastType; } void ccColorGradientDlg::getColors(QColor& first, QColor& second) const { assert(customRampRadioButton->isChecked()); first = s_firstColor; second = s_secondColor; } double ccColorGradientDlg::getBandingFrequency() const { //ugly hack: we use 's_lastFreq' here as the frequency is only requested //when the dialog is accepted s_lastFreq = bandingFreqSpinBox->value(); return s_lastFreq; } void ccColorGradientDlg::changeFirstColor() { QColor newCol = QColorDialog::getColor(s_firstColor, this); if (newCol.isValid()) { s_firstColor = newCol; ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor); } } void ccColorGradientDlg::changeSecondColor() { QColor newCol = QColorDialog::getColor(s_secondColor, this); if (newCol.isValid()) { s_secondColor = newCol; ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor); } }
31.221311
101
0.631137
91abcc4e5cff1535f9fe5d288498f031d2373a63
4,016
hpp
C++
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_POF_ANNOTATION_SERIALIZER_HPP #define COH_POF_ANNOTATION_SERIALIZER_HPP #include "coherence/lang.ns" #include "coherence/io/pof/PofReader.hpp" #include "coherence/io/pof/PofSerializer.hpp" #include "coherence/io/pof/PofWriter.hpp" COH_OPEN_NAMESPACE3(coherence,io,pof) /** * A PofAnnotationSerializer provides annotation based (de)serialization. * This serializer must be instantiated with the intended class which is * eventually scanned for the presence of the following annotations. * <ul> * <li>coherence::io::pof::annotation::Portable</li> * <li>coherence::io::pof::annotation::PortableProperty</li> * </ul> * * This serializer supports classes iff they are annotated with the type level * annotation; Portable. This annotation is a marker indicating the ability * to (de)serialize using this serializer. * * All methods annotated with PortableProperty are explicitly * deemed POF serializable with the option of specifying overrides to * provide explicit behaviour such as: * <ul> * <li>explicit POF indexes</li> * <li>Custom coherence::io::pof::reflect::Codec to * specify concrete implementations / customizations</li> * </ul> * * The PortableProperty::getIndex() (POF index) can be omitted iff the * auto-indexing feature is enabled. This is enabled by instantiating this * class with the \c fAutoIndex constructor argument. This feature * determines the index based on any explicit indexes specified and the name * of the portable properties. Currently objects with multiple versions is * not supported. The following illustrates the auto index algorithm: * <table border=1> * <tr><td>Name</td><td>Explicit Index</td><td>Determined Index</td></tr> * <tr><td>c</td><td>1</td><td>1</td> * <tr><td>a</td><td></td><td>0</td> * <tr><td>b</td><td></td><td>2</td> * </table> * * <b>NOTE:</b> This implementation does support objects that implement * Evolvable. * * @author hr 2011.06.29 * * @since 3.7.1 * * @see COH_REGISTER_TYPED_CLASS * @see COH_REGISTER_POF_ANNOTATED_CLASS * @see COH_REGISTER_POF_ANNOTATED_CLASS_AI * @see Portable */ class COH_EXPORT PofAnnotationSerializer : public class_spec<PofAnnotationSerializer, extends<Object>, implements<PofSerializer> > { friend class factory<PofAnnotationSerializer>; // ----- constructors --------------------------------------------------- protected: /** * Constructs a PofAnnotationSerializer. * * @param nTypeId the POF type id * @param vClz type this serializer is aware of * @param fAutoIndex turns on the auto index feature, default = false */ PofAnnotationSerializer(int32_t nTypeId, Class::View vClz, bool fAutoIndex = false); // ----- PofSerializer interface ---------------------------------------- public: /** * {@inheritDoc} */ virtual void serialize(PofWriter::Handle hOut, Object::View v) const; /** * {@inheritDoc} */ virtual Object::Holder deserialize(PofReader::Handle hIn) const; // ---- helpers --------------------------------------------------------- protected: /** * Initialize this class based on the provided information. * * @param nTypeId the POF type id * @param vClz type this serializer is aware of * @param fAutoIndex turns on the auto index feature */ virtual void initialize(int32_t nTypeId, Class::View vClz, bool fAutoIndex); // ---- data members ---------------------------------------------------- private: /** * A structural definition of the type information. */ FinalHandle<Object> f_ohTypeMetadata; }; COH_CLOSE_NAMESPACE3 #endif // COH_POF_ANNOTATION_SERIALIZER_HPP
33.190083
92
0.648904
91ac79154451b0bc07a8f99de2afe9a24afbf899
687
cpp
C++
GrandpaGetsHisGroove/Source/GrandpaGetsHisGroove/GrandpaGetsHisGrooveGameMode.cpp
Broar/sa-gamedev-2016
dae257f8f90c5950fae98cd66bde5af17da4b84a
[ "MIT" ]
null
null
null
GrandpaGetsHisGroove/Source/GrandpaGetsHisGroove/GrandpaGetsHisGrooveGameMode.cpp
Broar/sa-gamedev-2016
dae257f8f90c5950fae98cd66bde5af17da4b84a
[ "MIT" ]
null
null
null
GrandpaGetsHisGroove/Source/GrandpaGetsHisGroove/GrandpaGetsHisGrooveGameMode.cpp
Broar/sa-gamedev-2016
dae257f8f90c5950fae98cd66bde5af17da4b84a
[ "MIT" ]
null
null
null
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "GrandpaGetsHisGroove.h" #include "GrandpaGetsHisGrooveGameMode.h" #include "GrandpaGetsHisGroovePlayerController.h" #include "GrandpaGetsHisGrooveCharacter.h" AGrandpaGetsHisGrooveGameMode::AGrandpaGetsHisGrooveGameMode() { // use our custom PlayerController class PlayerControllerClass = AGrandpaGetsHisGroovePlayerController::StaticClass(); // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/TopDownCPP/Blueprints/TopDownCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } }
36.157895
120
0.819505
91adf96fa00a4e220217519094393215a1cf1770
4,088
hpp
C++
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
1
2021-11-25T01:11:34.000Z
2021-11-25T01:11:34.000Z
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
null
null
null
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
null
null
null
// // Canvas.hpp // the-manipulator // // Created by Sidharth Mishra on 2/18/18. // #ifndef Canvas_hpp #define Canvas_hpp #include <memory> #include <map> #include "Picture.hpp" #include "Tmnper.hpp" namespace Manipulator { /** * The canvas where the pictures are drawn. */ using namespace std; class Canvas { /** * All the pictures added to the canvas. * I feel that having a map with Z-Index makes it easier for me to implement * the selected image movement thingy! */ std::map<int,std::shared_ptr<Manipulator::Picture>> pictures; // // denotes the z-depth? // int currentDepth; // // pointer to the foreground picture. // std::shared_ptr<Manipulator::Picture> foregroundPic; // // the depth of the selected picture // int selectionDepth; public: /** * Initializes the canvas with initial properties. */ Canvas(); /** * Adds the picture at the filePath to the canvas, if not added returns false. */ bool addPicture(std::string filePath, float tx, float ty); // // The selection render pass using the color selection method // void beginSelectionRenderPass(); void endSelectionRenderPass(); /** * Renders the canvas, drawing the pictures, one at a time in the order they were added to it. */ void render(); /** * Saves the canvas composition to disk with the provided fileName. */ bool saveCompositionToDisk(std::string fileName); /** * Manipulates the Picture depending on the mode of its manipulator: * - Scales/resizes the current - selected picture or the picture on the foreground. * - 2D translation of the foregroundPic. Does nothing if there is no foregroundPic or no selected pic. * - Computes the rotation by taking into account the delta w.r.t. the center of the * border of the selected picture. */ void manipulatePicture(const ofVec2f &src, const ofVec2f &dest); /** * Selects the picture on the foreground. */ void selectForegroundPicture(); /** * De-Selects the picture on the foreground. */ void deselectForegroundPicture(); /** * Selects the picture at the specified (x,y) co-ordinate if possible. */ void selectPictureAt(int x, int y); /** * Moves the selected image up in the z. (-ve) */ void cyclePicturesUp(); /** * Moves the selected image down in the z. (+ve) */ void cyclePicturesDown(); /** * Deletes the selected picture from the canvas. */ void deletePicture(); // Processing for constrained TRS of selected image // s -- scale // x -- x translate // y -- y translate // r -- rotate void processConstrained(char flag, bool isPositive); /* ------------------------------------------------------------ */ /** * Saves the canvas state to disk with the provided fileName. */ bool saveStateToDisk(std::string fileName); /** * Loads the canvas state from the disk. */ void loadStateFromDisk(std::string fileName); /** * Serializes the contents of the Canvas into a string to be saved onto disk. */ string toString(); /** * De-serializes the contents of the string restoring the canvas. */ void fromString(string contents); /* ------------------------------------------------------------ */ }; } #endif /* Canvas_hpp */
28
111
0.518836
91b5701c29df069d7c47d5e8cdbb85b3183b0582
1,255
cpp
C++
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
// Dinic - O(n^2 * m) // Max flow const int N = 1e5 + 5; const int INF = 0x3f3f3f3f; struct edge { int v, c, f; }; int n, s, t, h[N], st[N]; vector<edge> edgs; vector<int> g[N]; // directed from u to v with cap(u, v) = c void add_edge(int u, int v, int c) { int k = edgs.size(); edgs.push_back({v, c, 0}); edgs.push_back({u, 0, 0}); g[u].push_back(k); g[v].push_back(k+1); } int bfs() { memset(h, 0, sizeof h); h[s] = 1; queue<int> q; q.push(s); while(q.size()) { int u = q.front(); q.pop(); for(auto i : g[u]) { int v = edgs[i].v; if(!h[v] and edgs[i].f < edgs[i].c) h[v] = h[u] + 1, q.push(v); } } return h[t]; } int dfs(int u, int flow) { if(!flow or u == t) return flow; for(int &i = st[u]; i < g[u].size(); i++) { edge &dir = edgs[g[u][i]], &rev = edgs[g[u][i]^1]; int v = dir.v; if(h[v] != h[u] + 1) continue; int inc = min(flow, dir.c - dir.f); inc = dfs(v, inc); if(inc) { dir.f += inc, rev.f -= inc; return inc; } } return 0; } int dinic() { int flow = 0; while(bfs()) { memset(st, 0, sizeof st); while(int inc = dfs(s, INF)) flow += inc; } return flow; }
19.920635
55
0.467729
91b78f33891c2e2ba7f7dc198195baf90da2033d
4,582
cpp
C++
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
8
2016-09-10T05:45:59.000Z
2019-04-06T13:27:18.000Z
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
1
2017-11-18T19:49:37.000Z
2018-05-05T09:49:27.000Z
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
1
2015-12-06T20:51:10.000Z
2015-12-06T20:51:10.000Z
#include "gtest/gtest.h" #include "yunomi/array/fixedlengtharray.hpp" TEST(TestFixedLengthArray, test_init){ yunomi::array::FixedLengthArray array(10, 1); EXPECT_EQ(10, array.size()); EXPECT_EQ(1, array.bits_per_slot()); } TEST(TestFixedLengthArray, test_ten_values){ yunomi::array::FixedLengthArray array(10, 4); EXPECT_EQ(10, array.size()); EXPECT_EQ(4, array.bits_per_slot()); for(std::size_t i = 0; i < 10; ++i){ array[i] = i; EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 0; i < 10; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values){ yunomi::array::FixedLengthArray array(1000, 10); EXPECT_EQ(1000, array.size()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_resize){ yunomi::array::FixedLengthArray array(1000, 10); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } array.resize(1500, 10); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_resize2){ yunomi::array::FixedLengthArray array(1000, 10); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } array.resize(1500, 11); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template){ yunomi::array::ConstLengthArray<10> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(10, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_8bit){ yunomi::array::ConstLengthArray<8> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(8, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i % 256; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i % 256, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i % 256, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_16bit){ yunomi::array::ConstLengthArray<16> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(16, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_32bit){ yunomi::array::ConstLengthArray<32> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(32, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_64bit){ yunomi::array::ConstLengthArray<64> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(64, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } //TODO write tests //TODO write tests for the size==0
29
64
0.576168
91b9c11ee85bd7fb70b44e8e5b0058dd47d0d269
7,635
hpp
C++
kernel/bb/Brick11/src/pilot.hpp
Bhaskers-Blu-Org2/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
270
2015-07-17T15:43:43.000Z
2019-04-21T12:13:58.000Z
kernel/bb/Brick11/src/pilot.hpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
null
null
null
kernel/bb/Brick11/src/pilot.hpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
106
2015-07-20T10:40:34.000Z
2019-04-25T10:02:26.000Z
#pragma once #include "ieee80211a_cmn.h" #include "ieee80211facade.hpp" #include <intalg.h> // // Pilot sequence as defined in 802.11a // const char PilotSgn[128] = { 0, 0, 0, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, -1, 0, 0, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, -1, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0, -1, 0, 0, -1, 0, -1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, // # 127: reserved for PLCP signal }; DEFINE_LOCAL_CONTEXT(T11aAddPilot, CF_VOID); template<short BPSK_MOD = 10720> class T11aAddPilot { public: template<TFILTER_ARGS> class Filter : public TFilter<TFILTER_PARAMS> { private: uchar m_PilotIndex; void _init () { m_PilotIndex = 127; } public: DEFINE_IPORT(COMPLEX16, 48); DEFINE_OPORT(COMPLEX16, 64); public: REFERENCE_LOCAL_CONTEXT(Filter); STD_TFILTER_CONSTRUCTOR(Filter) { // The output symbols contain data subcarrriers, pilot subcarriers, and zero subcarriers. // Here we prepare the output pin queue with zero buffer, to make symbol composition easier. opin().zerobuf(); _init (); } STD_TFILTER_RESET() { _init (); } STD_TFILTER_FLUSH() { } BOOL_FUNC_PROCESS(ipin) { while (ipin.check_read()) { const COMPLEX16 *in = ipin.peek(); COMPLEX16 *out = opin().append(); add_pilot (out, in); m_PilotIndex++; if (m_PilotIndex >= 127) m_PilotIndex = 0; ipin.pop(); Next()->Process(opin()); } return true; } FINL void add_pilot (COMPLEX16* out, const COMPLEX16* in ) { ulong i; for (i = 64 - 26; i < 64; i++) { if (i == 64 - 7 || i == 64 - 21) continue; out[i] = *in; in ++; } for (i = 1; i <= 26; i++) { if (i == 7 || i == 21) continue; out[i] = *in; in ++; } if (!PilotSgn[m_PilotIndex]) { out[7].re = BPSK_MOD; out[7].im = 0; out[21].re = -BPSK_MOD; out[21].im = 0; out[64-7].re = BPSK_MOD; out[64-7].im = 0; out[64-21].re = BPSK_MOD; out[64-21].im = 0; } else { out[7].re = - BPSK_MOD; out[7].im = 0; out[21].re = BPSK_MOD; out[21].im = 0; out[64-7].re = - BPSK_MOD; out[64-7].im = 0; out[64-21].re = - BPSK_MOD; out[64-21].im = 0; } //printf ( "add pilot\n" ); //for ( int i=0; i< 16; i++ ) { // for (int j=0; j<4; j++ ) { // printf ( "<%d, %d> ", out[i*4+j].re, out[i*4+j].im ); // } // printf ( "\n" ); //} } }; }; // pilot freq compensation on 64 complexes DEFINE_LOCAL_CONTEXT(TPilotTrack, CF_PhaseCompensate, CF_PilotTrack, CF_11aRxVector); template<TFILTER_ARGS> class TPilotTrack : public TFilter<TFILTER_PARAMS> { private: CTX_VAR_RW (FP_RAD, CFO_tracker); CTX_VAR_RW (FP_RAD, SFO_tracker); CTX_VAR_RW (FP_RAD, CFO_comp ); CTX_VAR_RW (FP_RAD, SFO_comp ); CTX_VAR_RW (vcs, CompCoeffs, [16] ); CTX_VAR_RW (ulong, symbol_count); protected: FINL void _rotate ( vcs * dst, vcs * src, vcs * coeffs ) { rep_mul<7> (dst, src, coeffs ); rep_mul<7> (dst+9, src+9, coeffs+9 ); } FINL void _build_coeff ( COMPLEX16* pcoeffs, FP_RAD ave, FP_RAD delta ) { FP_RAD th = ave - delta * 26; int i; for (i = 64-26; i < 64; i++) { pcoeffs[i].re = ucos(th); pcoeffs[i].im = -usin(th); th += delta; } th += delta; // 0 subcarrier, dc // subcarrier 1 - 26 for (i = 1; i <= 26; i++) { pcoeffs[i].re = ucos(th); pcoeffs[i].im = -usin(th); th += delta; } } FINL void _pilot_track ( vcs * input, vcs * output ) { COMPLEX16* pc = (COMPLEX16*) input; // FP_RAD th1 = uatan2 ( pc[64-21].im, pc[64-21].re ); FP_RAD th2 = uatan2 ( pc[64-7].im, pc[64-7].re ); FP_RAD th3 = uatan2 ( pc[7].im, pc[7].re ); FP_RAD th4 = uatan2 ( -pc[21].im, -pc[21].re ); if (PilotSgn[symbol_count]) { th1 += FP_PI; th2 += FP_PI; th3 += FP_PI; th4 += FP_PI; } symbol_count++; if (symbol_count >= 127) symbol_count = 0; _dump_text ( "Pilots: <%d,%d> %d <%d,%d> %d <%d,%d> %d <%d,%d> %d \n\n", pc[64-21].re, pc[64-21].im, th1, pc[64-7].re, pc[64-7].im, th2, pc[7].re, pc[7].im, th3, pc[21].re, pc[21].im, th4 ); // subcarrier rotation = const_rotate + i * delta_rotate // estimate the const part FP_RAD avgTheta = (th1 + th2 + th3 + th4) / 4; // estimate the delta part FP_RAD delTheta = ((th3 - th1) / (21 + 7) + (th4 - th2) / (21 + 7)) >> 1; // pilot rotate vcs rotate_coeffs[16]; _build_coeff ( (COMPLEX16*) rotate_coeffs, avgTheta, delTheta ); _rotate ( output, input, rotate_coeffs ); // debug _dump_symbol<64>( "after pilot", (COMPLEX16*) output); // update tracker CFO_tracker += avgTheta >> 2; SFO_tracker += delTheta >> 2; CFO_comp += avgTheta + (CFO_tracker ); SFO_comp += delTheta + (SFO_tracker ); // Debug _dump_text ( "Tracker:: avg %lf del %lf CFO %lf SFO %lf\nFreqComp:: CFO %lf SFO %lf\n", fprad2rad (avgTheta), fprad2rad (delTheta), fprad2rad (CFO_tracker), fprad2rad (SFO_tracker), fprad2rad (CFO_comp), fprad2rad (SFO_comp) ); _build_coeff ( (COMPLEX16*) CompCoeffs, CFO_comp, SFO_comp ); } public: DEFINE_IPORT(COMPLEX16, 64); DEFINE_OPORT(COMPLEX16, 64); public: REFERENCE_LOCAL_CONTEXT(TPilotTrack); STD_TFILTER_CONSTRUCTOR(TPilotTrack) BIND_CONTEXT (CF_PilotTrack::CFO_tracker, CFO_tracker) BIND_CONTEXT (CF_PilotTrack::SFO_tracker, SFO_tracker) BIND_CONTEXT (CF_PilotTrack::symbol_count, symbol_count) BIND_CONTEXT (CF_PhaseCompensate::CFO_comp, CFO_comp) BIND_CONTEXT (CF_PhaseCompensate::SFO_comp, SFO_comp) BIND_CONTEXT (CF_PhaseCompensate::CompCoeffs, CompCoeffs) { } STD_TFILTER_RESET() { } BOOL_FUNC_PROCESS(ipin) { while (ipin.check_read()) { vcs *input = (vcs*)ipin.peek(); vcs *output = (vcs*)opin().append(); // _dump_symbol<64>("before pilot\n", (COMPLEX16*) input); _pilot_track ( input, output ); ipin.pop(); bool rc = Next()->Process(opin()); if (!rc) return false; } return true; } };
28.173432
101
0.472692
91ba70ddc6aa008b545aa52db848a7b88fafef6e
1,238
cpp
C++
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
// $Id$ // Copyright (c) 2009 Oliver Lau <oliver@ersatzworld.net> #include "stdafx.h" VOID Warn(LPTSTR lpszMessage) { MessageBox(NULL, (LPCTSTR)lpszMessage, TEXT("Fehler"), MB_OK); } VOID Error(LPTSTR lpszFunction, LONG lErrCode) { LPVOID lpMsgBuf; LPVOID lpDisplayBuf; if (lErrCode == 0) lErrCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s fehlgeschlagen mit Fehler %d: %s"), lpszFunction, lErrCode, lpMsgBuf); MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Fehler"), MB_OK); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); } VOID ErrorExit(LPTSTR lpszFunction, LONG lErrCode) { Error(lpszFunction, lErrCode); ExitProcess(lErrCode); }
27.511111
93
0.64378
91bbe1f1e423082754525c7a24e8c6c981b1580a
498
cpp
C++
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
5
2022-02-08T09:36:54.000Z
2022-02-10T08:47:17.000Z
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
null
null
null
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
3
2021-12-10T16:11:46.000Z
2022-02-15T15:07:41.000Z
#include "Fenetre.h" #include "Souris.h" int main (int argc, char **argv){ gtk_init(&argc, &argv); Fenetre f; Souris s; int b, x, y; f.apparait("Test TP1",500,400,0,0,100,100,100); s.associerA(f); f.choixCouleurTrace(255,100,100); f.ecrit(10,100,"Bravo, vous avez bien parametre votre environnement !!"); f.choixCouleurTrace(0,0,0); f.ecrit(100,240,"CLIQUER POUR QUITTER"); while (!s.testeBoutons(x, y, b)); f.disparait(); return 0; }
17.172414
77
0.608434
91bf84920e2f84cee2312fae1434faf045fc4cc4
622
cpp
C++
source/globjects/source/AttachedRenderbuffer.cpp
kateyy/globjects
4c5fc073063ca52ea32ce0adb57009a3c52f72a8
[ "MIT" ]
18
2016-09-03T05:12:25.000Z
2022-02-23T15:52:33.000Z
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
1
2016-05-04T09:06:29.000Z
2016-05-04T09:06:29.000Z
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
7
2016-04-20T13:58:50.000Z
2018-07-09T15:47:26.000Z
#include <globjects/AttachedRenderbuffer.h> #include <cassert> #include <globjects/Renderbuffer.h> using namespace gl; namespace globjects { AttachedRenderbuffer::AttachedRenderbuffer(Framebuffer * fbo, const GLenum attachment, Renderbuffer * renderBuffer) : FramebufferAttachment(fbo, attachment) , m_renderBuffer(renderBuffer) { } bool AttachedRenderbuffer::isRenderBufferAttachment() const { return true; } Renderbuffer * AttachedRenderbuffer::renderBuffer() { return m_renderBuffer; } const Renderbuffer * AttachedRenderbuffer::renderBuffer() const { return m_renderBuffer; } } // namespace globjects
17.771429
116
0.790997
91bfc642eda962ce91587806eaa7a91d8024a553
4,510
cpp
C++
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 09:33 on 5 Mar 2017 #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <complex> #include <deque> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <utility> #include <bitset> #include <numeric> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_V = 1e5 + 10; const int MAX_LOG_V = 20; int V, A[MAX_V], Q; vector<int> G[MAX_V]; int parent[MAX_LOG_V][MAX_V], depth[MAX_V]; int dp_max[MAX_LOG_V][MAX_V], dp_min[MAX_LOG_V][MAX_V]; int dp_up[MAX_LOG_V][MAX_V], dp_down[MAX_LOG_V][MAX_V]; void dfs(int v, int p, int d) { parent[0][v] = p; depth[v] = d; if (p != -1) { dp_max[0][v] = max(A[v], A[p]); dp_min[0][v] = min(A[v], A[p]); dp_up[0][v] = max(0, A[p] - A[v]); dp_down[0][v] = max(0, A[v] - A[p]); } for (int i = 0; i < G[v].size(); i++) if (G[v][i] != p) dfs(G[v][i], v, d + 1); } void init(int V) { memset(dp_max, 0, sizeof dp_max); memset(dp_min, 0x3f, sizeof dp_min); dfs(0, -1, 0); for (int k = 0; k + 1 < MAX_LOG_V; k++) for (int v = 0; v < V; v++) if (parent[k][v] < 0) parent[k + 1][v] = -1; else { int u = parent[k][v]; parent[k + 1][v] = parent[k][u]; dp_max[k + 1][v] = max(dp_max[k][v], dp_max[k][u]); dp_min[k + 1][v] = min(dp_min[k][v], dp_min[k][u]); dp_up[k + 1][v] = max(max(dp_up[k][v], dp_up[k][u]), dp_max[k][u] - dp_min[k][v]); dp_down[k + 1][v]= max(max(dp_down[k][v], dp_down[k][u]), dp_max[k][v] - dp_min[k][u]); } } int lca(int u, int v) { if (depth[u] > depth[v]) swap(u, v); for (int k = 0; k < MAX_LOG_V; k++) if ((depth[v] - depth[u]) >> k & 1) v = parent[k][v]; if (u == v) return u; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (parent[k][v] != parent[k][u]) { v = parent[k][v]; u = parent[k][u]; } return parent[0][u]; } int up(int v, int s, int &imin) { imin = INF; int res = 0, pre_min = INF; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (s >> k & 1) { imin = min(imin, dp_min[k][v]); res = max(res, dp_up[k][v]); res = max(res, dp_max[k][v] - pre_min); pre_min = min(pre_min, dp_min[k][v]); v = parent[k][v]; } return res; } int down(int v, int s, int &imax) { imax = 0; int res = 0, pre_max = 0; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (s >> k & 1) { imax = max(imax, dp_max[k][v]); res = max(res, dp_down[k][v]); res = max(res, pre_max - dp_min[k][v]); pre_max = max(pre_max, dp_max[k][v]); v = parent[k][v]; } return res; } int main(int argc, char const *argv[]) { scanf("%d", &V); for (int i = 0; i < V; i++) scanf("%d", A + i); for (int i = 0, u, v; i < V - 1; i++) { scanf("%d%d", &u, &v); --u, --v; G[u].push_back(v); G[v].push_back(u); } init(V); scanf("%d", &Q); for (int i = 0, u, v; i < Q; i++) { scanf("%d%d", &u, &v); --u, --v; int p = lca(u, v); // cout << p << " " << u << "<->" << v << endl; int imax, imin; int iup = up(u, depth[u] - depth[p], imin); int idown = down(v, depth[v] - depth[p], imax); // cout << imin << " " << imax << endl; printf("%d\n", max(max(iup, idown), imax - imin)); } return 0; }
29.096774
118
0.497339
91c2b85dd910620172b6fd358a4f88b066339835
1,042
cpp
C++
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
1
2021-09-21T23:24:37.000Z
2021-09-21T23:24:37.000Z
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
null
null
null
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
null
null
null
#include <algorithm> #include <catch2/catch.hpp> #include <vector> std::vector<int> calc_ans(const std::vector<int> &seq, int l); TEST_CASE("D. Лавочки в атриуме", " ") { REQUIRE(calc_ans({ 0, 2 }, 5) == std::vector<int>{ 2 }); REQUIRE(calc_ans({ 1, 4, 8, 11 }, 13) == std::vector<int>{ 4, 8 }); REQUIRE(calc_ans({ 1, 6, 8, 11, 12, 13 }, 14) == std::vector<int>{ 6, 8 }); REQUIRE(calc_ans({ 0 }, 1) == std::vector<int>{ 0 }); } bool isOdd(long long n) { if (n % 2 == 1) { return true; } return false; } std::vector<int> calc_ans(const std::vector<int> &seq, int l) { int border = 0; std::vector<int> ans; if (seq.size() == 1) { ans.push_back(seq[0]); } else { border = l / 2; auto it = std::lower_bound(seq.begin(), seq.end(), border); if (isOdd(l)) { if (*(it) == border) { ans.push_back(*it); } else { ans.push_back(*(it - 1)); ans.push_back(*(it)); } } else { ans.push_back(*(it - 1)); ans.push_back(*(it)); } } return ans; }
22.170213
77
0.53167
91c4a0ead6e52ce6c394ce7b7155be6042fb6f51
1,684
cpp
C++
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
// (c) 2021 Jens Ganter-Benzing. Licensed under the MIT license. #include <iostream> #include <colmc/setup.h> #include <colmc/sequences.h> using namespace colmc; struct color { const char* esc_sequence; const char* name; }; const struct color bg_colors[] = { { back::black, "black " }, { back::red, "red " }, { back::green, "green " }, { back::yellow, "yellow " }, { back::blue, "blue " }, { back::magenta, "magenta" }, { back::cyan, "cyan " }, { back::white, "white " } }; const struct color fg_colors[] = { { fore::black, "black " }, { fore::red, "red " }, { fore::green, "green " }, { fore::yellow, "yellow " }, { fore::blue, "blue " }, { fore::magenta, "magenta" }, { fore::cyan, "cyan " }, { fore::white, "white " } }; int main() { setup(); std::cout << " "; for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) { std::cout << fg_colors[fg_index].esc_sequence << fg_colors[fg_index].name; } std::cout << std::endl; for (std::size_t bg_index = 0; bg_index < (sizeof(bg_colors)/sizeof(bg_colors[0])); ++bg_index) { std::cout << bg_colors[bg_index].esc_sequence << fore::reset << bg_colors[bg_index].name; for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) { std::cout << back::reset << " "; std::cout << bg_colors[bg_index].esc_sequence; std::cout << fg_colors[fg_index].esc_sequence << fore::dim << "X " << fore::normal << "X " << fore::bright << "X " << reset_all; } std::cout << std::endl; } std::cout << reset_all << "Press return to terminate"; std::cin.get(); return 0; }
30.071429
132
0.589074
91c6879681bb3ad66670d6360cc3f0a4fac38d31
2,807
cp
C++
Comm/Mod/Streams.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Comm/Mod/Streams.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Comm/Mod/Streams.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE CommStreams; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) IMPORT Meta; CONST (* portable error codes: *) done* = 0; noSuchProtocol* = 1; invalidLocalAdr* = 2; invalidRemoteAdr* = 3; networkDown* = 4; localAdrInUse* = 5; remoteAdrInUse* = 6; TYPE Adr* = POINTER TO ARRAY OF CHAR; Stream* = POINTER TO ABSTRACT RECORD END; StreamAllocator* = PROCEDURE (localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER); Listener* = POINTER TO ABSTRACT RECORD END; ListenerAllocator* = PROCEDURE (localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER); PROCEDURE (s: Stream) RemoteAdr* (): Adr, NEW, ABSTRACT; PROCEDURE (s: Stream) IsConnected* (): BOOLEAN, NEW, ABSTRACT; PROCEDURE (s: Stream) WriteBytes* ( IN x: ARRAY OF BYTE; beg, len: INTEGER; OUT written: INTEGER), NEW, ABSTRACT; PROCEDURE (s: Stream) ReadBytes* ( VAR x: ARRAY OF BYTE; beg, len: INTEGER; OUT read: INTEGER), NEW, ABSTRACT; PROCEDURE (s: Stream) Close*, NEW, ABSTRACT; PROCEDURE NewStream* (protocol, localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER); VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name; v: RECORD (Meta.Value) p: StreamAllocator END; BEGIN ASSERT(protocol # "", 20); res := noSuchProtocol; mod := protocol$; Meta.Lookup(mod, m); IF m.obj = Meta.modObj THEN m.Lookup("NewStream", p); IF p.obj = Meta.procObj THEN p.GetVal(v, ok); IF ok THEN v.p(localAdr, remoteAdr, s, res) END END END END NewStream; PROCEDURE (l: Listener) LocalAdr* (): Adr, NEW, ABSTRACT; PROCEDURE (l: Listener) Accept* (OUT s: Stream), NEW, ABSTRACT; PROCEDURE (l: Listener) Close*, NEW, ABSTRACT; PROCEDURE NewListener* (protocol, localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER); VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name; v: RECORD(Meta.Value) p: ListenerAllocator END; BEGIN ASSERT(protocol # "", 20); res := noSuchProtocol; mod := protocol$; Meta.Lookup(mod, m); IF m.obj = Meta.modObj THEN m.Lookup("NewListener", p); IF p.obj = Meta.procObj THEN p.GetVal(v, ok); IF ok THEN v.p(localAdr, l, res) END END END END NewListener; END CommStreams.
32.639535
105
0.56466
91ca06b4ec287cce73acf4d73eb84dcf5e090adb
587
hxx
C++
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Elastic/Apm/Util/String.hxx" #include "Elastic/Apm/Util/Optional.hxx" namespace Elastic { namespace Apm { namespace Config { using namespace Elastic::Apm; class IRawSnapshot { protected: using String = Util::String; template< typename T > using Optional = Util::Optional< T >; public: struct ValueData { String value; String dbgValueSourceDesc; }; virtual Optional< ValueData > operator[]( const char* optName ) const = 0; protected: ~IRawSnapshot() = default; }; } } } // namespace Elastic::Apm::Config
16.305556
78
0.667802
91cad30ec6590d8dda7374c959f0048d19154093
467
cpp
C++
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
19
2019-12-10T07:35:08.000Z
2021-09-27T11:49:37.000Z
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
22
2020-02-09T15:39:53.000Z
2020-03-02T19:04:40.000Z
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
2
2020-02-17T21:20:43.000Z
2020-03-02T00:42:08.000Z
/// (c) Ben Jones 2019 #include "IdentifierReceiverEvaluator.hpp" #include "parser/LanguageException.hpp" #include <utility> namespace arrow { IdentifierReceiverEvaluator::IdentifierReceiverEvaluator(Token tok) : m_tok(std::move(tok)) { } void IdentifierReceiverEvaluator::evaluate(Type incoming, Environment & environment) const { // automatically does a replace environment.add(m_tok.raw, std::move(incoming)); } }
24.578947
94
0.702355
91ce8c90b43c369c3352048a25ece820de97be26
814
cpp
C++
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "PythonSchedulePipe.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// PythonSchedulePipe::PythonSchedulePipe() { } ////////////////////////////////////////////////////////////////////////// PythonSchedulePipe::~PythonSchedulePipe() { } ////////////////////////////////////////////////////////////////////////// void PythonSchedulePipe::initialize( const pybind::object & _cb, const pybind::args & _args ) { m_cb = _cb; m_args = _args; } ////////////////////////////////////////////////////////////////////////// float PythonSchedulePipe::onSchedulerPipe( uint32_t _id, uint32_t _index ) { float delay = m_cb.call_args( _id, _index, m_args ); return delay; } }
31.307692
97
0.388206
91d1246dbb9d80b62a7368a32a0b933ea8a5ccea
5,318
cpp
C++
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
2
2021-10-03T08:57:00.000Z
2021-10-03T12:28:52.000Z
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
null
null
null
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
2
2021-09-13T11:15:25.000Z
2021-10-03T08:57:11.000Z
/* * Copyright (c) 2021 Huawei Device 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 "slide_window_processor.h" #include <memory> #include "aie_log.h" #include "aie_macros.h" #include "aie_retcode_inner.h" #include "securec.h" using namespace OHOS::AI::Feature; namespace { const uint8_t ILLEGAL_BUFFER_MULTIPLIER = 0; } SlideWindowProcessor::SlideWindowProcessor() : isInitialized_(false), workBuffer_(nullptr), inputFeature_(nullptr), inType_(UNKNOWN), typeSize_(0), startIndex_(0), initIndex_(0), bufferSize_(0), windowSize_(0), stepSize_(0) {} SlideWindowProcessor::~SlideWindowProcessor() { Release(); } int32_t SlideWindowProcessor::Init(const FeatureProcessorConfig *config) { if (isInitialized_) { HILOGE("[SlideWindowProcessor]Fail to init more than once. Release it, then try again"); return RETCODE_FAILURE; } if (config == nullptr) { HILOGE("[SlideWindowProcessor]Fail to init with null config"); return RETCODE_FAILURE; } auto localConfig = *(static_cast<const SlideWindowProcessorConfig *>(config)); if (localConfig.dataType == UNKNOWN) { HILOGE("[SlideWindowProcessor]Fail with unsupported dataType[UNKNOWN]"); return RETCODE_FAILURE; } if (localConfig.windowSize < localConfig.stepSize) { HILOGE("[SlideWindowProcessor]Illegal configuration. The stepSize cannot be greater than windowSize"); return RETCODE_FAILURE; } if (localConfig.bufferMultiplier == ILLEGAL_BUFFER_MULTIPLIER) { HILOGE("[SlideWindowProcessor]Illegal configuration. The bufferMultiplier cannot be zero"); return RETCODE_FAILURE; } inType_ = localConfig.dataType; typeSize_ = CONVERT_DATATYPE_TO_SIZE(inType_); windowSize_ = localConfig.windowSize; stepSize_ = localConfig.stepSize * typeSize_; initIndex_ = (windowSize_ * typeSize_) - stepSize_; startIndex_ = initIndex_; bufferSize_ = (windowSize_ * localConfig.bufferMultiplier) * typeSize_; if (windowSize_ > MAX_SAMPLE_SIZE) { HILOGE("[SlideWindowProcessor]The required memory size is larger than MAX_SAMPLE_SIZE[%zu]", MAX_SAMPLE_SIZE); return RETCODE_FAILURE; } AIE_NEW(workBuffer_, char[bufferSize_]); if (workBuffer_ == nullptr) { HILOGE("[SlideWindowProcessor]Fail to allocate memory for workBuffer"); return RETCODE_FAILURE; } (void)memset_s(workBuffer_, bufferSize_, 0, bufferSize_); inputFeature_ = workBuffer_; isInitialized_ = true; return RETCODE_SUCCESS; } void SlideWindowProcessor::Release() { AIE_DELETE_ARRAY(workBuffer_); inputFeature_ = nullptr; isInitialized_ = false; } int32_t SlideWindowProcessor::Process(const FeatureData &input, FeatureData &output) { if (!isInitialized_) { HILOGE("[SlideWindowProcessor]Fail to process without successfully init"); return RETCODE_FAILURE; } if (input.dataType != inType_) { HILOGE("[SlideWindowProcessor]Fail with unmatched input dataType"); return RETCODE_FAILURE; } if (input.data == nullptr || input.size == 0) { HILOGE("[SlideWindowProcessor]Fail with NULL input"); return RETCODE_FAILURE; } size_t inputBytes = input.size * typeSize_; if (inputBytes != stepSize_) { HILOGE("[SlideWindowProcessor]Fail with unmatched input dataSize, expected [%zu]", stepSize_ / typeSize_); return RETCODE_FAILURE; } if (output.data != nullptr || output.size != 0) { HILOGE("[SlideWindowProcessor]Fail with non-empty output"); return RETCODE_FAILURE; } output.dataType = inType_; // Update the last window by the input data of new window errno_t retCode = memcpy_s(workBuffer_ + startIndex_, bufferSize_ - startIndex_, input.data, inputBytes); if (retCode != EOK) { HILOGE("[SlideWindowProcessor]Fail to copy input data to workBuffer [%d]", retCode); return RETCODE_FAILURE; } output.data = inputFeature_; output.size = windowSize_; startIndex_ += stepSize_; // Slide to the next position inputFeature_ += stepSize_; // Post-processing if (bufferSize_ - startIndex_ < stepSize_) { errno_t retCode = memmove_s(workBuffer_, bufferSize_, inputFeature_, initIndex_); if (retCode != EOK) { HILOGE("[SlideWindowProcessor]Fail with memory move. Error code[%d]", retCode); return RETCODE_FAILURE; } startIndex_ = initIndex_; inputFeature_ = workBuffer_; } return RETCODE_SUCCESS; }
36.176871
115
0.672245
91d1a1704e26fdad9ce7d50a91d33736456872b1
2,677
cpp
C++
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
null
null
null
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
null
null
null
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
1
2020-09-06T12:47:47.000Z
2020-09-06T12:47:47.000Z
#pragma once #include "mylibrary/EnemyController.h" #include <cinder/app/AppBase.h> #include "cinder/Rand.h" #include "mylibrary/CoordinateConversions.h" #include "mylibrary/ProjectWideConstants.h" namespace mylibrary { using std::list; EnemyController::EnemyController() = default; void EnemyController::setup(b2World &my_world) { // Setting up world and location for test world_ = &my_world; location_for_test = new b2Vec2(0, 0); } void EnemyController::update() { for (auto p = enemies.begin(); p != enemies.end();) { // if the enemy is dead, it removes the body if (!enemies.empty() && p->IsDead()) { world_->DestroyBody(p->GetBody()); p = enemies.erase(p); } else { p->update(); ++p; } } } void EnemyController::draw() { for (auto &particle : enemies) { particle.draw(); } } void EnemyController::AddEnemies(int amount) { int kTestAmount = 3; // I add 3 enemies in my test cases there test amount is three float world_width; if (amount <= kTestAmount) { world_width = global::kLeftMostIndex; } else { world_width = (conversions::ToBox2DCoordinates( static_cast<float>(cinder::app::getWindowWidth()))); } for (int i = 0; i < amount; i++) { b2BodyDef body_def; body_def.type = b2_dynamicBody; // Sets the position of the enemy on top of the screen somewhere if (location_for_test->y != global::kLowerMostIndex) { body_def.position.Set(ci::randFloat(world_width), global::kLowerMostIndex); } else { body_def.position.Set(location_for_test->x, location_for_test->y); location_for_test->y = kActualY; } CreateBody(body_def); } } b2BodyDef &EnemyController::CreateBody(b2BodyDef &body_def) { Enemy enemy; // Creating enemy and its corresponding properties body_def.userData = &enemy; body_def.bullet = true; enemy.SetBody(world_->CreateBody(&body_def)); b2PolygonShape dynamic_box; // Setting dimensions of enemy dynamic_box.SetAsBox( conversions::ToBox2DCoordinates(global::kBoxDimensions.x), conversions::ToBox2DCoordinates(global::kBoxDimensions.y)); b2FixtureDef fixture_def; // Setting properties of fixture fixture_def.shape = &dynamic_box; fixture_def.density = global::kDensity; fixture_def.friction = global::kFriction; fixture_def.restitution = global::kRestitution / kBounceLimiter; // bounce // Setting body properties enemy.GetBody()->CreateFixture(&fixture_def); enemy.setup(global::kBoxDimensions); enemies.push_back(enemy); return body_def; } std::list<Enemy> &EnemyController::GetEnemies() { return enemies; } } // namespace mylibrary
29.417582
77
0.694061
91d36c33b4309f5b67ce330f27d457282e6e7748
3,077
cpp
C++
tests/test_task_wine.cpp
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
6
2015-04-14T19:42:38.000Z
2015-11-12T17:41:35.000Z
tests/test_task_wine.cpp
cyy1991/nano
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
93
2015-04-10T19:02:38.000Z
2016-03-09T17:56:16.000Z
tests/test_task_wine.cpp
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
2
2015-05-27T16:42:31.000Z
2015-08-21T14:39:55.000Z
#include "task.h" #include "utest.h" using namespace nano; NANO_BEGIN_MODULE(test_wine) NANO_CASE(failed) { const auto task = get_tasks().get("wine"); NANO_REQUIRE(task); task->from_json(to_json("path", "/dev/null?!")); NANO_CHECK(!task->load()); } NANO_CASE(default_config) { const auto task = nano::get_tasks().get("wine"); NANO_REQUIRE(task); json_t json; task->to_json(json); size_t folds = 0; from_json(json, "folds", folds); NANO_CHECK_EQUAL(folds, 10u); } NANO_CASE(loading) { const auto idims = tensor3d_dim_t{13, 1, 1}; const auto odims = tensor3d_dim_t{3, 1, 1}; const auto target_sum = scalar_t(2) - static_cast<scalar_t>(nano::size(odims)); const auto folds = size_t(10); const auto samples = size_t(178); const auto task = nano::get_tasks().get("wine"); NANO_REQUIRE(task); task->from_json(to_json("folds", folds)); NANO_REQUIRE(task->load()); task->describe("wine"); NANO_CHECK_EQUAL(task->idims(), idims); NANO_CHECK_EQUAL(task->odims(), odims); NANO_CHECK_EQUAL(task->fsize(), folds); NANO_CHECK_EQUAL(task->size(), folds * samples); for (size_t f = 0; f < task->fsize(); ++ f) { for (const auto p : {protocol::train, protocol::valid, protocol::test}) { for (size_t i = 0, size = task->size({f, p}); i < size; ++ i) { const auto sample = task->get({f, p}, i, i + 1); const auto& input = sample.idata(0); const auto& target = sample.odata(0); NANO_CHECK_EQUAL(input.dims(), idims); NANO_CHECK_EQUAL(target.dims(), odims); NANO_CHECK_CLOSE(target.vector().sum(), target_sum, epsilon0<scalar_t>()); } NANO_CHECK_EQUAL(task->labels({f, p}).size(), static_cast<size_t>(nano::size(odims))); } NANO_CHECK_EQUAL(task->size({f, protocol::train}), 40 * samples / 100); NANO_CHECK_EQUAL(task->size({f, protocol::valid}), 30 * samples / 100); NANO_CHECK_EQUAL(task->size({f, protocol::test}), 54); NANO_CHECK_EQUAL( task->size({f, protocol::train}) + task->size({f, protocol::valid}) + task->size({f, protocol::test}), task->size() / task->fsize()); NANO_CHECK_LESS_EQUAL(task->duplicates(f), size_t(0)); NANO_CHECK_LESS_EQUAL(task->intersections(f), size_t(0)); } NANO_CHECK_LESS_EQUAL(task->duplicates(), size_t(0)); NANO_CHECK_LESS_EQUAL(task->intersections(), size_t(0)); NANO_CHECK_EQUAL(task->labels().size(), static_cast<size_t>(nano::size(odims))); } NANO_END_MODULE()
34.573034
110
0.524212
91d6c987140b6541aca2aed66d50f33a51601c24
4,924
cpp
C++
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "stdafx.h" #include "PropertiesDialog.h" ///////////////////////////////////////////////////////////////////////////// // CPropertiesDialog dialog CPropertiesDialog::CPropertiesDialog(const CString& title, XmlNodeRef& node, CWnd* pParent /*=NULL*/, bool bShowSearchBar /*=false*/) : CXTResizeDialog(CPropertiesDialog::IDD, pParent) { //{{AFX_DATA_INIT(CPropertiesDialog) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_bShowSearchBar = bShowSearchBar; m_title = title; m_node = node; } void CPropertiesDialog::DoDataExchange(CDataExchange* pDX) { CXTResizeDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPropertiesDialog) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPropertiesDialog, CXTResizeDialog) //{{AFX_MSG_MAP(CPropertiesDialog) ON_WM_DESTROY() ON_WM_CLOSE() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPropertiesDialog message handlers BOOL CPropertiesDialog::OnInitDialog() { CXTResizeDialog::OnInitDialog(); SetWindowText(m_title); CRect rc; GetClientRect(rc); m_wndProps.Create(WS_CHILD | WS_VISIBLE | WS_BORDER, rc, this); m_wndProps.SetUpdateCallback(functor(*this, &CPropertiesDialog::OnPropertyChange)); if (m_bShowSearchBar) { int inputH = 18; m_searchLabel.Create("Search:", WS_CHILD | WS_VISIBLE, rc, this, NULL); m_searchLabel.ModifyStyleEx(WS_EX_CLIENTEDGE, 0); m_input.Create(WS_CHILD | WS_VISIBLE | ES_WANTRETURN | ES_AUTOHSCROLL | WS_TABSTOP, rc, this, NULL); m_input.SetFont(CFont::FromHandle((HFONT)::GetStockObject(SYSTEM_FONT))); m_input.ModifyStyleEx(0, WS_EX_STATICEDGE); m_input.SetWindowText(""); m_wndProps.MoveWindow(rc.left + 4, rc.top + 10 + inputH, rc.right - 8, rc.bottom - 28 - inputH, true); } else { m_wndProps.MoveWindow(rc.left + 4, rc.top + 4, rc.right - 8, rc.bottom - 24, true); } if (m_node) { m_wndProps.CreateItems(m_node); } AutoLoadPlacement("Dialogs\\PropertyDlg"); ConfigureLayout(); if (m_bShowSearchBar) { m_input.SetFocus(); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CPropertiesDialog::PreTranslateMessage(MSG* msg) { if (msg->message == WM_KEYUP) { if (m_bShowSearchBar && (&m_input == GetFocus())) { CString result; m_input.GetWindowText(result); m_wndProps.RestrictToItemsContaining(result); } } else if (msg->message == WM_KEYDOWN) { if (msg->wParam == VK_RETURN) { // Hey, dialog, please don't gobble up the enter key. // It's necessary for edit controls within the property control to work optimally. m_wndProps.SendMessage(WM_KEYDOWN, VK_RETURN, 0); } } return CXTResizeDialog::PreTranslateMessage(msg); } void CPropertiesDialog::OnDestroy() { CXTResizeDialog::OnDestroy(); } void CPropertiesDialog::OnClose() { // reset search bar information m_wndProps.RestrictToItemsContaining(""); m_wndProps.RemoveAllItems(); CXTResizeDialog::OnClose(); } void CPropertiesDialog::OnSize(UINT nType, int cx, int cy) { CXTResizeDialog::OnSize(nType, cx, cy); if (m_wndProps.m_hWnd) { ConfigureLayout(); } } void CPropertiesDialog::ConfigureLayout() { CRect rc; GetClientRect(rc); if (m_bShowSearchBar) { int inputH = 18; m_searchLabel.MoveWindow(rc.left + 4, rc.top + 4, 50, inputH, SWP_NOZORDER); m_input.MoveWindow(rc.left + 58, rc.top + 4, rc.right - 4 - 58, inputH, SWP_NOZORDER); m_wndProps.MoveWindow(rc.left + 4, rc.top + 10 + inputH, rc.right - 8, rc.bottom - 28 - inputH, true); } else { m_wndProps.MoveWindow(rc.left + 4, rc.top + 4, rc.right - 8, rc.bottom - 24, true); } } void CPropertiesDialog::OnPropertyChange(IVariable* pVar) { if (m_varCallback) { m_varCallback(pVar); } } void CPropertiesDialog::OnCancel() { DestroyWindow(); }
26.907104
133
0.647238
91d9b1be00d77e8275bd5320f99ca23afed93674
509
hpp
C++
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Datatypes.hpp" #include <SFML/Graphics/RenderWindow.hpp> class SceneManager; class ResourceManager; class Scene { public: ~Scene() = default; virtual void HandleInput(sf::Event& event) = 0; virtual void Update(float dt) = 0; virtual void Draw(sf::RenderWindow& window) = 0; virtual void Load() = 0; virtual void Unload() = 0; virtual uint32 GetType() const = 0; protected: SceneManager* m_SceneManager = nullptr; ResourceManager* m_ResourceManager = nullptr; };
18.178571
49
0.72888
91daa744e6036e1ebcf5ffd4390aefcb7762e1e3
3,539
cpp
C++
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = unsigned long long; vector<string> split_string(string); // Complete the sherlockAndMinimax function below. int sherlockAndMinimax_(vector<int> arr, int p, int q) { set<int> arr2(arr.begin(), arr.end()); int retVal = p; int maX = -1; int beg = p; int end = q; // special cases if(*arr2.begin() >= q) { return p; } else if(*prev(arr2.end()) <= p) { return q; } else if(*arr2.begin() > p && *arr2.begin() < q) { retVal = p; maX = abs(p - *arr2.begin()); beg = *arr2.begin(); } for(int i = beg; i <= end; ++i) { auto it = arr2.lower_bound(i); if(it == arr2.end()) { /* int tmp = max(maX, abs(i - *prev(arr2.end()))); if(tmp != maX) { maX = tmp; retVal = i; } */ int tmp = max(maX, abs(q - *prev(arr2.end()))); if(tmp != maX) { maX = tmp; retVal = q; } break; } else { if(*it != i) { // I need the min of prev and this one auto prv = prev(it); int tmp; if(prv != arr2.end()) { int m = min(abs(i - *prv), abs(i - *it)); tmp = max(maX, m); } else { tmp = max(maX, abs(i - *it)); } if(tmp != maX) { maX = tmp; retVal = i; } } else { // min() = 0, nothin to do } } //cout << "i: " << i << " maX: " << maX << " retVal: " << retVal << "\n"; } return retVal; } int sherlockAndMinimax(vector<int> arr, int p, int q) { set<int> arr2(arr.begin(), arr.end()); int retVal = p; int maX = -1; int beg = p; int end = q; // special cases if(*arr2.begin() >= q) { return p; } else if(*prev(arr2.end()) <= p) { return q; } } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string arr_temp_temp; getline(cin, arr_temp_temp); vector<string> arr_temp = split_string(arr_temp_temp); vector<int> arr(n); for (int i = 0; i < n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } string pq_temp; getline(cin, pq_temp); vector<string> pq = split_string(pq_temp); int p = stoi(pq[0]); int q = stoi(pq[1]); int result = sherlockAndMinimax(arr, p, q); fout << result << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
23.751678
115
0.472167
91de5fa1a8e651537de6d2da28989c95dbbf40f9
10,420
cpp
C++
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
252
2021-08-18T10:43:37.000Z
2022-03-20T18:43:59.000Z
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
3
2021-12-01T09:08:33.000Z
2022-01-14T08:56:19.000Z
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
10
2021-11-30T16:17:54.000Z
2022-03-28T17:56:18.000Z
#include "Mesh.h" #include "Core/Json.h" #include "Core/Base64.h" #include <SDL_rwops.h> #include <string> // *********************************************************************** int Primitive::GetNumVertices() { return (int)m_vertices.size(); } // *********************************************************************** Vec3f Primitive::GetVertexPosition(int index) { return m_vertices[index].pos; } // *********************************************************************** Vec4f Primitive::GetVertexColor(int index) { return m_vertices[index].col; } // *********************************************************************** Vec2f Primitive::GetVertexTexCoord(int index) { return m_vertices[index].tex; } // *********************************************************************** Vec3f Primitive::GetVertexNormal(int index) { return m_vertices[index].norm; } // *********************************************************************** int Primitive::GetMaterialTextureId() { return m_baseColorTexture; } // *********************************************************************** Mesh::~Mesh() { } // *********************************************************************** int Mesh::GetNumPrimitives() { return (int)m_primitives.size(); } // *********************************************************************** Primitive* Mesh::GetPrimitive(int index) { return &m_primitives[index]; } // *********************************************************************** // Actually owns the data struct Buffer { char* pBytes{ nullptr }; size_t byteLength{ 0 }; }; // Does not actually own the data struct BufferView { // pointer to some place in a buffer char* pBuffer{ nullptr }; size_t length{ 0 }; enum Target { Array, ElementArray }; Target target; }; struct Accessor { // pointer to some place in a buffer view char* pBuffer{ nullptr }; int count{ 0 }; enum ComponentType { Byte, UByte, Short, UShort, UInt, Float }; ComponentType componentType; enum Type { Scalar, Vec2, Vec3, Vec4, Mat2, Mat3, Mat4 }; Type type; }; // *********************************************************************** std::vector<Mesh*> Mesh::LoadMeshes(const char* filePath) { std::vector<Mesh*> outMeshes; // Consider caching loaded json files somewhere since LoadScene and LoadMeshes are doing duplicate work here SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb"); uint64_t size = SDL_RWsize(pFileRead); char* pData = new char[size]; SDL_RWread(pFileRead, pData, size, 1); SDL_RWclose(pFileRead); std::string file(pData, pData + size); delete[] pData; JsonValue parsed = ParseJsonFile(file); bool validGltf = parsed["asset"]["version"].ToString() == "2.0"; if (!validGltf) return std::vector<Mesh*>(); std::vector<Buffer> rawDataBuffers; JsonValue& jsonBuffers = parsed["buffers"]; for (int i = 0; i < jsonBuffers.Count(); i++) { Buffer buf; buf.byteLength = jsonBuffers[i]["byteLength"].ToInt(); buf.pBytes = new char[buf.byteLength]; std::string encodedBuffer = jsonBuffers[i]["uri"].ToString().substr(37); memcpy(buf.pBytes, DecodeBase64(encodedBuffer).data(), buf.byteLength); rawDataBuffers.push_back(buf); } std::vector<BufferView> bufferViews; JsonValue& jsonBufferViews = parsed["bufferViews"]; for (int i = 0; i < jsonBufferViews.Count(); i++) { BufferView view; int bufIndex = jsonBufferViews[i]["buffer"].ToInt(); view.pBuffer = rawDataBuffers[bufIndex].pBytes + jsonBufferViews[i]["byteOffset"].ToInt(); //@Incomplete, byte offset could not be provided, in which case we assume 0 view.length = jsonBufferViews[i]["byteLength"].ToInt(); // @Incomplete, target may not be provided int target = jsonBufferViews[i]["target"].ToInt(); if (target == 34963) view.target = BufferView::ElementArray; else if (target = 34962) view.target = BufferView::Array; bufferViews.push_back(view); } std::vector<Accessor> accessors; JsonValue& jsonAccessors = parsed["accessors"]; accessors.reserve(jsonAccessors.Count()); for (int i = 0; i < jsonAccessors.Count(); i++) { Accessor acc; JsonValue& jsonAcc = jsonAccessors[i]; int idx = jsonAcc["bufferView"].ToInt(); acc.pBuffer = bufferViews[idx].pBuffer + jsonAcc["byteOffset"].ToInt(); acc.count = jsonAcc["count"].ToInt(); int compType = jsonAcc["componentType"].ToInt(); switch (compType) { case 5120: acc.componentType = Accessor::Byte; break; case 5121: acc.componentType = Accessor::UByte; break; case 5122: acc.componentType = Accessor::Short; break; case 5123: acc.componentType = Accessor::UShort; break; case 5125: acc.componentType = Accessor::UInt; break; case 5126: acc.componentType = Accessor::Float; break; default: break; } std::string type = jsonAcc["type"].ToString(); if (type == "SCALAR") acc.type = Accessor::Scalar; else if (type == "VEC2") acc.type = Accessor::Vec2; else if (type == "VEC3") acc.type = Accessor::Vec3; else if (type == "VEC4") acc.type = Accessor::Vec4; else if (type == "MAT2") acc.type = Accessor::Mat2; else if (type == "MAT3") acc.type = Accessor::Mat3; else if (type == "MAT4") acc.type = Accessor::Mat4; accessors.push_back(acc); } outMeshes.reserve(parsed["meshes"].Count()); for (int i = 0; i < parsed["meshes"].Count(); i++) { JsonValue& jsonMesh = parsed["meshes"][i]; Mesh* pMesh = new Mesh(); pMesh->m_name = jsonMesh.HasKey("name") ? jsonMesh["name"].ToString() : ""; for (int j = 0; j < jsonMesh["primitives"].Count(); j++) { JsonValue& jsonPrimitive = jsonMesh["primitives"][j]; Primitive prim; if (jsonPrimitive.HasKey("mode")) { if (jsonPrimitive["mode"].ToInt() != 4) { return std::vector<Mesh*>(); // Unsupported topology type } } // Get material texture if (jsonPrimitive.HasKey("material")) { int materialId = jsonPrimitive["material"].ToInt(); JsonValue& jsonMaterial = parsed["materials"][materialId]; JsonValue& pbr = jsonMaterial["pbrMetallicRoughness"]; if (pbr.HasKey("baseColorTexture")) { int textureId = pbr["baseColorTexture"]["index"].ToInt(); int imageId = parsed["textures"][textureId]["source"].ToInt(); prim.m_baseColorTexture = imageId; } } int nVerts = accessors[jsonPrimitive["attributes"]["POSITION"].ToInt()].count; JsonValue& jsonAttr = jsonPrimitive["attributes"]; Vec3f* vertPositionBuffer = (Vec3f*)accessors[jsonAttr["POSITION"].ToInt()].pBuffer; Vec3f* vertNormBuffer = jsonAttr.HasKey("NORMAL") ? (Vec3f*)accessors[jsonAttr["NORMAL"].ToInt()].pBuffer : nullptr; Vec2f* vertTexCoordBuffer = jsonAttr.HasKey("TEXCOORD_0") ? (Vec2f*)accessors[jsonAttr["TEXCOORD_0"].ToInt()].pBuffer : nullptr; // Interlace vertex data std::vector<VertexData> indexedVertexData; indexedVertexData.reserve(nVerts); if (jsonAttr.HasKey("COLOR_0")) { Vec4f* vertColBuffer = (Vec4f*)accessors[jsonAttr["COLOR_0"].ToInt()].pBuffer; for (int i = 0; i < nVerts; i++) { indexedVertexData.push_back({vertPositionBuffer[i], vertColBuffer[i], vertTexCoordBuffer[i], vertNormBuffer[i]}); } } else { for (int i = 0; i < nVerts; i++) { indexedVertexData.push_back({vertPositionBuffer[i], Vec4f(1.0f, 1.0f, 1.0f, 1.0f), vertTexCoordBuffer[i], vertNormBuffer[i]}); } } // Flatten indices int nIndices = accessors[jsonPrimitive["indices"].ToInt()].count; uint16_t* indexBuffer = (uint16_t*)accessors[jsonPrimitive["indices"].ToInt()].pBuffer; prim.m_vertices.reserve(nIndices); for (int i = 0; i < nIndices; i++) { uint16_t index = indexBuffer[i]; prim.m_vertices.push_back(indexedVertexData[index]); } pMesh->m_primitives.push_back(std::move(prim)); } outMeshes.push_back(pMesh); } for (int i = 0; i < rawDataBuffers.size(); i++) { delete rawDataBuffers[i].pBytes; } return std::move(outMeshes); } // *********************************************************************** std::vector<Image*> Mesh::LoadTextures(const char* filePath) { std::vector<Image*> outImages; // Consider caching loaded json files somewhere since LoadScene/LoadMeshes/LoadImages are doing duplicate work here SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb"); uint64_t size = SDL_RWsize(pFileRead); char* pData = new char[size]; SDL_RWread(pFileRead, pData, size, 1); SDL_RWclose(pFileRead); std::string file(pData, pData + size); delete[] pData; JsonValue parsed = ParseJsonFile(file); bool validGltf = parsed["asset"]["version"].ToString() == "2.0"; if (!validGltf) return std::vector<Image*>(); if (parsed.HasKey("images")) { outImages.reserve(parsed["images"].Count()); for (size_t i = 0; i < parsed["images"].Count(); i++) { JsonValue& jsonImage = parsed["images"][i]; std::string type = jsonImage["mimeType"].ToString(); std::string imagePath = "Assets/" + jsonImage["name"].ToString() + "." + type.substr(6, 4); Image* pImage = new Image(imagePath); outImages.emplace_back(pImage); } } return std::move(outImages); }
30.828402
174
0.533685
91de6d6f2835be44a67f4886901402cab72c55e3
4,432
hh
C++
net.ssa/xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//============================================================================= // // OpenMesh // Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen // www.openmesh.org // //----------------------------------------------------------------------------- // // License // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published // by the Free Software Foundation, version 2. // // 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // //----------------------------------------------------------------------------- // // $Revision: 1.7 $ // $Date: 2004/01/13 15:23:32 $ // //============================================================================= #ifndef OPENMESH_MESHCHECKER_HH #define OPENMESH_MESHCHECKER_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/System/omstream.hh> #include <OpenMesh/Core/Utils/GenProg.hh> #include <OpenMesh/Core/Attributes/Attributes.hh> #include <iostream> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Utils { //== CLASS DEFINITION ========================================================= /** Check integrity of mesh. * * This class provides several functions to check the integrity of a mesh. */ template <class Mesh> class MeshCheckerT { public: /// constructor MeshCheckerT(const Mesh& _mesh) : mesh_(_mesh) {} /// destructor ~MeshCheckerT() {} /// what should be checked? enum CheckTargets { CHECK_EDGES = 1, CHECK_VERTICES = 2, CHECK_FACES = 4, CHECK_ALL = 255, }; /// check it, return true iff ok bool check( unsigned int _targets=CHECK_ALL, std::ostream& _os=omerr ); private: bool is_deleted(typename Mesh::VertexHandle _vh) { return (mesh_.has_vertex_status() ? mesh_.status(_vh).deleted() : false); } bool is_deleted(typename Mesh::EdgeHandle _eh) { return (mesh_.has_edge_status() ? mesh_.status(_eh).deleted() : false); } bool is_deleted(typename Mesh::FaceHandle _fh) { return (mesh_.has_face_status() ? mesh_.status(_fh).deleted() : false); } // ref to mesh const Mesh& mesh_; }; //============================================================================= } // namespace Utils } // namespace OpenMesh //============================================================================= #if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_MESHCHECKER_C) #define OPENMESH_MESHCHECKER_TEMPLATES #include "MeshCheckerT.cc" #endif //============================================================================= #endif // OPENMESH_MESHCHECKER_HH defined //=============================================================================
38.53913
80
0.38944
91de7e1728ff20b377605f083a700c47bb1f9670
1,650
cpp
C++
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
1
2021-03-20T04:52:45.000Z
2021-03-20T04:52:45.000Z
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
null
null
null
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
1
2021-06-05T23:30:49.000Z
2021-06-05T23:30:49.000Z
#include <iostream> #include <fstream> #include <list> #include <vector> #include <chrono> #include <ctime> #include <climits> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> #include <g2o/core/base_unary_edge.h> #include <g2o/core/block_solver.h> #include <g2o/core/optimization_algorithm_levenberg.h> #include <g2o/solvers/dense/linear_solver_dense.h> #include <g2o/core/robust_kernel.h> #include <g2o/types/sba/types_six_dof_expmap.h> using namespace std; using namespace g2o; // 一次测量的值,包括一个世界坐标系下三维点与一个灰度值 struct Measurement { Measurement ( Eigen::Vector3d p, float g ) : pos_world ( p ), grayscale ( g ) {} Eigen::Vector3d pos_world; float grayscale; }; // inline 修饰内联函数, 像素坐标到相机坐标 inline Eigen::Vector3d pixelToCam ( int u, int v, int d, float fx, float fy, float cx, float cy, float scale ) { float zz = float ( d ) /scale; // Give a measurment float x_cam = zz* ( u-cx ) /fx; float y_cam = zz* ( v-cy ) /fy; return Eigen::Vector3d ( x_cam, y_cam, zz ); } // inline , 相机坐标到像素坐标 inline Eigen::Vector2d camToPixel ( float x, float y, float z, float fx, float fy, float cx, float cy ) { float u = fx*x/z+cx; float v = fy*y/z+cy; return Eigen::Vector2d ( u,v ); } // 直接法估计位姿 // 输入:测量值(空间点的灰度),新的灰度图,相机内参; 输出:相机位姿 // 返回:true为成功,false失败 bool poseEstimationDirect ( const vector<Measurement>& measurements, cv::Mat* gray, Eigen::Matrix3f& intrinsics, Eigen::Isometry3d& Tcw ); // Isometry3d --> 是 欧式 变换矩阵。 其实是一个 4 x 4 矩阵 int main(int argc, char const *argv[]) { /* code */ return 0; }
27.5
110
0.695152
91e8f446e650ca0fded7d5f413dc6a1eda5c0fc9
1,707
cpp
C++
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
2
2021-06-27T01:58:23.000Z
2021-08-16T20:24:29.000Z
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
2
2022-02-03T23:40:10.000Z
2022-03-15T06:22:29.000Z
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
1
2022-01-26T21:07:41.000Z
2022-01-26T21:07:41.000Z
#include <cage-core/entitiesVisitor.h> #include <cage-core/spatialStructure.h> #include "../game.h" #include "../grid.h" namespace { Holder<SpatialStructure> monstersData = newSpatialStructure({}); Holder<SpatialStructure> structsData = newSpatialStructure({}); Holder<SpatialQuery> monstersQuery = newSpatialQuery(monstersData.share()); Holder<SpatialQuery> structsQuery = newSpatialQuery(structsData.share()); void gameReset() { monstersData->clear(); structsData->clear(); } void gameUpdate() { monstersData->clear(); CAGE_ASSERT(globalGrid); entitiesVisitor([&](Entity *e, const MovementComponent &mv, const MonsterComponent &) { monstersData->update(e->name(), mv.position()); }, gameEntities(), false); monstersData->rebuild(); } struct Callbacks { EventListener<void()> gameResetListener; EventListener<void()> gameUpdateListener; Callbacks() { gameResetListener.attach(eventGameReset()); gameResetListener.bind<&gameReset>(); gameUpdateListener.attach(eventGameUpdate(), 30); gameUpdateListener.bind<&gameUpdate>(); } } callbacksInstance; } SpatialQuery *spatialMonsters() { return +monstersQuery; } SpatialQuery *spatialStructures() { return +structsQuery; } void spatialUpdateStructures() { structsData->clear(); CAGE_ASSERT(globalGrid); entitiesVisitor([&](Entity *e, const PositionComponent &pos, const BuildingComponent &) { structsData->update(e->name(), globalGrid->center(pos.tile)); }, gameEntities(), false); entitiesVisitor([&](Entity *e, const PositionComponent &pos, const TrapComponent &) { structsData->update(e->name(), globalGrid->center(pos.tile)); }, gameEntities(), false); structsData->rebuild(); }
23.708333
90
0.727592
91eb95f6a67a682eb83e45a9575e14e3f217c3b9
372
cpp
C++
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
#include "../include/Logger.hpp" #include <iostream> void Logger::LexicalError(const std::string &msg, int line, int index) { std::cerr << "Lexical Error -> " << line << ":" << index << " : " << msg << std::endl; } void Logger::RuntimeError(const std::string &msg, int line) { std::cerr << "Runtime Error -> Line " << line << " : " << msg << std::endl; }
23.25
70
0.572581
91ef59cbd345291b9cbc8c26db1740a71088a7ff
4,449
cpp
C++
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
// BSD 3-Clause License // Copyright (c) 2019, SCALE Lab, Brown University // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "Exports.hpp" #include <OpenPhySyn/Psn/Psn.hpp> #include <memory> #include "PsnLogger/PsnLogger.hpp" namespace psn { #ifndef OPENROAD_BUILD int import_def(const char* def_path) { return Psn::instance().readDef(def_path); } int import_lef(const char* lef_path, int ignore_routing_layers) { return Psn::instance().readLef(lef_path); } int import_lib(const char* lib_path) { return import_liberty(lib_path); } int import_liberty(const char* lib_path) { return Psn::instance().readLib(lib_path); } int export_def(const char* lib_path) { return Psn::instance().writeDef(lib_path); } int print_liberty_cells() { Liberty* liberty = Psn::instance().liberty(); if (!liberty) { PsnLogger::instance().error("Did not find any liberty files, use " "import_liberty <file name> first."); return -1; } sta::LibertyCellIterator cell_iter(liberty); while (cell_iter.hasNext()) { sta::LibertyCell* cell = cell_iter.next(); PsnLogger::instance().info("Cell: {}", cell->name()); } return 1; } #endif int set_wire_rc(float res_per_micon, float cap_per_micron) { Psn::instance().setWireRC(res_per_micon, cap_per_micron); return 1; } int set_max_area(float area) { Psn::instance().settings()->setMaxArea(area); return 1; } int link(const char* top_module) { return link_design(top_module); } int link_design(const char* top_module) { return Psn::instance().linkDesign(top_module); } void version() { print_version(); } int transform_internal(std::string transform_name, std::vector<std::string> args) { return Psn::instance().runTransform(transform_name, args); } void help() { print_usage(); } void print_usage() { Psn::instance().printUsage(); } void print_transforms() { Psn::instance().printTransforms(true); } void print_version() { Psn::instance().printVersion(); } Database& get_database() { return *(Psn::instance().database()); } Liberty& get_liberty() { return *(Psn::instance().liberty()); } int set_log(const char* level) { return set_log_level(level); } int set_log_level(const char* level) { return Psn::instance().setLogLevel(level); } int set_log_pattern(const char* pattern) { return Psn::instance().setLogPattern(pattern); } DatabaseHandler& get_handler() { return get_database_handler(); } DatabaseHandler& get_database_handler() { return *(Psn::instance().handler()); } SteinerTree* create_steiner_tree(const char* net_name) { auto net = Psn::instance().handler()->net(net_name); return create_steiner_tree(net); } SteinerTree* create_steiner_tree(Net* net) { auto pt = SteinerTree::create(net, &(Psn::instance()), 3); SteinerTree* tree = pt.get(); pt.release(); return tree; } } // namespace psn
22.469697
80
0.710497
91f3b792dec221d489aa79578b01b1f483bfe1c8
22,008
cpp
C++
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
1
2021-12-21T17:28:39.000Z
2021-12-21T17:28:39.000Z
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
null
null
null
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------// // Digital Scenario Framework // // by Giovanni Paolo Vigano', 2021 // //--------------------------------------------------------------------// // // Distributed under the MIT Software License. // See http://opensource.org/licenses/MIT // #include <SimplECircuitCybSys/SimplECircuitCybSys.h> #include <SimplECircuitCybSys/SimplECircuitSolver.h> #include <discenfw/xp/EnvironmentModel.h> #include <discenfw/util/MessageLog.h> #include <boost/config.hpp> // for BOOST_SYMBOL_EXPORT #include <iostream> #include <sstream> using namespace discenfw::xp; namespace { inline std::string BoolToString(bool val) { return val ? "true" : "false"; } } namespace simplecircuit_cybsys { SimplECircuitCybSys::SimplECircuitCybSys() { Circuit = std::make_unique<simplecircuit_cybsys::ElectronicCircuit>(); } void SimplECircuitCybSys::CreateEntityStateTypes() { if (ComponentEntityType) { return; } ComponentEntityType = CreateEntityStateType( "", "Electronic Component", { {"connections","0"}, {"connected","false"}, {"burnt out","false"}, }, { { "connected", { "true","false" } }, {"burnt out", { "true","false" }}, }, {} ); ResistorEntityType = CreateEntityStateType( "Electronic Component", "Resistor", { }, { {"connections",{"0","1","2"}}, }, { "Pin1", "Pin2" } ); LedEntityType = CreateEntityStateType( "Electronic Component", "LED", { {"lit up","false"}, }, { {"connections",{"0","1","2"}}, { "lit up", { "true","false" } }, }, { "Anode", "Cathode" } ); PowerEntityType = CreateEntityStateType( "Electronic Component", "Power Supply", { }, { {"connections",{"0","1","2"}}, }, { "+", "-" } ); SwitchEntityType = CreateEntityStateType( "Electronic Component", "Switch", { {"position","0"}, }, { {"connections",{"0","1","2","3"}}, { "position", { "0","1" } }, }, { "In", "Out0", "Out1" } ); } void SimplECircuitCybSys::ClearSystem() { Circuit->Components.clear(); } void SimplECircuitCybSys::InitFailureConditions() { // set a default failure condition (any component burnt out) PropertyCondition burntOutCond({ "burnt out",BoolToString(true) }); Condition anyBurntOut({ {EntityCondition::ANY,{burntOutCond}} }); FailureCondition = anyBurntOut; } void SimplECircuitCybSys::InitRoles() { std::shared_ptr<EnvironmentModel> model = GetModel(); if (model->GetRoleNames().empty()) { PropertyCondition burntOutCond({ "burnt out",BoolToString(true) }); Condition anyBurntOut({ { EntityCondition::ANY,{ burntOutCond } } }); xp::SetRole( "Default", {}, // SuccessCondition {}, // FailureCondition {}, // DeadlockCondition { // ResultReward { { ActionResult::IN_PROGRESS,0 }, { ActionResult::SUCCEEDED,1000 }, { ActionResult::FAILED,-1000 }, { ActionResult::DEADLOCK,-10 }, }, // PropertyCountRewards {}, // EntityConditionRewards { }, // FeatureRewards { } } ); } } void SimplECircuitCybSys::ResetSystem() { Circuit->Reset(); } bool SimplECircuitCybSys::ExecuteAction(const Action& action) { enum ActionId { CONNECT, SWITCH, DISCONNECT }; static std::map<std::string, ActionId> actionNames{ { "connect",CONNECT }, { "switch",SWITCH }, { "disconnect",DISCONNECT }, }; switch (actionNames[action.TypeId]) { case CONNECT: return DoConnectAction(action); case SWITCH: return DoSwitchAction(action); case DISCONNECT: return DoDisconnectAction(action); default: break; } return false; } void SimplECircuitCybSys::SynchronizeState(std::shared_ptr<xp::EnvironmentState> environmentState) { // TODO: alternative: just update existing entities and remove dangling entities? environmentState->Clear(); // synchronize component states for (const auto& comp : Circuit->Components) { std::string entityId = comp.first; const auto& component = comp.second; std::shared_ptr<Led> led = AsLed(component); std::shared_ptr<Switch> sw = AsSwitch(component); std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(component); std::shared_ptr<Resistor> resistor = AsResistor(component); // get the properties of the current component bool nowBurnt = component->BurntOut; bool nowConnected = component->Connected; int nowConn = component->GetConnectedLeadsCount(); bool nowLit = led && led->LitUp; int nowPos = (int)(sw && sw->Position == SwitchPosition::POS1); // update the entity state for the current component std::shared_ptr<EntityState> entState = environmentState->GetEntityState(entityId); if (!entState) { std::shared_ptr<EntityStateType> entType; if (!ComponentEntityType) { CreateEntityStateTypes(); } if (powerSupply) entType = PowerEntityType; else if (led) entType = LedEntityType; else if (sw) entType = SwitchEntityType; else if (resistor) entType = ResistorEntityType; //else if (transistor) entType = TransistorEntityType; else entType = ComponentEntityType; entState = EntityState::Make(entType->GetTypeName(),entType->GetModelName()); //entState = std::make_shared<EntityState>(entType->GetTypeName(),entType->GetModelName()); environmentState->SetEntityState(entityId, entState); } std::vector< std::pair<std::string, std::shared_ptr<ElectronicComponentLead> >> leads; component->GetLeads(leads); // store new component relationships for (const auto& eLead : leads) { if (!eLead.second->Connections.empty()) { RelationshipLink link; link.EntityId = eLead.second->Connections[0].Component; link.LinkId = eLead.second->Connections[0].Lead; entState->SetRelationship(eLead.first, link); } else { entState->RemoveRelationship(eLead.first); } } // set the properties for the entity state entState->SetPropertyValue("burnt out", BoolToString(nowBurnt)); entState->SetPropertyValue("connected", BoolToString(nowConnected)); entState->SetPropertyValue("connections", std::to_string(nowConn)); if (led) { entState->SetPropertyValue("lit up", BoolToString(nowLit)); } if (sw) { entState->SetPropertyValue("position", std::to_string(nowPos)); } if (LogEnabled) { if (nowBurnt) { LogStream << entityId << " => burnt out" << std::endl; FlushLog(LOG_DEBUG); } if (nowLit) { LogStream << entityId << " => lit up" << std::endl; FlushLog(LOG_DEBUG); } if (nowPos) { LogStream << entityId << " => on" << std::endl; FlushLog(LOG_DEBUG); } } } } const std::vector<ActionRef>& SimplECircuitCybSys::GetAvailableActions( const std::string& roleId, bool smartSelection ) const { CachedAvailableActions.clear(); std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply(); bool circuitIsComplete = false; if (smartSelection) { if(powerSupply && powerSupply->GetConnectedLeadsCount()==2) { circuitIsComplete = true; for (const auto& compItem : Circuit->Components) { // Check if at least one component is connected but not fully connected // (power supply was already checked) if (compItem.second != powerSupply && compItem.second->GetConnectedLeadsCount() == 1) { circuitIsComplete = false; break; } } } } std::vector<std::string> actionNames{ "connect", "switch" }; for (const auto& compItem : Circuit->Components) { std::string compId = compItem.first; std::shared_ptr<ElectronicComponent> component = compItem.second; bool powerSupplyConnected = powerSupply && powerSupply->AnyLeadConnected(); std::string powerId = Circuit->GetComponentName(powerSupply); if (!component->BurntOut) { auto sw = AsSwitch(component); if (sw) { bool canBeSwitched = true; if (smartSelection) { canBeSwitched = circuitIsComplete && sw->GetConnectedLeadsCount() > 1 && sw->Lead("In")->Connected(); } // possible deadlock: repeatedly switching --> deadlock detection required if (canBeSwitched) { CacheAvailableAction( { "switch",{ compId,sw->Position == SwitchPosition::POS0 ? "1" : "0" } } ); } // alternative solution: // allow switch-on only, this avoids possible deadlocks //if (canBeSwitched && sw->Position == SwitchPosition::POS0) //... } // if (!component->AllLeadsConnected()) ... // allow only 2 connections per component to simplify the circuit simulation if (component->GetConnectedLeadsCount() < 2) { std::vector< std::shared_ptr<ElectronicComponentLead> > leads; std::vector< std::string > leadNames; component->GetLeads(leads); component->GetLeadNames(leadNames); for (const auto& otherCompItem : Circuit->Components) { std::string otherCompId = otherCompItem.first; std::shared_ptr<ElectronicComponent> otherComponent = otherCompItem.second; bool connectingPowerSupply = (otherComponent == powerSupply || component == powerSupply); bool connectedToPowerSupply = (otherComponent->Connected || component->Connected); bool canBeConnected = (!otherComponent->BurntOut && otherComponent != component && !otherComponent->AllLeadsConnected() && !component->ConnectedTo(otherCompId) ); if (smartSelection) { canBeConnected = canBeConnected && (connectingPowerSupply || connectedToPowerSupply); } if (canBeConnected) { std::vector< std::shared_ptr<ElectronicComponentLead> > otherLeads; std::vector< std::string > otherLeadNames; otherComponent->GetLeads(otherLeads); otherComponent->GetLeadNames(otherLeadNames); for (size_t i = 0; i < leads.size(); i++) { const auto& lead = leads[i]; // allow only 1 connection per lead to simplify the circuit simulation if (!lead->Connected()) { for (size_t j = 0; j < otherLeads.size(); j++) { const auto& otherLead = otherLeads[j]; if (!otherLead->Connected()) { // prevent parallel connections of components to simplify the circuit simulation //if (otherLead != lead && !otherLead->ConnectedTo(compId, leadNames[i])) if (otherLead != lead && !otherLead->ConnectedTo(compId)) { CacheAvailableAction( { "connect", { compId, leadNames[i], otherCompId, otherLeadNames[j] } } ); } } } } } } } } } } return CachedAvailableActions; } bool SimplECircuitCybSys::DoConnectAction(const Action& action) { // decode parameters const std::string& component1Id = action.Params[0]; const std::string& lead1Id = action.Params[1]; const std::string& component2Id = action.Params[2]; const std::string& lead2Id = action.Params[3]; // prevent connecting a lead with itself if (component1Id == component2Id && lead1Id == lead2Id) { return false; } std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id); std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id); // check if components exist if (!component1 || !component2) { return false; } // check if already connected if (component1->ConnectedTo(component2Id, lead2Id)) { return false; } // allow only 1 connection per lead to simplify the circuit simulation if (component1->Lead(lead1Id)->Connected() || component2->Lead(lead2Id)->Connected()) { return false; } if (LogEnabled) { LogStream << "> " << component1Id << "/" << lead1Id << " <--> " << component2Id << "/" << lead2Id << std::endl; FlushLog(LOG_DEBUG); } // update the circuit Circuit->Connect(component1Id, lead1Id, component2Id, lead2Id); SolveElectronicCircuit(*Circuit); return true; } bool SimplECircuitCybSys::DoSwitchAction(const Action& action) { // decode parameters const std::string& switchId = action.Params[0]; const std::string& posId = action.Params[1]; bool pos = std::atoi(posId.c_str()) > 0; auto sw = AsSwitch(Circuit->FindComponent(switchId)); if (!sw) { return false; } if (LogEnabled) { LogStream << std::noboolalpha << "> " << switchId << ": " << pos << std::endl; FlushLog(LOG_DEBUG); } // update the circuit sw->Position = (SwitchPosition)pos; SolveElectronicCircuit(*Circuit); return true; } bool SimplECircuitCybSys::DoDisconnectAction(const Action& action) { size_t numParams = action.Params.size(); if(numParams!=2 && numParams!=4) { return false; } // decode parameters const std::string& component1Id = action.Params[0]; const std::string& lead1Id = action.Params[1]; std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id); if (!component1->Lead(lead1Id)->Connected()) { return false; } if (numParams == 2) { // update the circuit Circuit->Disconnect(component1Id, lead1Id); } else //if (numParams == 4) { const std::string& component2Id = action.Params[2]; const std::string& lead2Id = action.Params[3]; // prevent connecting a lead with itself if (component1Id == component2Id && lead1Id == lead2Id) { return false; } std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id); // check if components exist if (!component1 || !component2) { return false; } // check if already connected if (!component1->ConnectedTo(component2Id, lead2Id)) { return false; } if (!component2->Lead(lead2Id)->Connected()) { return false; } if (LogEnabled) { LogStream << "> " << component1Id << "/" << lead1Id << " X--X " << component2Id << "/" << lead2Id << std::endl; FlushLog(LOG_DEBUG); } // update the circuit Circuit->Disconnect(component1Id, lead1Id, component2Id, lead2Id); } SolveElectronicCircuit(*Circuit); return true; } std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::CreateComponentFromConfiguration( const std::string& config, std::string& compId) { std::istringstream iStr(config); if (!iStr.good()) { return nullptr; } std::shared_ptr<ElectronicComponent> comp; std::string compType; iStr >> compType >> compId; comp = MakeComponent(compType); if (comp) { ReadComponentConfiguration(iStr, comp); Circuit->Components[compId] = comp; } return comp; } const std::string SimplECircuitCybSys::GetComponentConfiguration(const std::string& compId) { std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId); if (!comp) { return ""; } std::ostringstream oStr; std::shared_ptr<Led> led = AsLed(comp); if (led) { oStr << led->Type->Name; } std::shared_ptr<Resistor> r = AsResistor(comp); if (r) { oStr << r->Ohm << " " << r->Max_mW; } std::shared_ptr<Switch> sw = AsSwitch(comp); if (sw) { oStr << sw->MaxVoltage_mV << " " << sw->MaxCurrent_mA; } std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp); if (powerSupply) { oStr << powerSupply->Voltage_mV << " " << powerSupply->MaxCurrent_mA; } return oStr.str(); } bool SimplECircuitCybSys::SetComponentConfiguration(const std::string& compId, const std::string& config) { std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId); if (!comp) { return false; } std::istringstream iStr(config); ReadComponentConfiguration(iStr, comp); return true; } bool SimplECircuitCybSys::SetConfiguration(const std::string& config) { Initialize(); Circuit->Components.clear(); bool firstRead = true; std::istringstream iStr(config); while (iStr.good()) { std::string compConfig; std::getline(iStr, compConfig); std::string compId; std::shared_ptr<ElectronicComponent> comp = CreateComponentFromConfiguration( compConfig, compId); if (firstRead &&!comp) { return false; } firstRead = false; } Initialize(true); return true; } const std::string SimplECircuitCybSys::GetConfiguration() { std::ostringstream oStr; for (const auto& comp : Circuit->Components) { oStr << comp.second->GetTypeName() << " " << comp.first << " "; oStr << GetComponentConfiguration(comp.first); oStr << "\n"; } return oStr.str(); } const std::string SimplECircuitCybSys::ReadEntityConfiguration(const std::string& entityId) { return GetComponentConfiguration(entityId); } bool SimplECircuitCybSys::WriteEntityConfiguration(const std::string& entityId, const std::string& config) { return SetComponentConfiguration(entityId, config); } bool SimplECircuitCybSys::ConfigureEntity(const std::string& entityId, const std::string& entityType, const std::string& config) { std::shared_ptr<ElectronicComponent> comp; if (Circuit->Components.find(entityId) != Circuit->Components.end()) { comp = Circuit->Components[entityId]; if (comp->GetTypeName() != entityType) { Circuit->Components.erase(entityId); comp = nullptr; } } if (!comp) { comp = MakeComponent(entityType); if (!comp) { return false; } Circuit->Components[entityId] = comp; } std::istringstream iStr(config); ReadComponentConfiguration(iStr, comp); return true; } bool SimplECircuitCybSys::RemoveEntity(const std::string& entityId) { if (Circuit->Components.find(entityId) != Circuit->Components.end()) { std::shared_ptr<ElectronicComponent> comp = Circuit->Components[entityId]; Circuit->Disconnect(entityId); Circuit->Components.erase(entityId); return true; } return false; } const std::string SimplECircuitCybSys::GetSystemInfo(const std::string& infoId) const { std::ostringstream oStr; if (infoId == "" || infoId == "CircuitSchema") { // create a schematic representation of the circuit in one text line std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply(); if (!powerSupply) return ""; std::shared_ptr<ElectronicComponentLead> posLead = powerSupply->GetPositiveLead(); std::shared_ptr<ElectronicComponentLead> negLead = powerSupply->GetNegativeLead(); if (!posLead->Connected() || !negLead->Connected()) return ""; int connectedComponents = 0; for (const auto& comp : Circuit->Components) { if (comp.second->GetConnectedLeadsCount() > 1) connectedComponents++; } std::vector<std::string> foundComponents; bool closedCircuit = Circuit->GetCircuitComponents(foundComponents); oStr << " (+)-"; for (std::string compName : foundComponents) { const auto& comp = Circuit->Components[compName]; const auto& sw = AsSwitch(comp); const auto& led = AsLed(comp); oStr << "-{" << compName; if (led && led->LitUp) oStr << "*"; if (sw && sw->Position == SwitchPosition::POS0) oStr << "o"; if (sw && sw->Position == SwitchPosition::POS1) oStr << "*"; oStr << "}-"; } if (closedCircuit) oStr << "-(-) {" << connectedComponents << "}"; } else if (infoId == "CircuitInfo") { // List circuit components and their state for (const auto& compPair : Circuit->Components) { const auto& component = compPair.second; if (component->GetConnectedLeadsCount() > 1) { oStr << compPair.first; const auto& sw = AsSwitch(component); if (sw) oStr << "#" << (int)sw->Position; const auto& led = AsLed(component); if (led && led->LitUp) oStr << "*"; if (component->BurntOut) { oStr << "[burnt out]"; } std::vector< std::shared_ptr<ElectronicComponentLead> > leads; component->GetLeads(leads); if (!leads.empty()) { oStr << "@"; } bool first = true; for (const auto& connLead : leads) { if (connLead->Connected()) { if (!first) oStr << ","; first = false; oStr << connLead->Name << ">" << connLead->Connections[0].Component << "." << connLead->Connections[0].Lead; } } oStr << " "; } } } std::string info = oStr.str(); return info; } void SimplECircuitCybSys::ReadComponentConfiguration(std::istringstream& iStr, std::shared_ptr<ElectronicComponent> comp) { std::shared_ptr<Led> led = AsLed(comp); if (led) { std::string ledType; iStr >> ledType; led->Type = GetLedType(ledType); if (!led->Type) { LogStream << "Unknown LED type: " << ledType << std::endl; FlushLog(LOG_ERROR); } } std::shared_ptr<Resistor> r = AsResistor(comp); if (r) { iStr >> r->Ohm >> r->Max_mW; } std::shared_ptr<Switch> sw = AsSwitch(comp); if (sw) { iStr >> sw->MaxVoltage_mV >> sw->MaxCurrent_mA; } std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp); if (powerSupply) { iStr >> powerSupply->Voltage_mV >> powerSupply->MaxCurrent_mA; } } std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::MakeComponent(const std::string& compType) { std::shared_ptr<ElectronicComponent> comp; if (compType == "PowerSupplyDC") { comp = std::make_shared<PowerSupplyDC>(); } else if (compType == "LED") { comp = std::make_shared<Led>(nullptr); } else if (compType == "Resistor") { comp = std::make_shared<Resistor>(); } else if (compType == "Switch") { comp = std::make_shared<Switch>(); } return comp; } extern "C" BOOST_SYMBOL_EXPORT SimplECircuitCybSys CyberSystem; SimplECircuitCybSys CyberSystem; } // namespace simplecircuit_cybsys
25.325662
129
0.639313
91f65d12c52f59ce95cf6cfcb87d5e478ce374e8
1,860
cpp
C++
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
4
2017-06-27T03:34:32.000Z
2018-03-12T01:30:25.000Z
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
null
null
null
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include <SDLInstance.h> #include <Window.h> #include <Vector4.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace SDLClassesTests { TEST_CLASS(SurfaceTest) { public: TEST_METHOD(SimpleDraw) { using namespace SDL; ::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Video | ::SDL::SDLInstance::InitParam::Events); Window wnd("HelloWorld", Rect<int32_t>{ Window::Center,Window::Center,1024,768 }, Window::WindowFlag::Null); auto& sur = wnd.GetWindowSurface(); sur.Clear(Color<uint8_t>{ 0,0,255,255 }); sur.Fill(Rect<int32_t>{ 50,50,150,150 }, Color<uint8_t>{ 0,255,0,255 }); std::vector<Rect<int32_t>> rects = { {750,350,200,200}, {0,350,200,200} }; sur.Fill(rects, Color<uint8_t>{ 255,0,0,255 }); wnd.UpdateWindowSurface(); sdl.Delay(500); sur.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) { return Color<uint8_t> { static_cast<uint8_t>(x % 255), static_cast<uint8_t>(y % 255), 128, 255 }; }); wnd.UpdateWindowSurface(); sdl.Delay(500); } TEST_METHOD(BlitTest) { using namespace SDL; ::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Everything); Window wnd("HelloWorld", Rect<int32_t>{ Window::Center, Window::Center, 1024, 768 }, Window::WindowFlag::Null); Surface sur1(512, 512, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); auto& wsur = wnd.GetWindowSurface(); sur1.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) { return Color<uint8_t> { static_cast<uint8_t>(x % 255), static_cast<uint8_t>(y % 255), 128, 255 }; }); wsur.BlitFrom(sur1, Rect<int32_t>{0, 0, 512, 512}, Rect<int32_t>{100, 100, 512, 512}); wnd.UpdateWindowSurface(); sdl.Delay(300); } }; }
25.833333
114
0.649462
91f82f77b5df8436fbb041aa30b09d76d3c6190c
1,254
hpp
C++
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:29 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Attribute #include "System/Attribute.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.AddComponentMenu class AddComponentMenu : public System::Attribute { public: // private System.String m_AddComponentMenu // Offset: 0x10 ::Il2CppString* m_AddComponentMenu; // private System.Int32 m_Ordering // Offset: 0x18 int m_Ordering; // public System.Void .ctor(System.String menuName) // Offset: 0x12E6D80 static AddComponentMenu* New_ctor(::Il2CppString* menuName); // public System.Void .ctor(System.String menuName, System.Int32 order) // Offset: 0x12E6DBC static AddComponentMenu* New_ctor(::Il2CppString* menuName, int order); }; // UnityEngine.AddComponentMenu } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::AddComponentMenu*, "UnityEngine", "AddComponentMenu"); #pragma pack(pop)
35.828571
90
0.698565
91fe1f3f1f9adda77b276622415cd80ae8fdd668
1,904
cpp
C++
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 "gui/menu-predicate.hh" #include "util/convenience.hh" namespace faint{ BoundMenuPred::BoundMenuPred(menu_item_id_t id, predicate_t predicate) : m_id(id), m_pred(predicate) {} void BoundMenuPred::Update(MenuReference& menu, const MenuFlags& flags) const{ bool enable = (flags.toolSelection && fl(MenuPred::TOOL_SELECTION, m_pred)) || (flags.rasterSelection && fl(MenuPred::RASTER_SELECTION, m_pred)) || (flags.objectSelection && fl(MenuPred::OBJECT_SELECTION, m_pred)) || (flags.hasObjects && fl(MenuPred::HAS_OBJECTS, m_pred)) || (flags.dirty && fl(MenuPred::DIRTY, m_pred)) || (flags.canUndo && fl(MenuPred::CAN_UNDO, m_pred)) || (flags.canRedo && fl(MenuPred::CAN_REDO, m_pred)) || (flags.numSelected > 1 && fl(MenuPred::MULTIPLE_SELECTED, m_pred)) || (flags.groupIsSelected && fl(MenuPred::GROUP_IS_SELECTED, m_pred)) || (flags.canMoveForward && fl(MenuPred::CAN_MOVE_FORWARD, m_pred)) || (flags.canMoveBackward && fl(MenuPred::CAN_MOVE_BACKWARD, m_pred)); menu.Enable(m_id, enable); } MenuPred::MenuPred(predicate_t predicate) : m_predicate(predicate) {} BoundMenuPred MenuPred::GetBound(menu_item_id_t id) const{ return BoundMenuPred(id, m_predicate); } }
37.333333
80
0.703256
91fe5ec015a859e4baf8fbfd0bede4e736578a86
1,417
hpp
C++
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021-2022 The Silkworm 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. */ #ifndef SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_ #define SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_ #include <silkworm/stagedsync/common.hpp> #include <silkworm/stagedsync/stage_senders/recovery_farm.hpp> namespace silkworm::stagedsync { class Senders final : public IStage { public: explicit Senders(NodeSettings* node_settings) : IStage(db::stages::kSendersKey, node_settings){}; ~Senders() override = default; StageResult forward(db::RWTxn& txn) final; StageResult unwind(db::RWTxn& txn, BlockNum to) final; StageResult prune(db::RWTxn& txn) final; std::vector<std::string> get_log_progress() final; bool stop() final; private: std::unique_ptr<recovery::RecoveryFarm> farm_{nullptr}; }; } // namespace silkworm::stagedsync #endif // SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_
32.953488
101
0.754411
6201580492f357eb45a9360ec184df9935f3f922
668
cpp
C++
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
17
2015-12-08T18:50:03.000Z
2022-03-16T01:23:20.000Z
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
null
null
null
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
6
2017-04-04T18:16:23.000Z
2020-06-28T11:07:22.000Z
#include <iostream> using namespace std; int main() { int T; bool first = false; cin >> T; while (T--) { if (first) printf("\n"); else first = true; string s; cin >> s; int i = 1; for (; i < s.length(); i++) { if (s.length() % i == 0) { bool ok = true; for (int j = 0; j < i && ok; j++) { for (int k = 1; k * i + j < s.length() && ok; k++) { ok = (s[j] == s[j + k * i]); } } if (ok) break; } } printf("%d\n", i); } return 0; }
23.034483
72
0.314371
6201cd24ce5a7f05c39a41e0ccc84a601d0df075
518
cc
C++
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int map(int (*fun)(const int*, const int), const int* array, const int len) { return fun(array, len); } int sum(const int* array, const int len) { int s = 0; for (int i=0; i<len; i++) s += array[i]; return s; } int prod(const int* array, const int len) { int s = 1; for (int i=0; i<len; i++) s *= array[i]; return s; } int main(int argc, char **argv) { int a[] = {1, 2, 3, 4}; cout << map(sum, a, 4) << endl; cout << map(prod, a, 4) << endl; return 0; }
14.388889
75
0.571429
620374730fb0995f6d6fc2b14626960db49fa7f4
1,061
cpp
C++
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
sw/e-paper-board/src/HttpFetcher.cpp
JakubAndrysek/E-paper-board-ESP32
538febf9775d31835b9f2fa61cd37ae120238fce
[ "MIT" ]
null
null
null
/** * @file HttpFetcher.cpp * @author Kuba Andrýsek (email@kubaandrysek.cz) * @brief Http Fetcher - získává data z internetu * @date 2022-04-10 * * @copyright Copyright (c) 2022 Kuba Andrýsek * */ #include "HttpFetcher.hpp" #include "exception/HttpRequestException.h" #include "exception/WifiConnException.h" #include <WiFi.h> #include <stdio.h> HttpFetcher::HttpFetcher() { } std::string HttpFetcher::getHTTPRequest(std::string url) { printf("HTTP GET: %s\n", url.c_str()); if (WiFi.status() != WL_CONNECTED) { throw WifiConnException(); } HTTPClient http; http.begin(url.c_str()); int httpResponseCode = http.GET(); std::string payload = "{}"; if (httpResponseCode > 0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); payload = http.getString().c_str(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); throw HttpRequestException(); } // Free resources http.end(); return payload; }
22.574468
58
0.638077
62042bb3c90a8a2a56ca9b18207acb9da501c99f
2,366
cc
C++
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
377
2018-10-24T08:34:21.000Z
2022-03-31T23:37:49.000Z
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
11
2020-01-22T13:34:46.000Z
2022-03-07T10:07:34.000Z
code/render/coregraphics/vertexlayout.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
23
2019-07-13T16:28:32.000Z
2022-03-20T09:00:59.000Z
//------------------------------------------------------------------------------ // vertexlayout.cc // (C)2017-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "coregraphics/config.h" #include "vertexlayout.h" #include "vertexsignaturepool.h" namespace CoreGraphics { VertexSignaturePool* layoutPool = nullptr; //------------------------------------------------------------------------------ /** */ const VertexLayoutId CreateVertexLayout(const VertexLayoutCreateInfo& info) { n_assert(info.comps.Size() > 0); VertexLayoutInfo loadInfo; Util::String sig; IndexT i; SizeT size = 0; for (i = 0; i < info.comps.Size(); i++) { sig.Append(info.comps[i].GetSignature()); info.comps[i].byteOffset += size; size += info.comps[i].GetByteSize(); } sig = Util::String::Sprintf("%s", sig.AsCharPtr()); Util::StringAtom atom(sig); loadInfo.signature = Util::StringAtom(sig); loadInfo.vertexByteSize = size; loadInfo.shader = Ids::InvalidId64; loadInfo.comps = info.comps; // reserve resource using signature as name, don't load again unless needed VertexLayoutId id = layoutPool->ReserveResource(atom, "render_system"); if (layoutPool->GetState(id) == Resources::Resource::Pending) layoutPool->LoadFromMemory(id, &loadInfo); return id; } //------------------------------------------------------------------------------ /** */ void DestroyVertexLayout(const VertexLayoutId id) { // FIXME: shutdownrace if(layoutPool->GetRefCount()) layoutPool->Unload(id.resourceId); } //------------------------------------------------------------------------------ /** */ const SizeT VertexLayoutGetSize(const VertexLayoutId id) { return layoutPool->GetVertexLayoutSize(id); } //------------------------------------------------------------------------------ /** */ const Util::Array<VertexComponent>& VertexLayoutGetComponents(const VertexLayoutId id) { return layoutPool->GetVertexComponents(id); } //------------------------------------------------------------------------------ /** */ const VertexLayoutId CreateCachedVertexLayout(const VertexLayoutId id, const ShaderProgramId shader) { return VertexLayoutId(); } } // CoreGraphics
27.511628
80
0.530854
6208788b1ab535205b5bf299020a212669e8d50f
1,897
cpp
C++
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
7
2018-10-31T08:22:17.000Z
2021-11-19T00:41:35.000Z
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
null
null
null
OOP_Video_Games_Data_Structures/Mario_Platformer/obstruction_sprite.cpp
estradjm/Class_Work
dc32f5d15ea53b3cace0a3bd873eab385bfb680d
[ "Apache-2.0" ]
1
2020-03-23T01:19:59.000Z
2020-03-23T01:19:59.000Z
#include "obstruction_sprite.h" #include "image_library.h" #include "image_sequence.h" namespace csis3700 { obstruction_sprite::obstruction_sprite(float initial_x, float initial_y, ALLEGRO_BITMAP *image) : sprite(initial_x, initial_y) { al_draw_bitmap(image, initial_x, initial_y, 0); if (image == image_library::get() -> get("ground.png")){ ground = new image_sequence; set_image_sequence(ground); ground -> add_image(image_library::get() -> get("ground.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("tube.png")){ tunnel = new image_sequence; set_image_sequence(tunnel); tunnel -> add_image(image_library::get() -> get("tube.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("coin.png")){ coin = new image_sequence; set_image_sequence(coin); coin -> add_image(image_library::get() -> get("coin.png"), 0.2); //is_coin() = true; } else if (image == image_library::get() -> get("castle.png")){ castle = new image_sequence; set_image_sequence(castle); castle -> add_image(image_library::get() -> get("castle.png"), 0.2); //is_coin() = false; } else if (image == image_library::get() -> get("brick.png")){ brick = new image_sequence; set_image_sequence(brick); brick -> add_image(image_library::get() -> get("brick.png"), 0.2); //is_coin() = false; } } vec2d obstruction_sprite::get_velocity() const { return vec2d(0,0); } void obstruction_sprite::set_velocity(const vec2d& v) { assert(false); } void obstruction_sprite::resolve(const collision& collision, sprite* other) { // do nothing, I am not an active participant in a collision } }
34.490909
132
0.600949
620df08526200389fea0d2478c6d953d8b88a02b
18,641
cc
C++
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
18
2019-12-29T17:27:55.000Z
2022-02-21T11:02:35.000Z
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
1
2021-07-22T12:04:53.000Z
2021-07-22T12:04:53.000Z
src/util.cc
unclearness/ugu
641c5170147091e82578fa6bcd84f3484172f487
[ "MIT" ]
2
2021-02-26T06:58:36.000Z
2021-07-05T12:24:09.000Z
/* * Copyright (C) 2019, unclearness * All rights reserved. */ #include <fstream> #include "ugu/util/io_util.h" #include "ugu/util/math_util.h" #include "ugu/util/raster_util.h" #include "ugu/util/rgbd_util.h" namespace { bool Depth2PointCloudImpl(const ugu::Image1f& depth, const ugu::Image3b& color, const ugu::Camera& camera, ugu::Mesh* point_cloud, bool with_texture, bool gl_coord) { if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } if (with_texture) { float depth_aspect_ratio = static_cast<float>(depth.cols) / static_cast<float>(depth.rows); float color_aspect_ratio = static_cast<float>(color.cols) / static_cast<float>(color.rows); const float aspect_ratio_diff_th{0.01f}; // 1% const float aspect_ratio_diff = std::abs(depth_aspect_ratio - color_aspect_ratio); if (aspect_ratio_diff > aspect_ratio_diff_th) { ugu::LOGE( "Depth2PointCloud depth aspect ratio %f and color aspect ratio %f " "are very " "different\n", depth_aspect_ratio, color_aspect_ratio); return false; } } point_cloud->Clear(); std::vector<Eigen::Vector3f> vertices; std::vector<Eigen::Vector3f> vertex_colors; for (int y = 0; y < camera.height(); y++) { for (int x = 0; x < camera.width(); x++) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } vertices.push_back(camera_p); if (with_texture) { Eigen::Vector2f uv(ugu::X2U(x, depth.cols), ugu::Y2V(y, depth.rows, false)); // nearest neighbor // todo: bilinear Eigen::Vector2i pixel_pos( static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))), static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false)))); Eigen::Vector3f pixel_color; const ugu::Vec3b& tmp_color = color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x()); pixel_color.x() = tmp_color[0]; pixel_color.y() = tmp_color[1]; pixel_color.z() = tmp_color[2]; vertex_colors.push_back(pixel_color); } } } // todo: add normal point_cloud->set_vertices(vertices); if (with_texture) { point_cloud->set_vertex_colors(vertex_colors); } return true; } bool Depth2MeshImpl(const ugu::Image1f& depth, const ugu::Image3b& color, const ugu::Camera& camera, ugu::Mesh* mesh, bool with_texture, bool with_vertex_color, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, const std::string& material_name, ugu::Image3f* point_cloud, ugu::Image3f* normal) { if (max_connect_z_diff < 0) { ugu::LOGE("Depth2Mesh max_connect_z_diff must be positive %f\n", max_connect_z_diff); return false; } if (x_step < 1) { ugu::LOGE("Depth2Mesh x_step must be positive %d\n", x_step); return false; } if (y_step < 1) { ugu::LOGE("Depth2Mesh y_step must be positive %d\n", y_step); return false; } if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2Mesh depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } if (with_texture) { float depth_aspect_ratio = static_cast<float>(depth.cols) / static_cast<float>(depth.rows); float color_aspect_ratio = static_cast<float>(color.cols) / static_cast<float>(color.rows); const float aspect_ratio_diff_th{0.01f}; // 1% const float aspect_ratio_diff = std::abs(depth_aspect_ratio - color_aspect_ratio); if (aspect_ratio_diff > aspect_ratio_diff_th) { ugu::LOGE( "Depth2Mesh depth aspect ratio %f and color aspect ratio %f are very " "different\n", depth_aspect_ratio, color_aspect_ratio); return false; } } mesh->Clear(); std::vector<Eigen::Vector2f> uvs; std::vector<Eigen::Vector3f> vertices; std::vector<Eigen::Vector3i> vertex_indices; std::vector<Eigen::Vector3f> vertex_colors; std::vector<std::pair<int, int>> vid2xy; std::vector<int> added_table(depth.cols * depth.rows, -1); int vertex_id{0}; for (int y = y_step; y < camera.height(); y += y_step) { for (int x = x_step; x < camera.width(); x += x_step) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } vertices.push_back(camera_p); vid2xy.push_back(std::make_pair(x, y)); Eigen::Vector2f uv(ugu::X2U(x, depth.cols), ugu::Y2V(y, depth.rows, false)); if (with_vertex_color) { // nearest neighbor // todo: bilinear Eigen::Vector2i pixel_pos( static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))), static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false)))); Eigen::Vector3f pixel_color; const ugu::Vec3b& tmp_color = color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x()); pixel_color.x() = tmp_color[0]; pixel_color.y() = tmp_color[1]; pixel_color.z() = tmp_color[2]; vertex_colors.push_back(pixel_color); } if (with_texture) { // +0.5f comes from mapping 0~1 to -0.5~width(or height)+0.5 // since uv 0 and 1 is pixel boundary at ends while pixel position is // the center of pixel uv.y() = 1.0f - uv.y(); uvs.emplace_back(uv); } added_table[y * camera.width() + x] = vertex_id; const int& current_index = vertex_id; const int& upper_left_index = added_table[(y - y_step) * camera.width() + (x - x_step)]; const int& upper_index = added_table[(y - y_step) * camera.width() + x]; const int& left_index = added_table[y * camera.width() + (x - x_step)]; const float upper_left_diff = std::abs(depth.at<float>(y - y_step, x - x_step) - d); const float upper_diff = std::abs(depth.at<float>(y - y_step, x) - d); const float left_diff = std::abs(depth.at<float>(y, x - x_step) - d); if (upper_left_index > 0 && upper_index > 0 && upper_left_diff < max_connect_z_diff && upper_diff < max_connect_z_diff) { vertex_indices.push_back( Eigen::Vector3i(upper_left_index, current_index, upper_index)); } if (upper_left_index > 0 && left_index > 0 && upper_left_diff < max_connect_z_diff && left_diff < max_connect_z_diff) { vertex_indices.push_back( Eigen::Vector3i(upper_left_index, left_index, current_index)); } vertex_id++; } } mesh->set_vertices(vertices); mesh->set_vertex_indices(vertex_indices); mesh->CalcNormal(); if (with_texture) { mesh->set_uv(uvs); mesh->set_uv_indices(vertex_indices); ugu::ObjMaterial material; color.copyTo(material.diffuse_tex); material.name = material_name; std::vector<ugu::ObjMaterial> materials; materials.push_back(material); mesh->set_materials(materials); std::vector<int> material_ids(vertex_indices.size(), 0); mesh->set_material_ids(material_ids); } if (with_vertex_color) { mesh->set_vertex_colors(vertex_colors); } if (point_cloud != nullptr) { ugu::Init(point_cloud, depth.cols, depth.rows, 0.0f); for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) { const auto& xy = vid2xy[i]; auto& p = point_cloud->at<ugu::Vec3f>(xy.second, xy.first); p[0] = mesh->vertices()[i][0]; p[1] = mesh->vertices()[i][1]; p[2] = mesh->vertices()[i][2]; } } if (normal != nullptr) { ugu::Init(normal, depth.cols, depth.rows, 0.0f); for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) { const auto& xy = vid2xy[i]; auto& n = normal->at<ugu::Vec3f>(xy.second, xy.first); n[0] = mesh->normals()[i][0]; n[1] = mesh->normals()[i][1]; n[2] = mesh->normals()[i][2]; } } return true; } } // namespace namespace ugu { bool Depth2PointCloud(const Image1f& depth, const Camera& camera, Image3f* point_cloud, bool gl_coord) { if (depth.cols != camera.width() || depth.rows != camera.height()) { ugu::LOGE( "Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are " "different\n", depth.cols, depth.rows, camera.width(), camera.height()); return false; } Init(point_cloud, depth.cols, depth.rows, 0.0f); #if defined(_OPENMP) && defined(UGU_USE_OPENMP) #pragma omp parallel for schedule(dynamic, 1) #endif for (int y = 0; y < camera.height(); y++) { for (int x = 0; x < camera.width(); x++) { const float& d = depth.at<float>(y, x); if (d < std::numeric_limits<float>::min()) { continue; } Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d); Eigen::Vector3f camera_p; camera.Unproject(image_p, &camera_p); if (gl_coord) { // flip y and z to align with OpenGL coordinate camera_p.y() = -camera_p.y(); camera_p.z() = -camera_p.z(); } Vec3f& pc = point_cloud->at<Vec3f>(y, x); pc[0] = camera_p[0]; pc[1] = camera_p[1]; pc[2] = camera_p[2]; } } return true; } bool Depth2PointCloud(const Image1f& depth, const Camera& camera, Mesh* point_cloud, bool gl_coord) { Image3b stub_color; return Depth2PointCloudImpl(depth, stub_color, camera, point_cloud, false, gl_coord); } bool Depth2PointCloud(const Image1f& depth, const Image3b& color, const Camera& camera, Mesh* point_cloud, bool gl_coord) { return Depth2PointCloudImpl(depth, color, camera, point_cloud, true, gl_coord); } bool Depth2Mesh(const Image1f& depth, const Camera& camera, Mesh* mesh, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, ugu::Image3f* point_cloud, ugu::Image3f* normal) { Image3b stub_color; return Depth2MeshImpl(depth, stub_color, camera, mesh, false, false, max_connect_z_diff, x_step, y_step, gl_coord, "illegal_material", point_cloud, normal); } bool Depth2Mesh(const Image1f& depth, const Image3b& color, const Camera& camera, Mesh* mesh, float max_connect_z_diff, int x_step, int y_step, bool gl_coord, const std::string& material_name, bool with_vertex_color, ugu::Image3f* point_cloud, ugu::Image3f* normal) { return Depth2MeshImpl(depth, color, camera, mesh, true, with_vertex_color, max_connect_z_diff, x_step, y_step, gl_coord, material_name, point_cloud, normal); } void WriteFaceIdAsText(const Image1i& face_id, const std::string& path) { std::ofstream ofs; ofs.open(path, std::ios::out); for (int y = 0; y < face_id.rows; y++) { for (int x = 0; x < face_id.cols; x++) { ofs << face_id.at<int>(y, x) << "\n"; } } ofs.flush(); } // FINDING OPTIMAL ROTATION AND TRANSLATION BETWEEN CORRESPONDING 3D POINTS // http://nghiaho.com/?page_id=671 Eigen::Affine3d FindRigidTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3d>& src, const std::vector<Eigen::Vector3d>& dst) { if (src.size() < 3 || src.size() != dst.size()) { return Eigen::Affine3d::Identity(); } Eigen::Vector3d src_centroid; src_centroid.setZero(); for (const auto& p : src) { src_centroid += p; } src_centroid /= static_cast<double>(src.size()); Eigen::Vector3d dst_centroid; dst_centroid.setZero(); for (const auto& p : dst) { dst_centroid += p; } dst_centroid /= static_cast<double>(dst.size()); Eigen::MatrixXd normed_src(3, src.size()); for (auto i = 0; i < src.size(); i++) { normed_src.col(i) = src[i] - src_centroid; } Eigen::MatrixXd normed_dst(3, dst.size()); for (auto i = 0; i < dst.size(); i++) { normed_dst.col(i) = dst[i] - dst_centroid; } Eigen::MatrixXd normed_dst_T = normed_dst.transpose(); Eigen::Matrix3d H = normed_src * normed_dst_T; // TODO: rank check Eigen::JacobiSVD<Eigen::Matrix3d> svd( H, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Matrix3d R = svd.matrixV() * svd.matrixU().transpose(); double det = R.determinant(); constexpr double assert_eps = 0.001; assert(std::abs(std::abs(det) - 1.0) < assert_eps); if (det < 0) { Eigen::JacobiSVD<Eigen::Matrix3d> svd2( R, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Matrix3d V = svd2.matrixV(); V.coeffRef(0, 2) *= -1.0; V.coeffRef(1, 2) *= -1.0; V.coeffRef(2, 2) *= -1.0; R = V * svd2.matrixU().transpose(); } assert(std::abs(det - 1.0) < assert_eps); Eigen::Vector3d t = dst_centroid - R * src_centroid; Eigen::Affine3d T = Eigen::Translation3d(t) * R; return T; } Eigen::Affine3d FindRigidTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3f>& src, const std::vector<Eigen::Vector3f>& dst) { std::vector<Eigen::Vector3d> src_d, dst_d; auto to_double = [](const std::vector<Eigen::Vector3f>& fvec, std::vector<Eigen::Vector3d>& dvec) { std::transform(fvec.begin(), fvec.end(), std::back_inserter(dvec), [](const Eigen::Vector3f& f) { return f.cast<double>(); }); }; to_double(src, src_d); to_double(dst, dst_d); return FindRigidTransformFrom3dCorrespondences(src_d, dst_d); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3d>& src, const std::vector<Eigen::Vector3d>& dst) { Eigen::MatrixXd src_(src.size(), 3); for (auto i = 0; i < src.size(); i++) { src_.row(i) = src[i]; } Eigen::MatrixXd dst_(dst.size(), 3); for (auto i = 0; i < dst.size(); i++) { dst_.row(i) = dst[i]; } return FindSimilarityTransformFrom3dCorrespondences(src_, dst_); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const std::vector<Eigen::Vector3f>& src, const std::vector<Eigen::Vector3f>& dst) { Eigen::MatrixXd src_(src.size(), 3); for (auto i = 0; i < src.size(); i++) { src_.row(i) = src[i].cast<double>(); } Eigen::MatrixXd dst_(dst.size(), 3); for (auto i = 0; i < dst.size(); i++) { dst_.row(i) = dst[i].cast<double>(); } return FindSimilarityTransformFrom3dCorrespondences(src_, dst_); } Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences( const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst) { Eigen::MatrixXd R; Eigen::MatrixXd t; Eigen::MatrixXd scale; Eigen::MatrixXd T; bool ret = FindSimilarityTransformFromPointCorrespondences(src, dst, R, t, scale, T); assert(R.rows() == 3 && R.cols() == 3); assert(t.rows() == 3 && t.cols() == 1); assert(T.rows() == 4 && T.cols() == 4); Eigen::Affine3d T_3d = Eigen::Affine3d::Identity(); if (ret) { T_3d = Eigen::Translation3d(t) * R * Eigen::Scaling(scale.diagonal()); } return T_3d; } bool FindSimilarityTransformFromPointCorrespondences( const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst, Eigen::MatrixXd& R, Eigen::MatrixXd& t, Eigen::MatrixXd& scale, Eigen::MatrixXd& T) { const size_t n_data = src.rows(); const size_t n_dim = src.cols(); if (n_data < 1 || n_dim < 1 || n_data < n_dim || src.rows() != dst.rows() || src.cols() != dst.cols()) { return false; } Eigen::VectorXd src_mean = src.colwise().mean(); Eigen::VectorXd dst_mean = dst.colwise().mean(); Eigen::MatrixXd src_demean = src.rowwise() - src_mean.transpose(); Eigen::MatrixXd dst_demean = dst.rowwise() - dst_mean.transpose(); Eigen::MatrixXd A = dst_demean.transpose() * src_demean / static_cast<double>(n_data); Eigen::VectorXd d = Eigen::VectorXd::Ones(n_dim); double det_A = A.determinant(); if (det_A < 0) { d.coeffRef(n_dim - 1, 0) = -1; } T = Eigen::MatrixXd::Identity(n_dim + 1, n_dim + 1); Eigen::JacobiSVD<Eigen::MatrixXd> svd( A, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::MatrixXd U = svd.matrixU(); Eigen::MatrixXd S = svd.singularValues().asDiagonal(); Eigen::MatrixXd V = svd.matrixV(); double det_U = U.determinant(); double det_V = V.determinant(); double det_orgR = det_U * det_V; constexpr double assert_eps = 0.001; assert(std::abs(std::abs(det_orgR) - 1.0) < assert_eps); int rank_A = static_cast<int>(svd.rank()); if (rank_A == 0) { // null matrix case return false; } else if (rank_A == n_dim - 1) { if (det_orgR > 0) { // Valid rotation case R = U * V.transpose(); } else { // Mirror (reflection) case double s = d.coeff(n_dim - 1, 0); d.coeffRef(n_dim - 1, 0) = -1; R = U * d.asDiagonal() * V.transpose(); d.coeffRef(n_dim - 1, 0) = s; } } else { // degenerate case R = U * d.asDiagonal() * V.transpose(); } assert(std::abs(R.determinant() - 1.0) < assert_eps); // Eigen::MatrixXd src_demean_cov = // (src_demean.adjoint() * src_demean) / double(n_data); double src_var = src_demean.rowwise().squaredNorm().sum() / double(n_data) + 1e-30; double uniform_scale = 1.0 / src_var * (S * d.asDiagonal()).trace(); // Question: Is it possible to estimate non-uniform scale? scale = Eigen::MatrixXd::Identity(R.rows(), R.cols()); scale *= uniform_scale; t = dst_mean - scale * R * src_mean; T.block(0, 0, n_dim, n_dim) = scale * R; T.block(0, n_dim, n_dim, 1) = t; return true; } } // namespace ugu
32.362847
80
0.612682
620eedbea94b69b261f8911bc2a684500a7554ec
2,874
hpp
C++
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
JinmingHu-MSFT/azure-sdk-for-cpp
933486385a54a5a09a7444dbd823425f145ad75a
[ "MIT" ]
1
2022-01-19T22:54:41.000Z
2022-01-19T22:54:41.000Z
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Client Certificate Credential and options. */ #pragma once #include "azure/identity/dll_import_export.hpp" #include <azure/core/credentials/credentials.hpp> #include <azure/core/credentials/token_credential_options.hpp> #include <azure/core/url.hpp> #include <memory> #include <string> namespace Azure { namespace Identity { namespace _detail { class TokenCredentialImpl; } // namespace _detail /** * @brief Options for client certificate authentication. * */ struct ClientCertificateCredentialOptions final : public Core::Credentials::TokenCredentialOptions { }; /** * @brief Client Certificate Credential authenticates with the Azure services using a Tenant ID, * Client ID and a client certificate. * */ class ClientCertificateCredential final : public Core::Credentials::TokenCredential { private: std::unique_ptr<_detail::TokenCredentialImpl> m_tokenCredentialImpl; Core::Url m_requestUrl; std::string m_requestBody; std::string m_tokenHeaderEncoded; std::string m_tokenPayloadStaticPart; void* m_pkey; public: /** * @brief Constructs a Client Secret Credential. * * @param tenantId Tenant ID. * @param clientId Client ID. * @param clientCertificatePath Client certificate path. * @param options Options for token retrieval. */ explicit ClientCertificateCredential( std::string const& tenantId, std::string const& clientId, std::string const& clientCertificatePath, Core::Credentials::TokenCredentialOptions const& options = Core::Credentials::TokenCredentialOptions()); /** * @brief Constructs a Client Secret Credential. * * @param tenantId Tenant ID. * @param clientId Client ID. * @param clientCertificatePath Client certificate path. * @param options Options for token retrieval. */ explicit ClientCertificateCredential( std::string const& tenantId, std::string const& clientId, std::string const& clientCertificatePath, ClientCertificateCredentialOptions const& options); /** * @brief Destructs `%ClientCertificateCredential`. * */ ~ClientCertificateCredential() override; /** * @brief Gets an authentication token. * * @param tokenRequestContext A context to get the token in. * @param context A context to control the request lifetime. * * @throw Azure::Core::Credentials::AuthenticationException Authentication error occurred. */ Core::Credentials::AccessToken GetToken( Core::Credentials::TokenRequestContext const& tokenRequestContext, Core::Context const& context) const override; }; }} // namespace Azure::Identity
29.628866
100
0.699026
620f429f3f495053b9bf74c5e30eff72907278fe
1,950
cc
C++
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibFormats/CastorObjects/src/CastorChannelCoder.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** \class CastorChannelCoder Container for ADC<->fQ conversion constants for HCAL/Castor QIE $Original author: ratnikov */ #include <iostream> #include "CalibFormats/CastorObjects/interface/CastorChannelCoder.h" #include "CalibFormats/CastorObjects/interface/QieShape.h" CastorChannelCoder::CastorChannelCoder(const float fOffset[16], const float fSlope[16]) { // [CapId][Range] for (int range = 0; range < 4; range++) { for (int capId = 0; capId < 4; capId++) { mOffset[capId][range] = fOffset[index(capId, range)]; mSlope[capId][range] = fSlope[index(capId, range)]; } } } double CastorChannelCoder::charge(const reco::castor::QieShape& fShape, int fAdc, int fCapId) const { int range = (fAdc >> 6) & 0x3; double charge = fShape.linearization(fAdc) / mSlope[fCapId][range] + mOffset[fCapId][range]; // std::cout << "CastorChannelCoder::charge-> " << fAdc << '/' << fCapId // << " result: " << charge << std::endl; return charge; } int CastorChannelCoder::adc(const reco::castor::QieShape& fShape, double fCharge, int fCapId) const { int adc = -1; //nothing found yet // search for the range for (int range = 0; range < 4; range++) { double qieCharge = (fCharge - mOffset[fCapId][range]) * mSlope[fCapId][range]; double qieChargeMax = fShape.linearization(32 * range + 31) + 0.5 * fShape.binSize(32 * range + 31); if (range == 3 && qieCharge > qieChargeMax) adc = 127; // overflow if (qieCharge > qieChargeMax) continue; // next range for (int bin = 32 * range; bin < 32 * (range + 1); bin++) { if (qieCharge < fShape.linearization(bin) + 0.5 * fShape.binSize(bin)) { adc = bin; break; } } if (adc >= 0) break; // found } if (adc < 0) adc = 0; // underflow // std::cout << "CastorChannelCoder::adc-> " << fCharge << '/' << fCapId // << " result: " << adc << std::endl; return adc; }
35.454545
108
0.620513
62118b04432af314622917fa5f785e503a02649d
3,583
cpp
C++
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
src/aten/src/ATen/native/npu/DiagKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020, Huawei Technologies.All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "ATen/native/npu/utils/OpAdapter.h" namespace at { namespace native { using namespace at::native::npu; namespace { SmallVector<int64_t, SIZE> diag_npu_output_size( const Tensor& self, int64_t diagonal) { SmallVector<int64_t, SIZE> shape; // input is 1-d if (self.dim() == 1) { shape.emplace_back(self.size(0) + diagonal); shape.emplace_back(self.size(0) + diagonal); return shape; } // input is 2-d int64_t m = self.size(0); // row int64_t n = self.size(1); // col if (m == n) { shape.emplace_back(m - diagonal); } else if (m < n) { shape.emplace_back(diagonal <= n - m ? m : n - diagonal); } else { shape.emplace_back(n - diagonal); } return shape; } } // namespace Tensor& diag_out_npu_nocheck(Tensor& result, const Tensor& self, int64_t diagonal) { // judging and executing the NPU operator // If input is a 1-D tensor, then returns a 2-D square tensor with the elements of input as the diagonal. // If input is a matrix (2-D tensor), then returns a 1-D tensor with the diagonal elements of input. OpCommand cmd; if (self.dim() == 1) { cmd.Name("Diag"); } else { cmd.Name("DiagPart"); } cmd.Input(self) .Output(result) .Attr("diagonal", diagonal) .Run(); return result; } Tensor& diag_out_npu(Tensor& result, const Tensor& self, int64_t diagonal) { TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ",self.dim()); diagonal = make_wrap_dim(diagonal, self.dim()); TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); auto outputSize = diag_npu_output_size(self, diagonal); OpPreparation::CheckOut( {self}, result, self, outputSize); OpPipeWithDefinedOut pipe; return pipe.CheckMemory({self}, {result}) .Func([&self, &diagonal](Tensor& result){diag_out_npu_nocheck(result, self, diagonal);}) .Call(result); } Tensor diag_npu(const Tensor& self, int64_t diagonal) { TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ",self.dim()); diagonal = make_wrap_dim(diagonal, self.dim()); TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); // calculate the output size auto outputSize = diag_npu_output_size(self, diagonal); // construct the output tensor of the NPU Tensor result = OpPreparation::ApplyTensor(self, outputSize); // calculate the output result of the NPU diag_out_npu_nocheck(result, self, diagonal); return result; } } // namespace native } // namespace at
34.12381
114
0.673179
6211bc69c80917d0126fa9ea034fd82551348b1d
203
cpp
C++
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
20
2021-04-02T04:30:08.000Z
2022-03-01T09:52:01.000Z
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
null
null
null
core/objects/utility/Dynamic.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
1
2022-01-22T11:44:52.000Z
2022-01-22T11:44:52.000Z
#include "objects/utility/Dynamic.h" NAMESPACE_SPH_BEGIN Dynamic::Dynamic() = default; /// Needs to be in .cpp to compile with clang, for some reason Dynamic::~Dynamic() = default; NAMESPACE_SPH_END
18.454545
62
0.748768
6212bc8831b2ba6f1511f39ce1398e5a6770e78c
5,734
cpp
C++
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
18
2015-05-24T20:28:46.000Z
2021-01-27T02:34:43.000Z
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
null
null
null
Codes/String/SuffixArrayShort.cpp
cjtoribio/Algorithms
78499613a9b018eb5e489307b14e31e5fe8227e3
[ "MIT" ]
4
2015-05-24T20:28:32.000Z
2021-01-30T04:04:55.000Z
typedef vector<int> VI; struct SuffixArray { int N; string A; VI SA, RA, LCP; SuffixArray(const string &B) : N(B.size()), A(B), SA(B.size()), RA(B.size()), LCP(B.size()) { for (int i = 0; i < N; ++i) SA[i] = i, RA[i] = A[i]; if(N == 1) RA[0] = 0; } void countingSort(int H) { auto vrank = [&](int i) { return SA[i]+H<N ? RA[SA[i]+H]+1 : 0; }; int maxRank = *max_element(RA.begin(), RA.end()); VI nSA(N); VI freq(maxRank + 2); for (int i = 0; i < N; ++i) freq[vrank(i)]++; for (int i = 1; i < freq.size(); ++i) freq[i] += freq[i-1]; for (int i = N-1, p, m; i >= 0; --i) nSA[--freq[vrank(i)]] = SA[i]; copy(nSA.begin(), nSA.end(), SA.begin()); } void buildSA() { VI nRA(N); for (int H = 1; H < N; H <<= 1) { countingSort(H); countingSort(0); int rank = nRA[SA[0]] = 0; for (int i = 1; i < N; ++i) { if (RA[SA[i]] != RA[SA[i - 1]]) rank++; else if (SA[i - 1] + H >= N || SA[i] + H >= N) rank++; else if (RA[SA[i] + H] != RA[SA[i - 1] + H]) rank++; nRA[SA[i]] = rank; } copy(nRA.begin(), nRA.end(), RA.begin()); } } void buildSA2(){ if (N == 1) { this->SA[0] = 0, this->RA[0] = 0; return; } VI T(N+3), SA(N+3); for(int i = 0; i < A.size(); ++i) T[i] = A[i]; suffixArray(T, SA, N, 256); for(int i = 0; i < N; ++i) RA[ SA[i] ] = i; for(int i = 0; i < N; ++i) this->SA[i] = SA[i]; } inline bool leq(int a1, int a2, int b1, int b2) { return (a1 < b1 || (a1 == b1 && a2 <= b2)); } inline bool leq(int a1, int a2, int a3, int b1, int b2, int b3) { return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3))); } static void radixPass(VI &a, VI &b, VI::iterator r, int n, int K) { VI c(K+1); for (int i = 0; i < n; i++) c[r[a[i]]]++; for (int i = 1; i <= K; i++) c[i] += c[i-1]; for (int i = n-1; i >= 0; --i) b[--c[r[a[i]]]] = a[i]; } void suffixArray(VI &T, VI &SA, int n, int K) { int n0 = (n + 2) / 3, n1 = (n + 1) / 3, n2 = n / 3, n02 = n0 + n2; VI R(n02+3), SA12(n02+3), R0(n0), SA0(n0); for (int i = 0, j = 0; i < n + (n0 - n1); i++) if (i % 3 != 0) R[j++] = i; radixPass(R, SA12, T.begin() + 2, n02, K); radixPass(SA12, R, T.begin() + 1, n02, K); radixPass(R, SA12, T.begin(), n02, K); int name = 0, c0 = -1, c1 = -1, c2 = -1; for (int i = 0; i < n02; i++) { if (T[SA12[i]] != c0 || T[SA12[i] + 1] != c1 || T[SA12[i] + 2] != c2) { name++; c0 = T[SA12[i]]; c1 = T[SA12[i] + 1]; c2 = T[SA12[i] + 2]; } if (SA12[i] % 3 == 1) { R[SA12[i] / 3] = name; } else { R[SA12[i] / 3 + n0] = name; } } if (name < n02) { suffixArray(R, SA12, n02, name); for (int i = 0; i < n02; i++) R[SA12[i]] = i + 1; } else for (int i = 0; i < n02; i++) SA12[R[i] - 1] = i; for (int i = 0, j = 0; i < n02; i++) if (SA12[i] < n0) R0[j++] = 3 * SA12[i]; radixPass(R0, SA0, T.begin(), n0, K); for (int p = 0, t = n0 - n1, k = 0; k < n; k++) { #define GetI() (SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2) int i = GetI(); // pos of current offset 12 suffix int j = SA0[p]; // pos of current offset 0 suffix if (SA12[t] < n0 ? // different compares for mod 1 and mod 2 suffixes leq(T[i], R[SA12[t] + n0], T[j], R[j / 3]) : leq(T[i], T[i + 1], R[SA12[t] - n0 + 1], T[j], T[j + 1], R[j / 3 + n0])) { // suffix from SA12 is smaller SA[k] = i; t++; if (t == n02) // done --- only SA0 suffixes left for (k++; p < n0; p++, k++) SA[k] = SA0[p]; } else { // suffix from SA0 is smaller SA[k] = j; p++; if (p == n0) // done --- only SA12 suffixes left for (k++; t < n02; t++, k++) SA[k] = GetI(); } } } void buildLCP() { for (int i = 0, k = 0; i < N; ++i) if (RA[i] != N - 1) { for (int j = SA[RA[i] + 1]; A[i + k] == A[j + k];) ++k; LCP[RA[i]] = k; if (k)--k; } } vector<VI> RLCP; void BuildRangeQueries() { int L = 31 - __builtin_clz(N) + 1; RLCP = vector<VI>(L, VI(N)); RLCP[0] = LCP; for (int i = 1; i < L; ++i) { for (int j = 0; j+(1<<(i-1)) < N; ++j) RLCP[i][j] = min(RLCP[i - 1][j], RLCP[i-1][j + (1<<(i-1))]); } } int lcp(int i, int j) { if (i == j) return N - SA[i]; int b = 31 - __builtin_clz(j-i); return min(RLCP[b][i], RLCP[b][j-(1<<b)]); } long long ops = 0; int match(int idx, const string &P){ for(int i = 0; i < P.size() && i + idx < N; ++i){ ops++; if(A[i+idx] != P[i]) return i; } return min(N-idx, (int)P.size()); } int cmp(int idx, const string &P){ int m = match(idx, P); if(m == P.size())return 0; if(m == N-idx)return -1; return A[idx+m] < P[m] ? -1 : (A[idx+m] == P[m] ? 0 : 1); } // MlogN (low constant) int lowerBound(const string &P){ int lo = 0, hi = N; while(lo < hi){ int mid = (lo + hi)/2; if(cmp(SA[mid], P) < 0) lo = mid+1; else hi = mid; } return lo; } // MlogN (low constant) int upperBound(const string &P){ int lo = 0, hi = N; while(lo < hi){ int mid = (lo + hi)/2; if(cmp(SA[mid], P) <= 0) lo = mid+1; else hi = mid; } return lo; } // M + logN (high constant) (slow in practice) int lowerBound2(const string &P, int deb = 0){ int lo = 0, hi = N; int k = match(SA[0], P), pm = 0; while(lo < hi){ int m = (lo + hi)/2; int rlcp= lcp(min(pm,m), max(m,pm)); if(rlcp > k && pm != m){ if(pm < m)lo = m+1; else hi = m; }else if(rlcp < k && pm != m){ if(pm < m)hi = m; else lo = m+1; }else{ while(k < P.size() && SA[m]+k < N && P[k] == A[SA[m]+k]) k++; if(k == P.size()) hi = m; else if(SA[m]+k == N) lo = m+1; else if(A[SA[m]+k] < P[k]) lo = m+1; else hi = m; pm = m; } } return lo; } };
26.423963
109
0.452389
62136af601e00088f3ae6ae1cf8da2f99a03591b
424
cpp
C++
Engine/Engine/Id.cpp
OpenOrigin/ExperimentalD3D11
509ae716e98d327c4ede7585f9b2c6fc9ffcdd73
[ "MIT" ]
null
null
null
Engine/Engine/Id.cpp
OpenOrigin/ExperimentalD3D11
509ae716e98d327c4ede7585f9b2c6fc9ffcdd73
[ "MIT" ]
null
null
null
Engine/Engine/Id.cpp
OpenOrigin/ExperimentalD3D11
509ae716e98d327c4ede7585f9b2c6fc9ffcdd73
[ "MIT" ]
null
null
null
#include "Engine.h" Id::Id(){ wchar_t string[40]; CoCreateGuid(&m_guid); StringFromGUID2(m_guid, string, 40); m_string = string; } Id::~Id(){ } std::wstring Id::toString() const{ return m_string; } const wchar_t * Id::toCString() const{ return m_string.c_str(); } bool Id::operator== (const Id &id) const{ return m_guid == id.m_guid; } bool Id::operator!= (const Id &id) const{ return m_guid != id.m_guid; }
14.133333
41
0.660377
62156bb4143b403e6bd804aa6095f394decd67db
39,862
cpp
C++
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
14
2017-02-17T17:12:40.000Z
2021-12-22T01:55:06.000Z
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
null
null
null
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
1
2019-10-15T08:10:10.000Z
2019-10-15T08:10:10.000Z
// // DefaultForwardRenderer.cpp // Kuplung // // Created by Sergey Petrov on 12/16/15. // Copyright © 2015 supudo.net. All rights reserved. // #include "DefaultForwardRenderer.hpp" #include "kuplung/utilities/stb/stb_image_write.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_decompose.hpp> DefaultForwardRenderer::DefaultForwardRenderer(ObjectsManager& managerObjects) : fileOutputImage(), managerObjects(managerObjects) { this->solidLight = new ModelFace_LightSource_Directional(); this->lightingPass_DrawMode = -1; this->GLSL_LightSourceNumber_Directional = 0; this->GLSL_LightSourceNumber_Point = 0; this->GLSL_LightSourceNumber_Spot = 0; } DefaultForwardRenderer::~DefaultForwardRenderer() { GLint maxColorAttachments = 1; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments); GLuint colorAttachment; GLenum att = GL_COLOR_ATTACHMENT0; for (colorAttachment = 0; colorAttachment < static_cast<GLuint>(maxColorAttachments); colorAttachment++) { att += colorAttachment; GLint param; GLuint objName; glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &param); if (GL_RENDERBUFFER == param) { glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &param); objName = reinterpret_cast<GLuint*>(&param)[0]; glDeleteRenderbuffers(1, &objName); } else if (GL_TEXTURE == param) { glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &param); objName = reinterpret_cast<GLuint*>(&param)[0]; glDeleteTextures(1, &objName); } } glDeleteProgram(this->shaderProgram); glDeleteFramebuffers(1, &this->renderFBO); glDeleteRenderbuffers(1, &this->renderRBO); for (size_t i = 0; i < this->mfLights_Directional.size(); i++) { delete this->mfLights_Directional[i]; } for (size_t i = 0; i < this->mfLights_Point.size(); i++) { delete this->mfLights_Point[i]; } for (size_t i = 0; i < this->mfLights_Spot.size(); i++) { delete this->mfLights_Spot[i]; } } void DefaultForwardRenderer::init() { this->GLSL_LightSourceNumber_Directional = 8; this->GLSL_LightSourceNumber_Point = 4; this->GLSL_LightSourceNumber_Spot = 4; this->Setting_RenderSkybox = false; this->initShaderProgram(); } bool DefaultForwardRenderer::initShaderProgram() { bool success = true; // vertex shader std::string shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.vert"; std::string shaderSourceVertex = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_vertex = shaderSourceVertex.c_str(); // tessellation control shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tcs"; std::string shaderSourceTCS = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_tess_control = shaderSourceTCS.c_str(); // tessellation evaluation shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tes"; std::string shaderSourceTES = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_tess_eval = shaderSourceTES.c_str(); // geometry shader shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.geom"; std::string shaderSourceGeometry = Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_geometry = shaderSourceGeometry.c_str(); // fragment shader - parts std::string shaderSourceFragment; std::vector<std::string> fragFiles = {"vars", "effects", "lights", "mapping", "shadow_mapping", "misc", "pbr"}; for (size_t i = 0; i < fragFiles.size(); i++) { shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face_" + fragFiles[i] + ".frag"; shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str()); } shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.frag"; shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str()); const char* shader_fragment = shaderSourceFragment.c_str(); this->shaderProgram = glCreateProgram(); bool shaderCompilation = true; shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_VERTEX_SHADER, shader_vertex); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_CONTROL_SHADER, shader_tess_control); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_EVALUATION_SHADER, shader_tess_eval); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_GEOMETRY_SHADER, shader_geometry); shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_FRAGMENT_SHADER, shader_fragment); if (!shaderCompilation) return false; glLinkProgram(this->shaderProgram); GLint programSuccess = GL_TRUE; glGetProgramiv(this->shaderProgram, GL_LINK_STATUS, &programSuccess); if (programSuccess != GL_TRUE) { Settings::Instance()->funcDoLog("[DefaultForwardRenderer] Error linking program " + std::to_string(this->shaderProgram) + "!"); Settings::Instance()->glUtils->printProgramLog(this->shaderProgram); return success = false; } else { #ifdef Def_Kuplung_OpenGL_4x glPatchParameteri(GL_PATCH_VERTICES, 3); #endif this->glGS_GeomDisplacementLocation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_displacementLocation"); this->glTCS_UseCullFace = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseCullFace"); this->glTCS_UseTessellation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseTessellation"); this->glTCS_TessellationSubdivision = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_TessellationSubdivision"); this->glFS_AlphaBlending = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_alpha"); this->glFS_CelShading = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_celShading"); this->glFS_CameraPosition = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_cameraPosition"); this->glVS_IsBorder = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_isBorder"); this->glFS_OutlineColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_outlineColor"); this->glFS_UIAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_UIAmbient"); this->glFS_GammaCoeficient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_gammaCoeficient"); this->glVS_MVPMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVPMatrix"); this->glFS_MMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ModelMatrix"); this->glVS_WorldMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_WorldMatrix"); this->glFS_MVMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVMatrix"); this->glVS_NormalMatrix = glGetUniformLocation(this->shaderProgram, "vs_normalMatrix"); this->glFS_ScreenResX = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResX"); this->glFS_ScreenResY = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResY"); this->glMaterial_ParallaxMapping = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_userParallaxMapping"); this->gl_ModelViewSkin = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_modelViewSkin"); this->glFS_solidSkin_materialColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_materialColor"); this->solidLight->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.inUse"); this->solidLight->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.direction"); this->solidLight->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.ambient"); this->solidLight->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.diffuse"); this->solidLight->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.specular"); this->solidLight->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthAmbient"); this->solidLight->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthDiffuse"); this->solidLight->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthSpecular"); // light - directional for (int i = 0; i < this->GLSL_LightSourceNumber_Directional; i++) { ModelFace_LightSource_Directional* f = new ModelFace_LightSource_Directional(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].direction").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Directional.push_back(f); } // light - point for (int i = 0; i < this->GLSL_LightSourceNumber_Point; i++) { ModelFace_LightSource_Point* f = new ModelFace_LightSource_Point(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].position").c_str()); f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].constant").c_str()); f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].linear").c_str()); f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].quadratic").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Point.push_back(f); } // light - spot for (int i = 0; i < this->GLSL_LightSourceNumber_Spot; i++) { ModelFace_LightSource_Spot* f = new ModelFace_LightSource_Spot(); f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].inUse").c_str()); f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].position").c_str()); f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].direction").c_str()); f->gl_CutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].cutOff").c_str()); f->gl_OuterCutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].outerCutOff").c_str()); f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].constant").c_str()); f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].linear").c_str()); f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].quadratic").c_str()); f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].ambient").c_str()); f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].diffuse").c_str()); f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].specular").c_str()); f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthAmbient").c_str()); f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthDiffuse").c_str()); f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthSpecular").c_str()); this->mfLights_Spot.push_back(f); } // material this->glMaterial_Refraction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.refraction"); this->glMaterial_SpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specularExp"); this->glMaterial_IlluminationModel = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.illumination_model"); this->glMaterial_HeightScale = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.heightScale"); this->glMaterial_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.ambient"); this->glMaterial_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.diffuse"); this->glMaterial_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specular"); this->glMaterial_Emission = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.emission"); this->glMaterial_SamplerAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_ambient"); this->glMaterial_SamplerDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_diffuse"); this->glMaterial_SamplerSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specular"); this->glMaterial_SamplerSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specularExp"); this->glMaterial_SamplerDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_dissolve"); this->glMaterial_SamplerBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_bump"); this->glMaterial_SamplerDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_displacement"); this->glMaterial_HasTextureAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_ambient"); this->glMaterial_HasTextureDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_diffuse"); this->glMaterial_HasTextureSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specular"); this->glMaterial_HasTextureSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specularExp"); this->glMaterial_HasTextureDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_dissolve"); this->glMaterial_HasTextureBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_bump"); this->glMaterial_HasTextureDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_displacement"); // effects - gaussian blur this->glEffect_GB_W = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_w"); this->glEffect_GB_Radius = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_radius"); this->glEffect_GB_Mode = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_mode"); // effects - bloom this->glEffect_Bloom_doBloom = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.doBloom"); this->glEffect_Bloom_WeightA = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightA"); this->glEffect_Bloom_WeightB = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightB"); this->glEffect_Bloom_WeightC = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightC"); this->glEffect_Bloom_WeightD = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightD"); this->glEffect_Bloom_Vignette = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_Vignette"); this->glEffect_Bloom_VignetteAtt = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_VignetteAtt"); // effects - tone mapping this->glEffect_ToneMapping_ACESFilmRec2020 = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ACESFilmRec2020"); } return success; } void DefaultForwardRenderer::createFBO() { glGenFramebuffers(1, &this->renderFBO); glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO); this->generateAttachmentTexture(false, false); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->renderTextureColorBuffer, 0); const int screenWidth = Settings::Instance()->SDL_DrawableSize_Width; const int screenHeight = Settings::Instance()->SDL_DrawableSize_Height; glGenRenderbuffers(1, &this->renderRBO); glBindRenderbuffer(GL_RENDERBUFFER, this->renderRBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, screenWidth, screenHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->renderRBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) Settings::Instance()->funcDoLog("[Kuplung-DefaultForwardRenderer] Framebuffer is not complete!"); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void DefaultForwardRenderer::generateAttachmentTexture(GLboolean depth, GLboolean stencil) { GLenum attachment_type = GL_RGB; if (!depth && !stencil) attachment_type = GL_RGB; else if (depth && !stencil) attachment_type = GL_DEPTH_COMPONENT; else if (!depth && stencil) attachment_type = GL_STENCIL_INDEX; int screenWidth = Settings::Instance()->SDL_DrawableSize_Width; int screenHeight = Settings::Instance()->SDL_DrawableSize_Height; glGenTextures(1, &this->renderTextureColorBuffer); glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer); if (!depth && !stencil) glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(attachment_type), screenWidth, screenHeight, 0, attachment_type, GL_UNSIGNED_BYTE, nullptr); else glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, screenWidth, screenHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } std::string DefaultForwardRenderer::renderImage(const FBEntity& file, std::vector<ModelFaceBase*>* meshModelFaces) { this->fileOutputImage = file; std::string endFile; int width = Settings::Instance()->SDL_DrawableSize_Width; int height = Settings::Instance()->SDL_DrawableSize_Height; this->createFBO(); glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO); this->renderSceneToFBO(meshModelFaces); glBindFramebuffer(GL_FRAMEBUFFER, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); unsigned char* pixels = new unsigned char[3 * width * height]; glBindFramebuffer(GL_READ_FRAMEBUFFER, this->renderFBO); glBlitFramebuffer(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, 0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); glBindFramebuffer(GL_FRAMEBUFFER, 0); unsigned char* line_tmp = new unsigned char[3 * width]; unsigned char* line_a = pixels; unsigned char* line_b = pixels + (3 * width * (height - 1)); while (line_a < line_b) { memcpy(line_tmp, line_a, width * 3); memcpy(line_a, line_b, width * 3); memcpy(line_b, line_tmp, width * 3); line_a += width * 3; line_b -= width * 3; } endFile = file.path + ".bmp"; stbi_write_bmp(endFile.c_str(), width, height, 3, pixels); delete[] pixels; delete[] line_tmp; return endFile; } void DefaultForwardRenderer::renderSceneToFBO(std::vector<ModelFaceBase*>* meshModelFaces) { this->matrixProjection = this->managerObjects.matrixProjection; this->matrixCamera = this->managerObjects.camera->matrixCamera; this->vecCameraPosition = this->managerObjects.camera->cameraPosition; this->uiAmbientLight = this->managerObjects.Setting_UIAmbientLight; this->lightingPass_DrawMode = this->managerObjects.Setting_LightingPass_DrawMode; glViewport(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); if (this->Setting_RenderSkybox) this->managerObjects.renderSkybox(); glUseProgram(this->shaderProgram); for (size_t i = 0; i < (*meshModelFaces).size(); i++) { ModelFaceData* mfd = (ModelFaceData*)(*meshModelFaces)[i]; glm::mat4 matrixModel = glm::mat4(1.0); matrixModel *= this->managerObjects.grid->matrixModel; matrixModel = glm::scale(matrixModel, glm::vec3(mfd->scaleX->point, mfd->scaleY->point, mfd->scaleZ->point)); matrixModel = glm::translate(matrixModel, glm::vec3(mfd->positionX->point, mfd->positionY->point, mfd->positionZ->point)); matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateX->point), glm::vec3(1, 0, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateY->point), glm::vec3(0, 1, 0)); matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateZ->point), glm::vec3(0, 0, 1)); matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0)); mfd->matrixGrid = this->managerObjects.grid->matrixModel; mfd->matrixProjection = this->matrixProjection; mfd->matrixCamera = this->matrixCamera; mfd->matrixModel = matrixModel; mfd->Setting_ModelViewSkin = this->managerObjects.viewModelSkin; mfd->lightSources = this->managerObjects.lightSources; mfd->setOptionsFOV(this->managerObjects.Setting_FOV); mfd->setOptionsOutlineColor(this->managerObjects.Setting_OutlineColor); mfd->setOptionsOutlineThickness(this->managerObjects.Setting_OutlineThickness); mfd->setOptionsSelected(0); glm::mat4 mvpMatrix = this->matrixProjection * this->matrixCamera * matrixModel; glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrix)); glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(matrixModel)); glm::mat4 matrixModelView = this->matrixCamera * matrixModel; glUniformMatrix4fv(this->glFS_MVMatrix, 1, GL_FALSE, glm::value_ptr(matrixModelView)); glm::mat3 matrixNormal = glm::inverseTranspose(glm::mat3(this->matrixCamera * matrixModel)); glUniformMatrix3fv(this->glVS_NormalMatrix, 1, GL_FALSE, glm::value_ptr(matrixNormal)); glm::mat4 matrixWorld = matrixModel; glUniformMatrix4fv(this->glVS_WorldMatrix, 1, GL_FALSE, glm::value_ptr(matrixWorld)); // blending if (mfd->meshModel.ModelMaterial.Transparency < 1.0f || mfd->Setting_Alpha < 1.0f) { glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); if (mfd->meshModel.ModelMaterial.Transparency < 1.0f) glUniform1f(this->glFS_AlphaBlending, mfd->meshModel.ModelMaterial.Transparency); else glUniform1f(this->glFS_AlphaBlending, mfd->Setting_Alpha); } else { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDisable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUniform1f(this->glFS_AlphaBlending, 1.0); } // tessellation glUniform1i(this->glTCS_UseCullFace, mfd->Setting_UseCullFace); glUniform1i(this->glTCS_UseTessellation, mfd->Setting_UseTessellation); glUniform1i(this->glTCS_TessellationSubdivision, mfd->Setting_TessellationSubdivision); // cel-shading glUniform1i(this->glFS_CelShading, mfd->Setting_CelShading); // camera position glUniform3f(this->glFS_CameraPosition, this->vecCameraPosition.x, this->vecCameraPosition.y, this->vecCameraPosition.z); // screen size glUniform1f(this->glFS_ScreenResX, Settings::Instance()->SDL_DrawableSize_Width); glUniform1f(this->glFS_ScreenResY, Settings::Instance()->SDL_DrawableSize_Height); // Outline color glUniform3f(this->glFS_OutlineColor, mfd->getOptionsOutlineColor().r, mfd->getOptionsOutlineColor().g, mfd->getOptionsOutlineColor().b); // ambient color for editor glUniform3f(this->glFS_UIAmbient, this->uiAmbientLight.r, this->uiAmbientLight.g, this->uiAmbientLight.b); // geometry shader displacement glUniform3f(this->glGS_GeomDisplacementLocation, mfd->displaceX->point, mfd->displaceY->point, mfd->displaceZ->point); // mapping glUniform1i(this->glMaterial_ParallaxMapping, mfd->Setting_ParallaxMapping); // gamma correction glUniform1f(this->glFS_GammaCoeficient, this->managerObjects.Setting_GammaCoeficient); // render skin glUniform1i(this->gl_ModelViewSkin, mfd->Setting_ModelViewSkin); glUniform3f(this->glFS_solidSkin_materialColor, mfd->solidLightSkin_MaterialColor.r, mfd->solidLightSkin_MaterialColor.g, mfd->solidLightSkin_MaterialColor.b); glUniform1i(this->solidLight->gl_InUse, 1); glUniform3f(this->solidLight->gl_Direction, this->managerObjects.SolidLight_Direction.x, this->managerObjects.SolidLight_Direction.y, this->managerObjects.SolidLight_Direction.z); glUniform3f(this->solidLight->gl_Ambient, this->managerObjects.SolidLight_Ambient.r, this->managerObjects.SolidLight_Ambient.g, this->managerObjects.SolidLight_Ambient.b); glUniform3f(this->solidLight->gl_Diffuse, this->managerObjects.SolidLight_Diffuse.r, this->managerObjects.SolidLight_Diffuse.g, this->managerObjects.SolidLight_Diffuse.b); glUniform3f(this->solidLight->gl_Specular, this->managerObjects.SolidLight_Specular.r, this->managerObjects.SolidLight_Specular.g, this->managerObjects.SolidLight_Specular.b); glUniform1f(this->solidLight->gl_StrengthAmbient, this->managerObjects.SolidLight_Ambient_Strength); glUniform1f(this->solidLight->gl_StrengthDiffuse, this->managerObjects.SolidLight_Diffuse_Strength); glUniform1f(this->solidLight->gl_StrengthSpecular, this->managerObjects.SolidLight_Specular_Strength); // lights size_t lightsCount_Directional = 0, lightsCount_Point = 0, lightsCount_Spot = 0; for (size_t j = 0; j < mfd->lightSources.size(); j++) { Light* light = mfd->lightSources[j]; assert(light->type == LightSourceType_Directional || light->type == LightSourceType_Point || light->type == LightSourceType_Spot); switch (light->type) { case LightSourceType_Directional: { if (lightsCount_Directional < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional)) { ModelFace_LightSource_Directional* f = this->mfLights_Directional[lightsCount_Directional]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Directional += 1; } break; } case LightSourceType_Point: { if (lightsCount_Point < static_cast<size_t>(this->GLSL_LightSourceNumber_Point)) { ModelFace_LightSource_Point* f = this->mfLights_Point[lightsCount_Point]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z); // factors glUniform1f(f->gl_Constant, light->lConstant->point); glUniform1f(f->gl_Linear, light->lLinear->point); glUniform1f(f->gl_Quadratic, light->lQuadratic->point); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Point += 1; } break; } case LightSourceType_Spot: { if (lightsCount_Spot < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot)) { ModelFace_LightSource_Spot* f = this->mfLights_Spot[lightsCount_Spot]; glUniform1i(f->gl_InUse, 1); // light glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z); glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z); // cutoff glUniform1f(f->gl_CutOff, glm::cos(glm::radians(light->lCutOff->point))); glUniform1f(f->gl_OuterCutOff, glm::cos(glm::radians(light->lOuterCutOff->point))); // factors glUniform1f(f->gl_Constant, light->lConstant->point); glUniform1f(f->gl_Linear, light->lLinear->point); glUniform1f(f->gl_Quadratic, light->lQuadratic->point); // color glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b); glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b); glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b); // light factors glUniform1f(f->gl_StrengthAmbient, light->ambient->strength); glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength); glUniform1f(f->gl_StrengthSpecular, light->specular->strength); lightsCount_Spot += 1; } break; } } } for (size_t j = lightsCount_Directional; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional); j++) { glUniform1i(this->mfLights_Directional[j]->gl_InUse, 0); } for (size_t j = lightsCount_Point; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Point); j++) { glUniform1i(this->mfLights_Point[j]->gl_InUse, 0); } for (size_t j = lightsCount_Spot; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot); j++) { glUniform1i(this->mfLights_Spot[j]->gl_InUse, 0); } // material glUniform1f(this->glMaterial_Refraction, mfd->Setting_MaterialRefraction->point); glUniform1f(this->glMaterial_SpecularExp, mfd->Setting_MaterialSpecularExp->point); glUniform1i(this->glMaterial_IlluminationModel, static_cast<int>(mfd->materialIlluminationModel)); glUniform1f(this->glMaterial_HeightScale, mfd->displacementHeightScale->point); glUniform3f(this->glMaterial_Ambient, mfd->materialAmbient->color.r, mfd->materialAmbient->color.g, mfd->materialAmbient->color.b); glUniform3f(this->glMaterial_Diffuse, mfd->materialDiffuse->color.r, mfd->materialDiffuse->color.g, mfd->materialDiffuse->color.b); glUniform3f(this->glMaterial_Specular, mfd->materialSpecular->color.r, mfd->materialSpecular->color.g, mfd->materialSpecular->color.b); glUniform3f(this->glMaterial_Emission, mfd->materialEmission->color.r, mfd->materialEmission->color.g, mfd->materialEmission->color.b); if (mfd->vboTextureAmbient > 0 && mfd->meshModel.ModelMaterial.TextureAmbient.UseTexture) { glUniform1i(this->glMaterial_HasTextureAmbient, 1); glUniform1i(this->glMaterial_SamplerAmbient, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureAmbient); } else glUniform1i(this->glMaterial_HasTextureAmbient, 0); if (mfd->vboTextureDiffuse > 0 && mfd->meshModel.ModelMaterial.TextureDiffuse.UseTexture) { glUniform1i(this->glMaterial_HasTextureDiffuse, 1); glUniform1i(this->glMaterial_SamplerDiffuse, 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDiffuse); } else glUniform1i(this->glMaterial_HasTextureDiffuse, 0); if (mfd->vboTextureSpecular > 0 && mfd->meshModel.ModelMaterial.TextureSpecular.UseTexture) { glUniform1i(this->glMaterial_HasTextureSpecular, 1); glUniform1i(this->glMaterial_SamplerSpecular, 2); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecular); } else glUniform1i(this->glMaterial_HasTextureSpecular, 0); if (mfd->vboTextureSpecularExp > 0 && mfd->meshModel.ModelMaterial.TextureSpecularExp.UseTexture) { glUniform1i(this->glMaterial_HasTextureSpecularExp, 1); glUniform1i(this->glMaterial_SamplerSpecularExp, 3); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecularExp); } else glUniform1i(this->glMaterial_HasTextureSpecularExp, 0); if (mfd->vboTextureDissolve > 0 && mfd->meshModel.ModelMaterial.TextureDissolve.UseTexture) { glUniform1i(this->glMaterial_HasTextureDissolve, 1); glUniform1i(this->glMaterial_SamplerDissolve, 4); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDissolve); } else glUniform1i(this->glMaterial_HasTextureDissolve, 0); if (mfd->vboTextureBump > 0 && mfd->meshModel.ModelMaterial.TextureBump.UseTexture) { glUniform1i(this->glMaterial_HasTextureBump, 1); glUniform1i(this->glMaterial_SamplerBump, 5); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureBump); } else glUniform1i(this->glMaterial_HasTextureBump, 0); if (mfd->vboTextureDisplacement > 0 && mfd->meshModel.ModelMaterial.TextureDisplacement.UseTexture) { glUniform1i(this->glMaterial_HasTextureDisplacement, 1); glUniform1i(this->glMaterial_SamplerDisplacement, 6); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDisplacement); } else glUniform1i(this->glMaterial_HasTextureDisplacement, 0); // effects - gaussian blur glUniform1i(this->glEffect_GB_Mode, mfd->Effect_GBlur_Mode - 1); glUniform1f(this->glEffect_GB_W, mfd->Effect_GBlur_Width->point); glUniform1f(this->glEffect_GB_Radius, mfd->Effect_GBlur_Radius->point); // effects - bloom // TODO: Bloom effect glUniform1i(this->glEffect_Bloom_doBloom, mfd->Effect_Bloom_doBloom); glUniform1f(this->glEffect_Bloom_WeightA, mfd->Effect_Bloom_WeightA); glUniform1f(this->glEffect_Bloom_WeightB, mfd->Effect_Bloom_WeightB); glUniform1f(this->glEffect_Bloom_WeightC, mfd->Effect_Bloom_WeightC); glUniform1f(this->glEffect_Bloom_WeightD, mfd->Effect_Bloom_WeightD); glUniform1f(this->glEffect_Bloom_Vignette, mfd->Effect_Bloom_Vignette); glUniform1f(this->glEffect_Bloom_VignetteAtt, mfd->Effect_Bloom_VignetteAtt); // effects - tone mapping glUniform1i(this->glEffect_ToneMapping_ACESFilmRec2020, mfd->Effect_ToneMapping_ACESFilmRec2020); glUniform1f(this->glVS_IsBorder, 0.0); // model draw glUniform1f(this->glVS_IsBorder, 0.0); glm::mat4 mtxModel = glm::scale(matrixModel, glm::vec3(1.0, 1.0, 1.0)); glm::mat4 mvpMatrixDraw = this->matrixProjection * this->matrixCamera * mtxModel; glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrixDraw)); glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(mtxModel)); mfd->vertexSphereVisible = this->managerObjects.Setting_VertexSphere_Visible; mfd->vertexSphereRadius = this->managerObjects.Setting_VertexSphere_Radius; mfd->vertexSphereSegments = this->managerObjects.Setting_VertexSphere_Segments; mfd->vertexSphereColor = this->managerObjects.Setting_VertexSphere_Color; mfd->vertexSphereIsSphere = this->managerObjects.Setting_VertexSphere_IsSphere; mfd->vertexSphereShowWireframes = this->managerObjects.Setting_VertexSphere_ShowWireframes; mfd->renderModel(true); } glUseProgram(0); }
57.027182
251
0.736365
6217a1836b7e95e4c902fa7d2642aa70a2c8edc7
4,122
cpp
C++
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_block_matching.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
#include <opencv2/opencv.hpp> const char *windowDisparity = "Disparity"; cv::Mat imgLeft; cv::Mat imgRight; cv::Mat imgDisparity16S; cv::Mat imgDisparity8U; int ndisparities= 16*5; int SADWindowSize= 21; double minVal; double maxVal; cv::StereoBM sbm( cv::StereoBM::NARROW_PRESET,ndisparities,SADWindowSize ); void on_trackbar( int, void* ) { std::cout <<"ndisparities: " <<16*ndisparities <<std::endl; std::cout <<"SADWindowSize: " <<SADWindowSize <<std::endl; if(SADWindowSize%2 !=0 && SADWindowSize>4) { sbm.init(cv::StereoBM::NARROW_PRESET,16*ndisparities ,SADWindowSize); sbm( imgLeft, imgRight, imgDisparity16S, CV_16S ); minMaxLoc( imgDisparity16S, &minVal, &maxVal ); imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal)); cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL ); cv::imshow( windowDisparity, imgDisparity8U ); } } //For an in-depth discussion of the block matching algorithm, see pages 438-444 of Learning OpenCV. //https://github.com/opencv/opencv/blob/2.4/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp int disparity_map_using_sbm_example(int argc, char ** argv) { //char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"}; char* n_argv[] = { "stereo_block_matching", "rect_left01.jpg", "rect_right01.jpg"}; int length = sizeof(n_argv)/sizeof(n_argv[0]); argc=length; argv = n_argv; imgLeft = cv::imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE ); imgRight = cv::imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE ); //-- And create the image in which we will save our disparities imgDisparity16S = cv::Mat( imgLeft.rows, imgLeft.cols, CV_16S ); imgDisparity8U = cv::Mat( imgLeft.rows, imgLeft.cols, CV_8UC1 ); //-- 2. Call the constructor for StereoBM //ndisparities must be multiple of 8 //-- 3. Calculate the disparity image sbm( imgLeft, imgRight, imgDisparity16S, CV_16S ); //-- Check its extreme values minMaxLoc( imgDisparity16S, &minVal, &maxVal ); printf("Min disp: %f Max value: %f \n", minVal, maxVal); //-- 4. Display it as a CV_8UC1 image imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal)); cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL ); cv::imshow( windowDisparity, imgDisparity8U ); //Create trackbars in "Control" window ndisparities=ndisparities/16; cv::createTrackbar("ndisparities (multipled by 16)", windowDisparity, &ndisparities, 20,on_trackbar); //ndisparities (0 - 20) cv::createTrackbar("SADWindowSize (must be odd, be within 5..255) ", windowDisparity, &SADWindowSize, 255,on_trackbar); //SADWindowSize(0 - 100) //-- 5. Save the image //imwrite("SBM_sample.png", imgDisparity16S); // cv::reprojectImageTo3D(imgDisparity8U,) cv::waitKey(0); return 0; } void disparity_map_using_sgbm_example(int argc, char ** argv) { char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"}; int length = sizeof(n_argv)/sizeof(n_argv[0]); argc=length; argv = n_argv; cv::Mat img1, img2, g1, g2; cv::Mat disp, disp8; img1 = cv::imread(argv[1]); img2 = cv::imread(argv[2]); cv::cvtColor(img1, g1, CV_BGR2GRAY); cv::cvtColor(img2, g2, CV_BGR2GRAY); cv::StereoSGBM sbm; sbm.SADWindowSize = 3; sbm.numberOfDisparities = 144; sbm.preFilterCap = 63; sbm.minDisparity = -39; sbm.uniquenessRatio = 10; sbm.speckleWindowSize = 100; sbm.speckleRange = 32; sbm.disp12MaxDiff = 1; sbm.fullDP = false; sbm.P1 = 216; sbm.P2 = 864; sbm(g1, g2, disp); normalize(disp, disp8, 0, 255, CV_MINMAX, CV_8U); imshow("left", img1); imshow("right", img2); imshow("disp", disp8); cv::waitKey(0); // cv::finds } int main(int argc, char** argv) { // disparity_map_using_sgbm_example(argc, argv); disparity_map_using_sbm_example(argc, argv); }
25.288344
148
0.673459
6218b5bec030cb10643d1c699b703620e70da83f
950
cpp
C++
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
1
2019-05-01T04:51:14.000Z
2019-05-01T04:51:14.000Z
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
mingyuefly/geekTimeCode
d97c5f29a429ac9cc7289ac34e049ea43fa58822
[ "MIT" ]
null
null
null
// // main.cpp // dynamicPragrammingPractice // // Created by Gguomingyue on 2019/2/20. // Copyright © 2019 Gmingyue. All rights reserved. // #include <iostream> using namespace std; static char a[6] = {'m', 'i', 't', 'c', 'm', 'u'}; static char b[6] = {'m', 't', 'a', 'c', 'n', 'u'}; static int n = 6; static int m = 6; static int minDist = 100; void lowestLD(int i, int j, int edist) { if (i == n || j == m) { if (i < n) { edist += (n - i); } if (j < m) { edist += (m - j); } if (edist < minDist) { minDist = edist; } return; } if (a[i] == b[j]) { lowestLD(i+1, j+1, edist); } else { lowestLD(i+1, j, edist+1); lowestLD(i, j+1, edist+1); lowestLD(i+1, j+1, edist+1); } } int main(int argc, const char * argv[]) { lowestLD(0, 0, 0); cout << minDist << endl; return 0; }
19.791667
51
0.458947
6220912b9a447006b2176693483116c5a94863e7
4,939
cpp
C++
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
5
2021-12-22T02:43:41.000Z
2022-03-20T19:18:44.000Z
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
1
2022-01-11T06:18:04.000Z
2022-01-11T06:18:04.000Z
src/xbox/xbox_interface.cpp
abaire/xbdm_gdb_bridge
06440896f1f2863cd81cedd3e2bcae1efc32f286
[ "Unlicense" ]
null
null
null
#include "xbox_interface.h" #include <unistd.h> #include <boost/asio/dispatch.hpp> #include <cassert> #include <iostream> #include <utility> #include "gdb/gdb_transport.h" #include "net/delegating_server.h" #include "net/select_thread.h" #include "notification/xbdm_notification.h" #include "util/logging.h" #include "xbox/bridge/gdb_bridge.h" #include "xbox/debugger/xbdm_debugger.h" #include "xbox/xbdm_context.h" XBOXInterface::XBOXInterface(std::string name, IPAddress xbox_address) : name_(std::move(name)), xbox_address_(std::move(xbox_address)) {} void XBOXInterface::Start() { Stop(); select_thread_ = std::make_shared<SelectThread>(); xbdm_context_ = std::make_shared<XBDMContext>(name_, xbox_address_, select_thread_); select_thread_->Start(); } void XBOXInterface::Stop() { if (select_thread_) { select_thread_->Stop(); select_thread_.reset(); } if (xbdm_context_) { xbdm_context_->Shutdown(); xbdm_context_.reset(); } } bool XBOXInterface::ReconnectXBDM() { if (!xbdm_context_) { return false; } return xbdm_context_->Reconnect(); } bool XBOXInterface::AttachDebugger() { if (!xbdm_debugger_) { xbdm_debugger_ = std::make_shared<XBDMDebugger>(xbdm_context_); } return xbdm_debugger_->Attach(); } void XBOXInterface::DetachDebugger() { if (!xbdm_debugger_) { return; } xbdm_debugger_->Shutdown(); xbdm_debugger_.reset(); } bool XBOXInterface::StartGDBServer(const IPAddress& address) { StopGDBServer(); gdb_executor_ = std::make_shared<boost::asio::thread_pool>(1); if (!xbdm_debugger_) { xbdm_debugger_ = std::make_shared<XBDMDebugger>(xbdm_context_); } gdb_bridge_ = std::make_shared<GDBBridge>(xbdm_context_, xbdm_debugger_); gdb_server_ = std::make_shared<DelegatingServer>( name_ + "__gdb_server", [this](int sock, IPAddress& address) { this->OnGDBClientConnected(sock, address); }); select_thread_->AddConnection(gdb_server_); return gdb_server_->Listen(address); } void XBOXInterface::StopGDBServer() { if (gdb_server_) { gdb_server_->Close(); gdb_server_.reset(); } if (gdb_bridge_) { gdb_bridge_->Stop(); gdb_bridge_.reset(); } if (gdb_executor_) { gdb_executor_->stop(); gdb_executor_->join(); gdb_executor_.reset(); } } bool XBOXInterface::GetGDBListenAddress(IPAddress& ret) const { if (!gdb_server_) { return false; } ret = gdb_server_->Address(); return true; } bool XBOXInterface::StartNotificationListener(const IPAddress& address) { if (!xbdm_context_) { return false; } return xbdm_context_->StartNotificationListener(address); } void XBOXInterface::AttachDebugNotificationHandler() { if (debug_notification_handler_id_ > 0) { return; } debug_notification_handler_id_ = xbdm_context_->RegisterNotificationHandler( [](const std::shared_ptr<XBDMNotification>& notification) { std::cout << *notification << std::endl; }); } void XBOXInterface::DetachDebugNotificationHandler() { if (debug_notification_handler_id_ <= 0) { return; } xbdm_context_->UnregisterNotificationHandler(debug_notification_handler_id_); debug_notification_handler_id_ = 0; } std::shared_ptr<RDCPProcessedRequest> XBOXInterface::SendCommandSync( std::shared_ptr<RDCPProcessedRequest> command) { assert(xbdm_context_); return xbdm_context_->SendCommandSync(std::move(command)); } std::future<std::shared_ptr<RDCPProcessedRequest>> XBOXInterface::SendCommand( std::shared_ptr<RDCPProcessedRequest> command) { assert(xbdm_context_); return xbdm_context_->SendCommand(std::move(command)); } void XBOXInterface::OnGDBClientConnected(int sock, IPAddress& address) { assert(gdb_bridge_); if (gdb_bridge_->HasGDBClient()) { LOG_XBDM(warning) << "Disallowing additional GDB connection from " << address; shutdown(sock, SHUT_RDWR); close(sock); return; } LOG_XBDM(trace) << "GDB channel established from " << address; auto transport = std::make_shared<GDBTransport>( "GDB", sock, address, [this](const std::shared_ptr<GDBPacket>& packet) { this->OnGDBPacketReceived(packet); }); // Bounce to the executor so the select thread is not blocked by any attempt // to communicate with XBDM. assert(gdb_executor_); boost::asio::dispatch(*gdb_executor_, [this, transport]() mutable { this->xbdm_debugger_->Attach(); this->xbdm_debugger_->HaltAll(); this->select_thread_->AddConnection(transport); this->gdb_bridge_->AddTransport(transport); }); } void XBOXInterface::OnGDBPacketReceived( const std::shared_ptr<GDBPacket>& packet) { assert(gdb_executor_); boost::asio::dispatch(*gdb_executor_, [this, packet]() mutable { this->DispatchGDBPacket(packet); }); } void XBOXInterface::DispatchGDBPacket( const std::shared_ptr<GDBPacket>& packet) { gdb_bridge_->HandlePacket(*packet); }
26.411765
79
0.715125
6223b18bd74bb8dd8120c7c358f1f1422a950de1
4,420
hpp
C++
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/IO/FileInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.IO.FileSystemInfo #include "System/IO/FileSystemInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: StreamWriter class StreamWriter; } // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // Size: 0x68 #pragma pack(push, 1) // Autogenerated type: System.IO.FileInfo // [ComVisibleAttribute] Offset: D7C894 class FileInfo : public System::IO::FileSystemInfo { public: // private System.String _name // Size: 0x8 // Offset: 0x60 ::Il2CppString* name; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // Creating value type constructor for type: FileInfo FileInfo(::Il2CppString* name_ = {}) noexcept : name{name_} {} // public System.Void .ctor(System.String fileName) // Offset: 0x1933E44 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static FileInfo* New_ctor(::Il2CppString* fileName) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(fileName))); } // private System.Void Init(System.String fileName, System.Boolean checkHost) // Offset: 0x1933EE4 void Init(::Il2CppString* fileName, bool checkHost); // private System.String GetDisplayPath(System.String originalPath) // Offset: 0x1933FD4 ::Il2CppString* GetDisplayPath(::Il2CppString* originalPath); // public System.String get_DirectoryName() // Offset: 0x1934070 ::Il2CppString* get_DirectoryName(); // public System.IO.StreamWriter CreateText() // Offset: 0x19340D8 System::IO::StreamWriter* CreateText(); // public System.IO.StreamWriter AppendText() // Offset: 0x1934140 System::IO::StreamWriter* AppendText(); // private System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1933FDC // Implemented from: System.IO.FileSystemInfo // Base method: System.Void FileSystemInfo::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static FileInfo* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(info, context))); } // public override System.String get_Name() // Offset: 0x1934068 // Implemented from: System.IO.FileSystemInfo // Base method: System.String FileSystemInfo::get_Name() ::Il2CppString* get_Name(); // public override System.Boolean get_Exists() // Offset: 0x19341A8 // Implemented from: System.IO.FileSystemInfo // Base method: System.Boolean FileSystemInfo::get_Exists() bool get_Exists(); // public override System.String ToString() // Offset: 0x193429C // Implemented from: System.Object // Base method: System.String Object::ToString() ::Il2CppString* ToString(); }; // System.IO.FileInfo #pragma pack(pop) static check_size<sizeof(FileInfo), 96 + sizeof(::Il2CppString*)> __System_IO_FileInfoSizeCheck; static_assert(sizeof(FileInfo) == 0x68); } DEFINE_IL2CPP_ARG_TYPE(System::IO::FileInfo*, "System.IO", "FileInfo");
47.021277
162
0.703846
62262d7d75a5698815745d969c27290e961e9934
4,906
cpp
C++
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
1
2021-09-25T12:49:37.000Z
2021-09-25T12:49:37.000Z
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
null
null
null
pxr/base/tf/pyTracing.cpp
yurivict/USD
3b097e3ba8fabf1777a1256e241ea15df83f3065
[ "Apache-2.0" ]
1
2018-10-03T19:08:33.000Z
2018-10-03T19:08:33.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/tf/pyTracing.h" #ifdef PXR_PYTHON_SUPPORT_ENABLED #include "pxr/base/tf/pyInterpreter.h" #include "pxr/base/tf/pyUtils.h" #include "pxr/base/tf/staticData.h" #include <memory> #include <tbb/spin_mutex.h> // This is from python, needed for PyFrameObject. #include <frameobject.h> #include <list> #include <mutex> using std::list; PXR_NAMESPACE_OPEN_SCOPE typedef list<std::weak_ptr<TfPyTraceFn> > TraceFnList; static TfStaticData<TraceFnList> _traceFns; static bool _traceFnInstalled; static tbb::spin_mutex _traceFnMutex; static void _SetTraceFnEnabled(bool enable); static void _InvokeTraceFns(TfPyTraceInfo const &info) { // Take the lock, and swap out the list of trace fns for an empty list. We // do this so we don't hold the lock and call unknown code. If functions // expire while we're executing, that's fine since we .lock() each one to // get a dereferenceable shared_ptr, and if new functions are added, that's // okay too since we splice the copy back into the official list when we're // done. TraceFnList local; { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); local.splice(local.end(), *_traceFns); } // Walk the fns, and invoke them if they're present, erase them if they're // not. for (TraceFnList::iterator i = local.begin(); i != local.end();) { if (TfPyTraceFnId ptr = i->lock()) { (*ptr)(info); ++i; } else { local.erase(i++); } } // Now splice the local back into the real list. { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); _traceFns->splice(_traceFns->end(), local); // If the list is empty, uninstall the trace fn. if (_traceFns->empty()) _SetTraceFnEnabled(false); } } static int _TracePythonFn(PyObject *, PyFrameObject *frame, int what, PyObject *arg); static void _SetTraceFnEnabled(bool enable) { // NOTE! mutex must be locked by caller! if (enable && !_traceFnInstalled && Py_IsInitialized()) { _traceFnInstalled = true; PyEval_SetTrace(_TracePythonFn, NULL); } else if (!enable && _traceFnInstalled) { _traceFnInstalled = false; PyEval_SetTrace(NULL, NULL); } } static int _TracePythonFn(PyObject *, PyFrameObject *frame, int what, PyObject *arg) { // Build up a trace info struct. TfPyTraceInfo info; info.arg = arg; info.funcName = TfPyString_AsString(frame->f_code->co_name); info.fileName = TfPyString_AsString(frame->f_code->co_filename); info.funcLine = frame->f_code->co_firstlineno; info.what = what; _InvokeTraceFns(info); return 0; } void Tf_PyFabricateTraceEvent(TfPyTraceInfo const &info) { // NOTE: assumes python lock is held by caller. Due to that assumption, we // know that the list of trace functions could only be growing during this // function, and could not go to zero, and have the python trace function be // disabled. So it's safe for us to check the _traceFnInstalled flag here. if (_traceFnInstalled) _InvokeTraceFns(info); } TfPyTraceFnId TfPyRegisterTraceFn(TfPyTraceFn const &f) { tbb::spin_mutex::scoped_lock lock(_traceFnMutex); TfPyTraceFnId ret(new TfPyTraceFn(f)); _traceFns->push_back(ret); _SetTraceFnEnabled(true); return ret; } void Tf_PyTracingPythonInitialized() { static std::once_flag once; std::call_once(once, [](){ TF_AXIOM(Py_IsInitialized()); tbb::spin_mutex::scoped_lock lock(_traceFnMutex); if (!_traceFns->empty()) _SetTraceFnEnabled(true); }); } PXR_NAMESPACE_CLOSE_SCOPE #endif // PXR_PYTHON_SUPPORT_ENABLED
31.050633
80
0.683245
6229c2d484d9b4c389c63aaaa3e3980fbf6198d1
1,106
cpp
C++
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
random_noise_generator/random_noise_factory.cpp
eborghi10/noisy_fit_2d
a1839fac91eda333b9869c9a7add5c6e757a58e2
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <string> // Base class #include "noises/random_noise_base.h" // Noise classes #include "noises/linear.h" #include "noises/quadratic.h" #include "noises/simplified_cholesky.h" namespace rng { using RandomNoiseBasePtr = std::unique_ptr<RandomNoiseBase>; class RandomNoiseFactory { public: /** * \brief Generator of RandomNoiseBase. * \param type Type of noise generator. Available options are: linear, quadratic and cholesky. * \return Pointer to RandomNoiseBase. */ static RandomNoiseBasePtr Make(const std::string& type = "linear") { std::cout << "Noise = " << type << std::endl; if(type == "linear") { return std::make_unique<LinearNoise>(); } else if(type == "quadratic") { return std::make_unique<QuadraticNoise>(); } else if(type == "cholesky") { return std::make_unique<SimplifiedCholesky>(); } else { // Default uses linear return std::make_unique<LinearNoise>(); } // Another example: https://en.wikipedia.org/wiki/Anscombe%27s_quartet } }; } // namespace rng
24.577778
96
0.67179
62337011da9d3d36f5ce052d32f3d148646109d5
177
hpp
C++
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
6
2017-02-15T01:50:32.000Z
2019-07-05T13:50:57.000Z
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
40
2017-04-06T13:29:02.000Z
2018-04-20T23:39:21.000Z
Cpf/Plugins/Platform/Concurrency/Interface/Concurrency/Concurrency.hpp
All8Up/cpf
81c68fbb69619261a5aa058cda73e35812ed3543
[ "MIT" ]
3
2017-08-03T15:17:01.000Z
2019-03-08T07:58:59.000Z
////////////////////////////////////////////////////////////////////////// #pragma once namespace CPF { namespace Concurrency { static constexpr int kMaxThreads = 64; } }
16.090909
74
0.412429
62337383665e6d6b0264360ab9ed7e191ee04b7a
168
hpp
C++
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
20
2016-09-19T20:37:36.000Z
2022-02-26T14:16:28.000Z
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
6
2016-12-27T16:49:01.000Z
2020-11-22T16:50:29.000Z
src/main.hpp
ziggi/rustext
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
[ "MIT" ]
1
2019-02-21T08:10:43.000Z
2019-02-21T08:10:43.000Z
/* About: rustext main Author: ziggi */ #ifndef MAIN_H #define MAIN_H #include <map> #include "common.hpp" #include "converter.hpp" logprintf_t logprintf; #endif
10.5
24
0.720238
62360aef9279d488b4ee2c24e9591aedb0cd169d
834
cpp
C++
src/actions/move_by_action.cpp
tomalbrc/rawket-engine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
null
null
null
src/actions/move_by_action.cpp
tomalbrc/rawket-engine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
1
2016-03-18T13:54:22.000Z
2016-08-11T22:02:28.000Z
src/actions/move_by_action.cpp
tomalbrc/FayEngine
2b7da4f33c874154120fc2d1529081f4f4ae33c7
[ "MIT" ]
null
null
null
// // move_by_action.cpp // rawket // // Created by Tom Albrecht on 09.12.15. // // #include "move_by_action.hpp" RKT_NAMESPACE_BEGIN move_by_action_ptr move_by_action::create(double pduration, vec2f offset) { move_by_action_ptr p(new move_by_action()); p->init(pduration, offset); return p; } bool move_by_action::init(double pduration, vec2f offset) { changeInVec2Value = offset; duration = pduration*1000; return true; } void move_by_action::update() { auto popos = currentVec2Value(); target->setPosition(popos); if (SDL_GetTicks()-startTick > duration) finished = true, target->setPosition(changeInVec2Value+startVec2Value); } void move_by_action::start() { startTick = SDL_GetTicks(); startVec2Value = target->getPosition(); finished = false; } RKT_NAMESPACE_END
19.857143
116
0.707434
623939f0120a593b016902b94a91af7d88e57e7c
8,257
cpp
C++
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Equations/Fluid/HottailRateTermHighZ.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Implementation of equation term representing the runaway generation rate * due to hottail when using an analytic distribution function */ #include "DREAM/Equations/Fluid/HottailRateTermHighZ.hpp" using namespace DREAM; /** * Constructor. * * gsl_altPc* contains parameters and functions needed * to evaluate the critical runaway momentum in the hottail * calculation using a gsl root-finding algorithm * (using the 'alternative' model for pc in Ida's MSc thesis) */ HottailRateTermHighZ::HottailRateTermHighZ( FVM::Grid *grid, AnalyticDistributionHottail *dist, FVM::UnknownQuantityHandler *unknowns, IonHandler *ionHandler, CoulombLogarithm *lnL, real_t sf ) : HottailRateTerm(grid, dist, unknowns,sf), lnL(lnL), id_ncold(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD)), id_Efield(unknowns->GetUnknownID(OptionConstants::UQTY_E_FIELD)), id_tau(unknowns->GetUnknownID(OptionConstants::UQTY_TAU_COLL)) { SetName("HottailRateTermHighZ"); AddUnknownForJacobian(unknowns,id_Efield); AddUnknownForJacobian(unknowns,id_ncold); AddUnknownForJacobian(unknowns,id_tau); //AddUnknownForJacobian(unknowns,id_ni); // Zeff and lnL (nfree) jacobian //AddUnknownForJacobian(unknowns,id_Tcold); // lnL jacobian this->fdfsolver = gsl_root_fdfsolver_alloc(gsl_root_fdfsolver_secant); gsl_params.ionHandler = ionHandler; gsl_params.rGrid = grid->GetRadialGrid(); gsl_params.dist = dist; gsl_func.f = &(PcFunc); gsl_func.df = &(PcFunc_df); gsl_func.fdf = &(PcFunc_fdf); gsl_func.params = &gsl_params; this->GridRebuilt(); } /** * Destructor */ HottailRateTermHighZ::~HottailRateTermHighZ(){ Deallocate(); gsl_root_fdfsolver_free(fdfsolver); } /** * Called after the grid is rebuilt; (re)allocates memory * for all quantities */ bool HottailRateTermHighZ::GridRebuilt(){ this->HottailRateTerm::GridRebuilt(); Deallocate(); pCrit_prev = new real_t[nr]; return true; } /** * Rebuilds quantities used by this equation term. * Note that the equation term uses the _energy distribution_ * from AnalyticDistributionHottail which differs from the * full distribution function by a factor of 4*pi */ void HottailRateTermHighZ::Rebuild(const real_t t, const real_t dt, FVM::UnknownQuantityHandler*) { this->dt = dt; bool newTimeStep = (t!=tPrev); if(newTimeStep) tPrev = t; for(len_t ir=0; ir<nr; ir++){ if(newTimeStep) pCrit_prev[ir] = pCrit[ir]; real_t fAtPc, dfdpAtPc; pCrit[ir] = evaluateCriticalMomentum(ir, fAtPc, dfdpAtPc); real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt; if (dotPc > 0) // ensure non-negative runaway rate dotPc = 0; gamma[ir] = -pCrit[ir]*pCrit[ir]*dotPc*fAtPc; // generation rate // set derivative of gamma with respect to pCrit (used for jacobian) dGammaDPc[ir] = -(2*pCrit[ir]*dotPc*fAtPc + pCrit[ir]*pCrit[ir]*fAtPc/dt + pCrit[ir]*pCrit[ir]*dotPc*dfdpAtPc); } } /** * Function whose root (with respect to p) represents the * critical runaway momentum in the 'alternative' model */ real_t HottailRateTermHighZ::PcFunc(real_t p, void *par) { if(p<0) // handle case where algorithm leaves the physical domain of non-negative momenta p=0; PcParams *params = (PcParams*)par; len_t ir = params->ir; real_t Eterm = params->Eterm; real_t ncold = params->ncold; real_t tau = params->tau; real_t lnL = params->lnL; real_t dFdpOverF; params->F = params->dist->evaluateEnergyDistributionFromTau(ir,p,tau,&params->dFdp,nullptr, &dFdpOverF); real_t Ec = 4*M_PI*ncold*lnL*Constants::r0*Constants::r0*Constants::c * Constants::me * Constants::c / Constants::ec; real_t E = Eterm/Ec; real_t EPF = params->rGrid->GetEffPassFrac(ir); real_t Zeff = params->ionHandler->GetZeff(ir); real_t p2 = p*p; real_t gamma = sqrt(1+p2); // for the non-relativistic distribution, this function is // approximately linear, yielding efficient root finding return sqrt((p/gamma)*cbrt( p2*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3*(1+Zeff))); // previous equivalent expression: // real_t g3 = (1+p2)*gamma; // return sqrt(cbrt( p2*p2*p*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3.0*(1+Zeff)*g3)); } /** * Returns the derivative of PcFunc with respect to p */ real_t HottailRateTermHighZ::PcFunc_df(real_t p, void *par) { real_t h = 1e-3*p; return (PcFunc(p+h,par) - PcFunc(p,par)) / h; } /** * Method which sets both f=PcFunc and df=PcFunc_df */ void HottailRateTermHighZ::PcFunc_fdf(real_t p, void *par, real_t *f, real_t *df){ real_t h = 1e-3*p; *f = PcFunc(p,par); *df = (PcFunc(p+h, par) - *f) / h; } /** * Evaluates the 'alternative' critical momentum pc using Ida's MSc thesis (4.35) */ real_t HottailRateTermHighZ::evaluateCriticalMomentum(len_t ir, real_t &f, real_t &dfdp){ gsl_params.ir = ir; gsl_params.lnL = lnL->evaluateAtP(ir,0); gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir]; gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir]; gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir]; real_t root = (pCrit_prev[ir] == 0) ? 5*distHT->GetInitialThermalMomentum(ir) : pCrit_prev[ir]; RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC); f = gsl_params.F; dfdp = gsl_params.dFdp; return root; } /** * Evaluates the jacobian of CriticalMomentum with * respect to the unknown with id 'derivId' */ real_t HottailRateTermHighZ::evaluatePartialCriticalMomentum(len_t ir, len_t derivId){ gsl_params.ir = ir; gsl_params.lnL = lnL->evaluateAtP(ir,0); gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir]; gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir]; gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir]; real_t h = 0; if(derivId == id_Efield){ h = (1.0+fabs(gsl_params.Eterm))*sqrt(RELTOL_FOR_PC), gsl_params.Eterm += h; } else if (derivId == id_ncold){ h = (1.0+fabs(gsl_params.ncold))*sqrt(RELTOL_FOR_PC), gsl_params.ncold += h; } else if (derivId == id_tau){ h = (1.0+fabs(gsl_params.tau))*sqrt(RELTOL_FOR_PC), gsl_params.tau += h; } real_t root = pCrit[ir]; RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC); return (root - pCrit[ir])/h; } /** * Sets the Jacobian of this equation term */ bool HottailRateTermHighZ::SetJacobianBlock(const len_t /*uqtyId*/, const len_t derivId, FVM::Matrix *jac, const real_t*){ if(!HasJacobianContribution(derivId)) return false; for(len_t ir=0; ir<nr; ir++){ const len_t xiIndex = this->GetXiIndexForEDirection(ir); const len_t np1 = this->grid->GetMomentumGrid(ir)->GetNp1(); real_t V = GetVolumeScaleFactor(ir); // Check if the quantity w.r.t. which we differentiate is a // fluid quantity, in which case it has np1=1, xiIndex=0 len_t np1_op = np1, xiIndex_op = xiIndex; if (unknowns->GetUnknown(derivId)->NumberOfElements() == nr) { np1_op = 1; xiIndex_op = 0; } real_t dPc = evaluatePartialCriticalMomentum(ir, derivId); real_t dGamma = dPc * dGammaDPc[ir]; if(derivId==id_tau){ // add contribution from explicit tau dependence in f real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt; if (dotPc > 0) // ensure non-negative runaway rate dotPc = 0; real_t tau = unknowns->GetUnknownData(id_tau)[ir]; real_t dFdTauAtPc; distHT->evaluateEnergyDistributionFromTau(ir, pCrit[ir], tau, nullptr, nullptr, nullptr, &dFdTauAtPc); dGamma -= pCrit[ir]*pCrit[ir]*dotPc*dFdTauAtPc; } jac->SetElement(ir + np1*xiIndex, ir + np1_op*xiIndex_op, scaleFactor * dGamma * V); } return true; } /** * Deallocator */ void HottailRateTermHighZ::Deallocate(){ if(pCrit_prev != nullptr) delete [] pCrit_prev; }
34.987288
138
0.669977
623a159d3ca2db1b550deccf4256c78327c053ba
3,197
hpp
C++
Examples/ProgAnalysis/Cfg.hpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
src/wpds/Examples/ProgAnalysis/Cfg.hpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
src/wpds/Examples/ProgAnalysis/Cfg.hpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
#ifndef _WALI_CFG_HPP_ #define _WALI_CFG_HPP_ /* * @author Akash Lal */ /* * This file includes an abstract class for a Control Flow Graph (CFG). A CFG is represented * as a graph over CFGNodes and CFGEdges. * * This abstract class is meant to provide just enough interface to be able to * construct a WPDS. */ #include "wali/Key.hpp" #include "wali/SemElem.hpp" #include "wali/MergeFn.hpp" #include <set> class CFGNode; class CFGEdge; class CFG; // Abstract class denoting a CFG node class CFGNode { public: // Return a unique identifier for the CFG node virtual int getId() const = 0; // Return a WPDS key that is unique for the CFG node. A sample // implementation for this method is provided using the getId // method. However, wali provides several ways of obtaining keys: // see [... NAK?] virtual wali::Key getWpdsKey() const { return wali::getKey(getId()); /* To use a priority-based key (see TODO) one can use the following code: * return wali::getKey( wali::getKey(getPriorityNumber()), wali::getKey(getId()) ); * * This assume the presence of a function "int CFGNode::getPriorityNumber()" that * returns a (possibily non-unique) priority for the CFGNode. */ } // Return the set of outgoing edges //std::set<CFGEdge *> getOutgoingEdges() = 0; virtual ~CFGNode() {} }; // Abstract class denoting a CFG edge class CFGEdge { // The source and target nodes of the edge CFGNode *src, *tgt; // If this edge is a call edge, then callee is the called // procedure. For simplicity, we assume that a call edge // has only one callee. (The presence of multiple callees // do not pose any challenge specific to WPDSs.) CFG* callee; public: // Return the source node of the edge CFGNode *getSource() const { return src; } // Return the target node of the edge CFGNode *getTarget() const { return tgt; } // Is this edge a call edge? virtual bool isCall() const = 0; // Get callee, if this is a call edge CFG *getCallee() const { if(!isCall()) return 0; return callee; } // Return the weight (or abstract transformer) associated // with the CFG edge. The convention for call edges is that // this function should provide the transformer associated with // just the call instruction, not the called procedure. virtual wali::sem_elem_t getWeight() const = 0; // Return the merge function associated with the edge. This is only // invoked for call edges. virtual wali::merge_fn_t getMergeFn() const = 0; virtual ~CFGEdge() {} }; // Abstract class for denoting a CFG. We assume that a CFG has a // unique entry node (that has no predecessors) and a unique exit // node (that has no successors). class CFG { // Entry and exit nodes of the CFG CFGNode *entryNode, *exitNode; public: // Return the entry node of the CFG CFGNode *getEntry() const { return entryNode; } // Return the exit node of the CFG CFGNode *getExit() const { return exitNode; } // Return the set of all CFG edges contained in this CFG virtual const std::set<CFGEdge *> & getEdges() const = 0; virtual ~CFG() {} }; #endif // _WALI_CFG_HPP_
25.373016
92
0.684079
623bfc1dbecdd6ebf1bfdefa4e2bb2b501853294
2,740
cpp
C++
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
timdecode/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
MyelinsheathXD/LifeBrush
dbc65bcc0ec77f9168e08cf7b39539af94420725
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright (c) 2019 Timothy Davison. All rights reserved. #include "LifeBrush.h" #include "Simulation/FlexElements.h" #include "Brownian.h" void USingleParticleBrownianSimulation::attach() { rand.GenerateNewSeed(); } void USingleParticleBrownianSimulation::detach() { } void USingleParticleBrownianSimulation::tick(float deltaT) { auto& browns = graph->componentStorage<FSingleParticleBrownian>(); auto& velocities = graph->componentStorage<FVelocityGraphObject>(); // make sure we have velocities for (FSingleParticleBrownian& brown : browns) { if( !brown.isValid() ) continue; if (!velocities.componentPtrForNode(brown.nodeHandle())) { FGraphNode& node = graph->node(brown.nodeHandle()); node.addComponent<FVelocityGraphObject>(*graph); } } for (FSingleParticleBrownian& brown : browns) { if( !brown.isValid() ) continue; brown.time -= deltaT; if (brown.time > 0.0f) continue; brown.time = rand.FRandRange(minTime, maxTime); float scale = FMath::Clamp(1.0f - brown.dampening, 0.0f, 1.0f); FVector dv = scale * rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed); if (auto velocity = velocities.componentPtrForNode(brown.nodeHandle())) { velocity->linearVelocity = (velocity->linearVelocity + dv).GetClampedToMaxSize(15.0f); } } } void UGlobalParticleBrownianSimulation::attach() { rand.GenerateNewSeed(); } void UGlobalParticleBrownianSimulation::detach() { } void UGlobalParticleBrownianSimulation::tick(float deltaT) { if (!enabled) return; auto& particles = graph->componentStorage<FFlexParticleObject>(); auto& velocities = graph->componentStorage<FVelocityGraphObject>(); for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; if (!velocities.componentPtrForNode(particle.nodeHandle())) { FGraphNode& node = graph->node(particle.nodeHandle()); node.addComponent<FVelocityGraphObject>(*graph); } } // find _times Num int32 timeSize = 0; for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; int32 timeIndex = particle.nodeHandle().index; if (timeIndex > timeSize) timeSize = timeIndex; } _times.SetNum(timeSize + 1); // make sure we have velocities for (FFlexParticleObject& particle : particles) { if (!particle.isValid()) continue; int32 timeIndex = particle.nodeHandle().index; float& timeLeft = _times[timeIndex]; timeLeft -= deltaT; if (timeLeft > 0.0f) continue; timeLeft = rand.FRandRange(minTime, maxTime); FVelocityGraphObject * velocity = velocities.componentPtrForNode(particle.nodeHandle()); FVector dv = rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed); velocity->linearVelocity += dv; } }
21.574803
90
0.724453
623c158b82f5ffc0d0db2e2fb7c1f16ace9c978f
2,652
cpp
C++
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
1
2016-05-21T12:45:20.000Z
2016-05-21T12:45:20.000Z
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
null
null
null
src/Camera2D.cpp
jasonwnorris/SuperAwesomeGameEngine
908adf2099898b2c2028a8c8e8887f1d53be181f
[ "MIT" ]
null
null
null
// Camera2D.cpp // SAGE Includes #include <SAGE/Camera2D.hpp> namespace SAGE { const Camera2D Camera2D::DefaultCamera; int Camera2D::DefaultWidth = 1280; int Camera2D::DefaultHeight = 720; Camera2D::Camera2D() { m_Position = Vector2::Zero; m_Rotation = 0.0f; m_Scale = Vector2::One; m_Width = DefaultWidth; m_Height = DefaultHeight; } Camera2D::~Camera2D() { } Vector2 Camera2D::GetPosition() const { return m_Position; } float Camera2D::GetRotation() const { return m_Rotation; } Vector2 Camera2D::GetScale() const { return m_Scale; } int Camera2D::GetWidth() const { return m_Width; } int Camera2D::GetHeight() const { return m_Height; } glm::mat4 Camera2D::GetProjectionMatrix(View p_View) const { switch (p_View) { default: case View::Orthographic: return glm::ortho(0.0f, (float)m_Width, (float)m_Height, 0.0f, 1.0f, -1.0f); case View::Perspective: return glm::perspective(45.0f, (float)m_Width / (float)m_Height, 0.1f, 1000.0f); } } glm::mat4 Camera2D::GetModelViewMatrix() const { glm::mat4 modelViewMatrix; modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3((float)m_Width / 2.0f, (float)m_Height / 2.0f, 0.0f)); modelViewMatrix = glm::scale(modelViewMatrix, glm::vec3(m_Scale.X, m_Scale.Y, 1.0f)); modelViewMatrix = glm::rotate(modelViewMatrix, m_Rotation, glm::vec3(0.0f, 0.0f, 1.0f)); modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3(-m_Position.X, -m_Position.Y, 0.0f)); return modelViewMatrix; } void Camera2D::SetPosition(const Vector2& p_Position) { m_Position = p_Position; } void Camera2D::SetRotation(float p_Rotation) { m_Rotation = p_Rotation; } void Camera2D::SetScale(const Vector2& p_Scale) { m_Scale = p_Scale; } void Camera2D::SetTransformation(const Vector2& p_Position, float p_Rotation, const Vector2& p_Scale) { m_Position = p_Position; m_Rotation = p_Rotation; m_Scale = p_Scale; } void Camera2D::SetWidth(int p_Width) { m_Width = p_Width; } void Camera2D::SetHeight(int p_Height) { m_Height = p_Height; } void Camera2D::SetDimensions(int p_Width, int p_Height) { m_Width = p_Width; m_Height = p_Height; } void Camera2D::Translate(const Vector2& p_Translation) { m_Position += p_Translation; } void Camera2D::Rotate(float p_Rotation) { m_Rotation += p_Rotation; } void Camera2D::Scale(const Vector2& p_Scale) { m_Scale += p_Scale; } void Camera2D::ScreenToWorld(const Vector2& p_ScreenPosition, Vector2& p_WorldPosition) const { } void Camera2D::WorldToScreen(const Vector2& p_WorldPosition, Vector2& p_ScreenPosition) const { } }
19.791045
116
0.707391
9a8b7cab21f5563369369e89adf76a80a30f01c3
5,975
cpp
C++
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
opengl/texture.cpp
yRezaei/cpp-utils
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
[ "MIT" ]
null
null
null
#include "../rendering/gl_utility.hpp" #include "texture.h" namespace gl { int format_to_texture(image::Format format) { switch (format) { case image::ALPHA: case image::GRAYSCALE: return GL_RED; case image::GRAYSCALE_ALPHA: ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!"); case image::RGB: return GL_RGB; case image::BGR: return GL_BGR; case image::RGBA: return GL_RGBA; case image::BGRA: return GL_BGRA; default: ASSERT("Unkown format '" + image::FormatStrings[format] + "'."); } } int internal_texture_format(image::Format format) { switch (format) { case image::ALPHA: case image::GRAYSCALE: return GL_RED; case image::GRAYSCALE_ALPHA: ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!"); case image::RGB: case image::BGR: return GL_RGB; case image::RGBA: return GL_RGBA; case image::BGRA: return GL_BGRA; default: ASSERT("Unkown format '" + image::FormatStrings[format] + "'."); } } Texture::Texture(image::Format format, const glm::ivec2 & size, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); std::vector<uint8_t> pixels(size_.x * size_.y * format_size(format_), 0); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Bitmap const & bitmap, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(bitmap.format), size_(bitmap.size) { GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, bitmap.buffer.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Format format, const glm::ivec2 & size, const std::vector<uint8_t>& pixels, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { if (id_ != 0) glDeleteTextures(1, &id_); GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data())); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::Texture(image::Format format, const glm::ivec2 & size, const uint8_t * data, TextureFilter texture_filter, TextureWrapping texture_wrapping) : id_(0u), format_(format), size_(size) { if (id_ != 0) glDeleteTextures(1, &id_); GL_CHECK(glGenTextures(1, &id_)); ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id."); GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_)); { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping); GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } glBindTexture(GL_TEXTURE_2D, 0); } Texture::~Texture() { if (id_ != 0) glDeleteTextures(1, &id_); } const glm::ivec2 & Texture::size() { return size_; } void Texture::set_data(const std::vector<uint8_t>& data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data())); } void Texture::set_data(const glm::ivec4 & rect, const std::vector<uint8_t>& data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data())); } void Texture::set_data(const std::uint8_t* data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } void Texture::set_data(const glm::ivec4 & rect, const std::uint8_t* data) { glBindTexture(GL_TEXTURE_2D, id_); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data)); } void Texture::bind() { glBindTexture(GL_TEXTURE_2D, id_); } void Texture::unbind() { glBindTexture(GL_TEXTURE_2D, 0); } }
33.757062
167
0.743096
9a90a34a50edc5648df12b76cb1b02e0be8f77fc
737
cpp
C++
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
1
2022-03-31T21:45:03.000Z
2022-03-31T21:45:03.000Z
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
InfoX/lungimea_coordonate_segment.cpp
jbara2002/Informatica_LCIB
ff9db6d7d6119ba835750cc2d408079f76b852df
[ "CC0-1.0" ]
null
null
null
// Citesc coordonatele A(x1,y1), B(x2,y2). // Afiseaza lungimea AB si coordonatele mijlocului segmentului AB. #include <iostream> #include <math.h> using namespace std; int main(){ float x1, y1, x2, y2, ab, c1, c2; cout << "Introdu coordonata punctului A - x1: "; cin >> x1; cout << "Introdu coordonata punctului A - y1: "; cin >> y1; cout << "Introdu coordonata punctului B - x2: "; cin >> x2; cout << "Introdu coordonata punctului B - y2: "; cin >> y2; ab=sqrt(pow((x1-x2),2)+pow((y1-y2),2)); c1=(x1+x2)/2; c2=(y1+y2)/2; cout << "Lungimea segmentului AB: " << ab << endl; cout << "Coordonatele mijlocului segmentului: " << "A(" << x1+c1 << ")" << " , " << "B(" << y1+c2 << ")" << endl; }
29.48
117
0.573948