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
0173d54babdf4883a3150eb0599e66987bd23a3b
5,591
cpp
C++
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved. #include "Components/CsWidgetComponent.h" #include "CsCoreDEPRECATED.h" // Types #include "Types/CsTypes.h" // Library #include "Library/CsLibrary_Common.h" // UI #include "UI/CsUserWidget.h" #include "UI/Simple/CsSimpleWidget.h" #include "Pawn/CsPawn.h" #include "Player/CsPlayerController.h" UCsWidgetComponent::UCsWidgetComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UCsWidgetComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (bMinDrawDistance) OnTick_Handle_DrawDistance(); if (Visibility == ECsVisibility::Hidden) return; if (ScaleByDistance) OnTick_Handle_Scale(); if (!bOnCalcCamera) { ACsPlayerController* LocalController = UCsLibrary_Common::GetLocalPlayerController<ACsPlayerController>(GetWorld()); OnTick_Handle_LocalCamera(LocalController->MinimalViewInfoCache.Location, LocalController->MinimalViewInfoCache.Rotation); } if (!FollowLocalCamera && FollowOwner) OnTick_Handle_Movement(); } UUserWidget* UCsWidgetComponent::GetWidget() { return Widget; } // Camera #pragma region void UCsWidgetComponent::OnCalcCamera(const uint8& MappingId, const float& DeltaTime, const struct FMinimalViewInfo& OutResult) { if (Visibility == ECsVisibility::Hidden) return; OnTick_Handle_LocalCamera(OutResult.Location, OutResult.Rotation); } void UCsWidgetComponent::OnTick_Handle_LocalCamera(const FVector& ViewLocation, const FRotator& ViewRotation) { if (!FollowLocalCamera && !LookAtLocalCamera) return; FVector CameraLocation = ViewLocation; FRotator CameraRotation = ViewRotation; if (FollowLocalCamera) { if (UCsLibrary_Common::IsVR()) { UCsLibrary_Common::GetHMDWorldViewPoint(GetWorld(), CameraLocation, CameraRotation); } CameraRotation.Roll = 0.f; const FVector Forward = ViewRotation.Vector(); const FVector Location = ViewLocation + DistanceProjectedOutFromCamera * Forward; SetWorldLocation(Location); FRotator Rotation = (-Forward).Rotation(); CameraLockAxes.ApplyLock(Rotation); //Rotation.Roll = 0.0f; //const FRotator Rotation = FRotator(-ViewRotation.Pitch, ViewRotation.Yaw + 180.0f, 0.0f); SetWorldRotation(Rotation); } else if (LookAtLocalCamera) { //ViewRotation.Roll = 0.f; FRotator Rotation = FRotator(-ViewRotation.Pitch, ViewRotation.Yaw + 180.0f, 0.0f); CameraLockAxes.ApplyLock(Rotation); SetWorldRotation(Rotation); } } #pragma endregion Camera // Info #pragma region void UCsWidgetComponent::SetInfo(const FVector2D& Size, const FTransform& Transform, const bool& InFollowLocalCamera, const bool& InLookAtLocalCamera) { SetDrawSize(Size); SetRelativeTransform(Transform); FollowLocalCamera = InFollowLocalCamera; LookAtLocalCamera = InLookAtLocalCamera; } void UCsWidgetComponent::SetInfo(const FCsWidgetComponentInfo& Info) { SetInfo(Info.DrawSize, Info.Transform, Info.FollowCamera, Info.LookAtCamera); DistanceProjectedOutFromCamera = Info.DistanceProjectedOutFromCamera; CameraLockAxes = Info.LockAxes; bMinDrawDistance = Info.bMinDrawDistance; MyMinDrawDistance = Info.MinDrawDistance; ScaleByDistance = Info.ScaleByDistance; FollowOwner = Info.FollowOwner; LocationOffset = Info.Transform.GetTranslation(); } void UCsWidgetComponent::SetInfo(const FCsWidgetActorInfo& Info) { SetInfo(Info.DrawSize, Info.Transform, false, false); } #pragma endregion Info // Visibility #pragma region void UCsWidgetComponent::Show() { Visibility = ECsVisibility::Visible; if (UCsUserWidget* UserWidget = Cast<UCsUserWidget>(Widget)) { UserWidget->Show(); } else if (UCsSimpleWidget* SimpleWidget = Cast<UCsSimpleWidget>(Widget)) { SimpleWidget->Show(); } else if (Widget) { Widget->SetIsEnabled(true); Widget->SetVisibility(ESlateVisibility::Visible); } Activate(); SetComponentTickEnabled(true); SetHiddenInGame(false); SetVisibility(true); } void UCsWidgetComponent::Hide() { Visibility = ECsVisibility::Hidden; if (UCsUserWidget* UserWidget = Cast<UCsUserWidget>(Widget)) { UserWidget->Hide(); } else if (UCsSimpleWidget* SimpleWidget = Cast<UCsSimpleWidget>(Widget)) { SimpleWidget->Hide(); } else if (Widget) { Widget->SetIsEnabled(false); Widget->SetVisibility(ESlateVisibility::Hidden); } SetVisibility(false); SetHiddenInGame(true); SetComponentTickEnabled(false); Deactivate(); } void UCsWidgetComponent::OnTick_Handle_Scale() { ACsPawn* LocalPawn = UCsLibrary_Common::GetLocalPawn<ACsPawn>(GetWorld()); const float Distance = (LocalPawn->GetActorLocation() - GetComponentLocation()).Size2D(); const float Scale = MyMinDrawDistance.Distance > 0 ? Distance / MyMinDrawDistance.Distance : 1.0f; SetRelativeScale3D(Scale * FVector::OneVector); } void UCsWidgetComponent::OnTick_Handle_DrawDistance() { ACsPawn* LocalPawn = UCsLibrary_Common::GetLocalPawn<ACsPawn>(GetWorld()); const float DistanceSq = (LocalPawn->GetActorLocation() - GetComponentLocation()).SizeSquared2D(); if (DistanceSq < MyMinDrawDistance.DistanceSq) { if (Visibility == ECsVisibility::Visible) Hide(); } else { if (Visibility == ECsVisibility::Hidden) Show(); } } #pragma endregion Visibility // Movement #pragma region void UCsWidgetComponent::OnTick_Handle_Movement() { const FVector Location = GetOwner()->GetActorLocation() + LocationOffset; SetWorldLocation(Location); } #pragma endregion Movement
24.959821
150
0.764979
01763bf730e3956eed4037306a07412622ffb5a9
2,021
hpp
C++
include/Core/Tiles/Tileset.hpp
Sygmei/ObEngine
881b1471cd9824a0afed22b9a47131fd3ebc6009
[ "MIT" ]
442
2017-03-03T11:42:11.000Z
2021-05-20T13:40:02.000Z
include/Core/Tiles/Tileset.hpp
Sygmei/ObEngine
881b1471cd9824a0afed22b9a47131fd3ebc6009
[ "MIT" ]
308
2017-02-21T10:39:31.000Z
2021-05-14T21:30:56.000Z
include/Core/Tiles/Tileset.hpp
Sygmei/ObEngine
881b1471cd9824a0afed22b9a47131fd3ebc6009
[ "MIT" ]
45
2017-03-11T15:24:28.000Z
2021-05-09T15:21:42.000Z
#pragma once #include <map> #include <SFML/Graphics/VertexArray.hpp> #include <Graphics/RenderTarget.hpp> #include <Graphics/Texture.hpp> #include <Scene/Camera.hpp> #include <Types/Identifiable.hpp> #include <Types/Serializable.hpp> namespace obe::Tiles { class Tileset : public Types::Identifiable { private: uint32_t m_firstTileId; uint32_t m_columns; uint32_t m_count; uint32_t m_margin; uint32_t m_spacing; uint32_t m_tileWidth; uint32_t m_tileHeight; uint32_t m_imageWidth; uint32_t m_imageHeight; std::string m_imagePath; Graphics::Texture m_image; public: Tileset(const std::string& id, uint32_t firstTileId, uint32_t count, const std::string& imagePath, uint32_t columns, uint32_t tileWidth, uint32_t tileHeight, uint32_t margin = 0, uint32_t spacing = 0); uint32_t getFirstTileId() const; uint32_t getLastTileId() const; uint32_t getTileCount() const; uint32_t getMargin() const; uint32_t getSpacing() const; uint32_t getTileWidth() const; uint32_t getTileHeight() const; uint32_t getImageWidth() const; uint32_t getImageHeight() const; std::string getImagePath() const; Graphics::Texture getTexture() const; }; class TilesetCollection { private: std::vector<std::unique_ptr<Tileset>> m_tilesets; public: TilesetCollection(); void addTileset(uint32_t firstTileId, const std::string& id, const std::string& source, uint32_t columns, uint32_t width, uint32_t height, uint32_t count); [[nodiscard]] const Tileset& tilesetFromId(const std::string& id) const; [[nodiscard]] const Tileset& tilesetFromTileId(uint32_t tileId) const; [[nodiscard]] const size_t size() const; [[nodiscard]] std::vector<uint32_t> getTilesetsFirstTilesIds() const; void clear(); }; } // namespace obe::Scene
32.079365
100
0.660564
017768daea06f2b3bad9fa5c4261f7da65f3a67a
5,330
cpp
C++
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
1
2021-06-12T13:21:51.000Z
2021-06-12T13:21:51.000Z
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
// // TestOneDProblem.cpp MODIFICADO DO ORIGINAL // FemSC // // Created by Eduardo Ferri on 08/17/15. // // //TestOneDProblem cpp // Os testes foram preparados com um proposito educacional, // recomenda-se que o aluno entenda a funcionalidade de cada // teste e posteriormente use com seu cÛdigo caso a caso // Obs: O xmax e xmin estao tomados como 4 e 0, respectivamente, // caso estes valores sejam alterados, editar o teste TestNodes. // // #include <iostream> #include <math.h> #include "GeoNode.h" #include "GeoElement.h" #include "IntPointData.h" #include "CompElementTemplate.h" #include "Shape1d.h" #include "ShapeQuad.h" #include "ReadGmsh.h" #include "CompMesh.h" #include "GeoMesh.h" #include "GeoElement.h" #include "GeoElementTemplate.h" #include "MathStatement.h" #include "Poisson.h" #include "L2Projection.h" #include "Analysis.h" #include "IntRule.h" #include "IntRule1d.h" #include "IntRuleQuad.h" #include "IntRuleTetrahedron.h" #include "IntRuleTriangle.h" #include "Topology1d.h" #include "TopologyTriangle.h" #include "TopologyQuad.h" #include "TopologyTetrahedron.h" #include "PostProcess.h" #include "PostProcessTemplate.h" #include "DataTypes.h" #include "VTKGeoMesh.h" #include "CompElement.h" using std::cout; using std::endl; using std::cin; int main() { GeoMesh gmesh; ReadGmsh read; /* Malha triangulhar std::string filename("trian1.msh"); std::string filename("trian2.msh"); std::string filename("trian3.msh"); std::string filename("trian4.msh"); std::string filename("trian5.msh"); std::string filename("trian6.msh"); */ /* Malha quadratica std::string filename("quad0.msh"); std::string filename("quad1.msh"); std::string filename("quad2.msh"); std::string filename("quad3.msh"); std::string filename("quad4.msh"); std::string filename("quad5.msh"); std::string filename("quad6.msh"); */ std::string filename("trian6.msh"); read.Read(gmesh, filename); CompMesh cmesh(&gmesh); MatrixDouble perm(3, 3); perm.setZero(); perm(0, 0) = 1.; perm(1, 1) = 1.; perm(2, 2) = 1.; Poisson* mat1 = new Poisson(1, perm); mat1->SetDimension(2); auto force = [](const VecDouble& x, VecDouble& res) { res[0] = -90. * (-1. + x[0]) * (-1. + x[1]) * x[1] * cos(15. * x[0]) - 90. * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[0]) + 2250. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[1]) + 675. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * sin(15. * x[0]) - 2 * (-1. + x[0]) * x[0] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) - 2. * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + 300. * (-1. + x[0]) * x[0] * (-1. + x[1]) * sin(15. * x[1]) + 300. * (-1. + x[0]) * x[0] * x[1] * sin(15. * x[1]); }; mat1->SetForceFunction(force); MatrixDouble proj(1, 1), val1(1, 1), val2(1, 1); proj.setZero(); val1.setZero(); val2.setZero(); L2Projection* bc_linha = new L2Projection(0, 2, proj, val1, val2); L2Projection* bc_point = new L2Projection(0, 3, proj, val1, val2); std::vector<MathStatement*> mathvec = { 0,mat1,bc_point,bc_linha }; cmesh.SetMathVec(mathvec); cmesh.SetDefaultOrder(1); cmesh.AutoBuild(); cmesh.Resequence(); Analysis locAnalysis(&cmesh); locAnalysis.RunSimulation(); PostProcessTemplate<Poisson> postprocess; auto exact = [](const VecDouble& x, VecDouble& val, MatrixDouble& deriv) { val[0] = (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])); deriv(0, 0) = 45. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[0]) + (-1. + x[0]) * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + x[0] * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])); deriv(1, 0) = (-1. + x[0]) * x[0] * (-1. + x[1]) * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + (-1. + x[0]) * x[0] * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15 * x[0])) - 150.* (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * sin(15. * x[1]); }; postprocess.AppendVariable("Sol"); postprocess.AppendVariable("DSol"); postprocess.AppendVariable("Flux"); postprocess.AppendVariable("Force"); postprocess.AppendVariable("SolExact"); postprocess.AppendVariable("DSolExact"); postprocess.SetExact(exact); mat1->SetExactSolution(exact); /* Malha triangulhar std::string filenamevtk("trian1.vtk"); std::string filenamevtk("trian2.vtk"); std::string filenamevtk("trian3.vtk"); std::string filenamevtk("trian4.vtk"); std::string filenamevtk("trian5.vtk"); std::string filenamevtk("trian6.vtk"); */ /* Malha quadratica std::string filenamevtk("quad0.vtk"); std::string filenamevtk("quad1.vtk"); std::string filenamevtk("quad2.vtk"); std::string filenamevtk("quad3.vtk"); std::string filenamevtk("quad4.vtk"); std::string filenamevtk("quad5.vtk"); std::string filenamevtk("quad6.vtk"); */ std::string filenamevtk("trian6.vtk"); locAnalysis.PostProcessSolution(filenamevtk, postprocess); VecDouble errvec; errvec = locAnalysis.PostProcessError(std::cout, postprocess); return 0; } void CreateTestMesh(CompMesh& mesh, int order) { DebugStop(); }
31.538462
536
0.593246
0177e04f79e8bbcea39736ba26a1a8493ddd5140
683
cxx
C++
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
/// /// Copyright (c) 2022 Hiroshi Nakashima /// /// This software is released under the MIT License, see LICENSE. /// #include "gtest/gtest.h" #include "cxxplug/cxxplug.hxx" TEST(utils, get_environment) { { const auto value = cxxplug::get_environment("TEST_ENVIRONMENT"); EXPECT_EQ(value, "test-environment"); } { const auto value = cxxplug::get_environment("non-existent", "error"); EXPECT_EQ(value, "error"); } } TEST(utils, get_library_name) { const auto library_name = cxxplug::get_library_name("test"); #ifdef _WIN32 const auto expect = "test.dll"; #else const auto expect = "libtest.so"; #endif // _WIN32 EXPECT_EQ(library_name, expect); }
22.766667
73
0.688141
0178901bb980db888ea41e06293f16fbc51d45bf
758
cpp
C++
16. Heap/top_k _frequent_eleemnt.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
225
2021-10-01T03:09:01.000Z
2022-03-11T11:32:49.000Z
16. Heap/top_k _frequent_eleemnt.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
252
2021-10-01T03:45:20.000Z
2021-12-07T18:32:46.000Z
16. Heap/top_k _frequent_eleemnt.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
911
2021-10-01T02:55:19.000Z
2022-02-06T09:08:37.000Z
#define pb push_back class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> ans ; unordered_map<int,int> mp ; for ( int i =0 ; i<nums.size(); i++) { mp[nums[i]] ++ ; } // priority_queue<pair<int,int>> pq ; for (auto x :mp ) pq.push(make_pair(x.second ,x.first) ) ; for ( int i=0 ; i< k ; i++){ ans.pb(pq.top().second) ; pq.pop() ; } return ans ; } }; //Given a non-empty array of integers, //find the top k elements which have the highest frequency in the array. //If two numbers have the same frequency then the larger number should be given preference.
25.266667
92
0.523747
017c55c48eca20afad7562e302b57bc3d0b76907
831
cpp
C++
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
3
2015-02-27T04:09:09.000Z
2021-05-11T16:02:55.000Z
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
null
null
null
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
2
2017-08-15T12:34:09.000Z
2020-05-17T07:30:05.000Z
#include <iostream> #include <memory> #include <string> #include <cstdlib> #include <unittest/assert.hpp> #include <unittest/error.hpp> void v1() { using unittest::v1::error; namespace assert = unittest::v1::assert; std::unique_ptr<int> ptr { new int }; try { assert::is_not_null(ptr.release()); } catch (...) { std::clog << "Unexpected error thrown" << std::endl; std::exit(EXIT_FAILURE); } try { assert::is_not_null(ptr.get()); } catch (error const& e) { if (std::string { "is-not-null" } != e.type()) { std::clog << "Unexpected error '" << e.type() << "' thrown" << std::endl; std::exit(EXIT_FAILURE); } } catch (...) { std::clog << "Unexpected error thrown" << std::endl; std::exit(EXIT_FAILURE); } } int main () { v1(); return EXIT_SUCCESS; }
21.307692
65
0.583634
01801849ac23992dc22a0048d412b27e1b3ea4e8
143
cpp
C++
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
1
2020-05-19T20:17:34.000Z
2020-05-19T20:17:34.000Z
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
null
null
null
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
1
2018-07-13T10:22:37.000Z
2018-07-13T10:22:37.000Z
#include"Chatbot.h" #include <iostream> using namespace std; int main() { Tuling xiaoling; xiaoling.Interface(); return 0; }
11.916667
23
0.643357
0181eef46a2b7d6d6418277e17ef875214245fb1
7,341
cc
C++
chrome/browser/ui/views/autofill/save_card_bubble_views.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/ui/views/autofill/save_card_bubble_views.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/autofill/save_card_bubble_views.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/autofill/save_card_bubble_views.h" #include <stddef.h> #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/ui/autofill/save_card_bubble_controller.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/legal_message_line.h" #include "grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/border.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/button/blue_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/link.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_constants.h" namespace autofill { namespace { // Fixed width of the bubble. const int kBubbleWidth = 395; std::unique_ptr<views::StyledLabel> CreateLegalMessageLineLabel( const LegalMessageLine& line, views::StyledLabelListener* listener) { std::unique_ptr<views::StyledLabel> label( new views::StyledLabel(line.text(), listener)); for (const LegalMessageLine::Link& link : line.links()) { label->AddStyleRange(link.range, views::StyledLabel::RangeStyleInfo::CreateForLink()); } return label; } } // namespace SaveCardBubbleViews::SaveCardBubbleViews(views::View* anchor_view, content::WebContents* web_contents, SaveCardBubbleController* controller) : LocationBarBubbleDelegateView(anchor_view, web_contents), controller_(controller), learn_more_link_(nullptr) { DCHECK(controller); views::BubbleDialogDelegateView::CreateBubble(this); } SaveCardBubbleViews::~SaveCardBubbleViews() {} void SaveCardBubbleViews::Show(DisplayReason reason) { ShowForReason(reason); } void SaveCardBubbleViews::Hide() { controller_ = nullptr; CloseBubble(); } views::View* SaveCardBubbleViews::CreateExtraView() { DCHECK(!learn_more_link_); learn_more_link_ = new views::Link(l10n_util::GetStringUTF16(IDS_LEARN_MORE)); learn_more_link_->SetUnderline(false); learn_more_link_->set_listener(this); return learn_more_link_; } views::View* SaveCardBubbleViews::CreateFootnoteView() { if (controller_->GetLegalMessageLines().empty()) return nullptr; // Use BoxLayout to provide insets around the label. View* view = new View(); view->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); // Add a StyledLabel for each line of the legal message. for (const LegalMessageLine& line : controller_->GetLegalMessageLines()) view->AddChildView(CreateLegalMessageLineLabel(line, this).release()); return view; } bool SaveCardBubbleViews::Accept() { controller_->OnSaveButton(); return true; } bool SaveCardBubbleViews::Cancel() { if (controller_) controller_->OnCancelButton(); return true; } bool SaveCardBubbleViews::Close() { // Override to prevent Cancel from being called when the bubble is hidden. // Return true to indicate that the bubble can be closed. return true; } int SaveCardBubbleViews::GetDialogButtons() const { // This is the default for BubbleDialogDelegateView, but it's not the default // for LocationBarBubbleDelegateView. return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL; } base::string16 SaveCardBubbleViews::GetDialogButtonLabel( ui::DialogButton button) const { return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ? IDS_AUTOFILL_SAVE_CARD_PROMPT_ACCEPT : IDS_AUTOFILL_SAVE_CARD_PROMPT_DENY); } bool SaveCardBubbleViews::ShouldDefaultButtonBeBlue() const { return true; } gfx::Size SaveCardBubbleViews::GetPreferredSize() const { return gfx::Size(kBubbleWidth, GetHeightForWidth(kBubbleWidth)); } base::string16 SaveCardBubbleViews::GetWindowTitle() const { return controller_->GetWindowTitle(); } void SaveCardBubbleViews::WindowClosing() { if (controller_) controller_->OnBubbleClosed(); } void SaveCardBubbleViews::LinkClicked(views::Link* source, int event_flags) { DCHECK_EQ(source, learn_more_link_); controller_->OnLearnMoreClicked(); } void SaveCardBubbleViews::StyledLabelLinkClicked(views::StyledLabel* label, const gfx::Range& range, int event_flags) { // Index of |label| within its parent's view hierarchy is the same as the // legal message line index. DCHECK this assumption to guard against future // layout changes. DCHECK_EQ(static_cast<size_t>(label->parent()->child_count()), controller_->GetLegalMessageLines().size()); const auto& links = controller_->GetLegalMessageLines()[label->parent()->GetIndexOf(label)] .links(); for (const LegalMessageLine::Link& link : links) { if (link.range == range) { controller_->OnLegalMessageLinkClicked(link.url); return; } } // |range| was not found. NOTREACHED(); } // Create view containing everything except for the footnote. std::unique_ptr<views::View> SaveCardBubbleViews::CreateMainContentView() { std::unique_ptr<View> view(new View()); view->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, views::kUnrelatedControlVerticalSpacing)); // Add the card type icon, last four digits and expiration date. views::View* description_view = new views::View(); description_view->SetLayoutManager(new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, views::kRelatedButtonHSpacing)); view->AddChildView(description_view); const CreditCard& card = controller_->GetCard(); views::ImageView* card_type_icon = new views::ImageView(); card_type_icon->SetImage( ResourceBundle::GetSharedInstance() .GetImageNamed(CreditCard::IconResourceId(card.type())) .AsImageSkia()); card_type_icon->SetTooltipText(card.TypeForDisplay()); card_type_icon->SetBorder( views::Border::CreateSolidBorder(1, SkColorSetA(SK_ColorBLACK, 10))); description_view->AddChildView(card_type_icon); description_view->AddChildView(new views::Label( base::string16(kMidlineEllipsis) + card.LastFourDigits())); description_view->AddChildView( new views::Label(card.AbbreviatedExpirationDateForDisplay())); // Optionally add label that will contain an explanation for upload. base::string16 explanation = controller_->GetExplanatoryMessage(); if (!explanation.empty()) { views::Label* explanation_label = new views::Label(explanation); explanation_label->SetMultiLine(true); explanation_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); view->AddChildView(explanation_label); } return view; } void SaveCardBubbleViews::Init() { SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); AddChildView(CreateMainContentView().release()); } } // namespace autofill
34.144186
80
0.720883
01843b26f300477b1298c52eeaa7c67d8a99c897
1,232
cpp
C++
sandbox/oldies/memtest/memtest.cpp
rboman/progs
c60b4e0487d01ccd007bcba79d1548ebe1685655
[ "Apache-2.0" ]
2
2021-12-12T13:26:06.000Z
2022-03-03T16:14:53.000Z
sandbox/oldies/memtest/memtest.cpp
rboman/progs
c60b4e0487d01ccd007bcba79d1548ebe1685655
[ "Apache-2.0" ]
5
2019-03-01T07:08:46.000Z
2019-04-28T07:32:42.000Z
sandbox/oldies/memtest/memtest.cpp
rboman/progs
c60b4e0487d01ccd007bcba79d1548ebe1685655
[ "Apache-2.0" ]
2
2017-12-13T13:13:52.000Z
2019-03-13T20:08:15.000Z
#include <iostream> int memtest() { // memtest.cpp --- long int step = 1024 * 1024; double *ptr = NULL; long int lastsiz = 0; int k = 0; do { long int size = (++k) * step; std::cout << "trying to allocate " << (size * sizeof(double)) / 1024 / 1024; std::cout << "Mo..." << std::flush; try { ptr = new double[size]; if (ptr) { std::cout << "succes." << std::endl << std::flush; lastsiz = size; delete[] ptr; } else { std::cout << "failure." << std::endl << std::flush; } } catch (...) { std::cout << "failure." << std::endl << std::flush; break; } } while (ptr); std::cout << "** Metafor::memtest: maximum (estimated) memory block : "; std::cout << (lastsiz * sizeof(double)) / 1024 / 1024 << "Mo..." << std::endl; // cout << "hit something followed by <ENTER>" << endl; // cin >> k; // memtest.cpp --- return lastsiz * (sizeof(double)) / (1024 * 1024); } int main() { return memtest(); }
22
77
0.417208
0184efcc3b5989736813b82f861630e2889a8d41
134
cpp
C++
first_app.cpp
venim1103/sdl-vulkan-demo
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
[ "Apache-2.0" ]
null
null
null
first_app.cpp
venim1103/sdl-vulkan-demo
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
[ "Apache-2.0" ]
null
null
null
first_app.cpp
venim1103/sdl-vulkan-demo
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
[ "Apache-2.0" ]
null
null
null
#include "first_app.hpp" namespace vulkan { void FirstApp::run() { SDL_Event event; while(!sdlwindow.shouldClose(&event)); } }
10.307692
40
0.69403
0184f99805058d61808eb95383e1f95ac4607084
1,013
cpp
C++
test/aoj/0560.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
1
2022-01-25T23:03:10.000Z
2022-01-25T23:03:10.000Z
test/aoj/0560.test.cpp
atree4728/competitive-library
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
[ "CC0-1.0" ]
6
2021-10-06T01:17:04.000Z
2022-01-16T14:45:47.000Z
test/aoj/0560.test.cpp
atree-GitHub/competitive-library
606b444036530b698a6363b1a41cdaa90a7f9578
[ "CC0-1.0" ]
null
null
null
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0560" #include <cassert> #include <iostream> #include "lib/data_structure/partial_sum_2D.hpp" int main() { using namespace std; size_t n, m, q; cin >> n >> m >> q; vector<string> field(n); for (auto &&elem: field) cin >> elem; vector<vector<int>> jcnt(n, vector(m, 0)), ocnt(n, vector(m, 0)), icnt(n, vector(m, 0)); for (size_t i = 0; i < n; i++) for (size_t j = 0; j < m; j++) { switch (field[i][j]) { case 'J': jcnt[i][j]++; break; case 'O': ocnt[i][j]++; break; case 'I': icnt[i][j]++; break; default: assert(false); } } CumSum2D<int> jc(jcnt), oc(ocnt), ic(icnt); while (q--) { size_t sx, sy, gx, gy; cin >> sx >> sy >> gx >> gy; cout << jc(sx - 1, sy - 1, gx, gy) << " " << oc(sx - 1, sy - 1, gx, gy) << " " << ic(sx - 1, sy - 1, gx, gy) << "\n"; } }
32.677419
92
0.467917
01854efcd74250706192739705de9ec6b2d42d42
3,151
cpp
C++
modules/task_2/kolesin_a_bubblesort/main.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2020-11-20T15:05:12.000Z
2020-11-20T15:05:12.000Z
modules/task_2/kolesin_a_bubblesort/main.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2021-02-13T03:00:05.000Z
2021-02-13T03:00:05.000Z
modules/task_2/kolesin_a_bubblesort/main.cpp
LioBuitrago/pp_2020_autumn_informatics
1ecc1b5dae978295778176ff11ffe42bedbc602e
[ "BSD-3-Clause" ]
1
2020-10-11T09:11:57.000Z
2020-10-11T09:11:57.000Z
// Copyright 2020 Kolesin Andrey #include <gtest-mpi-listener.hpp> #include <gtest/gtest.h> #include <stdio.h> #include <random> #include <vector> #include <algorithm> #include "./bubblesort.h" TEST(Count_Words, Test_1) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = {1}; parallelSort(&arr[0], arr.size()); if (rank == 0) { EXPECT_EQ(arr, std::vector<int>({1})); } } TEST(Count_Words, Test_5) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = {-4, 10, 10, 10, 10}; parallelSort(&arr[0], arr.size()); if (rank == 0) { EXPECT_EQ(arr, std::vector<int>({-4, 10, 10, 10, 10})); } } TEST(Count_Words, Test_6) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = {-4, 10, 10, 10, 10, -4}; parallelSort(&arr[0], arr.size()); if (rank == 0) { EXPECT_EQ(arr, std::vector<int>({-4, -4, 10, 10, 10, 10})); } } TEST(Count_Words, Test_12) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; parallelSort(&arr[0], arr.size()); if (rank == 0) { EXPECT_EQ(arr, std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})); } } TEST(Count_Words, Test_13) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; parallelSort(&arr[0], arr.size()); if (rank == 0) { EXPECT_EQ(arr, std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13})); } } TEST(Count_Words, Test_Random) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> arr = getRandomArray(); std::vector<int> arr2 = arr; if (rank == 0) { parallelSort(&arr[0], arr.size()); std::sort(arr2.begin(), arr2.end()); EXPECT_EQ(arr, arr2); } else { int a; parallelSort(&a, 0); } } // TEST(Count_Words, Test_CompareTime) { // int rank; // MPI_Comm_rank(MPI_COMM_WORLD, &rank); // std::vector<int> arr = getRandomArray(10000); // std::vector<int> arr2 = arr; // if (rank == 0) { // double t1 = MPI_Wtime(); // parallelSort(&arr[0],arr.size()); // double t2 = MPI_Wtime(); // SortMass(&arr2[0],arr2.size()); // double t3 = MPI_Wtime(); // std::cout<<"seq: "<<t3-t2<<std::endl<<"paral: "<<t2-t1<<std::endl; // std::cout<<"s/p: "<<(t3-t2)/(t2-t1)<<std::endl; // EXPECT_EQ(arr, arr2); // } // else{ // std::vector<int> a = {}; // parallelSort(&arr[0],2); // } // } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
30.592233
86
0.569026
0188369b84b64e22807211ad007ac4f33e189ef3
343
hpp
C++
src/sys/house.hpp
Hopobcn/EnTT-Pacman
5187472419f05b79fa9b92593e85fff7c0ae6ca1
[ "MIT" ]
null
null
null
src/sys/house.hpp
Hopobcn/EnTT-Pacman
5187472419f05b79fa9b92593e85fff7c0ae6ca1
[ "MIT" ]
null
null
null
src/sys/house.hpp
Hopobcn/EnTT-Pacman
5187472419f05b79fa9b92593e85fff7c0ae6ca1
[ "MIT" ]
null
null
null
// // house.hpp // EnTT Pacman // // Created by Indi Kernick on 29/9/18. // Copyright © 2018 Indi Kernick. All rights reserved. // #ifndef SYS_HOUSE_HPP #define SYS_HOUSE_HPP #include "util/registry.hpp" // These systems deal with ghosts entering and leaving the house void enterHouse(Registry &); void leaveHouse(Registry &); #endif
17.15
64
0.720117
01883cbbd16b6b273468c079782dda2d60153503
471
cpp
C++
src/mnis_bom.cpp
evanodell/mnis
40d5909ff836654d3618e05597b3047aebc9d737
[ "MIT" ]
1
2017-10-13T13:08:20.000Z
2017-10-13T13:08:20.000Z
src/mnis_bom.cpp
evanodell/mnis
40d5909ff836654d3618e05597b3047aebc9d737
[ "MIT" ]
1
2018-05-18T12:49:13.000Z
2021-04-04T15:36:06.000Z
src/mnis_bom.cpp
evanodell/mnis
40d5909ff836654d3618e05597b3047aebc9d737
[ "MIT" ]
null
null
null
#include <Rcpp.h> using namespace Rcpp; // mnis_bom //' Strip out BOM from JSON data //' //' @param x The GET return to strip BOM out of //' @export // [[Rcpp::export]] std::string mnis_bom(std::string x) { if (x.size() < 3) return x; if (x[0] == '\xEF' && x[1] == '\xBB' && x[2] == '\xBF') return x.substr(3); return x; } /*** R x <- "\uFEFFabcdef" print(x) print(mnis_bom(x)) identical(x, mnis_bom(x)) utf8ToInt(x) utf8ToInt(mnis_bom(x)) */
16.821429
57
0.573248
018e7beb17ff3ac7140452cde5d3b1849993d0f1
21,319
cc
C++
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
amilearning/PX4-Autopilot
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
[ "BSD-3-Clause" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: MagneticField.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "MagneticField.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace sensor_msgs { namespace msgs { namespace { const ::google::protobuf::Descriptor* MagneticField_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MagneticField_reflection_ = NULL; } // namespace void protobuf_AssignDesc_MagneticField_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_MagneticField_2eproto() { protobuf_AddDesc_MagneticField_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "MagneticField.proto"); GOOGLE_CHECK(file != NULL); MagneticField_descriptor_ = file->message_type(0); static const int MagneticField_offsets_[3] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, time_usec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, magnetic_field_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, magnetic_field_covariance_), }; MagneticField_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( MagneticField_descriptor_, MagneticField::default_instance_, MagneticField_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, _has_bits_[0]), -1, -1, sizeof(MagneticField), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, _internal_metadata_), -1); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_MagneticField_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MagneticField_descriptor_, &MagneticField::default_instance()); } } // namespace void protobuf_ShutdownFile_MagneticField_2eproto() { delete MagneticField::default_instance_; delete MagneticField_reflection_; } void protobuf_AddDesc_MagneticField_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_MagneticField_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::gazebo::msgs::protobuf_AddDesc_vector3d_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\023MagneticField.proto\022\020sensor_msgs.msgs\032" "\016vector3d.proto\"x\n\rMagneticField\022\021\n\ttime" "_usec\030\001 \002(\003\022-\n\016magnetic_field\030\002 \002(\0132\025.ga" "zebo.msgs.Vector3d\022%\n\031magnetic_field_cov" "ariance\030\003 \003(\002B\002\020\001", 177); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "MagneticField.proto", &protobuf_RegisterTypes); MagneticField::default_instance_ = new MagneticField(); MagneticField::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_MagneticField_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_MagneticField_2eproto { StaticDescriptorInitializer_MagneticField_2eproto() { protobuf_AddDesc_MagneticField_2eproto(); } } static_descriptor_initializer_MagneticField_2eproto_; // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MagneticField::kTimeUsecFieldNumber; const int MagneticField::kMagneticFieldFieldNumber; const int MagneticField::kMagneticFieldCovarianceFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MagneticField::MagneticField() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:sensor_msgs.msgs.MagneticField) } void MagneticField::InitAsDefaultInstance() { magnetic_field_ = const_cast< ::gazebo::msgs::Vector3d*>(&::gazebo::msgs::Vector3d::default_instance()); } MagneticField::MagneticField(const MagneticField& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:sensor_msgs.msgs.MagneticField) } void MagneticField::SharedCtor() { _cached_size_ = 0; time_usec_ = GOOGLE_LONGLONG(0); magnetic_field_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } MagneticField::~MagneticField() { // @@protoc_insertion_point(destructor:sensor_msgs.msgs.MagneticField) SharedDtor(); } void MagneticField::SharedDtor() { if (this != default_instance_) { delete magnetic_field_; } } void MagneticField::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MagneticField::descriptor() { protobuf_AssignDescriptorsOnce(); return MagneticField_descriptor_; } const MagneticField& MagneticField::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_MagneticField_2eproto(); return *default_instance_; } MagneticField* MagneticField::default_instance_ = NULL; MagneticField* MagneticField::New(::google::protobuf::Arena* arena) const { MagneticField* n = new MagneticField; if (arena != NULL) { arena->Own(n); } return n; } void MagneticField::Clear() { // @@protoc_insertion_point(message_clear_start:sensor_msgs.msgs.MagneticField) if (_has_bits_[0 / 32] & 3u) { time_usec_ = GOOGLE_LONGLONG(0); if (has_magnetic_field()) { if (magnetic_field_ != NULL) magnetic_field_->::gazebo::msgs::Vector3d::Clear(); } } magnetic_field_covariance_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool MagneticField::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:sensor_msgs.msgs.MagneticField) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int64 time_usec = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &time_usec_))); set_has_time_usec(); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_magnetic_field; break; } // required .gazebo.msgs.Vector3d magnetic_field = 2; case 2: { if (tag == 18) { parse_magnetic_field: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_magnetic_field())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_magnetic_field_covariance; break; } // repeated float magnetic_field_covariance = 3 [packed = true]; case 3: { if (tag == 26) { parse_magnetic_field_covariance: DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_magnetic_field_covariance()))); } else if (tag == 29) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 26, input, this->mutable_magnetic_field_covariance()))); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:sensor_msgs.msgs.MagneticField) return true; failure: // @@protoc_insertion_point(parse_failure:sensor_msgs.msgs.MagneticField) return false; #undef DO_ } void MagneticField::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:sensor_msgs.msgs.MagneticField) // required int64 time_usec = 1; if (has_time_usec()) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->time_usec(), output); } // required .gazebo.msgs.Vector3d magnetic_field = 2; if (has_magnetic_field()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->magnetic_field_, output); } // repeated float magnetic_field_covariance = 3 [packed = true]; if (this->magnetic_field_covariance_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_magnetic_field_covariance_cached_byte_size_); } for (int i = 0; i < this->magnetic_field_covariance_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteFloatNoTag( this->magnetic_field_covariance(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:sensor_msgs.msgs.MagneticField) } ::google::protobuf::uint8* MagneticField::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:sensor_msgs.msgs.MagneticField) // required int64 time_usec = 1; if (has_time_usec()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->time_usec(), target); } // required .gazebo.msgs.Vector3d magnetic_field = 2; if (has_magnetic_field()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->magnetic_field_, false, target); } // repeated float magnetic_field_covariance = 3 [packed = true]; if (this->magnetic_field_covariance_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _magnetic_field_covariance_cached_byte_size_, target); } for (int i = 0; i < this->magnetic_field_covariance_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->magnetic_field_covariance(i), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:sensor_msgs.msgs.MagneticField) return target; } int MagneticField::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:sensor_msgs.msgs.MagneticField) int total_size = 0; if (has_time_usec()) { // required int64 time_usec = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->time_usec()); } if (has_magnetic_field()) { // required .gazebo.msgs.Vector3d magnetic_field = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->magnetic_field_); } return total_size; } int MagneticField::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:sensor_msgs.msgs.MagneticField) int total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required int64 time_usec = 1; total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->time_usec()); // required .gazebo.msgs.Vector3d magnetic_field = 2; total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->magnetic_field_); } else { total_size += RequiredFieldsByteSizeFallback(); } // repeated float magnetic_field_covariance = 3 [packed = true]; { int data_size = 0; data_size = 4 * this->magnetic_field_covariance_size(); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _magnetic_field_covariance_cached_byte_size_ = data_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MagneticField::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:sensor_msgs.msgs.MagneticField) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const MagneticField* source = ::google::protobuf::internal::DynamicCastToGenerated<const MagneticField>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:sensor_msgs.msgs.MagneticField) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:sensor_msgs.msgs.MagneticField) MergeFrom(*source); } } void MagneticField::MergeFrom(const MagneticField& from) { // @@protoc_insertion_point(class_specific_merge_from_start:sensor_msgs.msgs.MagneticField) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } magnetic_field_covariance_.MergeFrom(from.magnetic_field_covariance_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_time_usec()) { set_time_usec(from.time_usec()); } if (from.has_magnetic_field()) { mutable_magnetic_field()->::gazebo::msgs::Vector3d::MergeFrom(from.magnetic_field()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void MagneticField::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:sensor_msgs.msgs.MagneticField) if (&from == this) return; Clear(); MergeFrom(from); } void MagneticField::CopyFrom(const MagneticField& from) { // @@protoc_insertion_point(class_specific_copy_from_start:sensor_msgs.msgs.MagneticField) if (&from == this) return; Clear(); MergeFrom(from); } bool MagneticField::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; if (has_magnetic_field()) { if (!this->magnetic_field_->IsInitialized()) return false; } return true; } void MagneticField::Swap(MagneticField* other) { if (other == this) return; InternalSwap(other); } void MagneticField::InternalSwap(MagneticField* other) { std::swap(time_usec_, other->time_usec_); std::swap(magnetic_field_, other->magnetic_field_); magnetic_field_covariance_.UnsafeArenaSwap(&other->magnetic_field_covariance_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MagneticField::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MagneticField_descriptor_; metadata.reflection = MagneticField_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // MagneticField // required int64 time_usec = 1; bool MagneticField::has_time_usec() const { return (_has_bits_[0] & 0x00000001u) != 0; } void MagneticField::set_has_time_usec() { _has_bits_[0] |= 0x00000001u; } void MagneticField::clear_has_time_usec() { _has_bits_[0] &= ~0x00000001u; } void MagneticField::clear_time_usec() { time_usec_ = GOOGLE_LONGLONG(0); clear_has_time_usec(); } ::google::protobuf::int64 MagneticField::time_usec() const { // @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.time_usec) return time_usec_; } void MagneticField::set_time_usec(::google::protobuf::int64 value) { set_has_time_usec(); time_usec_ = value; // @@protoc_insertion_point(field_set:sensor_msgs.msgs.MagneticField.time_usec) } // required .gazebo.msgs.Vector3d magnetic_field = 2; bool MagneticField::has_magnetic_field() const { return (_has_bits_[0] & 0x00000002u) != 0; } void MagneticField::set_has_magnetic_field() { _has_bits_[0] |= 0x00000002u; } void MagneticField::clear_has_magnetic_field() { _has_bits_[0] &= ~0x00000002u; } void MagneticField::clear_magnetic_field() { if (magnetic_field_ != NULL) magnetic_field_->::gazebo::msgs::Vector3d::Clear(); clear_has_magnetic_field(); } const ::gazebo::msgs::Vector3d& MagneticField::magnetic_field() const { // @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.magnetic_field) return magnetic_field_ != NULL ? *magnetic_field_ : *default_instance_->magnetic_field_; } ::gazebo::msgs::Vector3d* MagneticField::mutable_magnetic_field() { set_has_magnetic_field(); if (magnetic_field_ == NULL) { magnetic_field_ = new ::gazebo::msgs::Vector3d; } // @@protoc_insertion_point(field_mutable:sensor_msgs.msgs.MagneticField.magnetic_field) return magnetic_field_; } ::gazebo::msgs::Vector3d* MagneticField::release_magnetic_field() { // @@protoc_insertion_point(field_release:sensor_msgs.msgs.MagneticField.magnetic_field) clear_has_magnetic_field(); ::gazebo::msgs::Vector3d* temp = magnetic_field_; magnetic_field_ = NULL; return temp; } void MagneticField::set_allocated_magnetic_field(::gazebo::msgs::Vector3d* magnetic_field) { delete magnetic_field_; magnetic_field_ = magnetic_field; if (magnetic_field) { set_has_magnetic_field(); } else { clear_has_magnetic_field(); } // @@protoc_insertion_point(field_set_allocated:sensor_msgs.msgs.MagneticField.magnetic_field) } // repeated float magnetic_field_covariance = 3 [packed = true]; int MagneticField::magnetic_field_covariance_size() const { return magnetic_field_covariance_.size(); } void MagneticField::clear_magnetic_field_covariance() { magnetic_field_covariance_.Clear(); } float MagneticField::magnetic_field_covariance(int index) const { // @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.magnetic_field_covariance) return magnetic_field_covariance_.Get(index); } void MagneticField::set_magnetic_field_covariance(int index, float value) { magnetic_field_covariance_.Set(index, value); // @@protoc_insertion_point(field_set:sensor_msgs.msgs.MagneticField.magnetic_field_covariance) } void MagneticField::add_magnetic_field_covariance(float value) { magnetic_field_covariance_.Add(value); // @@protoc_insertion_point(field_add:sensor_msgs.msgs.MagneticField.magnetic_field_covariance) } const ::google::protobuf::RepeatedField< float >& MagneticField::magnetic_field_covariance() const { // @@protoc_insertion_point(field_list:sensor_msgs.msgs.MagneticField.magnetic_field_covariance) return magnetic_field_covariance_; } ::google::protobuf::RepeatedField< float >* MagneticField::mutable_magnetic_field_covariance() { // @@protoc_insertion_point(field_mutable_list:sensor_msgs.msgs.MagneticField.magnetic_field_covariance) return &magnetic_field_covariance_; } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace msgs } // namespace sensor_msgs // @@protoc_insertion_point(global_scope)
36.195246
143
0.735166
018f9341b13ea26fc66097e44c6d3fc1a3347ed6
3,657
cpp
C++
src/quit.cpp
meelgroup/RoundXOR
c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7
[ "MIT" ]
5
2021-10-29T18:39:10.000Z
2022-03-23T11:53:46.000Z
src/quit.cpp
meelgroup/RoundXOR
c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7
[ "MIT" ]
1
2022-02-09T10:56:21.000Z
2022-02-09T10:56:30.000Z
src/quit.cpp
meelgroup/linpb
c35d7316a46deed7cca0ab7eb314b5aa2ff7d7f7
[ "MIT" ]
null
null
null
/*********************************************************************** Copyright (c) 2014-2020, Jan Elffers Copyright (c) 2019-2020, Jo Devriendt Copyright (c) 2020, Stephan Gocht Parts of the code were copied or adapted from MiniSat. MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010 Niklas Sorensson 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 "quit.hpp" #include <iostream> #include "Solver.hpp" #include "globals.hpp" namespace rs { void quit::printSol(const std::vector<Lit>& sol) { printf("v"); for (Var v = 1; v < (Var)sol.size(); ++v) printf(sol[v] > 0 ? " x%d" : " -x%d", v); printf("\n"); } void quit::printSolAsOpb(const std::vector<Lit>& sol) { for (Var v = 1; v < (Var)sol.size(); ++v) { if (sol[v] > 0) std::cout << "+1 x" << v << " >= 1 ;\n"; else std::cout << "-1 x" << v << " >= 0 ;\n"; } } void quit::exit_SAT(const Solver& solver) { assert(solver.foundSolution()); if (solver.logger) solver.logger->flush(); if (options.verbosity.get() > 0) stats.print(); puts("s SATISFIABLE"); if (options.printSol) printSol(solver.lastSol); exit(10); } template <typename LARGE> void quit::exit_UNSAT(const Solver& solver, const LARGE& bestObjVal) { if (solver.logger) solver.logger->flush(); if (options.verbosity.get() > 0) stats.print(); if (solver.foundSolution()) { std::cout << "o " << bestObjVal << std::endl; std::cout << "s OPTIMUM FOUND" << std::endl; if (options.printSol) printSol(solver.lastSol); exit(30); } else { puts("s UNSATISFIABLE"); exit(20); } } template void quit::exit_UNSAT<int>(const Solver& solver, const int& bestObjVal); template void quit::exit_UNSAT<long long>(const Solver& solver, const long long& bestObjVal); template void quit::exit_UNSAT<int128>(const Solver& solver, const int128& bestObjVal); template void quit::exit_UNSAT<int256>(const Solver& solver, const int256& bestObjVal); template void quit::exit_UNSAT<bigint>(const Solver& solver, const bigint& bestObjVal); void quit::exit_UNSAT(const Solver& solver) { quit::exit_UNSAT<int>(solver, 0); } void quit::exit_INDETERMINATE(const Solver& solver) { if (solver.foundSolution()) exit_SAT(solver); if (solver.logger) solver.logger->flush(); if (options.verbosity.get() > 0) stats.print(); puts("s UNKNOWN"); exit(0); } DLL_PUBLIC void quit::exit_ERROR(const std::initializer_list<std::string>& messages) { std::cout << "Error: "; for (const std::string& m : messages) std::cout << m; std::cout << std::endl; exit(1); } } // namespace rs
36.57
93
0.67405
0192040515727a93065c7763efdbbe306a22e3e9
2,270
cpp
C++
OS/linux.cpp
partouf/GoPiGoCPP
b0605953cf5f810d7452b2a0d0592cd6715403d7
[ "MIT" ]
1
2016-03-08T13:30:39.000Z
2016-03-08T13:30:39.000Z
OS/linux.cpp
partouf/GoPiGoCPP
b0605953cf5f810d7452b2a0d0592cd6715403d7
[ "MIT" ]
null
null
null
OS/linux.cpp
partouf/GoPiGoCPP
b0605953cf5f810d7452b2a0d0592cd6715403d7
[ "MIT" ]
null
null
null
#include "linux.h" #include <stdio.h> #include <stdlib.h> #include <linux/i2c-dev.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdexcept> #include <string> GoPiGo::LinuxBoard::LinuxBoard(int AI2CDeviceNumber) : IBoard() { this->I2CDeviceNumber = AI2CDeviceNumber; this->fd = 0; this->busy = false; } GoPiGo::LinuxBoard::~LinuxBoard() { this->Disconnect(); } void GoPiGo::LinuxBoard::Disconnect() { ::close(fd); fd = 0; } bool GoPiGo::LinuxBoard::Connect() { int i, raw; std::string fileName = "/dev/i2c-" + std::to_string(I2CDeviceNumber); int address = 0x08; if ((fd = ::open(fileName.c_str(), O_RDWR)) < 0) { // Open port for reading and writing LastKnownError = "Failed to open i2c port - " + fileName; return false; } if (::ioctl(fd, I2C_SLAVE, address) < 0) { Disconnect(); // Set the port options and set the address of the device LastKnownError = "Unable to get bus access to talk to slave"; return false; } this->ReloadBoardVersion(); this->ReloadFirmwareVersion(); return true; } bool GoPiGo::LinuxBoard::IsConnected() { return (fd != 0); } void GoPiGo::LinuxBoard::Sleep(milliseconds_t ATime) { ::usleep(ATime * 1000); } bool GoPiGo::LinuxBoard::WriteBlock(char ACommand, char AValue1, char AValue2, char AValue3) { unsigned char w_buf[5]; w_buf[0] = 1; w_buf[1] = ACommand; w_buf[2] = AValue1; w_buf[3] = AValue2; w_buf[4] = AValue3; if ((::write(fd, w_buf, 5)) != 5) { LastKnownError = "Error writing to GoPiGo"; return false; } this->Sleep(70); return true; } char GoPiGo::LinuxBoard::ReadByte() { unsigned char r_buf[32]; int reg_size = 1; if (::read(fd, r_buf, reg_size) != reg_size) { throw new std::runtime_error("Error reading from GoPiGo"); return -1; } return r_buf[0]; } bool GoPiGo::LinuxBoard::LockWhenAvailable(int ATimeout) { // no need to use actual mutex until we're really going to use threads while (this->busy) { Sleep(1); } this->busy = true; return true; } bool GoPiGo::LinuxBoard::Unlock() { this->busy = false; return true; }
17.734375
92
0.629075
0193187f81e58e37d72b74708ccfa30e9e8df82d
922
cpp
C++
old/programs/cpp/roguelike.cpp
andruwne/druw2000.github.io
bbae45eb135ee25dd8d64c12ab9af69306388994
[ "MIT" ]
null
null
null
old/programs/cpp/roguelike.cpp
andruwne/druw2000.github.io
bbae45eb135ee25dd8d64c12ab9af69306388994
[ "MIT" ]
1
2018-04-10T02:33:32.000Z
2018-04-10T02:33:32.000Z
old/programs/cpp/roguelike.cpp
Druw2000/src
bbae45eb135ee25dd8d64c12ab9af69306388994
[ "MIT" ]
1
2019-02-22T22:12:26.000Z
2019-02-22T22:12:26.000Z
/* It would be cool to try out ncurses library and line drawing characters U+2550 ═ U+2551 ║ U+2554 ╔ U+2557 ╗ U+255A ╚ U+255D ╝ U+2560 ╠ U+2563 ╣ U+2566 ╦ U+2569 ╩ U+256C ╬ */ #include <iostream> #include <fstream> #include <string> #include <chrono> using namespace std; int room(); class rand_int; int main (int argc, char** argv) { // just testing a timer chrono::steady_clock::time_point t = chrono::steady_clock::now(); chrono::duration<float, milli> d = chrono::steady_clock::now() - t; cout << d.count() << endl; // ------------------ room(); return 0; } int room() { rand_int r{0, 100}; return 0; } class rand_int { rand_int(int lo, int hi) : p{lo,hi} { } // store the parameters int operator()() const { return r(); } private: uniform_int_distribution<>::param_type p; auto r = bind(uniform_int_distribution<>{p},default_random_engine{}); };
19.617021
77
0.616052
0197d688542c3d7014675a027dc5e9ae40b81266
8,257
cpp
C++
converter.cpp
jackMilano/QT-Converter
8089f1b028dee223bc536788789ca7aa96d44b95
[ "MIT" ]
null
null
null
converter.cpp
jackMilano/QT-Converter
8089f1b028dee223bc536788789ca7aa96d44b95
[ "MIT" ]
null
null
null
converter.cpp
jackMilano/QT-Converter
8089f1b028dee223bc536788789ca7aa96d44b95
[ "MIT" ]
null
null
null
#include "converter.h" #include "ui_converter.h" #include <QComboBox> #include <QEventLoop> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QVector> #include <QtWidgets> #include <cmath> #include <iostream> Converter::Converter(QWidget *parent) : QMainWindow(parent), _ui(new Ui::Converter), _cached(QVector<bool>(_currencyCodes.size())), _cachedValueDatetime(QVector<QDateTime>(_currencyCodes.size())), _currencyValues(QVector<QVector<double>>(_currencyCodes.size())), _currentIndexComboBox1(_currencyCodes.indexOf("GBP")), _currentIndexComboBox2(_currencyCodes.indexOf("EUR")), _qNetworkAccessManager(new QNetworkAccessManager(this)), _qValidator(new QDoubleValidator(INPUT_VAL_MIN, INPUT_VAL_MAX, 2, this)) { _ui->setupUi(this); // Initialization for(int i = 0; i < _currencyValues.size(); i++) { _currencyValues[i] = QVector<double>(_currencyCodes.size()); } for(const QString currencyCode : _currencyCodes) { _ui->comboBox->addItem(currencyCode); _ui->comboBox_2->addItem(currencyCode); } _ui->comboBox->setCurrentIndex(_currentIndexComboBox1); _ui->comboBox_2->setCurrentIndex(_currentIndexComboBox2); // Setting input validation _ui->lineEdit->setValidator(_qValidator); // Signals to slots connections connect(_ui->lineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(HandleLineEditTextEditedSignal(const QString &))); connect(_ui->lineEdit_2, SIGNAL(textEdited(const QString &)), this, SLOT(HandleLineEditTextEditedSignal(const QString &))); connect(_qNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReplyFinished(QNetworkReply*))); connect(_ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(ChangeCurrencyComboBox(const int))); connect(_ui->comboBox_2, SIGNAL(currentIndexChanged(int)), this, SLOT(ChangeCurrencyComboBox(const int))); // Showing default message in the status bar statusBar()->showMessage(tr("Insert the value you want to convert")); // The second qLineEdit start disabled DisableLineEdit(_ui->lineEdit_2); // First conversion starts as soon the program begins HandleEnteredText(_ui->lineEdit->text(), _ui->lineEdit, _ui->lineEdit_2); } Converter::~Converter() { delete _ui; } void Converter::HandleLineEditTextEditedSignal(const QString &inputText) { // The empty string is not filtered by validator if(inputText == nullptr || inputText == "") { return; } QObject * obj = sender(); QLineEdit * qLineEdit; QLineEdit * otherQLineEdit; if(obj == _ui->lineEdit) { _isFirstLineEdit = true; qLineEdit = _ui->lineEdit; otherQLineEdit = _ui->lineEdit_2; } else if(obj == _ui->lineEdit_2) { _isFirstLineEdit = false; qLineEdit = _ui->lineEdit_2; otherQLineEdit = _ui->lineEdit; } else { return; } HandleEnteredText(inputText, qLineEdit, otherQLineEdit); } void Converter::ReplyFinished(QNetworkReply * reply) { QLineEdit * qLineEdit = _isFirstLineEdit ? _ui->lineEdit : _ui->lineEdit_2; QLineEdit * otherQLineEdit = _isFirstLineEdit ? _ui->lineEdit_2 : _ui->lineEdit; if(reply->error()) { qDebug() << "ERROR!"; qDebug() << reply->errorString(); } else { const int index = _isFirstLineEdit ? _currentIndexComboBox1 : _currentIndexComboBox2; const int otherIndex = _isFirstLineEdit ? _currentIndexComboBox2 : _currentIndexComboBox1; const QJsonDocument qJsonDocument = QJsonDocument::fromJson(reply->readAll()); QJsonObject qJsonObject = qJsonDocument.object(); QJsonValue qJsonValue = qJsonObject.value("rates"); qJsonObject = qJsonValue.toObject(); int size = _currencyCodes.size(); for(int i = 0; i < size; i++) { QString currencyCode = _currencyCodes[i]; qJsonValue = qJsonObject.value(currencyCode); double currencyRelVal = qJsonValue.toDouble(); if(i == index) { continue; } _currencyValues[index][i] = currencyRelVal; } _cached[index] = true; _cachedValueDatetime[index] = QDateTime::currentDateTime(); ConvertAndShowValue(otherQLineEdit, index, otherIndex); } // Reenabling qLineEditInput EnableLineEdit(qLineEdit); EnableLineEdit(otherQLineEdit); reply->deleteLater(); } void Converter::ChangeCurrencyComboBox(const int newIndexComboBox) { QObject * obj = sender(); QComboBox * otherComboBox; int comboBoxIndex = -1; QLineEdit * qLineEdit; QLineEdit * otherQLineEdit; if(obj == _ui->comboBox) { otherComboBox = _ui->comboBox_2; comboBoxIndex = _currentIndexComboBox1; _currentIndexComboBox1 = newIndexComboBox; _isFirstLineEdit = true; qLineEdit = _ui->lineEdit; otherQLineEdit = _ui->lineEdit_2; } else if(obj == _ui->comboBox_2) { otherComboBox = _ui->comboBox; comboBoxIndex = _currentIndexComboBox2; _currentIndexComboBox2 = newIndexComboBox; _isFirstLineEdit = false; qLineEdit = _ui->lineEdit_2; otherQLineEdit = _ui->lineEdit; } else { return; } const int otherComboBoxIndex = otherComboBox->currentIndex(); if(newIndexComboBox == otherComboBoxIndex) { otherComboBox->setCurrentIndex(comboBoxIndex); return; } HandleEnteredText(qLineEdit->text(), qLineEdit, otherQLineEdit); return; } void Converter::HandleEnteredText(const QString &inputText, QLineEdit * const qLineEdit, QLineEdit * const otherQLineEdit) { const int index = _isFirstLineEdit ? _currentIndexComboBox1 : _currentIndexComboBox2; const int otherIndex = _isFirstLineEdit ? _currentIndexComboBox2 : _currentIndexComboBox1; // The input is converted into a number. _inputNumber = ConvertStringToNumber(inputText); // Disabling qLineEditInput DisableLineEdit(qLineEdit); DisableLineEdit(otherQLineEdit); // Let's check if we can use a cached value or values needs updating bool updateCurrencies = false; if(_cached[index]) { int secondsPassedFromLastUpdate = _cachedValueDatetime[index].secsTo(QDateTime::currentDateTime()); if(secondsPassedFromLastUpdate > UPDATE_CURRENCIES_INTERVAL) { updateCurrencies = true; } else { ConvertAndShowValue(otherQLineEdit, index, otherIndex); } } else { updateCurrencies = true; } if(updateCurrencies) { QString url = QString("https://api.fixer.io/latest?base=") + _currencyCodes[index]; _qNetworkAccessManager->get(QNetworkRequest(QUrl(url))); } else { EnableLineEdit(qLineEdit); EnableLineEdit(otherQLineEdit); } } void Converter::ConvertAndShowValue(QLineEdit * const qLineEdit, const int currentIndexFrom, const int currentIndexTo) { const double relVal = _currencyValues[currentIndexFrom][currentIndexTo]; double result = _inputNumber * relVal; result = roundf(result * 100.0f) / 100.0f; qLineEdit->setText(QString::number(result)); return; } void Converter::DisableLineEdit(QLineEdit * const qLineEdit) { qLineEdit->setReadOnly(true); // TODO: trasformare in campo della classe QPalette *palette = new QPalette(); palette->setColor(QPalette::Base, Qt::white); palette->setColor(QPalette::Text, Qt::darkGray); qLineEdit->setPalette(*palette); return; } void Converter::EnableLineEdit(QLineEdit * const qLineEdit) { qLineEdit->setReadOnly(false); qLineEdit->setPalette(qLineEdit->style()->standardPalette()); return; } const double Converter::ConvertStringToNumber(const QString &inputText) { const QByteArray qByteArray = inputText.toLatin1(); const char *inputTextCharArray = qByteArray.data(); double num = -1.0f; int sscanfRetVal = sscanf_s(inputTextCharArray, "%lf", &num); if(sscanfRetVal == 0 || sscanfRetVal == EOF) { return 0; } return num; }
28.870629
127
0.675669
019885849c6e40616f80020631204cd3811ae869
14,162
cpp
C++
graphicspiece.cpp
0yinf/Klotski
df3c3d6ea58d936e059b31c614bdafebd88e70ec
[ "MIT" ]
2
2017-09-17T16:16:15.000Z
2017-09-17T16:16:18.000Z
graphicspiece.cpp
0yinf/Klotski
df3c3d6ea58d936e059b31c614bdafebd88e70ec
[ "MIT" ]
1
2017-09-21T08:27:20.000Z
2017-09-21T08:27:20.000Z
graphicspiece.cpp
0yinf/Klotski
df3c3d6ea58d936e059b31c614bdafebd88e70ec
[ "MIT" ]
3
2017-09-13T02:44:46.000Z
2017-09-17T05:41:11.000Z
//#define IGNORE_VALID_MOVES #define MOVE_SYNC_THRESHOLD 0.6 //#define MOVE_DIRECTION_LIMIT_CANCEL_THRESHOLD 0.03 #include "common.h" #include "graphicspiece.h" #include "move.h" #include <QPainter> #include <QWidget> #include <QGraphicsScene> #include <QDebug> #include <QGraphicsSceneMouseEvent> #include <QSequentialAnimationGroup> #include <QKeyEvent> #include <QPropertyAnimation> #include <QFont> #include <cmath> GraphicsPiece::GraphicsPiece(int index, const Piece &piece) : piece_(piece), index_(index) { clearValidMoveDirection(); hovered_ = false; pressed_ = false; focused_ = false; in_animation_ = false; have_skin_ = false; edit_mode_ = false; virtual_initial_mouse_pos_ = QPointF(0, 0); piece_base_pos_ = QPointF(0, 0); setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable); setAcceptHoverEvents(true); qDebug() << "New GraphicsPiece" << index << piece_.geometry(); } const Piece &GraphicsPiece::piece() const { return piece_; } int GraphicsPiece::index() const { return index_; } void GraphicsPiece::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) if (have_skin_) { painter->setBrush(background_brush_); painter->drawRoundedRect(rect_, scale_ * 0.05, scale_ * 0.05); } QPen pen; pen.setColor(Qt::black); pen.setJoinStyle(Qt::RoundJoin); pen.setCapStyle(Qt::RoundCap); pen.setColor(Qt::black); pen.setJoinStyle(Qt::RoundJoin); pen.setCapStyle(Qt::RoundCap); if (focused_) { pen.setWidth(3); } else { pen.setWidth(2); } // Background painter->setPen(pen); if (pressed_) painter->setBrush(QColor(200, 200, 200, have_skin_ ? 64 : 128)); else painter->setBrush(QColor(128, 128, 128, have_skin_ ? 64 : 128)); painter->drawRoundedRect(rect_, scale_ * 0.05, scale_ * 0.05); // Arrows QRectF bounding_rect = boundingRect(); if (!in_animation_) { if (focused_ || have_skin_) { painter->setBrush(QBrush(Qt::white)); } else { painter->setBrush(QBrush(Qt::black)); } pen.setWidth(0); painter->setPen(pen); qreal free_space = scale_ * 0.05; if (can_move_up_) { QPolygonF polygon; polygon << QPointF(bounding_rect.width() / 2, free_space * 2) << QPointF(bounding_rect.width() / 2 - free_space * 2, free_space * 4) << QPointF(bounding_rect.width() / 2 + free_space * 2, free_space * 4); painter->drawPolygon(polygon); } if (can_move_down_) { QPolygonF polygon; polygon << QPointF(bounding_rect.width() / 2, bounding_rect.height() - free_space * 2) << QPointF(bounding_rect.width() / 2 - free_space * 2, bounding_rect.height() - free_space * 4) << QPointF(bounding_rect.width() / 2 + free_space * 2, bounding_rect.height() - free_space * 4); painter->drawPolygon(polygon); } if (can_move_left_) { QPolygonF polygon; polygon << QPointF(free_space * 2, bounding_rect.height() / 2) << QPointF(free_space * 4, bounding_rect.height() / 2 - free_space * 2) << QPointF(free_space * 4, bounding_rect.height() / 2 + free_space * 2); painter->drawPolygon(polygon); } if (can_move_right_) { QPolygonF polygon; polygon << QPointF(bounding_rect.width() - free_space * 2, bounding_rect.height() / 2) << QPointF(bounding_rect.width() - free_space * 4, bounding_rect.height() / 2 - free_space * 2) << QPointF(bounding_rect.width() - free_space * 4, bounding_rect.height() / 2 + free_space * 2); painter->drawPolygon(polygon); } } // Text if (have_skin_) { pen.setColor(Qt::white); } else { pen.setColor(Qt::black); } painter->setPen(pen); static QFont font("Microsoft YaHei", 20); QFontMetrics font_metrics(font); QSize text_size = font_metrics.size(Qt::TextSingleLine, tr("%1").arg(index_)); painter->setFont(font); painter->drawText( QPointF(bounding_rect.width() / 2 - text_size.width() / 2, bounding_rect.height() / 2 + text_size.height() / 2), QString("%1").arg(index_) ); } void GraphicsPiece::setBackgroundImage(const QImage &image) { if (image.isNull()) { have_skin_ = false; } else { have_skin_ = true; background_image_ = image; scaleBackgroundImageToBrush(); } update(); } void GraphicsPiece::scaleBackgroundImageToBrush() { background_brush_ = background_image_.scaled(boundingRect().size().toSize(), Qt::KeepAspectRatioByExpanding); } void GraphicsPiece::setEditMode(bool edit_mode) { edit_mode_ = edit_mode; addValidMoveDirection(Move()); // force refresh valid moves update(); } QRectF GraphicsPiece::boundingRect() const { return QRectF(QPointF(0, 0), piece_.size() * scale_); // ignore free space for easy drawing } QRectF GraphicsPiece::calcRect(const Piece &piece) { qreal space_height = scale_ * piece.size().height(); qreal space_width = scale_ * piece.size().width(); qreal free_space = scale_ * 0.05; QRectF res(0, 0, 0, 0); res.setSize(QSizeF(space_width - 2 * free_space, space_height - 2 * free_space)); res.moveTopLeft(QPointF( free_space, free_space)); // qDebug() << "calcRect" << "piece" << piece.geometry() << "calculated" << res; return res; } QPointF GraphicsPiece::calcPosition(const Piece &piece) { QPointF pos(piece.position().x() * scale_, piece.position().y() * scale_); // qDebug() << "calcPosition" << "piece" << piece.geometry() << "calculated" << pos; return pos; } QPointF GraphicsPiece::calcPosition(const QPoint &point) { QPointF pos(point.x() * scale_, point.y() * scale_); // qDebug() << "calcPosition" << "point" << point << "calculated" << pos; return pos; } void GraphicsPiece::onSceneResize() { if (scene() != nullptr) { scale_ = scene()->sceneRect().width() / kHorizontalUnit; rect_ = calcRect(piece_); piece_base_pos_ = calcPosition(piece_); setPos(piece_base_pos_); if (have_skin_) { scaleBackgroundImageToBrush(); } qDebug() << "GraphicsPiece" << index_ << "Resize boundingRect" << boundingRect() << "pos" << pos(); update(); } else { qDebug() << "Invalid" << "scene_"; rect_ = QRectF(0, 0, 0, 0); } } void GraphicsPiece::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsObject::hoverEnterEvent(event); setFocus(); hovered_ = true; qDebug() << this << "hoverEnterEvent"; } void GraphicsPiece::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsObject::hoverLeaveEvent(event); hovered_ = false; qDebug() << this << "hoverLeaveEvent"; } void GraphicsPiece::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsObject::mousePressEvent(event); pressed_ = true; update(); // update color if (event->button() & Qt::LeftButton) { // moving_direction_ = Direction::invalid; virtual_initial_mouse_pos_ = event->scenePos(); } if (edit_mode_ && (event->button() & Qt::RightButton)) { rotatePiece(); } qDebug() << this << "mousePressEvent" << event->button(); } void GraphicsPiece::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (in_animation_) { return; } if (event->button() & Qt::LeftButton) { QGraphicsObject::mouseMoveEvent(event); return; } QPointF current_mouse_pos = event->scenePos(); QPointF mouse_move = current_mouse_pos - virtual_initial_mouse_pos_; QPointF piece_move = QPointF(0, 0); if (std::abs(mouse_move.y()) > std::abs(mouse_move.x())) { if (mouse_move.y() < 0) { if (can_move_up_) { piece_move = QPointF(0, mouse_move.y()); if (abs(piece_move.y()) > scale_ * MOVE_SYNC_THRESHOLD) { applyMove(Move(index_, 0, -1), false); virtual_initial_mouse_pos_.setY(virtual_initial_mouse_pos_.y() - scale_); piece_move = QPointF(0, scale_ + mouse_move.y()); } } } else if (can_move_down_) { piece_move = QPointF(0, mouse_move.y()); if (abs(piece_move.y()) > scale_ * MOVE_SYNC_THRESHOLD) { applyMove(Move(index_, 0, 1), false); virtual_initial_mouse_pos_.setY(virtual_initial_mouse_pos_.y() + scale_); piece_move = QPointF(0, -scale_ + mouse_move.y()); } } } else { if (mouse_move.x() < 0) { if (can_move_left_) { piece_move = QPointF(mouse_move.x(), 0); if (abs(piece_move.x()) > scale_ * MOVE_SYNC_THRESHOLD) { applyMove(Move(index_, -1, 0), false); virtual_initial_mouse_pos_.setX(virtual_initial_mouse_pos_.x() - scale_); piece_move = QPointF(scale_ + mouse_move.x(), 0); } } } else { if (can_move_right_) { piece_move = QPointF(mouse_move.x(), 0); if (abs(piece_move.x()) > scale_ * MOVE_SYNC_THRESHOLD) { applyMove(Move(index_, 1, 0), false); virtual_initial_mouse_pos_.setX(virtual_initial_mouse_pos_.x() + scale_); piece_move = QPointF(- scale_ + mouse_move.x(), 0); } } } // if (abs(piece_move.x()) > scale_) // piece_move.setX(piece_move.x() > 0 ? scale_ : -scale_); } qDebug("%d, %d, %d, %d", can_move_up_, can_move_down_, can_move_left_, can_move_right_); qDebug() << "virtual_initial_mouse_pos_" << virtual_initial_mouse_pos_; qDebug() << "current_mouse_pos" << current_mouse_pos; qDebug() << "piece_base_pos_" << piece_base_pos_; qDebug() << "mouse_move" << mouse_move; qDebug() << "piece_move" << piece_move; setPos(piece_base_pos_ + piece_move); update(); // QGraphicsObject::mouseMoveEvent(event); qDebug() << this << "mouseMoveEvent" << event->button(); } void GraphicsPiece::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { QGraphicsObject::mouseReleaseEvent(event); pressed_ = false; update(); if (!in_animation_) { applyMove(Move(-1, 0, 0)); } qDebug() << this << "mouseReleaseEvent" << event->button(); } void GraphicsPiece::keyPressEvent(QKeyEvent *event) { QGraphicsObject::keyPressEvent(event); int x = 0, y = 0; switch (event->key()) { case Qt::Key_W: case Qt::Key_Up: y = can_move_up_ ? -1 : 0; break; case Qt::Key_S: case Qt::Key_Down: y = can_move_down_ ? 1 : 0; break; case Qt::Key_A: case Qt::Key_Left: x = can_move_left_ ? -1 : 0; break; case Qt::Key_D: case Qt::Key_Right: x = can_move_right_ ? 1 : 0; break; case Qt::Key_R: if (edit_mode_) { rotatePiece(); } break; } qDebug() << "Keypress move" << x << y; if (x != 0 || y != 0) { applyMove(Move(index_, x, y)); } qDebug() << this << "keyPressEvent"; } void GraphicsPiece::focusInEvent(QFocusEvent *event) { qDebug() << index_ << event; focused_ = true; // gain focus will auto update } void GraphicsPiece::focusOutEvent(QFocusEvent *event) { qDebug() << index_ << event; focused_ = false; update(); } void GraphicsPiece::clearValidMoveDirection() { if(!edit_mode_) { can_move_up_ = can_move_down_ = can_move_right_ = can_move_left_ = false; } qDebug() << "Piece" << index_ << "clearValidMoveDirection"; update(); } void GraphicsPiece::addValidMoveDirection(const Move &valid_move) { qDebug() << "Piece" << index_ << "adding valid move direction"; if(!edit_mode_) { if (valid_move.y() == -1) can_move_up_ = true; else if (valid_move.y() == 1) can_move_down_ = true; else if (valid_move.x() == -1) can_move_left_ = true; else if (valid_move.x() == 1) can_move_right_ = true; } else { can_move_down_ = can_move_right_ = can_move_left_ = can_move_up_ = true; } update(); } void GraphicsPiece::applyMove(const Move &move, bool animate) { static std::size_t emitted = 0; if (move.id() != emitted) { piece_ << move; QPointF last_piece_base_pos = piece_base_pos_; piece_base_pos_ = calcPosition(piece_); if (animate) { QPropertyAnimation *animation = new QPropertyAnimation(this, "pos"); animation->setEndValue(piece_base_pos_); animation->setDuration(200); if (move.isNull()) { animation->setStartValue(pos()); animation->start(QPropertyAnimation::DeleteWhenStopped); } else { animation->setStartValue(last_piece_base_pos); addAnimation(animation); } } qDebug() << "Move" << &move << "Finished on View"; if (move.index() != -1) { emitted = move.id(); qDebug() << "[EMIT] syncMove(move)"; emit syncMove(move); } } else { qDebug() << "Move" << &move << "required on View but have be down"; } } void GraphicsPiece::animationFinished() { in_animation_ = false; update(); } void GraphicsPiece::animationStarted() { in_animation_ = true; // auto update by animation } void GraphicsPiece::rotatePiece() { QRect old_rect = piece_.geometry(); piece_ = Piece(QRect(old_rect.x(), old_rect.y(), old_rect.height(), old_rect.width())); onSceneResize(); // resize graphics piece scene()->update(); emit pieceRotated(index_); }
33.961631
116
0.59695
0199c6f043091081dc9b62b0896afc710cd495d8
2,333
cpp
C++
luna2d/platform/wp/lunawplog.cpp
stepanp/luna2d
b9dbec8cabaaf4c3c0a4f99720350d25a8b42fcf
[ "MIT" ]
30
2015-01-06T20:42:55.000Z
2022-01-12T01:46:47.000Z
luna2d/platform/wp/lunawplog.cpp
stepanp/luna2d
b9dbec8cabaaf4c3c0a4f99720350d25a8b42fcf
[ "MIT" ]
null
null
null
luna2d/platform/wp/lunawplog.cpp
stepanp/luna2d
b9dbec8cabaaf4c3c0a4f99720350d25a8b42fcf
[ "MIT" ]
13
2016-04-26T15:42:44.000Z
2022-03-21T02:40:58.000Z
//----------------------------------------------------------------------------- // luna2d engine // Copyright 2014-2017 Stepan Prokofjev // // 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 "lunawplog.h" #include "lunawstring.h" #include <windows.h> using namespace luna2d; // Print log message with given log level void PrintLog(const std::wstring& level, const char* message, va_list va) { int size = _vscprintf(message, va) + 1; // Get required buffer size for "vsprintf_s" std::string buf; buf.resize(size); vsprintf_s(&buf[0], size, message, va); // Prtint log level if(!level.empty()) { OutputDebugString(level.c_str()); OutputDebugString(L":"); } // Print log message OutputDebugString(ToWString(buf).c_str()); OutputDebugString(L"\n"); } // Log info void LUNAWpLog::Info(const char* message, ...) { va_list va; va_start(va, message); PrintLog(L"", message, va); va_end(va); } // Log warning void LUNAWpLog::Warning(const char* message, ...) { va_list va; va_start(va, message); PrintLog(L"Warning", message, va); va_end(va); } // Log error void LUNAWpLog::Error(const char* message, ...) { va_list va; va_start(va, message); PrintLog(L"Error", message, va); va_end(va); }
28.802469
86
0.676382
019ded58dc8cb5bb2ae9c8f747fb644d00efffe2
431
hpp
C++
Hurrican/src/enemies/Gegner_Diamant.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
21
2018-04-13T10:45:45.000Z
2022-03-29T14:53:43.000Z
Hurrican/src/enemies/Gegner_Diamant.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
10
2018-07-03T02:08:44.000Z
2021-05-17T16:13:21.000Z
Hurrican/src/enemies/Gegner_Diamant.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
3
2021-10-08T12:35:05.000Z
2022-03-03T06:03:49.000Z
#ifndef _GEGNER_DIAMANT_H #define _GEGNER_DIAMANT_H #include "GegnerClass.hpp" #include "Gegner_Stuff.hpp" class GegnerDiamant : public GegnerClass { public: GegnerDiamant(int Wert1, int Wert2, // Konstruktor bool Light); void GegnerExplode() override; // Gegner explodiert void DoKI() override; // Gegner individuell mit seiner eigenen kleinen KI bewegen }; #endif
25.352941
95
0.672854
019e2d5982570cba05a08d57a7d44f0e0ca3a6c1
1,231
cpp
C++
playground/meta-programming/if-else.cpp
llHoYall/Cpp_Playground
3f50237c7530e31be571e67ad2a627d1f33bbf51
[ "MIT" ]
null
null
null
playground/meta-programming/if-else.cpp
llHoYall/Cpp_Playground
3f50237c7530e31be571e67ad2a627d1f33bbf51
[ "MIT" ]
null
null
null
playground/meta-programming/if-else.cpp
llHoYall/Cpp_Playground
3f50237c7530e31be571e67ad2a627d1f33bbf51
[ "MIT" ]
null
null
null
/******************************************************************************* * @brief Template Meta programming: If-Else * @author llHoYall <hoya128@gmail.com> * @version v1.0 * @history * 2018.12.29 Created. ******************************************************************************/ /* Include Headers -----------------------------------------------------------*/ #include <iostream> /* Private Functions ---------------------------------------------------------*/ static void TrueStatement(void) { std::cout << " True Statement" << std::endl; } static void FalseStatement(void) { std::cout << " False Statement" << std::endl; } /* Templates -----------------------------------------------------------------*/ template<bool predicate> class IfElse {}; template<> class IfElse<true> { public: static inline void func(void) { TrueStatement(); } }; template<> class IfElse<false> { public: static inline void func(void) { FalseStatement(); } }; /* Main Routine --------------------------------------------------------------*/ auto Main_IfElse(void) -> int { std::cout << "> Template Meta Programming: If-Else" << std::endl; IfElse<(2 + 3 == 5)>::func(); std::cout << std::endl; return 0; }
24.62
80
0.434606
019e9cff3c65cc2e178cb19d59c226d7d94b6a88
456
hpp
C++
courses/compilation/cpp/dnn/step_2/include/dnn/propagation.hpp
JohanMabille/MAP586
d20e01f101ff3f57c96129833835a1cd46071a6d
[ "BSD-3-Clause" ]
4
2022-01-28T15:55:49.000Z
2022-02-15T12:14:32.000Z
courses/compilation/cpp/dnn/step_2/include/dnn/propagation.hpp
JohanMabille/MAP586
d20e01f101ff3f57c96129833835a1cd46071a6d
[ "BSD-3-Clause" ]
null
null
null
courses/compilation/cpp/dnn/step_2/include/dnn/propagation.hpp
JohanMabille/MAP586
d20e01f101ff3f57c96129833835a1cd46071a6d
[ "BSD-3-Clause" ]
3
2021-12-27T08:57:07.000Z
2022-01-17T22:22:02.000Z
#ifndef DNN_PROPAGATION #define DNN_PROPAGATION #include "types.hpp" namespace dnn { void forward_propagation(const array_t& input, const weights_t& weights, matrix_t& aggregation, matrix_t& activation); void backward_propagation(const array_t& input, const array_t& expected, const weights_t& weights, const matrix_t& aggregation, const matrix_t& activation, matrix_t& delta); } #endif
35.076923
122
0.688596
019ed6cc10cfeca30386e45142fbed1c86a29e88
3,553
cpp
C++
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
PowerOfNames/PonX
cac2c67168857409b40f9f76e9570868668370fd
[ "Apache-2.0" ]
null
null
null
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
PowerOfNames/PonX
cac2c67168857409b40f9f76e9570868668370fd
[ "Apache-2.0" ]
null
null
null
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
PowerOfNames/PonX
cac2c67168857409b40f9f76e9570868668370fd
[ "Apache-2.0" ]
null
null
null
#include "pxpch.h" #include "Povox/Renderer/RayTracing/RayTracerTesting.h" #include "Povox/Renderer/RenderCommand.h" #include "Povox/Renderer/VertexArray.h" #include "Povox/Renderer/Texture.h" namespace Povox { struct TracerData { Ref<VertexArray> VertexArray; Ref<Shader> RayMarchingShader; Ref<Texture> MapData1, MapData2, MapData3; }; static TracerData* s_TracerData; void RayTracer::Init() { PX_PROFILE_FUNCTION(); RenderCommand::Init(); s_TracerData = new TracerData(); s_TracerData->VertexArray = VertexArray::Create(); float vertices[12] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; Ref<VertexBuffer> vertexBuffer = VertexBuffer::Create(vertices, sizeof(vertices)); vertexBuffer->SetLayout({ {ShaderDataType::Float3, "a_Position"} }); s_TracerData->VertexArray->AddVertexBuffer(vertexBuffer); uint32_t indices[6] = { 0, 1, 2, 2, 3, 0 }; Ref<IndexBuffer> indexBuffer = IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t)); s_TracerData->VertexArray->SetIndexBuffer(indexBuffer); s_TracerData->MapData1 = Texture2D::Create("MapData", 8, 64); uint32_t mapData1[512]; for (unsigned int i = 0; i < 512; i++) { mapData1[i] = 0x00000000; } mapData1[0] = 0xffffffff; mapData1[511] = 0xffffffff; s_TracerData->MapData1->SetData(&mapData1, sizeof(uint32_t) * 512); s_TracerData->MapData2 = Texture2D::Create("MapData", 1, 2); uint32_t mapData2[2]; for (unsigned int i = 0; i < 2; i++) { mapData2[i] = 0x22222222; } mapData2[1] = 0x77007700; s_TracerData->MapData2->SetData(&mapData2, sizeof(uint32_t) * 2); s_TracerData->MapData3 = Texture2D::Create("MapData", 1, 1); uint32_t MapData3[1]; for (unsigned int i = 0; i < 1; i++) { MapData3[i] = 0x22222222; } s_TracerData->MapData3->SetData(&MapData3, sizeof(uint32_t) * 1); s_TracerData->RayMarchingShader = Shader::Create("assets/shaders/RayMarchingShader.glsl"); s_TracerData->RayMarchingShader->Bind(); //s_TracerData->RayMarchingShader->SetInt("u_MapData", 0); } void RayTracer::Shutdown() { delete s_TracerData; } void RayTracer::BeginScene(PerspectiveCamera& camera, Light& lightsource) { PX_PROFILE_FUNCTION(); //s_TracerData->RayMarchingShader->SetMat4("u_ViewProjection", camera.GetViewProjection()); s_TracerData->RayMarchingShader->SetFloat("u_PointLightIntensity", lightsource.GetIntensity()); s_TracerData->RayMarchingShader->SetFloat3("u_PointLightPos", lightsource.GetPosition()); s_TracerData->RayMarchingShader->SetFloat3("u_PointLightColor", lightsource.GetColor()); s_TracerData->VertexArray->Bind(); } void RayTracer::EndScene() { } void RayTracer::Trace(PerspectiveCameraController& cameraController) { PX_PROFILE_FUNCTION(); PerspectiveCamera cam = cameraController.GetCamera(); s_TracerData->RayMarchingShader->SetFloat3("u_CameraPos", cam.GetPosition()); s_TracerData->RayMarchingShader->SetFloat3("u_CameraFront", cam.GetFront()); s_TracerData->RayMarchingShader->SetFloat3("u_CameraUp", cam.GetUp()); s_TracerData->RayMarchingShader->SetFloat("u_AspectRatio", cam.GetAspectRatio()); s_TracerData->RayMarchingShader->SetFloat2("u_WindowDims", glm::vec2(cameraController.GetWindowWidth(), cameraController.GetWindowHeight())); s_TracerData->RayMarchingShader->SetInt("u_FOV", cameraController.GetFOV()); s_TracerData->VertexArray->Bind(); s_TracerData->MapData2->Bind(); RenderCommand::DrawIndexed(s_TracerData->VertexArray, 6); } }
28.653226
143
0.723614
019ee8efe8f3ac6ac6a1188e277b8ecde4de275b
7,839
cxx
C++
tests/test_string_algo.cxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
tests/test_string_algo.cxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
tests/test_string_algo.cxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * Distributed under the Boost Software License, Version 1.0. */ #include <string> #include <vector> #include <catch2/catch.hpp> #include <ivy/charenc/utf32.hxx> #include <ivy/regex.hxx> #include <ivy/string/join.hxx> #include <ivy/string/match.hxx> #include <ivy/string/split.hxx> #include <ivy/string/trim.hxx> TEST_CASE("ivy:string:join 1-element vector<string> with iterators", "[ivy][string][join]") { std::vector<std::string> strings{"foo"}; std::string r1 = ivy::join(strings.begin(), strings.end(), ","); REQUIRE(r1 == "foo"); } TEST_CASE("ivy:string:join 1-element vector<string> with range", "[ivy][string][join]") { std::vector<std::string> strings{"foo"}; std::string r1 = ivy::join(strings, ","); REQUIRE(r1 == "foo"); } TEST_CASE("ivy:string:join 3-element vector<string> with iterators", "[ivy][string][join]") { std::vector<std::string> strings{"foo", "bar", "quux"}; std::string r1 = ivy::join(strings.begin(), strings.end(), ","); REQUIRE(r1 == "foo,bar,quux"); } TEST_CASE("ivy:string:join 3-element vector<string> with range", "[ivy][string][join]") { std::vector<std::string> strings{"foo", "bar", "quux"}; std::string r1 = ivy::join(strings, ","); REQUIRE(r1 == "foo,bar,quux"); } TEST_CASE("ivy:string:join 3-element vector<string_view> with range", "[ivy][string][join]") { std::vector<std::string_view> strings{"foo", "bar", "quux"}; std::string r1 = ivy::join(strings, ","); REQUIRE(r1 == "foo,bar,quux"); } #if 0 TEST_CASE("ivy:string:match_regex: integer", "[ivy][string][match][match_regex]") { ivy::string test_string = U"123foo"; ivy::u32regex re(U"^[0-9]+"); auto r = ivy::match_regex(test_string, re); REQUIRE(r.first.has_value()); REQUIRE(r.first->size() == 1); auto i_match = (*r.first)[0]; REQUIRE(i_match == U"123"); REQUIRE(r.second == U"foo"); } TEST_CASE("ivy:string:match_regex: no match", "[ivy][string][match][match_regex]") { ivy::string test_string = U"foo123"; ivy::regex re(U"^[0-9]+"); auto r = ivy::match_regex(test_string, re); REQUIRE(!r.first.has_value()); REQUIRE(r.second == U"foo123"); } #endif TEST_CASE("ivy:string:match_string: match", "[ivy][string][match][match_string]") { using namespace std::string_view_literals; ivy::string test_string = U"foo123"; auto [p, rest] = ivy::match_string(test_string, U"fo"); REQUIRE(p); REQUIRE(*p == U"fo"); REQUIRE(rest == U"o123"); } TEST_CASE("ivy:string:match_string: no match", "[ivy][string][match][match_string]") { using namespace std::string_view_literals; ivy::string test_string = U"foo123"; auto [p, rest] = ivy::match_string(test_string, U"123"); REQUIRE(!p); REQUIRE(rest == U"foo123"); } TEST_CASE("ivy:string:match_int: positive decimal integer", "[ivy][string][match][match_int]") { using namespace std::string_view_literals; ivy::string test_string = U"123foo"; auto [i, rest] = ivy::match_int<std::int64_t>(test_string); REQUIRE(i); REQUIRE(*i == 123); REQUIRE(rest == U"foo"); } TEST_CASE("ivy:string:match_int: negative decimal integer", "[ivy][string][match][match_int]") { using namespace std::string_view_literals; ivy::string test_string = U"-123foo"; auto [i, rest] = ivy::match_int<std::int64_t>(test_string); REQUIRE(i); REQUIRE(*i == -123); REQUIRE(rest == U"foo"); } TEST_CASE("ivy:string:match_int: positive hex integer", "[ivy][string][match][match_int]") { using namespace std::string_view_literals; ivy::string test_string = U"1024quux"; auto [i, rest] = ivy::match_int<std::int64_t>(test_string, 16); REQUIRE(i); REQUIRE(*i == 0x1024); REQUIRE(rest == U"quux"); } TEST_CASE("ivy:string:match_int: negative hex integer", "[ivy][string][match][match_int]") { using namespace std::string_view_literals; ivy::string test_string = U"-1024quux"; auto [i, rest] = ivy::match_int<std::int64_t>(test_string, 16); REQUIRE(i); REQUIRE(*i == -0x1024); REQUIRE(rest == U"quux"); } TEST_CASE("ivy:string:match_whitespace: simple", "[ivy][string][match][match_whitespace]") { using namespace std::string_view_literals; ivy::string test_string = U" foo"; auto [ws, rest] = ivy::match_whitespace(test_string); REQUIRE(ws); REQUIRE(*ws == U" "); REQUIRE(rest == U"foo"); } TEST_CASE("ivy:string:match_whitespace: trailing space", "[ivy][string][match][match_whitespace]") { using namespace std::string_view_literals; ivy::string test_string = U" foo "sv; auto [ws, rest] = ivy::match_whitespace(test_string); REQUIRE(ws); REQUIRE(*ws == U" "); REQUIRE(rest == U"foo "); } TEST_CASE("ivy:string:match_whitespace: no match", "[ivy][string][match][match_whitespace]") { using namespace std::string_view_literals; ivy::string test_string = U"foo"; auto [ws, rest] = ivy::match_whitespace(test_string); REQUIRE(!ws); REQUIRE(rest == U"foo"); } TEST_CASE("ivy:string:trim:triml: simple", "[ivy][string][trim][triml]") { using namespace std::string_view_literals; ivy::string test_string = U" foo "; auto trimmed = ivy::triml(test_string); REQUIRE(trimmed == U"foo "); } TEST_CASE("ivy:string:trim:triml: no whitespace", "[ivy][string][trim][triml]") { using namespace std::string_view_literals; ivy::string test_string = U"foo"; auto trimmed = ivy::triml(test_string); REQUIRE(trimmed == U"foo"); } TEST_CASE("ivy:string:split: simple string_view", "[ivy][string][split]") { using namespace std::string_view_literals; std::vector<ivy::string> bits; ivy::string test_1 = U"foo$bar$baz"; ivy::split(test_1, '$', std::back_inserter(bits)); REQUIRE(bits.size() == 3); REQUIRE(bits[0] == U"foo"); REQUIRE(bits[1] == U"bar"); REQUIRE(bits[2] == U"baz"); } TEST_CASE("ivy:string:split: single element", "[ivy][string][split]") { using namespace std::string_view_literals; std::vector<ivy::string> bits; ivy::string test_1 = U"foobar"; ivy::split(test_1, '$', std::back_inserter(bits)); REQUIRE(bits.size() == 1); REQUIRE(bits[0] == U"foobar"); } TEST_CASE("ivy:string:split: empty first token", "[ivy][string][split]") { using namespace std::string_view_literals; std::vector<ivy::string> bits; ivy::string test_1 = U"$foo$bar"; ivy::split(test_1, '$', std::back_inserter(bits)); REQUIRE(bits.size() == 3); REQUIRE(bits[0] == U""); REQUIRE(bits[1] == U"foo"); REQUIRE(bits[2] == U"bar"); } TEST_CASE("ivy:string:split: empty last token", "[ivy][string][split]") { using namespace std::string_view_literals; std::vector<ivy::string> bits; ivy::string test_1 = U"foo$bar$"; ivy::split(test_1, '$', std::back_inserter(bits)); REQUIRE(bits.size() == 3); REQUIRE(bits[0] == U"foo"); REQUIRE(bits[1] == U"bar"); REQUIRE(bits[2] == U""); } TEST_CASE("ivy:string:split: simple string", "[ivy][string][split]") { using namespace std::string_literals; std::vector<ivy::string> bits; ivy::string test_1 = U"foo$bar$baz"; ivy::split(test_1, '$', std::back_inserter(bits)); REQUIRE(bits.size() == 3); REQUIRE(bits[0] == U"foo"); REQUIRE(bits[1] == U"bar"); REQUIRE(bits[2] == U"baz"); }
27.699647
80
0.60148
019f4e5b9a6bfc4569ad707f56c4bd5e2d12f115
5,964
cpp
C++
demos/gravitygizmo/src/player.cpp
leftidev/leng
9df738a9f5d8f90d2a01234d4d4b13311017d93e
[ "MIT" ]
null
null
null
demos/gravitygizmo/src/player.cpp
leftidev/leng
9df738a9f5d8f90d2a01234d4d4b13311017d93e
[ "MIT" ]
null
null
null
demos/gravitygizmo/src/player.cpp
leftidev/leng
9df738a9f5d8f90d2a01234d4d4b13311017d93e
[ "MIT" ]
null
null
null
#include "player.h" #include <iostream> namespace leng { Player::Player(float x, float y, float width, float height, const std::string& path) : Entity(x, y, width, height, path) { upHeld = false; downHeld = false; rightHeld = false; leftHeld = false; inAir = true; jumped = true; canDoubleJump = false; normalGravity = true; respawn = false; deathFlicker = true; direction = Direction::RIGHT; MAX_MOVE_VELOCITY = 1.0f; JUMP_VELOCITY = 1.40f; MAX_GRAVITY_VELOCITY = 2.0f; GRAVITY = 0.10f; ACCELERATION = 0.35; deaths = 0; levelCompleted = false; startPosition.x = x; startPosition.y = y; } Player::~Player() { delete bubble; } void Player::update(std::vector<leng::Block*> blocks, std::vector<Enemy*> enemies, float deltaTime) { Entity::update(); if(!deathFlicker) { // Player is in air, apply gravity if (inAir) { jumped = true; if(normalGravity) { velocity.y -= GRAVITY; } else { velocity.y += GRAVITY; } } else { velocity.y = 0.0f; } if(velocity.y < -MAX_GRAVITY_VELOCITY) { velocity.y = -MAX_GRAVITY_VELOCITY; } if(velocity.y > MAX_GRAVITY_VELOCITY) { velocity.y = MAX_GRAVITY_VELOCITY; } position.y += velocity.y * deltaTime; // Assume player is in air, this makes player fall off platform ledges inAir = true; // Check collisions on Y-axis applyCollisions(glm::fvec2(0.0f, velocity.y), blocks, enemies); // Check movement on x-axis if(rightHeld) { direction = Direction::RIGHT; if(normalGravity) { sprite.originalDirection(); } else { sprite.flipY(); } // Apply acceleration velocity.x += ACCELERATION; if (velocity.x > MAX_MOVE_VELOCITY) { velocity.x = MAX_MOVE_VELOCITY; } } else if(leftHeld) { direction = Direction::LEFT; if(normalGravity) { sprite.flipX(); } else { sprite.flipXY(); } // Apply acceleration velocity.x -= ACCELERATION; if (velocity.x < -MAX_MOVE_VELOCITY) { velocity.x = -MAX_MOVE_VELOCITY; } } else { velocity.x = 0.0f; } position.x += velocity.x * deltaTime; // Check collisions on X-axis applyCollisions(glm::fvec2(velocity.x, 0.0f), blocks, enemies); } else { if(deathFlickerCounter == 3) { deathFlickerCounter = 0; deathFlicker = false; } if(alphaDown) { sprite.color.a -= 0.10f; if(sprite.color.a <= 0.0f) { alphaDown = false; alphaUp = true; } } if(alphaUp) { sprite.color.a += 0.10f; if(sprite.color.a >= 1.0f) { alphaUp = false; alphaDown = true; deathFlickerCounter++; } } } } // Collisions void Player::applyCollisions(glm::fvec2 Velocity, std::vector<Block*> blocks, std::vector<Enemy*> enemies) { // Collide with level tiles for (unsigned int i = 0; i < blocks.size(); i++) { if (collideWithTile(position, width, height, blocks[i])) { if(blocks[i]->type == SOLID || blocks[i]->type == DISAPPEARING) { // Collide from left if (Velocity.x > 0) { position.x = blocks[i]->position.x - width; } // Collide from right else if (Velocity.x < 0) { position.x = blocks[i]->position.x + blocks[i]->width; } if(normalGravity) { // Collide from below if (Velocity.y > 0) { velocity.y = 0; position.y = blocks[i]->position.y - height; inAir = true; } // Collide from above else if (Velocity.y < 0) { velocity.y = 0; position.y = blocks[i]->position.y + blocks[i]->height; inAir = false; jumped = false; canDoubleJump = false; } } else { // Collide from below if (Velocity.y > 0) { velocity.y = 0; position.y = blocks[i]->position.y - height; inAir = false; jumped = false; canDoubleJump = false; } // Collide from above else if (Velocity.y < 0) { velocity.y = 0; position.y = blocks[i]->position.y + blocks[i]->height; inAir = true; } } } else if(blocks[i]->type == KILL || blocks[i]->type == KILLREVERSE) { respawn = true; restart(); deaths++; } else if(blocks[i]->type == EXIT) { levelCompleted = true; } } } // Collide with enemies for (unsigned int i = 0; i < enemies.size(); i++) { if (collideWithTile(position, width, height, enemies[i])) { if(enemies[i]->bubbled) { enemies[i]->destroyed = true; } else { respawn = true; restart(); deaths++; } } } } void Player::jump() { jumped = true; inAir = true; canDoubleJump = true; if(normalGravity) { velocity.y = JUMP_VELOCITY; } else { velocity.y = -JUMP_VELOCITY; } } void Player::doubleJump() { if(canDoubleJump) { inAir = true; canDoubleJump = false; if(normalGravity) { velocity.y = JUMP_VELOCITY; } else { velocity.y = -JUMP_VELOCITY; } } } void Player::gravityBendInvert() { if(normalGravity && !inAir) { normalGravity = false; if(direction == Direction::RIGHT) { sprite.flipY(); } else if (direction == Direction::LEFT) { sprite.flipXY(); } } } void Player::gravityBend() { if(!normalGravity && !inAir) { normalGravity = true; if(direction == Direction::RIGHT) { sprite.originalDirection(); } else if (direction == Direction::LEFT) { sprite.flipX(); } } } void Player::restart() { deathFlicker = true; velocity.x = 0.0f; velocity.y = 0.0f; normalGravity = true; position.x = startPosition.x; position.y = startPosition.y; } void Player::shootBubble() { if(bubble == nullptr) { if(direction == Direction::RIGHT) { bubble = new Projectile(position.x + width + 1, position.y, 52, 52, "assets/textures/bubble_78x78.png", glm::fvec2(1.0f, 0.0f)); } else { bubble = new Projectile(position.x - width - 1, position.y, 52, 52, "assets/textures/bubble_78x78.png", glm::fvec2(-1.0f, 0.0f)); } } } } // namespace leng
22.088889
134
0.598592
01a0efd0f8c35898ee28b2f5badd32cbed94b497
1,728
cpp
C++
CPlusPlus/UserDefinedTypes/struct_particles.cpp
stijnvanhoey/training-material
d8e23c2aefaaafbd6a6d5e059147831c651f21ec
[ "CC0-1.0" ]
null
null
null
CPlusPlus/UserDefinedTypes/struct_particles.cpp
stijnvanhoey/training-material
d8e23c2aefaaafbd6a6d5e059147831c651f21ec
[ "CC0-1.0" ]
null
null
null
CPlusPlus/UserDefinedTypes/struct_particles.cpp
stijnvanhoey/training-material
d8e23c2aefaaafbd6a6d5e059147831c651f21ec
[ "CC0-1.0" ]
1
2019-01-07T22:45:34.000Z
2019-01-07T22:45:34.000Z
#include <cmath> #include <functional> #include <iostream> #include <random> using namespace std; struct Particle { double x, y, z; double mass; }; Particle init_particle(function<double()> pos_distr, function<double()> mass_distr); void move_particle(Particle& p, double dx, double dy, double dz); double dist(const Particle& p1, const Particle& p2); ostream& operator<<(ostream& out, const Particle& p); int main() { auto engine {mt19937_64(1234)}; auto pos_distr = bind(uniform_real_distribution<double>(-1.0, 1.0), ref(engine)); auto mass_distr = bind(uniform_real_distribution<double>(0.0, 1.0), ref(engine)); Particle p1 = init_particle(pos_distr, mass_distr); Particle p2 = init_particle(pos_distr, mass_distr); cout << p1 << endl << p2 << endl; move_particle(p1, 0.5, 0.5, 0.5); cout << "moved: " << p1 << endl; cout << "distance = " << dist(p1, p2) << endl; return 0; } double sqr(double x) { return x*x; } Particle init_particle(std::function<double()> pos_distr, std::function<double()> mass_distr) { Particle p { .x = pos_distr(), .y = pos_distr(), .z = pos_distr(), .mass = mass_distr(), }; return p; } void move_particle(Particle& p, double dx, double dy, double dz) { p.x += dx; p.y += dy; p.z += dz; } double dist(const Particle& p1, const Particle& p2) { return sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y) + sqr(p1.z - p2.z)); } ostream& operator<<(ostream& out, const Particle& p) { return out << "(" << p.x << ", " << p.y << ", " << p.z << ")" << ", mass = " << p.mass; }
27
72
0.570023
01a3a615852f421a860e6011a67dc0de0036e85a
294
cpp
C++
All_code/67.cpp
jnvshubham7/cpp-programming
7d00f4a3b97b9308e337c5d3547fd3edd47c5e0b
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
All_code/67.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
All_code/67.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); long long int a[n]; int sum=0; for(int i=0;i<n;i++){ cin>>a[i]; sum=sum+a[i]; } cout<<sum; return 0; }
14
38
0.482993
01a6e736f7d9374023cc774afc226b6bc2eef20d
4,794
tpp
C++
hardware/libraries/TinyGSM-master/src/TinyGsmGSMLocation.tpp
oscillator25/saaf-water
909edd23eaa3a57c80ccfcebcb0a735305389088
[ "Apache-2.0" ]
32
2021-09-10T17:17:02.000Z
2022-03-03T11:01:38.000Z
hardware/libraries/TinyGSM-master/src/TinyGsmGSMLocation.tpp
oscillator25/saaf-water
909edd23eaa3a57c80ccfcebcb0a735305389088
[ "Apache-2.0" ]
1
2021-07-31T14:45:56.000Z
2021-07-31T14:46:32.000Z
hardware/libraries/TinyGSM-master/src/TinyGsmGSMLocation.tpp
oscillator25/saaf-water
909edd23eaa3a57c80ccfcebcb0a735305389088
[ "Apache-2.0" ]
6
2021-11-18T05:59:46.000Z
2022-01-09T09:18:37.000Z
/** * @file TinyGsmGSMLocation.h * @author Volodymyr Shymanskyy * @license LGPL-3.0 * @copyright Copyright (c) 2016 Volodymyr Shymanskyy * @date Nov 2016 */ #ifndef SRC_TINYGSMGSMLOCATION_H_ #define SRC_TINYGSMGSMLOCATION_H_ #include "TinyGsmCommon.h" #define TINY_GSM_MODEM_HAS_GSM_LOCATION template <class modemType> class TinyGsmGSMLocation { public: /* * GSM Location functions */ String getGsmLocationRaw() { return thisModem().getGsmLocationRawImpl(); } String getGsmLocation() { return thisModem().getGsmLocationRawImpl(); } bool getGsmLocation(float* lat, float* lon, float* accuracy = 0, int* year = 0, int* month = 0, int* day = 0, int* hour = 0, int* minute = 0, int* second = 0) { return thisModem().getGsmLocationImpl(lat, lon, accuracy, year, month, day, hour, minute, second); }; bool getGsmLocationTime(int* year, int* month, int* day, int* hour, int* minute, int* second) { float lat = 0; float lon = 0; float accuracy = 0; return thisModem().getGsmLocation(&lat, &lon, &accuracy, year, month, day, hour, minute, second); } /* * CRTP Helper */ protected: inline const modemType& thisModem() const { return static_cast<const modemType&>(*this); } inline modemType& thisModem() { return static_cast<modemType&>(*this); } /* * GSM Location functions * Template is based on SIMCOM commands */ protected: // String getGsmLocationImpl() { // thisModem().sendAT(GF("+CIPGSMLOC=1,1")); // if (thisModem().waitResponse(10000L, GF("+CIPGSMLOC:")) != 1) { return // ""; } String res = thisModem().stream.readStringUntil('\n'); // thisModem().waitResponse(); // res.trim(); // return res; // } String getGsmLocationRawImpl() { // AT+CLBS=<type>,<cid> // <type> 1 = location using 3 cell's information // 3 = get number of times location has been accessed // 4 = Get longitude latitude and date time thisModem().sendAT(GF("+CLBS=1,1")); // Should get a location code of "0" indicating success if (thisModem().waitResponse(120000L, GF("+CLBS: ")) != 1) { return ""; } int8_t locationCode = thisModem().streamGetIntLength(2); // 0 = success, else, error if (locationCode != 0) { thisModem().waitResponse(); // should be an ok after the error return ""; } String res = thisModem().stream.readStringUntil('\n'); thisModem().waitResponse(); res.trim(); return res; } bool getGsmLocationImpl(float* lat, float* lon, float* accuracy = 0, int* year = 0, int* month = 0, int* day = 0, int* hour = 0, int* minute = 0, int* second = 0) { // AT+CLBS=<type>,<cid> // <type> 1 = location using 3 cell's information // 3 = get number of times location has been accessed // 4 = Get longitude latitude and date time thisModem().sendAT(GF("+CLBS=4,1")); // Should get a location code of "0" indicating success if (thisModem().waitResponse(120000L, GF("+CLBS: ")) != 1) { return false; } int8_t locationCode = thisModem().streamGetIntLength(2); // 0 = success, else, error if (locationCode != 0) { thisModem().waitResponse(); // should be an ok after the error return false; } // init variables float ilat = 0; float ilon = 0; float iaccuracy = 0; int iyear = 0; int imonth = 0; int iday = 0; int ihour = 0; int imin = 0; int isec = 0; ilat = thisModem().streamGetFloatBefore(','); // Latitude ilon = thisModem().streamGetFloatBefore(','); // Longitude iaccuracy = thisModem().streamGetIntBefore(','); // Positioning accuracy // Date & Time iyear = thisModem().streamGetIntBefore('/'); imonth = thisModem().streamGetIntBefore('/'); iday = thisModem().streamGetIntBefore(','); ihour = thisModem().streamGetIntBefore(':'); imin = thisModem().streamGetIntBefore(':'); isec = thisModem().streamGetIntBefore('\n'); // Set pointers if (lat != NULL) *lat = ilat; if (lon != NULL) *lon = ilon; if (accuracy != NULL) *accuracy = iaccuracy; if (iyear < 2000) iyear += 2000; if (year != NULL) *year = iyear; if (month != NULL) *month = imonth; if (day != NULL) *day = iday; if (hour != NULL) *hour = ihour; if (minute != NULL) *minute = imin; if (second != NULL) *second = isec; // Final OK thisModem().waitResponse(); return true; } }; #endif // SRC_TINYGSMGSMLOCATION_H_
31.96
80
0.583438
01a7c79f1c5b69a783f597b7707f36eb1668bac3
725
cpp
C++
examples/simple/simple.cpp
leegang/WifiConfig
e49f1e641e050e2ea207636cac6e8c77829c8672
[ "MIT" ]
6
2019-06-19T09:42:59.000Z
2022-02-23T23:11:20.000Z
examples/simple/simple.cpp
leegang/WifiConfig
e49f1e641e050e2ea207636cac6e8c77829c8672
[ "MIT" ]
3
2019-05-22T14:56:05.000Z
2020-09-29T03:28:04.000Z
examples/simple/simple.cpp
leegang/WifiConfig
e49f1e641e050e2ea207636cac6e8c77829c8672
[ "MIT" ]
4
2019-05-22T14:52:45.000Z
2020-09-08T09:12:22.000Z
#include <Arduino.h> #include <WiFiConfig.h> struct Config { char name[20] = {0}; bool enabled = false; int hour = 0; } config; ConfigManager configManager; void setup() { Serial.begin(115200); configManager.setAPName("Config Demo"); configManager.setAPFilename("/index.html"); configManager.addParameterGroup("app", new Metadata("Application", "Example of application properties")) .addParameter("name", config.name, 20, new Metadata("Name")) .addParameter("enabled", &config.enabled, new Metadata("Enabled")) .addParameter("hour", &config.hour, new Metadata("Hour")); configManager.begin(config); } void loop() { configManager.loop(); delay(1000); }
20.714286
108
0.664828
01ab1d194ef773e9550ad4b8bdfef6e9358c50f7
13,862
cpp
C++
src/core/Application.cpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
12
2019-12-28T21:45:23.000Z
2022-03-28T12:40:44.000Z
src/core/Application.cpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
null
null
null
src/core/Application.cpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
1
2021-05-31T10:22:41.000Z
2021-05-31T10:22:41.000Z
#include "Application.hpp" #include <memory> #include <iostream> #include <string> #include <utility> #include "imgui.h" #include "imgui-SFML.h" #include "imgui_internal.h" #include "trafficsim/RoadTile.hpp" #include "trafficsim/StraightRoad.hpp" #include "trafficsim/RoadIntersection.hpp" #include "trafficsim/RoadTrisection.hpp" #include "trafficsim/RoadJunction.hpp" #include "trafficsim/HomeRoad.hpp" #include "trafficsim/HomeBuilding.hpp" namespace ts { Application *Application::AppInstance = nullptr; Application::Application() : builder_(map_, window_), statistics_(map_, window_, logs_), time_line_(map_), data_(logs_) { AppInstance = this; data_.loadTexturesFromFile("texture_list.txt"); StraightRoad::SetTexture(data_.getTexture("straight_road")); HomeRoad::SetTexture(data_.getTexture("home_road")); RoadTurn::SetTextures(data_.getTexture("right_turn"), data_.getTexture("left_turn")); RoadIntersection::SetTextures(data_.getTexture("right_intersection"), data_.getTexture("left_intersection")); RoadTrisection::SetTextures(data_.getTexture("right_trisection"), data_.getTexture("left_trisection")); RoadJunction::SetTextures(data_.getTexture("right_junction"), data_.getTexture("left_junction")); Car::AddTexture(data_.getTexture("blue_car")); Car::AddTexture(data_.getTexture("brown_car")); Car::AddTexture(data_.getTexture("green_car")); Car::AddTexture(data_.getTexture("grey_car")); Car::AddTexture(data_.getTexture("white_car")); Car::AddTexture(data_.getTexture("red_car")); Car::AddTexture(data_.getTexture("teal_car")); HomeBuilding::SetTexture(data_.getTexture("home_building")); OfficeBuilding::SetTexture(data_.getTexture("office_building")); window_.setViewPos({map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount() / 2, map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount() / 2}); window_.setZoom(3.f); } void Application::run() { float last_time = time_line_.getRealTime(); sf::Vector2i delta_mouse_pos = sf::Mouse::getPosition(); //Main loop while (window_.isOpen()) { window_.pollEvent(); map_.update(time_line_.getGameTime(), time_line_.getFrameTime() * time_line_.getMultiplier()); time_line_.update(app_state_ == State::Simulating); handleInputBuffers(delta_mouse_pos - sf::Mouse::getPosition()); delta_mouse_pos = sf::Mouse::getPosition(); window_.clear(); //Drawing happens between window.clear() and window.draw() window_.draw(map_); drawGUI(); window_.display(); } } void Application::changeState(State new_state) { app_state_ = new_state; switch (app_state_) { case Editing: builder_.setBuildingMode(true); map_.setSimulating(false); break; case Simulating: builder_.setBuildingMode(false); map_.setSimulating(true); break; default: break; } } const char *state_mode(State state) { return (const char *[]){ "Editing", "Simulating"}[state]; } void Application::drawGUI() { ImGui::Begin("Log"); ImGui::BeginChild(""); for (unsigned int i = logs_.size(); i > 0; --i) { ImGui::Text("Log: %s", logs_[i - 1].c_str()); } ImGui::EndChild(); ImGui::End(); if (app_state_ == Simulating) { time_line_.drawGUI(); statistics_.drawGUI(); drawHeatMap(); } if (app_state_ == Editing) builder_.drawGUI(); if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { static char buf[32]; const char *c; std::string file_name; ImGui::InputText("Filename", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Enter))) { file_name = buf + std::string(".csv"); c = file_name.c_str(); data_.loadMap(c, builder_, map_.grid_); } if (ImGui::MenuItem("Load", "Enter")) { file_name = buf + std::string(".csv"); c = file_name.c_str(); data_.loadMap(c, builder_, map_.grid_); } if (ImGui::MenuItem("Save", "Ctrl+S")) { // ".ts" for traffic sim :) file_name = buf + std::string(".csv"); c = file_name.c_str(); data_.saveMap(c, map_.grid_); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Mode")) { for (int i = 0; i < State::StateCount; i++) { State new_state = static_cast<State>(i); if (ImGui::MenuItem(state_mode(new_state), "", app_state_ == new_state)) changeState(new_state); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Scale")) { if (ImGui::MenuItem("Scale: 100%", "Ctrl+1", ImGui::GetFont()->Scale == 1.f)) ImGui::GetFont()->Scale = 1.f; if (ImGui::MenuItem("Scale: 125%", "Ctrl+2", ImGui::GetFont()->Scale == 1.25f)) ImGui::GetFont()->Scale = 1.25f; if (ImGui::MenuItem("Scale: 150%", "Ctrl+3", ImGui::GetFont()->Scale == 1.5f)) ImGui::GetFont()->Scale = 1.5f; if (ImGui::MenuItem("Scale: 200%", "Ctrl+4", ImGui::GetFont()->Scale == 2.f)) ImGui::GetFont()->Scale = 2.f; if (ImGui::MenuItem("Scale: 250%", "Ctrl+5", ImGui::GetFont()->Scale == 2.5f)) ImGui::GetFont()->Scale = 2.5f; if (ImGui::MenuItem("Scale: 300%", "Ctrl+6", ImGui::GetFont()->Scale == 3.f)) ImGui::GetFont()->Scale = 3.f; ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } } void Application::drawHeatMap() { ImGui::Begin("Heat map"); ImDrawList *draw_list = ImGui::GetWindowDrawList(); ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; draw_list->AddRectFilled(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.x), IM_COL32(119, 160, 93, 180)); draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.x), IM_COL32(255, 255, 255, 255)); // Map view // at the end canvas_size.x on purpose to get square float canvas_view_w = window_.getView().getSize().x / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x; float canvas_view_h = window_.getView().getSize().y / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x; float canvas_view_x = {window_.getView().getCenter().x / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x}; float canvas_view_y = {window_.getView().getCenter().y / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x}; sf::Vector2f view_pos_min = {canvas_view_x - canvas_view_w / 2 + canvas_pos.x, canvas_view_y - canvas_view_h / 2 + canvas_pos.y}; sf::Vector2f view_pos_max = {canvas_view_x + canvas_view_w / 2 + canvas_pos.x, canvas_view_y + canvas_view_h / 2 + canvas_pos.y}; draw_list->AddRect(view_pos_min, view_pos_max, IM_COL32(255, 255, 255, 255), 0, 15.f, 5.0f); float canvas_tile_size = canvas_size.x / map_.grid_.getSideCount(); const unsigned int time_window = 24 * 60 * 60 / 96; float g_time = time_line_.getGameTime().asSeconds(); unsigned int time_index = g_time / time_window; float time_passed = (g_time / time_window - (int)(g_time / time_window)) * time_window; const int max_cars_per_sample = 500; // No std::tuple struct TileSample { TileSample(const ImVec2 &p1, const ImVec2 &p2, const sf::Color &c) : p1(p1), p2(p2), c(c){}; const ImVec2 p1; const ImVec2 p2; const sf::Color c; }; // Heatmap for (unsigned int i = 0; i < map_.grid_.getTotalTileCount(); ++i) { if (map_.grid_.getTile(i)->getCategory() == TileCategory::RoadCategory) { sf::Vector2f p_min = {(i % map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.x, int(i / map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.y}; sf::Vector2f p_max = p_min + sf::Vector2f(canvas_tile_size, canvas_tile_size); std::uint16_t car_count = map_.grid_.getTile(i)->getNode()->getCarsPassed().at(time_index); draw_list->AddRectFilled(p_min, p_max, IM_COL32(26, 26, 26, 255)); float heat_color = 255 - (car_count * time_window / time_passed) / max_cars_per_sample * 255; if (heat_color > 0) draw_list->AddRectFilled(p_min, p_max, IM_COL32(255, heat_color, heat_color, heat_color)); } if (map_.grid_.getTile(i)->getCategory() == TileCategory::BuildingCategory) { sf::Vector2f p_min = {(i % map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.x, int(i / map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.y}; sf::Vector2f p_max = p_min + sf::Vector2f(canvas_tile_size, canvas_tile_size); draw_list->AddRectFilled(p_min, p_max, IM_COL32(47, 58, 224, 255)); map_.grid_.getTile(i)->getNode()->getCarsPassed().at(time_index); } } bool adding_preview = false; ImGui::InvisibleButton("canvas", canvas_size); sf::Vector2f mouse_pos_in_canvas = sf::Vector2f(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); if (ImGui::IsItemHovered()) { if (ImGui::IsMouseDown(0)) { sf::Vector2f new_center = (mouse_pos_in_canvas / canvas_size.x) * (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()); window_.setViewPos(new_center); } } draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.) draw_list->PopClipRect(); ImGui::End(); } void Application::handleEvent(const sf::Event &ev) { builder_.handleInput(ev); statistics_.handleInput(ev); switch (ev.type) { case sf::Event::KeyPressed: key_buffer_[ev.key.code] = true; break; case sf::Event::KeyReleased: key_buffer_[ev.key.code] = false; break; case sf::Event::MouseButtonPressed: button_buffer_[ev.mouseButton.button] = true; break; case sf::Event::MouseButtonReleased: button_buffer_[ev.mouseButton.button] = false; break; default: break; } // Shortcuts if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Num1 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 1.f; else if (ev.key.code == sf::Keyboard::Num2 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 1.25f; else if (ev.key.code == sf::Keyboard::Num3 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 1.5f; else if (ev.key.code == sf::Keyboard::Num4 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 2.f; else if (ev.key.code == sf::Keyboard::Num5 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 2.5f; else if (ev.key.code == sf::Keyboard::Num6 && key_buffer_[sf::Keyboard::LControl]) ImGui::GetFont()->Scale = 3.f; else if (ev.key.code == sf::Keyboard::S && key_buffer_[sf::Keyboard::LControl]) data_.saveMap(data_.getCurrentFileName(), map_.grid_); else if (ev.key.code == sf::Keyboard::O && key_buffer_[sf::Keyboard::LControl]) { //data_.loadMap("test.csv", builder_, map_.grid_); } else if (ev.key.code == sf::Keyboard::Up && key_buffer_[sf::Keyboard::LShift]) { float zoom_vals[6] = {1.f, 1.25, 1.5f, 2.f, 2.5f, 3.f}; if (window_.gui_zoom_index < 5) { window_.gui_zoom_index++; ImGui::GetFont()->Scale = zoom_vals[window_.gui_zoom_index]; } } else if (ev.key.code == sf::Keyboard::Down && key_buffer_[sf::Keyboard::LShift]) { float zoom_vals[6] = {1.f, 1.25, 1.5f, 2.f, 2.5f, 3.f}; if (window_.gui_zoom_index > 0) { window_.gui_zoom_index--; ImGui::GetFont()->Scale = zoom_vals[window_.gui_zoom_index]; } } } } void Application::handleInputBuffers(const sf::Vector2i &delta_mp) { // LEFT mouse button is pressed down if (button_buffer_[sf::Mouse::Left]) { // store temporarily selected "radio button" option such as "Add Road" // if left control is down add a road if (key_buffer_[sf::Keyboard::LControl] && app_state_ == Editing) builder_.slideAction(window_.convert(sf::Mouse::getPosition(window_.getWindow())), AddRoad); // if left shift is down remove road or building else if (key_buffer_[sf::Keyboard::LShift] && app_state_ == Editing) builder_.slideAction(window_.convert(sf::Mouse::getPosition(window_.getWindow())), Remove); // if no control or shift keys pressed move map else { window_.moveView(delta_mp); } } } void Application::close() { ImGui::SFML::Shutdown(); } Application *Application::GetInstance() { return AppInstance; } } // namespace ts
38.292818
171
0.608931
01abc6bf05dae881136da2cea20d766c99ee050a
529
cpp
C++
utils.cpp
VietaFan/backgammon-probs
0752be1d055bf9f583044323744cc7fe2d65a75b
[ "Apache-2.0" ]
null
null
null
utils.cpp
VietaFan/backgammon-probs
0752be1d055bf9f583044323744cc7fe2d65a75b
[ "Apache-2.0" ]
null
null
null
utils.cpp
VietaFan/backgammon-probs
0752be1d055bf9f583044323744cc7fe2d65a75b
[ "Apache-2.0" ]
null
null
null
#include "utils.h" int choose_dp[50][50]; int combin_diffs[20][20][20]; void init_choosedp(int maxn) { for (int i=0; i<maxn; ++i) { choose_dp[0][i] = 0; choose_dp[i][0] = 1; } for (int i=1; i<maxn; ++i) { for (int j=1; j<=i; ++j) choose_dp[i][j] = choose_dp[i-1][j]+choose_dp[i-1][j-1]; choose_dp[i][i+1] = 0; } } void init_combindiffs(int mmax, int nmax) { for (int n=0; n<=nmax; ++n) for (int m=0; m<=mmax; ++m) for (int a=0; a<=n; ++a) combin_diffs[n][m][a] = choose_dp[n+m][m]-choose_dp[n+m-a][m]; }
25.190476
66
0.565217
01aedd45e7ea4136002fda83b4302b5bbd28ae42
66
cpp
C++
test/query-manager/Runner.cpp
izenecloud/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
77
2015-02-12T20:59:20.000Z
2022-03-05T18:40:49.000Z
test/query-manager/Runner.cpp
fytzzh/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
1
2017-04-28T08:55:47.000Z
2017-07-10T10:10:53.000Z
test/query-manager/Runner.cpp
fytzzh/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
33
2015-01-05T03:03:05.000Z
2022-02-06T04:22:46.000Z
#define BOOST_TEST_MODULE Query Manager #include "TestRunner.inl"
22
39
0.833333
01b0d628d63692a37ac776da1c881343806e3b6e
105,658
cpp
C++
Remote.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
37
2015-07-23T04:02:51.000Z
2021-09-23T08:39:12.000Z
Remote.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
1
2018-08-30T08:33:38.000Z
2018-08-30T08:33:38.000Z
Remote.cpp
kengonakajima/moyai
70077449eb2446de6c24de928050ad8affc6df3d
[ "Zlib" ]
8
2015-07-23T04:02:58.000Z
2020-11-10T14:52:12.000Z
#include "common.h" #include "client.h" #include "Remote.h" #include "JPEGCoder.h" #include "crc32.h" #ifdef USE_UNTZ #include "threading/Threading.h" // To implement lock around send buffer inside libuv RCriticalSection g_lock; #endif #include "ConvertUTF.h" //////// void Moyai::globalInitNetwork() { static bool g_global_init_done = false; if( g_global_init_done ) return; #ifdef WIN32 WSADATA data; WSAStartup(MAKEWORD(2,0), &data); #endif #ifndef WIN32 signal( SIGPIPE, SIG_IGN ); #endif } void uv_run_times( int maxcount ) { for(int i=0;i<maxcount;i++) { uv_run( uv_default_loop(), UV_RUN_NOWAIT ); } } /////////// void setupPacketColorReplacerShaderSnapshot( PacketColorReplacerShaderSnapshot *outpkt, ColorReplacerShader *crs ) { outpkt->shader_id = crs->id; outpkt->epsilon = crs->epsilon; copyColorToPacketColor( &outpkt->from_color, &crs->from_color ); copyColorToPacketColor( &outpkt->to_color, &crs->to_color ); } ////////////// void copyPrimToPacketPrim( PacketPrim*out, Prim *src ) { out->prim_id = src->id; out->prim_type = src->type; out->a.x = src->a.x; out->a.y = src->a.y; out->b.x = src->b.x; out->b.y = src->b.y; copyColorToPacketColor( &out->color, &src->color ); // print("copyColorToPacketColor: out:%d %d %d %d", out->color.r, out->color.g, out->color.b, out->color.a ); out->line_width = src->line_width; } void makePacketProp2DSnapshot( PacketProp2DSnapshot *out, Prop2D *tgt, Prop2D *parent ) { out->prop_id = tgt->id; if( parent ) { out->layer_id = 0; out->parent_prop_id = parent->id; } else { out->layer_id = tgt->getParentLayer()->id; out->parent_prop_id = 0; } out->loc.x = tgt->loc.x; out->loc.y = tgt->loc.y; out->scl.x = tgt->scl.x; out->scl.y = tgt->scl.y; out->index = tgt->index; out->tiledeck_id = tgt->deck ? tgt->deck->id : 0; if(out->tiledeck_id==0 && tgt->grid_used_num==0 && tgt->children_num==0 && !tgt->prim_drawer) { print("WARNING: tiledeck is 0 for prop %d ind:%d grid:%d childnum:%d", tgt->id , tgt->index, tgt->grid_used_num, tgt->children_num ); } out->debug = tgt->debug_id; out->fliprotbits = toFlipRotBits(tgt->xflip,tgt->yflip,tgt->uvrot); out->rot = tgt->rot; copyColorToPacketColor(&out->color,&tgt->color); out->shader_id = tgt->fragment_shader ? tgt->fragment_shader->id : 0; out->optbits = 0; if( tgt->use_additive_blend ) out->optbits |= PROP2D_OPTBIT_ADDITIVE_BLEND; out->priority = tgt->priority; // print("ss prop:%d FS:%d size:%d", tgt->id, out->shader_id, sizeof(*out)); } void Tracker2D::scanProp2D( Prop2D *parentprop ) { PacketProp2DSnapshot *out = & pktbuf[cur_buffer_index]; makePacketProp2DSnapshot(out,target_prop2d,parentprop); } void Tracker2D::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } static const int CHANGED_LOC = 0x1; static const int CHANGED_INDEX = 0x2; static const int CHANGED_SCL = 0x4; static const int CHANGED_ROT = 0x8; static const int CHANGED_FLIPROTBITS = 0x10; static const int CHANGED_COLOR = 0x20; static const int CHANGED_SHADER = 0x40; static const int CHANGED_OPTBITS = 0x80; static const int CHANGED_PRIORITY = 0x100; int getPacketProp2DSnapshotDiff( PacketProp2DSnapshot *s0, PacketProp2DSnapshot *s1 ) { int changes = 0; if(s0->loc.x != s1->loc.x) changes |= CHANGED_LOC; if(s0->loc.y != s1->loc.y) changes |= CHANGED_LOC; if(s0->index != s1->index ) changes |= CHANGED_INDEX; if(s0->scl.x != s1->scl.x) changes |= CHANGED_SCL; if(s0->scl.y != s1->scl.y) changes |= CHANGED_SCL; if(s0->rot != s1->rot ) changes |= CHANGED_ROT; if( s0->fliprotbits != s1->fliprotbits ) changes |= CHANGED_FLIPROTBITS; if(s0->color.r != s1->color.r ) changes |= CHANGED_COLOR; if(s0->color.g != s1->color.g ) changes |= CHANGED_COLOR; if(s0->color.b != s1->color.b ) changes |= CHANGED_COLOR; if(s0->color.a != s1->color.a ) changes |= CHANGED_COLOR; if(s0->shader_id != s1->shader_id ) changes |= CHANGED_SHADER; if(s0->optbits != s1->optbits ) changes |= CHANGED_OPTBITS; if(s0->priority != s1->priority ) changes |= CHANGED_PRIORITY; return changes; } // send packet if necessary int Tracker2D::checkDiff() { PacketProp2DSnapshot *curpkt, *prevpkt; if(cur_buffer_index==0) { curpkt = & pktbuf[0]; prevpkt = & pktbuf[1]; } else { curpkt = & pktbuf[1]; prevpkt = & pktbuf[0]; } return getPacketProp2DSnapshotDiff( curpkt, prevpkt ); } void Tracker2D::broadcastDiff( bool force ) { int diff = checkDiff(); if( diff || force ) { if( diff == CHANGED_LOC && (!force) ) { int prev_buffer_index = cur_buffer_index==0?1:0; Vec2 v0(pktbuf[prev_buffer_index].loc.x,pktbuf[prev_buffer_index].loc.y); Vec2 v1(pktbuf[cur_buffer_index].loc.x,pktbuf[cur_buffer_index].loc.y); float l = v0.len(v1); target_prop2d->loc_sync_score+= l; if(v0.x!=v1.x||v0.y!=v1.y) target_prop2d->loc_changed=true; // only location changed! if( target_prop2d->locsync_mode == LOCSYNCMODE_LINEAR ) { bool to_send = true; if(target_prop2d->loc_sync_score > parent_rh->linear_sync_score_thres ) { target_prop2d->loc_sync_score=0; target_prop2d->loc_changed=false; } else if( target_prop2d->poll_count>2 ){ to_send = false; } if(to_send) { Vec2 vel = (v1 - v0) / target_prop2d->getParentLayer()->last_dt; parent_rh->nearcastUS1UI3F2( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC_VEL, pktbuf[cur_buffer_index].prop_id, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y, vel.x, vel.y ); } // print("l:%f lss:%f id:%d", l, target_prop2d->loc_sync_score, target_prop2d->id); } else { target_prop2d->loc_sync_score+=1; // avoid missing syncing stopped props if( target_prop2d->loc_sync_score < parent_rh->nonlinear_sync_score_thres ) { if( !parent_rh->appendNonlinearChangelist( target_prop2d, &pktbuf[cur_buffer_index] ) ) { // must send if changelist is full // prt("FL %d", target_prop2d->id); parent_rh->nearcastUS1UI3( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC, pktbuf[cur_buffer_index].prop_id, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y ); } } else { // prt("NL LOC SCORE:%d prop:%d",target_prop2d->loc_sync_score, target_prop2d->id ); target_prop2d->loc_sync_score=0; target_prop2d->loc_changed=false; // dont use changelist sorting for big changes parent_rh->nearcastUS1UI3( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC, pktbuf[cur_buffer_index].prop_id, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y ); } } } else if( diff == CHANGED_SCL && (!force) ) { parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_PROP2D_SCALE, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].scl.x, pktbuf[cur_buffer_index].scl.y ); } else if( diff == CHANGED_ROT && (!force) ) { parent_rh->broadcastUS1UI1F1( PACKETTYPE_S2C_PROP2D_ROT, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].rot ); } else if( diff == CHANGED_COLOR && (!force) ) { parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_PROP2D_COLOR, pktbuf[cur_buffer_index].prop_id, (const char*)&pktbuf[cur_buffer_index].color, sizeof(PacketColor)); } else if( diff == CHANGED_INDEX && (!force) ) { parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_INDEX, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].index ); } else if( diff == (CHANGED_INDEX | CHANGED_LOC) && (!force) ) { parent_rh->broadcastUS1UI4( PACKETTYPE_S2C_PROP2D_INDEX_LOC, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].index, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y ); } else if( diff == (CHANGED_LOC | CHANGED_SCL ) && (!force) ) { parent_rh->nearcastUS1UI3F2( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC_SCL, pktbuf[cur_buffer_index].prop_id, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y, pktbuf[cur_buffer_index].scl.x, pktbuf[cur_buffer_index].scl.y ); } else if( diff == CHANGED_FLIPROTBITS && (!force) ) { parent_rh->broadcastUS1UI1UC1( PACKETTYPE_S2C_PROP2D_FLIPROTBITS, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].fliprotbits ); } else if( diff == CHANGED_OPTBITS && (!force) ) { parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_OPTBITS, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].optbits ); } else if( diff == CHANGED_PRIORITY && (!force) ) { parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_PRIORITY, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].priority ); } else { // prt("SS%d ",diff); parent_rh->broadcastUS1Bytes( PACKETTYPE_S2C_PROP2D_SNAPSHOT, (const char*)&pktbuf[cur_buffer_index], sizeof(PacketProp2DSnapshot) ); if( target_prop2d->target_client_id > 0 ) { parent_rh->broadcastUS1UI2( PACKETTYPE_S2R_PROP2D_TARGET_CLIENT,target_prop2d->id, target_prop2d->target_client_id, true); } } } } Tracker2D::~Tracker2D() { parent_rh->notifyProp2DDeleted(target_prop2d); } void RemoteHead::notifyProp2DDeleted( Prop2D *deleted ) { broadcastUS1UI1( PACKETTYPE_S2C_PROP2D_DELETE, deleted->id ); } void RemoteHead::notifyChildCleared( Prop2D *owner_prop, Prop2D *child_prop ) { broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_CLEAR_CHILD, owner_prop->id, child_prop->id ); } void RemoteHead::notifyGridDeleted( Grid *deleted ) { broadcastUS1UI1( PACKETTYPE_S2C_GRID_DELETE, deleted->id ); } void RemoteHead::addClient( Client *cl ) { Client *stored = cl_pool.get(cl->id); if(!stored) { cl->parent_rh = this; cl_pool.set(cl->id,cl); } } void RemoteHead::delClient( Client *cl ) { cl_pool.del(cl->id); } Client *RemoteHead::getFirstClient() { // normal clients first and then reprecated clients if(cl_pool.size()==0) { if(reprecator) { Client *cl = reprecator->logical_cl_pool.getFirst(); return cl; } else { return NULL; } } return cl_pool.getFirst(); } int RemoteHead::getClientCount() { return cl_pool.size(); } // Assume all props in all layers are Prop2Ds. void RemoteHead::track2D() { if(enable_timestamp) broadcastTimestamp(); clearChangelist(); for(int i=0;i<Moyai::MAXGROUPS;i++) { Layer *layer = (Layer*) target_moyai->getGroupByIndex(i); if(!layer)continue; if(layer->hasDynamicCameras()) { layer->onTrackDynamicCameras(); } else if(layer->camera) layer->camera->onTrack(this); if(layer->hasDynamicViewports()) { layer->onTrackDynamicViewports(); } else if(layer->viewport) layer->viewport->onTrack(this); Prop *cur = layer->prop_top; while(cur) { Prop2D *p = (Prop2D*) cur; p->onTrack(this, NULL); cur = cur->next; } } broadcastSortedChangelist(); } uint32_t getFileCRC32(const char *path) { const size_t MAXBUFSIZE = 1024*1024*16; char *buf = (char*) MALLOC(MAXBUFSIZE); assert(buf); size_t sz = MAXBUFSIZE; bool res = readFile( path, buf, &sz ); assertmsg(res, "getFileCRC32: file '%s' read error", path ); uint32_t crc32val = crc32_4bytes(buf,sz,0); FREE(buf); print("getFileCRC32: path:%s len:%d crc32:%x", path, sz, crc32val ); return crc32val; } void RemoteHead::appendFileEntry(const char *path) { assert(file_ents_used<elementof(file_ents) ); FileEntry *fe=&file_ents[file_ents_used]; fe->crc32 = getFileCRC32(path); fe->size=getFileSize(path); strncpy(fe->path,path,sizeof(fe->path)); file_ents_used++; print("appendFileEntry: path:%s", path); } bool RemoteHead::isPathAllowed(const char *path ) { for(int i=0;i<file_ents_used;i++) { FileEntry *fe=&file_ents[i]; if(fe->size>0 && strcmp(fe->path,path)==0) { return true; } } return false; } void RemoteHead::scanFiles() { if( window_width==0 || window_height==0) { assertmsg( false, "remotehead: window size not set?"); } // Image, Texture, tiledeck std::unordered_map<int,Image*> imgmap; std::unordered_map<int,Texture*> texmap; std::unordered_map<int,Deck*> dkmap; std::unordered_map<int,Font*> fontmap; std::unordered_map<int,ColorReplacerShader*> crsmap; for(int i=0;i<Moyai::MAXGROUPS;i++) { Group *grp = target_moyai->getGroupByIndex(i); if(!grp)continue; Prop *cur = grp->prop_top; while(cur) { Prop2D *p = (Prop2D*) cur; if(p->deck) { dkmap[p->deck->id] = p->deck; if( p->deck->tex) { texmap[p->deck->tex->id] = p->deck->tex; if( p->deck->tex->image ) { imgmap[p->deck->tex->image->id] = p->deck->tex->image; } } } if(p->fragment_shader) { ColorReplacerShader *crs = dynamic_cast<ColorReplacerShader*>(p->fragment_shader); // TODO: avoid using dyncast.. if(crs) { crsmap[crs->id] = crs; } } for(int i=0;i<p->grid_used_num;i++) { Grid *g = p->grids[i]; if(g->deck) { dkmap[g->deck->id] = g->deck; if( g->deck->tex) { texmap[g->deck->tex->id] = g->deck->tex; if( g->deck->tex->image ) { imgmap[g->deck->tex->image->id] = g->deck->tex->image; } } } } TextBox *tb = dynamic_cast<TextBox*>(cur); // TODO: refactor this! if(tb) { if(tb->font) { fontmap[tb->font->id] = tb->font; } } cur = cur->next; } } // Files for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) { Image *img = it->second; if( img->last_load_file_path[0] ) { print("sending file path:'%s' in image %d", img->last_load_file_path, img->id ); appendFileEntry(img->last_load_file_path); } } for( std::unordered_map<int,Font*>::iterator it = fontmap.begin(); it != fontmap.end(); ++it ) { Font *f = it->second; appendFileEntry(f->last_load_file_path); } // TODO: send shader source and status // sounds for(int i=0;i<elementof(target_soundsystem->sounds);i++){ if(!target_soundsystem)break; Sound *snd = target_soundsystem->sounds[i]; if(!snd)continue; if(snd->last_load_file_path[0]) appendFileEntry(snd->last_load_file_path); } } void RemoteHead::sendScannedFileList(Stream *outstream) { for(int i=0;i<file_ents_used;i++) { FileEntry *fe=&file_ents[i]; sendUS1UI2Str( outstream, PACKETTYPE_S2C_FILE_INFO, fe->size, fe->crc32, fe->path ); } sendUS1(outstream,PACKETTYPE_S2C_FILE_INFO_END); } // Send all IDs of tiledecks, layers, textures, fonts, viwports by scanning all props and grids. // This occurs only when new player is comming in. void RemoteHead::scanSendAllPrerequisites( Stream *outstream ) { if( window_width==0 || window_height==0) { assertmsg( false, "remotehead: window size not set?"); } std::unordered_map<int,Viewport*> vpmap; std::unordered_map<int,Camera*> cammap; // Viewport , Camera for(int i=0;i<Moyai::MAXGROUPS;i++) { Group *grp = target_moyai->getGroupByIndex(i); if(!grp)continue; Layer *l = (Layer*) grp; // assume all groups are layers if(l->viewport) { vpmap[l->viewport->id] = l->viewport; } if(l->camera) { cammap[l->camera->id] = l->camera; } } for( std::unordered_map<int,Viewport*>::iterator it = vpmap.begin(); it != vpmap.end(); ++it ) { Viewport *vp = it->second; print("sending viewport_create id:%d sz:%d,%d scl:%f,%f", vp->id, vp->screen_width, vp->screen_height, vp->scl.x, vp->scl.y ); sendViewportCreateScale(outstream,vp); } for( std::unordered_map<int,Camera*>::iterator it = cammap.begin(); it != cammap.end(); ++it ) { Camera *cam = it->second; print("sending camera_create id:%d", cam->id ); sendCameraCreateLoc(outstream,cam); } // Layers(Groups) don't need scanning props for(int i=0;i<Moyai::MAXGROUPS;i++) { Layer *l = (Layer*) target_moyai->getGroupByIndex(i); if(!l)continue; print("sending layer_create id:%d",l->id); sendLayerSetup(outstream,l); } // Image, Texture, tiledeck std::unordered_map<int,Image*> imgmap; std::unordered_map<int,Texture*> texmap; std::unordered_map<int,Deck*> dkmap; std::unordered_map<int,Font*> fontmap; std::unordered_map<int,ColorReplacerShader*> crsmap; for(int i=0;i<Moyai::MAXGROUPS;i++) { Group *grp = target_moyai->getGroupByIndex(i); if(!grp)continue; Prop *cur = grp->prop_top; while(cur) { Prop2D *p = (Prop2D*) cur; if(p->deck) { dkmap[p->deck->id] = p->deck; if( p->deck->tex) { texmap[p->deck->tex->id] = p->deck->tex; if( p->deck->tex->image ) { imgmap[p->deck->tex->image->id] = p->deck->tex->image; } } } if(p->fragment_shader) { ColorReplacerShader *crs = dynamic_cast<ColorReplacerShader*>(p->fragment_shader); // TODO: avoid using dyncast.. if(crs) { crsmap[crs->id] = crs; } } for(int i=0;i<p->grid_used_num;i++) { Grid *g = p->grids[i]; if(g->deck) { dkmap[g->deck->id] = g->deck; if( g->deck->tex) { texmap[g->deck->tex->id] = g->deck->tex; if( g->deck->tex->image ) { imgmap[g->deck->tex->image->id] = g->deck->tex->image; } } } } TextBox *tb = dynamic_cast<TextBox*>(cur); // TODO: refactor this! if(tb) { if(tb->font) { fontmap[tb->font->id] = tb->font; } } cur = cur->next; } } // Files #if 0 for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) { Image *img = it->second; if( img->last_load_file_path[0] ) { print("sending file path:'%s' in image %d", img->last_load_file_path, img->id ); sendFile( outstream, img->last_load_file_path ); } } #endif for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) { Image *img = it->second; sendImageSetup(outstream,img); } for( std::unordered_map<int,Texture*>::iterator it = texmap.begin(); it != texmap.end(); ++it ) { Texture *tex = it->second; // print("sending texture_create id:%d", tex->id ); sendTextureCreateWithImage(outstream,tex); } for( std::unordered_map<int,Deck*>::iterator it = dkmap.begin(); it != dkmap.end(); ++it ) { Deck *dk = it->second; sendDeckSetup(outstream,dk); } for( std::unordered_map<int,Font*>::iterator it = fontmap.begin(); it != fontmap.end(); ++it ) { Font *f = it->second; sendFontSetupWithFile(outstream,f); } for( std::unordered_map<int,ColorReplacerShader*>::iterator it = crsmap.begin(); it != crsmap.end(); ++it ) { ColorReplacerShader *crs = it->second; sendColorReplacerShaderSetup(outstream,crs); } // sounds for(int i=0;i<elementof(target_soundsystem->sounds);i++){ if(!target_soundsystem)break; Sound *snd = target_soundsystem->sounds[i]; if(!snd)continue; sendSoundSetup(outstream,snd); } } // Send snapshots of all props and grids void RemoteHead::scanSendAllProp2DSnapshots( Stream *outstream ) { for(int i=0;i<Moyai::MAXGROUPS;i++) { Layer *layer = (Layer*) target_moyai->getGroupByIndex(i); if(!layer)continue; Prop *cur = layer->prop_top; while(cur) { Prop2D *p = (Prop2D*) cur; TextBox *tb = dynamic_cast<TextBox*>(p); if(tb) { if(!tb->tracker) { tb->tracker = new TrackerTextBox(this,tb); tb->tracker->scanTextBox(); } tb->tracker->broadcastDiff(true); } else { // prop body if(!p->tracker) { p->tracker = new Tracker2D(this,p); p->tracker->scanProp2D(NULL); } p->tracker->broadcastDiff(true); // grid for(int i=0;i<p->grid_used_num;i++) { Grid *g = p->grids[i]; if(!g->tracker) { g->tracker = new TrackerGrid(this,g); g->tracker->scanGrid(); } g->tracker->broadcastDiff(p, true ); } // prims if(p->prim_drawer) { if( !p->prim_drawer->tracker) p->prim_drawer->tracker = new TrackerPrimDrawer(this,p->prim_drawer); p->prim_drawer->tracker->scanPrimDrawer(); p->prim_drawer->tracker->broadcastDiff(p, true ); } // children for(int i=0;i<p->children_num;i++) { Prop2D *chp = p->children[i]; if(!chp->tracker) { chp->tracker = new Tracker2D(this,chp); chp->tracker->scanProp2D(p); } chp->tracker->broadcastDiff(true); } } cur = cur->next; } } } void RemoteHead::heartbeat(double dt) { if(enable_spritestream) track2D(); if(enable_videostream) broadcastCapturedScreen(); if( (!enable_videostream) && (!enable_spritestream) ) { print("RemoteHead::heartbeat: no streaming enabled, please call enableSpriteStream or enableVideoStream. "); } #ifdef USE_UNTZ if(audio_buf_ary){ RScopedLock _l(&g_lock); for(;;) { size_t used = audio_buf_ary->getUsedNum(); if(used==0)break; Buffer *b = audio_buf_ary->getTop(); assert(b); // print("heartbeat: audio used:%d next buf len:%d",audio_buf_ary->getUsedNum(), b->used ); assert(b->used % (sizeof(float)*2) == 0 ); // L+R of float sample broadcastUS1UI1Bytes( PACKETTYPE_S2C_CAPTURED_AUDIO, b->used/sizeof(float)/2, b->buf, b->used ); static int total_audio_samples_sent_bytes = 0; total_audio_samples_sent_bytes += b->used; // print("sent audio: %f %d", now(), total_audio_samples_sent_bytes ); audio_buf_ary->shift(); } } #endif flushBufferToNetwork(dt); if(reprecator) reprecator->heartbeat(); uv_run_times(100); } void RemoteHead::flushBufferToNetwork(double dt) { POOL_SCAN(cl_pool,Client) { Client *cl=it->second; bool to_send = cl->updateSendTimer(dt); if(to_send) cl->flushSendbufToNetwork(); } } static void remotehead_on_close_callback( uv_handle_t *s ) { print("remotehead_on_close_callback"); Client *cli = (Client*)s->data; cli->parent_rh->delClient(cli); // Call this before on_disconnect_cb to make it possible to delete prop in callback and it causes write to network if( cli->parent_rh->on_disconnect_cb ) { cli->parent_rh->on_disconnect_cb( cli->parent_rh, cli ); } delete cli; } static void remotehead_on_packet_callback( Stream *stream, uint16_t funcid, char *argdata, uint32_t argdatalen ) { Client *cli = (Client*)stream; // print("on_packet_callback. id:%d fid:%d len:%d", funcid, argdatalen ); switch(funcid) { case PACKETTYPE_PING: { uint32_t sec = get_u32(argdata+0); uint32_t usec = get_u32(argdata+4); sendUS1UI2( cli, PACKETTYPE_PING, sec, usec ); } break; case PACKETTYPE_C2S_KEYBOARD: { uint32_t keycode = get_u32(argdata); uint32_t action = get_u32(argdata+4); uint32_t modbits = get_u32(argdata+8); bool mod_shift,mod_ctrl,mod_alt; getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt); // print("kbd: %d %d %d %d %d", keycode, action, mod_shift, mod_ctrl, mod_alt ); if(cli->parent_rh->on_keyboard_cb) { cli->parent_rh->on_keyboard_cb(cli,keycode,action,mod_shift,mod_ctrl,mod_alt); } } break; case PACKETTYPE_C2S_MOUSE_BUTTON: { uint32_t button = get_u32(argdata); uint32_t action = get_u32(argdata+4); uint32_t modbits = get_u32(argdata+8); bool mod_shift,mod_ctrl,mod_alt; getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt); print("mou: %d %d %d %d %d", button, action, mod_shift, mod_ctrl, mod_alt ); if(cli->parent_rh->on_mouse_button_cb) { cli->parent_rh->on_mouse_button_cb(cli,button,action,mod_shift,mod_ctrl,mod_alt); } } break; case PACKETTYPE_C2S_CURSOR_POS: { float x = get_f32(argdata); float y = get_f32(argdata+4); if(cli->parent_rh->on_mouse_cursor_cb) { cli->parent_rh->on_mouse_cursor_cb(cli,x,y); } } break; case PACKETTYPE_C2S_REQUEST_FILE_LIST: { if(cli->parent_rh->file_ents_used==0) { cli->parent_rh->scanFiles(); } cli->parent_rh->sendScannedFileList(cli); } break; case PACKETTYPE_C2S_REQUEST_FILE: { uint8_t cstrlen=get_u8(argdata); char *path_utf8 = (char*)(argdata+1); char path[256]; snprintf(path,sizeof(path),"%.*s", cstrlen,path_utf8); print("requestfile: '%s'",path); if(!cli->parent_rh->isPathAllowed(path)) { print("path '%s' is not allowed", path); break; } print("sending file %s",path); sendFile(cli,path); } break; case PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT: { print("request_first_snapshot"); cli->parent_rh->scanSendAllPrerequisites(cli); cli->parent_rh->scanSendAllProp2DSnapshots(cli); } break; default: print("unhandled funcid: %d",funcid); break; } } static void remotehead_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) { Client *cl = (Client*) s->data; if(nread>0) { bool res = parseRecord( cl, &cl->recvbuf, inbuf->base, nread, remotehead_on_packet_callback ); if(!res) { print("receiveData failed"); uv_close( (uv_handle_t*)s, remotehead_on_close_callback ); return; } } else if( nread < 0 ) { print("remotehead_on_read_callback EOF. clid:%d", cl->id ); uv_close( (uv_handle_t*)s, remotehead_on_close_callback ); } } void moyai_libuv_alloc_buffer( uv_handle_t *handle, size_t suggested_size, uv_buf_t *outbuf ) { *outbuf = uv_buf_init( (char*) MALLOC(suggested_size), suggested_size ); } static void remotehead_on_accept_callback( uv_stream_t *listener, int status ) { if( status != 0 ) { print("remotehead_on_accept_callback status:%d", status); return; } uv_tcp_t *newsock = (uv_tcp_t*) MALLOC( sizeof(uv_tcp_t) ); uv_tcp_init( uv_default_loop(), newsock ); if( uv_accept( listener, (uv_stream_t*) newsock ) == 0 ) { uv_tcp_nodelay(newsock,1); RemoteHead *rh = (RemoteHead*)listener->data; Client *cl = new Client(newsock, rh, rh->enable_compression ); newsock->data = cl; cl->tcp = newsock; cl->parent_rh->addClient(cl); cl->send_wait=rh->send_wait_sec; print("remotehead_on_accept_callback. ok status:%d client-id:%d", status, cl->id ); int r = uv_read_start( (uv_stream_t*) newsock, moyai_libuv_alloc_buffer, remotehead_on_read_callback ); if(r) { print("uv_read_start: fail ret:%d",r); return; } sendWindowSize(cl, cl->parent_rh->window_width, cl->parent_rh->window_height); if(rh->enable_videostream) { JPEGCoder *jc = cl->parent_rh->jc; assert(jc); sendUS1UI3(cl, PACKETTYPE_S2C_JPEG_DECODER_CREATE, jc->capture_pixel_skip, jc->orig_w, jc->orig_h ); } if( cl->parent_rh->on_connect_cb ) { cl->parent_rh->on_connect_cb( cl->parent_rh, cl ); } } } bool init_tcp_listener( uv_tcp_t *l, void *data, int portnum, void (*cb)(uv_stream_t*l,int status) ) { int r = uv_tcp_init( uv_default_loop(), l ); if(r) { print("uv_tcp_init failed"); return false; } l->data = data; struct sockaddr_in addr; uv_ip4_addr("0.0.0.0", portnum, &addr ); r = uv_tcp_bind( l, (const struct sockaddr*) &addr, SO_REUSEADDR ); if(r) { print("uv_tcp_bind failed"); return false; } r = uv_listen( (uv_stream_t*)l, 10, cb ); if(r) { print("uv_listen failed"); return false; } return true; } // return false if can't // TODO: implement error handling bool RemoteHead::startServer( int portnum ) { return init_tcp_listener( &listener, (void*)this, portnum, remotehead_on_accept_callback ); } void RemoteHead::notifySoundPlay( Sound *snd, float vol ) { if(enable_spritestream) broadcastUS1UI1F1( PACKETTYPE_S2C_SOUND_PLAY, snd->id, vol ); } void RemoteHead::notifySoundStop( Sound *snd ) { if(enable_spritestream) broadcastUS1UI1( PACKETTYPE_S2C_SOUND_STOP, snd->id ); } // [numframes of float values for ch1][numframes of float values for ch2] void RemoteHead::appendAudioSamples( uint32_t numChannels, float *interleavedSamples, uint32_t numSamples ) { #ifdef USE_UNTZ if(!audio_buf_ary)return; RScopedLock _l(&g_lock); // print("pushing samples. numSamples:%d numChannels:%d", numSamples, numChannels ); bool ret = audio_buf_ary->push( (const char*)interleavedSamples, numSamples * numChannels * sizeof(float) ); if(!ret) print("appendAudioSamples: audio_buffer full?"); // print("appendAudioSamples pushed %d bytes. ret:%d used:%d", numSamples*sizeof(float), ret, audio_buffer->used ); #else print("appendAudioSamples is't implemented"); #endif } //////////////// TrackerGrid::TrackerGrid( RemoteHead *rh, Grid *target ) : target_grid(target), cur_buffer_index(0), parent_rh(rh) { for(int i=0;i<2;i++) { index_table[i] = NULL; flip_table[i] = NULL; texofs_table[i] = NULL; color_table[i] = NULL; } } TrackerGrid::~TrackerGrid() { parent_rh->notifyGridDeleted(target_grid); for(int i=0;i<2;i++) { if(index_table[i]) FREE( index_table[i] ); if(flip_table[i]) FREE( flip_table[i] ); if(texofs_table[i]) FREE( texofs_table[i] ); if(color_table[i]) FREE( color_table[i] ); } } void TrackerGrid::scanGrid() { if( target_grid->index_table) { if(!index_table[cur_buffer_index]) index_table[cur_buffer_index] = (int32_t*) MALLOC(target_grid->getCellNum() * sizeof(int32_t)); } if( target_grid->xflip_table || target_grid->yflip_table || target_grid->rot_table ) { if(!flip_table[cur_buffer_index]) flip_table[cur_buffer_index] = (uint8_t*) MALLOC(target_grid->getCellNum() * sizeof(uint8_t) ); } if( target_grid->texofs_table ) { if(!texofs_table[cur_buffer_index]) texofs_table[cur_buffer_index] = (PacketVec2*) MALLOC(target_grid->getCellNum() * sizeof(PacketVec2)); } if( target_grid->color_table ) { if(!color_table[cur_buffer_index]) color_table[cur_buffer_index] = (PacketColor*) MALLOC(target_grid->getCellNum() * sizeof(PacketColor)); } for(int y=0;y<target_grid->height;y++){ for(int x=0;x<target_grid->width;x++){ int ind = target_grid->index(x,y); if(index_table[cur_buffer_index]) { index_table[cur_buffer_index][ind] = target_grid->get(x,y); } if(flip_table[cur_buffer_index] ) { uint8_t bits = 0; if( target_grid->getXFlip(x,y) ) bits |= GTT_FLIP_BIT_X; if( target_grid->getYFlip(x,y) ) bits |= GTT_FLIP_BIT_Y; if( target_grid->getUVRot(x,y) ) bits |= GTT_FLIP_BIT_UVROT; flip_table[cur_buffer_index][ind] = bits; } if(texofs_table[cur_buffer_index]) { Vec2 texofs; target_grid->getTexOffset(x,y,&texofs); texofs_table[cur_buffer_index][ind].x = texofs.x; texofs_table[cur_buffer_index][ind].y = texofs.y; } if(color_table[cur_buffer_index]) { Color col = target_grid->getColor(x,y); copyColorToPacketColor(&color_table[cur_buffer_index][ind],&col); } } } } void TrackerGrid::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } // TODO: add a new packet type of sending changes in each cells. bool TrackerGrid::checkDiff( GRIDTABLETYPE gtt ) { char *curtbl, *prevtbl; int curind, prevind; if(cur_buffer_index==0) { curind = 0; prevind = 1; } else { curind = 1; prevind = 0; } switch(gtt) { case GTT_INDEX: curtbl = (char*) index_table[curind]; prevtbl = (char*) index_table[prevind]; break; case GTT_FLIP: curtbl = (char*) flip_table[curind]; prevtbl = (char*) flip_table[prevind]; break; case GTT_TEXOFS: curtbl = (char*) texofs_table[curind]; prevtbl = (char*) texofs_table[prevind]; break; case GTT_COLOR: curtbl = (char*) color_table[curind]; prevtbl = (char*) color_table[prevind]; break; } size_t compsz; switch(gtt){ case GTT_INDEX: compsz = target_grid->getCellNum() * sizeof(int32_t); break; case GTT_FLIP: compsz = target_grid->getCellNum() * sizeof(uint8_t); break; case GTT_TEXOFS: compsz = target_grid->getCellNum() * sizeof(Vec2); break; case GTT_COLOR: compsz = target_grid->getCellNum() * sizeof(PacketColor); #if 0 if(prevtbl&&curtbl){ int prevsum = bytesum(prevtbl,compsz); int cursum = bytesum(curtbl,compsz); if(prevsum!=cursum) { dump(prevtbl,compsz); print("----------------"); dump(curtbl,compsz); } } #endif break; } int cmp=0; if(curtbl && prevtbl) cmp = memcmp( curtbl, prevtbl, compsz ); return cmp; } void TrackerGrid::broadcastDiff( Prop2D *owner, bool force ) { bool have_index_diff = checkDiff( GTT_INDEX ); bool have_flip_diff = checkDiff( GTT_FLIP ); bool have_texofs_diff = checkDiff( GTT_TEXOFS ); bool have_color_diff = checkDiff( GTT_COLOR ); bool have_any_diff = ( have_index_diff || have_flip_diff || have_texofs_diff || have_color_diff ); if( force || have_any_diff ) { broadcastGridConfs(owner); } if( (have_index_diff || force ) && index_table[cur_buffer_index] ) { parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT, target_grid->id, (const char*) index_table[cur_buffer_index], target_grid->getCellNum() * sizeof(int32_t) ); } if( ( have_flip_diff || force ) && flip_table[cur_buffer_index] ) { parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT, target_grid->id, (const char*) flip_table[cur_buffer_index], target_grid->getCellNum() * sizeof(uint8_t) ); } if( ( have_texofs_diff || force ) && texofs_table[cur_buffer_index] ) { parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT, target_grid->id, (const char*) texofs_table[cur_buffer_index], target_grid->getCellNum() * sizeof(Vec2) ); } if( ( have_color_diff || force ) && color_table[cur_buffer_index] ) { parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT, target_grid->id, (const char*) color_table[cur_buffer_index], target_grid->getCellNum() * sizeof(PacketColor) ); } } void TrackerGrid::broadcastGridConfs( Prop2D *owner ) { parent_rh->broadcastUS1UI3( PACKETTYPE_S2C_GRID_CREATE, target_grid->id, target_grid->width, target_grid->height ); int dk_id = 0; if(target_grid->deck) dk_id = target_grid->deck->id; else if(owner->deck) dk_id = owner->deck->id; if(dk_id) parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_GRID_DECK, target_grid->id, dk_id ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_GRID_PROP2D, target_grid->id, owner->id ); } ///////////// TrackerTextBox::TrackerTextBox(RemoteHead *rh, TextBox *target) : target_tb(target), cur_buffer_index(0), parent_rh(rh) { memset( pktbuf, 0, sizeof(pktbuf) ); memset( strbuf, 0, sizeof(strbuf) ); } TrackerTextBox::~TrackerTextBox() { parent_rh->notifyProp2DDeleted(target_tb); } void TrackerTextBox::scanTextBox() { PacketProp2DSnapshot *out = & pktbuf[cur_buffer_index]; out->prop_id = target_tb->id; out->layer_id = target_tb->getParentLayer()->id; out->loc.x = target_tb->loc.x; out->loc.y = target_tb->loc.y; out->scl.x = target_tb->scl.x; out->scl.y = target_tb->scl.y; out->index = 0; // fixed out->tiledeck_id = 0; // fixed out->debug = target_tb->debug_id; out->rot = 0; // fixed out->fliprotbits = 0; // fixed copyColorToPacketColor(&out->color,&target_tb->color); out->priority = target_tb->priority; size_t copy_sz = (target_tb->len_str + 1) * sizeof(wchar_t); assertmsg( copy_sz <= MAX_STR_LEN, "textbox string too long" ); memcpy( strbuf[cur_buffer_index], target_tb->str, copy_sz ); str_bytes[cur_buffer_index] = copy_sz; // print("scantb: cpsz:%d id:%d s:%s l:%d cbi:%d",copy_sz, target_tb->id, target_tb->str, target_tb->len_str, cur_buffer_index ); } bool TrackerTextBox::checkDiff() { PacketProp2DSnapshot *curpkt, *prevpkt; size_t cur_str_bytes, prev_str_bytes; uint8_t *cur_str, *prev_str; if(cur_buffer_index==0) { curpkt = & pktbuf[0]; prevpkt = & pktbuf[1]; cur_str_bytes = str_bytes[0]; prev_str_bytes = str_bytes[1]; cur_str = strbuf[0]; prev_str = strbuf[1]; } else { curpkt = & pktbuf[1]; prevpkt = & pktbuf[0]; cur_str_bytes = str_bytes[1]; prev_str_bytes = str_bytes[0]; cur_str = strbuf[1]; prev_str = strbuf[0]; } int pktchanges = getPacketProp2DSnapshotDiff( curpkt, prevpkt ); bool str_changed = false; if( cur_str_bytes != prev_str_bytes ) { str_changed = true; } else if( memcmp( cur_str, prev_str, cur_str_bytes ) ){ str_changed = true; } if( str_changed ) { // print("string changed! id:%d l:%d", target_tb->id, cur_str_bytes ); } return pktchanges || str_changed; } void TrackerTextBox::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } void TrackerTextBox::broadcastDiff( bool force ) { if( checkDiff() || force ) { parent_rh->broadcastUS1UI1( PACKETTYPE_S2C_TEXTBOX_CREATE, target_tb->id ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_LAYER, target_tb->id, target_tb->getParentLayer()->id ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_FONT, target_tb->id, target_tb->font->id ); parent_rh->broadcastUS1UI1Wstr( PACKETTYPE_S2C_TEXTBOX_STRING, target_tb->id, target_tb->str, target_tb->len_str ); parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_TEXTBOX_LOC, target_tb->id, target_tb->loc.x, target_tb->loc.y ); parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_TEXTBOX_SCL, target_tb->id, target_tb->scl.x, target_tb->scl.y ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_PRIORITY, target_tb->id, target_tb->priority ); PacketColor pc; copyColorToPacketColor(&pc,&target_tb->color); parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_TEXTBOX_COLOR, target_tb->id, (const char*)&pc, sizeof(pc) ); } } ////////////// TrackerColorReplacerShader::~TrackerColorReplacerShader() { } void TrackerColorReplacerShader::scanShader() { PacketColorReplacerShaderSnapshot *out = &pktbuf[cur_buffer_index]; out->epsilon = target_shader->epsilon; copyColorToPacketColor( &out->from_color, &target_shader->from_color ); copyColorToPacketColor( &out->to_color, &target_shader->to_color ); } void TrackerColorReplacerShader::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } bool TrackerColorReplacerShader::checkDiff() { PacketColorReplacerShaderSnapshot *curpkt, *prevpkt; if(cur_buffer_index==0) { curpkt = &pktbuf[0]; prevpkt = &pktbuf[1]; } else { curpkt = &pktbuf[1]; prevpkt = &pktbuf[0]; } if( ( curpkt->epsilon != prevpkt->epsilon ) || ( curpkt->from_color.r != prevpkt->from_color.r ) || ( curpkt->from_color.g != prevpkt->from_color.g ) || ( curpkt->from_color.b != prevpkt->from_color.b ) || ( curpkt->from_color.a != prevpkt->from_color.a ) || ( curpkt->to_color.r != prevpkt->to_color.r ) || ( curpkt->to_color.g != prevpkt->to_color.g ) || ( curpkt->to_color.b != prevpkt->to_color.b ) || ( curpkt->to_color.a != prevpkt->to_color.a ) ) { return true; } else { return false; } } void TrackerColorReplacerShader::broadcastDiff( bool force ) { if( checkDiff() || force ) { PacketColorReplacerShaderSnapshot pkt; setupPacketColorReplacerShaderSnapshot( &pkt, target_shader ); parent_rh->broadcastUS1Bytes( PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT, (const char*)&pkt, sizeof(pkt) ); } } ////////////////// TrackerPrimDrawer::~TrackerPrimDrawer() { if( pktbuf[0] ) FREE(pktbuf[0]); if( pktbuf[1] ) FREE(pktbuf[1]); } void TrackerPrimDrawer::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } void TrackerPrimDrawer::scanPrimDrawer() { // ensure buffer if( pktmax[cur_buffer_index] < target_pd->prim_num ) { if( pktbuf[cur_buffer_index] ) { FREE( pktbuf[cur_buffer_index] ); } size_t sz = target_pd->prim_num * sizeof(PacketPrim); pktbuf[cur_buffer_index] = (PacketPrim*) MALLOC(sz); pktmax[cur_buffer_index] = target_pd->prim_num; } // // scan pktnum[cur_buffer_index] = target_pd->prim_num; for(int i=0;i<pktnum[cur_buffer_index];i++){ copyPrimToPacketPrim( &pktbuf[cur_buffer_index][i], target_pd->prims[i] ); } } bool TrackerPrimDrawer::checkDiff() { PacketPrim *curary, *prevary; int curnum, prevnum; if(cur_buffer_index==0) { curary = pktbuf[0]; curnum = pktnum[0]; prevary = pktbuf[1]; prevnum = pktnum[1]; } else { curary = pktbuf[1]; curnum = pktnum[1]; prevary = pktbuf[0]; prevnum = pktnum[0]; } if( prevnum != curnum ) return true; for(int i=0;i<curnum;i++ ) { PacketPrim *curpkt = &curary[i]; PacketPrim *prevpkt = &prevary[i]; if( ( curpkt->prim_id != prevpkt->prim_id ) || ( curpkt->prim_type != prevpkt->prim_type ) || ( curpkt->a.x != prevpkt->a.x ) || ( curpkt->a.y != prevpkt->a.y ) || ( curpkt->b.x != prevpkt->b.x ) || ( curpkt->b.y != prevpkt->b.y ) || ( curpkt->color.r != prevpkt->color.r ) || ( curpkt->color.g != prevpkt->color.g ) || ( curpkt->color.b != prevpkt->color.b ) || ( curpkt->color.a != prevpkt->color.a ) || ( curpkt->line_width != prevpkt->line_width ) ) { return true; } } return false; } void TrackerPrimDrawer::broadcastDiff( Prop2D *owner, bool force ) { if( checkDiff() || force ) { if( pktnum[cur_buffer_index] > 0 ) { // print("sending %d prims for prop %d", pktnum[cur_buffer_index], owner->id ); // for(int i=0;i<pktnum[cur_buffer_index];i++) print("#### primid:%d", pktbuf[cur_buffer_index][i].prim_id ); parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT, owner->id, (const char*) pktbuf[cur_buffer_index], pktnum[cur_buffer_index] * sizeof(PacketPrim) ); } } } ////////////////// TrackerImage::TrackerImage( RemoteHead *rh, Image *target ) : target_image(target), cur_buffer_index(0), parent_rh(rh) { size_t sz = target->getBufferSize(); for(int i=0;i<2;i++) { imgbuf[i] = (uint8_t*) MALLOC(sz); assert(imgbuf[i]); } } TrackerImage::~TrackerImage() { for(int i=0;i<2;i++) if( imgbuf[i] ) FREE(imgbuf[i]); } void TrackerImage::scanImage() { uint8_t *dest = imgbuf[cur_buffer_index]; memcpy( dest, target_image->buffer, target_image->getBufferSize() ); } void TrackerImage::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } bool TrackerImage::checkDiff() { uint8_t *curimg, *previmg; if( cur_buffer_index==0) { curimg = imgbuf[0]; previmg = imgbuf[1]; } else { curimg = imgbuf[1]; previmg = imgbuf[0]; } if( memcmp( curimg, previmg, target_image->getBufferSize() ) != 0 ) { return true; } else { return false; } } void TrackerImage::broadcastDiff( Deck *owner_dk, bool force ) { if( checkDiff() || force ) { assertmsg( owner_dk->getUperCell()>0, "only tiledeck is supported now" ); // print("TrackerImage::broadcastDiff bufsz:%d", target_image->getBufferSize() ); parent_rh->broadcastUS1UI3( PACKETTYPE_S2C_IMAGE_ENSURE_SIZE, target_image->id, target_image->width, target_image->height ); parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_IMAGE_RAW, target_image->id, (const char*) imgbuf[cur_buffer_index], target_image->getBufferSize() ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTURE_IMAGE, owner_dk->tex->id, target_image->id ); parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TILEDECK_TEXTURE, owner_dk->id, owner_dk->tex->id ); // to update tileeck's image_width/height } } //////////////////// TrackerCamera::TrackerCamera( RemoteHead *rh, Camera *target ) : target_camera(target), cur_buffer_index(0), parent_rh(rh) { } TrackerCamera::~TrackerCamera() { } void TrackerCamera::scanCamera() { locbuf[cur_buffer_index] = Vec2( target_camera->loc.x, target_camera->loc.y ); } void TrackerCamera::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } bool TrackerCamera::checkDiff() { Vec2 curloc, prevloc; if( cur_buffer_index == 0 ) { curloc = locbuf[0]; prevloc = locbuf[1]; } else { curloc = locbuf[1]; prevloc = locbuf[0]; } return curloc != prevloc; } void TrackerCamera::broadcastDiff( bool force ) { if( checkDiff() || force ) { parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_CAMERA_LOC, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y ); } } void TrackerCamera::unicastDiff( Client *dest, bool force ) { if( checkDiff() || force ) { if( dest->isLogical()) { sendUS1UI2F2( dest->getStream(), PACKETTYPE_S2R_CAMERA_LOC, dest->id, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y ); } else { sendUS1UI1F2( dest, PACKETTYPE_S2C_CAMERA_LOC, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y ); } } } void TrackerCamera::unicastCreate( Client *dest ) { print("TrackerCamera: unicastCreate. id:%d repr:%d",dest->id, dest->isLogical() ); if( dest->isLogical() ) { print("sending s2r_cam_creat clid:%d camid:%d",dest->id, target_camera->id); sendUS1UI2( dest->getStream(), PACKETTYPE_S2R_CAMERA_CREATE, dest->id, target_camera->id ); } else { print("sending s2c_cam_creat camid:%d",target_camera->id); sendUS1UI1( dest, PACKETTYPE_S2C_CAMERA_CREATE, target_camera->id ); } POOL_SCAN(target_camera->target_layers,Layer) { Layer *l = it->second; if(dest->isLogical()) { print("sending s2r_cam_dyn_lay cl:%d cam:%d lay:%d", dest->id, target_camera->id, l->id); sendUS1UI3( dest->getStream(), PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER, dest->id, target_camera->id, l->id ); } else { print("sending s2c_cam_dyN_lay cam:%d lay:%d ", target_camera->id, l->id); sendUS1UI2( dest, PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER, target_camera->id, l->id ); } } } ////////////////////// TrackerViewport::TrackerViewport( RemoteHead *rh, Viewport *target ) : target_viewport(target), cur_buffer_index(0), parent_rh(rh) { } TrackerViewport::~TrackerViewport() { } void TrackerViewport::scanViewport() { sclbuf[cur_buffer_index] = Vec2( target_viewport->scl.x, target_viewport->scl.y ); } void TrackerViewport::flipCurrentBuffer() { cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 ); } bool TrackerViewport::checkDiff() { Vec2 curscl, prevscl; if( cur_buffer_index == 0 ) { curscl = sclbuf[0]; prevscl = sclbuf[1]; } else { curscl = sclbuf[1]; prevscl = sclbuf[0]; } return curscl != prevscl; } void TrackerViewport::broadcastDiff( bool force ) { if( checkDiff() | force ) { parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_VIEWPORT_SCALE, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y ); } } void TrackerViewport::unicastDiff( Client *dest, bool force ) { if( checkDiff() || force ) { if(dest->isLogical()) { sendUS1UI2F2( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_SCALE, dest->id, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y ); } else { sendUS1UI1F2( dest, PACKETTYPE_S2C_VIEWPORT_SCALE, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y ); } } } void TrackerViewport::unicastCreate( Client *dest ) { print("TrackerViewport::unicastCreate. id:%d",dest->id); if(dest->isLogical()) { sendUS1UI2( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_CREATE, dest->id, target_viewport->id ); } else { sendUS1UI1( dest, PACKETTYPE_S2C_VIEWPORT_CREATE, target_viewport->id ); } for(std::unordered_map<unsigned int,Layer*>::iterator it = target_viewport->target_layers.idmap.begin(); it != target_viewport->target_layers.idmap.end(); ++it ) { Layer *l = it->second; print(" TrackerViewport::unicastCreate: camera_dynamic_layer:%d", l->id ); if(dest->isLogical()) { sendUS1UI3( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER, dest->id, target_viewport->id, l->id ); } else { sendUS1UI2( dest, PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER, target_viewport->id, l->id ); } } } ///////////////////// static void reprecator_on_packet_cb( Stream *s, uint16_t funcid, char *argdata, uint32_t argdatalen ) { // print("reprecator_on_packet_cb. funcid:%d",funcid); Client *realcl = (Client*)s; Reprecator *rep = realcl->parent_reprecator; assert(rep); RemoteHead *rh = rep->parent_rh; assert(rh); switch(funcid) { case PACKETTYPE_R2S_CLIENT_LOGIN: { int reproxy_cl_id = get_u32(argdata+0); Client *newcl = Client::createLogicalClient(s,rh); rep->addLogicalClient(newcl); print("received r2s_login. giving a new newclid:%d, reproxy_cl_id:%d",newcl->id, reproxy_cl_id); sendUS1UI2(realcl,PACKETTYPE_S2R_NEW_CLIENT_ID, newcl->id, reproxy_cl_id ); if(rh->on_connect_cb) { rh->on_connect_cb(rh,newcl); } } break; case PACKETTYPE_R2S_CLIENT_LOGOUT: { int gclid = get_u32(argdata+0); print("received r2s_client_logout gclid:%d",gclid); Client *logcl = rep->logical_cl_pool.get(gclid); if(logcl) { assert(logcl->id==gclid); print("found client, deleting"); if(logcl->parent_rh->on_disconnect_cb) { logcl->parent_rh->on_disconnect_cb( logcl->parent_rh,logcl); } rep->logical_cl_pool.del(logcl->id); delete logcl; } else { print("can't find logical client id:%d",gclid); } } break; case PACKETTYPE_R2S_KEYBOARD: { uint32_t logclid = get_u32(argdata+0); uint32_t kc = get_u32(argdata+4); uint32_t act = get_u32(argdata+8); uint32_t modbits = get_u32(argdata+12); // print("received r2s_kbd. logclid:%d kc:%d act:%d modbits:%d", logclid, kc, act, modbits ); bool mod_shift,mod_ctrl,mod_alt; getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt); Client *logcl = rep->getLogicalClient(logclid); if(logcl && rh->on_keyboard_cb) rh->on_keyboard_cb(logcl,kc,act,mod_shift,mod_ctrl,mod_alt); } break; case PACKETTYPE_R2S_MOUSE_BUTTON: { uint32_t logclid = get_u32(argdata+0); uint32_t btn = get_u32(argdata+4); uint32_t act = get_u32(argdata+8); uint32_t modbits = get_u32(argdata+12); // print("received r2s_mousebtn. logclid:%d b:%d a:%d mod:%d", logclid, btn,act,modbits); bool mod_shift,mod_ctrl,mod_alt; getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt); Client *logcl = rep->getLogicalClient(logclid); if(logcl && rh->on_mouse_button_cb )rh->on_mouse_button_cb(logcl,btn,act,mod_shift,mod_ctrl,mod_alt); } break; case PACKETTYPE_R2S_CURSOR_POS: { uint32_t logclid = get_u32(argdata+0); float x = get_f32(argdata+4); float y = get_f32(argdata+8); // print("received r2s_cursorpos. logclid:%d %f,%f",logclid,x,y); Client *logcl = rep->getLogicalClient(logclid); if(logcl && rh->on_mouse_cursor_cb ) rh->on_mouse_cursor_cb(logcl,x,y); } break; default: break; } } static void reprecator_on_close_callback( uv_handle_t *s ) { print("reprecator_on_close_callback"); Client *cl = (Client*)s->data; assert(cl->parent_reprecator); int ids_toclean[1024]; int ids_toclean_num=0; POOL_SCAN(cl->parent_reprecator->logical_cl_pool,Client) { Client *logcl = it->second; if(logcl->reprecator_stream == cl) { print("freeing logical client id:%d", logcl->id); if( logcl->parent_rh->on_disconnect_cb ) { logcl->parent_rh->on_disconnect_cb( logcl->parent_rh, logcl ); } if( ids_toclean_num==elementof(ids_toclean))break; ids_toclean[ids_toclean_num] = logcl->id; ids_toclean_num++; delete logcl; // yes we can use it=pool.erase(xx) but i dont like it.. } } for(int i=0;i<ids_toclean_num;i++) { print("deleting from pool:%d",ids_toclean[i]); cl->parent_reprecator->logical_cl_pool.del(ids_toclean[i]); } cl->parent_reprecator->delRealClient(cl); } static void reprecator_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) { // print("reprecator_on_read_callback nread:%d",nread); if(nread>0) { Client *cl = (Client*)s->data; bool res = parseRecord( cl, &cl->recvbuf, inbuf->base, nread, reprecator_on_packet_cb ); if(!res) { uv_close( (uv_handle_t*)s, reprecator_on_close_callback ); return; } } else if( nread<0) { print("reprecator_on_read_callback eof or error" ); uv_close( (uv_handle_t*)s, reprecator_on_close_callback ); } } static void reprecator_on_accept_callback( uv_stream_t *listener, int status ) { print("reprecator_on_accept_callback status:%d",status); if( status != 0) { print("reprecator_on_accept_callback status:%d",status); return; } uv_tcp_t *newsock = (uv_tcp_t*) MALLOC( sizeof(uv_tcp_t) ); uv_tcp_init( uv_default_loop(), newsock ); if( uv_accept( listener, (uv_stream_t*) newsock ) == 0 ) { uv_tcp_nodelay(newsock,1); Reprecator *rep = (Reprecator*)listener->data; Client *cl = new Client(newsock,rep,false); rep->addRealClient(cl); newsock->data=(void*)cl; int r = uv_read_start( (uv_stream_t*) newsock, moyai_libuv_alloc_buffer, reprecator_on_read_callback ); if(r) { print("uv_read_start: fail ret:%d",r); return; } print("accepted new reprecator"); sendWindowSize( cl, rep->parent_rh->window_width, rep->parent_rh->window_height); rep->parent_rh->scanSendAllPrerequisites(cl); rep->parent_rh->scanSendAllProp2DSnapshots(cl); } } void Reprecator::addRealClient( Client *cl) { Client *stored = cl_pool.get(cl->id); if(!stored) { cl->parent_reprecator = this; cl_pool.set(cl->id,cl); } } void Reprecator::delRealClient(Client*cl) { cl_pool.del(cl->id); } void Reprecator::addLogicalClient( Client *cl) { Client *stored = logical_cl_pool.get(cl->id); if(!stored) { logical_cl_pool.set(cl->id,cl); } } void Reprecator::delLogicalClient(Client*cl) { logical_cl_pool.del(cl->id); } Client *Reprecator::getLogicalClient(uint32_t logclid) { return logical_cl_pool.get(logclid); } Reprecator::Reprecator(RemoteHead *rh, int portnum) : parent_rh(rh) { if( ! init_tcp_listener( &listener, (void*)this, portnum, reprecator_on_accept_callback ) ) { assertmsg(false, "can't initialize reprecator server"); } print("Reprecator server started"); } void Reprecator::heartbeat() { POOL_SCAN(cl_pool,Client) { it->second->flushSendbuf(256*1024); } } ///////////////////// void RemoteHead::enableVideoStream( int w, int h, int pixel_skip ) { enable_videostream = true; assertmsg(!jc, "can't call enableVideoStream again"); jc = new JPEGCoder(w,h,pixel_skip); audio_buf_ary = new BufferArray(256); print("enableVideoStream done"); } void RemoteHead::enableReprecation(int portnum) { assertmsg(!reprecator, "can't enable reprecation twice"); reprecator = new Reprecator(this,portnum); } // Note: don't support dynamic cameras void RemoteHead::broadcastCapturedScreen() { assert(jc); Image *img = jc->getImage(); double t0 = now(); target_moyai->capture(img); double t1 = now(); size_t sz = jc->encode(); double t2 = now(); if((t1-t0)>0.04) print("slow screen capture. %f", t1-t0); if((t2-t1)>0.02) print("slow encode. %f sz:%d",t2-t1, sz); //print("broadcastCapturedScreen time:%f,%f size:%d", t1-t0,t2-t1,sz ); #if 0 writeFile("encoded.jpg", (char*)jc->compressed, jc->compressed_size); #endif broadcastUS1Bytes( PACKETTYPE_S2C_CAPTURED_FRAME, (const char*)jc->compressed, jc->compressed_size ); } void RemoteHead::broadcastTimestamp() { double t = now(); uint32_t sec = (uint32_t)t; uint32_t usec = (t - sec)*1000000; broadcastUS1UI2( PACKETTYPE_TIMESTAMP, sec, usec ); } const char *RemoteHead::funcidToString(PACKETTYPE pkt) { switch(pkt) { case PACKETTYPE_PING: return "PACKETTYPE_PING"; case PACKETTYPE_TIMESTAMP: return "PACKETTYPE_TIMESTAMP"; case PACKETTYPE_ZIPPED_RECORDS: return "PACKETTYPE_ZIPPED_RECORDS"; // client to server case PACKETTYPE_C2S_KEYBOARD: return "PACKETTYPE_C2S_KEYBOARD"; case PACKETTYPE_C2S_MOUSE_BUTTON: return "PACKETTYPE_C2S_MOUSE_BUTTON"; case PACKETTYPE_C2S_CURSOR_POS: return "PACKETTYPE_C2S_CURSOR_POS"; case PACKETTYPE_C2S_TOUCH_BEGIN: return "PACKETTYPE_C2S_TOUCH_BEGIN"; case PACKETTYPE_C2S_TOUCH_MOVE: return "PACKETTYPE_C2S_TOUCH_MOVE"; case PACKETTYPE_C2S_TOUCH_END: return "PACKETTYPE_C2S_TOUCH_END"; case PACKETTYPE_C2S_TOUCH_CANCEL: return "PACKETTYPE_C2S_TOUCH_CANCEL"; // reprecator to server case PACKETTYPE_R2S_CLIENT_LOGIN: return "PACKETTYPE_R2S_CLIENT_LOGIN"; case PACKETTYPE_R2S_CLIENT_LOGOUT: return "PACKETTYPE_R2S_CLIENT_LOGOUT"; case PACKETTYPE_R2S_KEYBOARD: return "PACKETTYPE_R2S_KEYBOARD"; case PACKETTYPE_R2S_MOUSE_BUTTON: return "PACKETTYPE_R2S_MOUSE_BUTTON"; case PACKETTYPE_R2S_CURSOR_POS: return "PACKETTYPE_R2S_CURSOR_POS"; case PACKETTYPE_S2R_NEW_CLIENT_ID: return "PACKETTYPE_S2R_NEW_CLIENT_ID"; case PACKETTYPE_S2R_CAMERA_CREATE: return "PACKETTYPE_S2R_CAMERA_CREATE"; case PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER: return "PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER"; case PACKETTYPE_S2R_CAMERA_LOC: return "PACKETTYPE_S2R_CAMERA_LOC"; case PACKETTYPE_S2R_VIEWPORT_CREATE: return "PACKETTYPE_S2R_VIEWPORT_CREATE"; case PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER: return "PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER"; case PACKETTYPE_S2R_VIEWPORT_SCALE: return "PACKETTYPE_S2R_VIEWPORT_SCALE"; case PACKETTYPE_S2R_PROP2D_TARGET_CLIENT: return "PACKETTYPE_S2R_PROP2D_TARGET_CLIENT"; case PACKETTYPE_S2R_PROP2D_LOC: return "PACKETTYPE_S2R_PROP2D_LOC"; // server to client case PACKETTYPE_S2C_PROP2D_SNAPSHOT: return "PACKETTYPE_S2C_PROP2D_SNAPSHOT"; case PACKETTYPE_S2C_PROP2D_LOC: return "PACKETTYPE_S2C_PROP2D_LOC"; case PACKETTYPE_S2C_PROP2D_INDEX: return "PACKETTYPE_S2C_PROP2D_INDEX"; case PACKETTYPE_S2C_PROP2D_SCALE: return "PACKETTYPE_S2C_PROP2D_SCALE"; case PACKETTYPE_S2C_PROP2D_ROT: return "PACKETTYPE_S2C_PROP2D_ROT"; case PACKETTYPE_S2C_PROP2D_FLIPROTBITS: return "PACKETTYPE_S2C_PROP2D_FLIPROTBITS"; case PACKETTYPE_S2C_PROP2D_COLOR: return "PACKETTYPE_S2C_PROP2D_COLOR"; case PACKETTYPE_S2C_PROP2D_OPTBITS: return "PACKETTYPE_S2C_PROP2D_OPTBITS"; case PACKETTYPE_S2C_PROP2D_PRIORITY: return "PACKETTYPE_S2C_PROP2D_PRIORITY"; case PACKETTYPE_S2C_PROP2D_DELETE: return "PACKETTYPE_S2C_PROP2D_DELETE"; case PACKETTYPE_S2C_PROP2D_CLEAR_CHILD: return "PACKETTYPE_S2C_PROP2D_CLEAR_CHILD"; case PACKETTYPE_S2C_PROP2D_LOC_VEL: return "PACKETTYPE_S2C_PROP2D_LOC_VEL"; case PACKETTYPE_S2C_PROP2D_INDEX_LOC: return "PACKETTYPE_S2C_PROP2D_INDEX_LOC"; case PACKETTYPE_S2C_PROP2D_LOC_SCL: return "PACKETTYPE_S2C_PROP2D_LOC_SCL"; case PACKETTYPE_S2C_LAYER_CREATE: return "PACKETTYPE_S2C_LAYER_CREATE"; case PACKETTYPE_S2C_LAYER_VIEWPORT: return "PACKETTYPE_S2C_LAYER_VIEWPORT"; case PACKETTYPE_S2C_LAYER_CAMERA: return "PACKETTYPE_S2C_LAYER_CAMERA"; case PACKETTYPE_S2C_VIEWPORT_CREATE: return "PACKETTYPE_S2C_VIEWPORT_CREATE"; // case PACKETTYPE_S2C_VIEWPORT_SIZE: 331, not used now case PACKETTYPE_S2C_VIEWPORT_SCALE: return "PACKETTYPE_S2C_VIEWPORT_SCALE"; case PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER: return "PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER"; case PACKETTYPE_S2C_CAMERA_CREATE: return "PACKETTYPE_S2C_CAMERA_CREATE"; case PACKETTYPE_S2C_CAMERA_LOC: return "PACKETTYPE_S2C_CAMERA_LOC"; case PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER: return "PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER"; case PACKETTYPE_S2C_TEXTURE_CREATE: return "PACKETTYPE_S2C_TEXTURE_CREATE"; case PACKETTYPE_S2C_TEXTURE_IMAGE: return "PACKETTYPE_S2C_TEXTURE_IMAGE"; case PACKETTYPE_S2C_IMAGE_CREATE: return "PACKETTYPE_S2C_IMAGE_CREATE"; case PACKETTYPE_S2C_IMAGE_LOAD_PNG: return "PACKETTYPE_S2C_IMAGE_LOAD_PNG"; case PACKETTYPE_S2C_IMAGE_ENSURE_SIZE: return "PACKETTYPE_S2C_IMAGE_ENSURE_SIZE"; case PACKETTYPE_S2C_IMAGE_RAW: return "PACKETTYPE_S2C_IMAGE_RAW"; case PACKETTYPE_S2C_TILEDECK_CREATE: return "PACKETTYPE_S2C_TILEDECK_CREATE"; case PACKETTYPE_S2C_TILEDECK_TEXTURE: return "PACKETTYPE_S2C_TILEDECK_TEXTURE"; case PACKETTYPE_S2C_TILEDECK_SIZE: return "PACKETTYPE_S2C_TILEDECK_SIZE"; case PACKETTYPE_S2C_GRID_CREATE: return "PACKETTYPE_S2C_GRID_CREATE"; case PACKETTYPE_S2C_GRID_DECK: return "PACKETTYPE_S2C_GRID_DECK"; case PACKETTYPE_S2C_GRID_PROP2D: return "PACKETTYPE_S2C_GRID_PROP2D"; case PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT"; case PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT"; case PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT"; case PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT"; case PACKETTYPE_S2C_GRID_DELETE: return "PACKETTYPE_S2C_GRID_DELETE"; case PACKETTYPE_S2C_TEXTBOX_CREATE: return "PACKETTYPE_S2C_TEXTBOX_CREATE"; case PACKETTYPE_S2C_TEXTBOX_FONT: return "PACKETTYPE_S2C_TEXTBOX_FONT"; case PACKETTYPE_S2C_TEXTBOX_STRING: return "PACKETTYPE_S2C_TEXTBOX_STRING"; case PACKETTYPE_S2C_TEXTBOX_LOC: return "PACKETTYPE_S2C_TEXTBOX_LOC"; case PACKETTYPE_S2C_TEXTBOX_SCL: return "PACKETTYPE_S2C_TEXTBOX_SCL"; case PACKETTYPE_S2C_TEXTBOX_COLOR: return "PACKETTYPE_S2C_TEXTBOX_COLOR"; case PACKETTYPE_S2C_TEXTBOX_PRIORITY: return "PACKETTYPE_S2C_TEXTBOX_PRIORITY"; case PACKETTYPE_S2C_TEXTBOX_LAYER: return "PACKETTYPE_S2C_TEXTBOX_LAYER"; case PACKETTYPE_S2C_FONT_CREATE: return "PACKETTYPE_S2C_FONT_CREATE"; case PACKETTYPE_S2C_FONT_CHARCODES: return "PACKETTYPE_S2C_FONT_CHARCODES"; case PACKETTYPE_S2C_FONT_LOADTTF: return "PACKETTYPE_S2C_FONT_LOADTTF"; case PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT: return "PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT"; case PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT: return "PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT"; case PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE: return "PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE"; case PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES: return "PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES"; case PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME: return "PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME"; case PACKETTYPE_S2C_SOUND_PLAY: return "PACKETTYPE_S2C_SOUND_PLAY"; case PACKETTYPE_S2C_SOUND_STOP: return "PACKETTYPE_S2C_SOUND_STOP"; case PACKETTYPE_S2C_SOUND_POSITION: return "PACKETTYPE_S2C_SOUND_POSITION"; case PACKETTYPE_S2C_JPEG_DECODER_CREATE: return "PACKETTYPE_S2C_JPEG_DECODER_CREATE"; case PACKETTYPE_S2C_CAPTURED_FRAME: return "PACKETTYPE_S2C_CAPTURED_FRAME"; case PACKETTYPE_S2C_CAPTURED_AUDIO: return "PACKETTYPE_S2C_CAPTURED_AUDIO"; case PACKETTYPE_S2C_FILE: return "PACKETTYPE_S2C_FILE"; case PACKETTYPE_S2C_WINDOW_SIZE: return "PACKETTYPE_S2C_WINDOW_SIZE"; case PACKETTYPE_C2S_REQUEST_FILE: return "PACKETTYPE_C2S_REQUEST_FILE"; case PACKETTYPE_C2S_REQUEST_FILE_LIST: return "PACKETTYPE_C2S_REQUEST_FILE_LIST"; case PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT: return "PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT"; case PACKETTYPE_S2C_FILE_INFO: return "PACKETTYPE_S2C_FILE_INFO"; case PACKETTYPE_S2C_FILE_INFO_END: return "PACKETTYPE_S2C_FILE_INFO_END"; case PACKETTYPE_ERROR: return "PACKETTYPE_ERROR"; case PACKETTYPE_MAX: return "PACKETTYPE_MAX"; } assertmsg(false,"invalid packet type:%d", pkt); return "invalid packet type"; } #if 1 #define FUNCID_LOG(id,sendfuncname) print( "%s %s", funcidToString(id),sendfuncname) #else #define FUNCID_LOG(id,sendfuncname) ; #endif #define REPRECATOR_ITER_SEND if(reprecator) POOL_SCAN(reprecator->cl_pool,Client) #define CLIENT_ITER_SEND for( ClientIteratorType it = cl_pool.idmap.begin(); it != cl_pool.idmap.end(); ++it ) void RemoteHead::broadcastUS1Bytes( uint16_t usval, const char *data, size_t datalen ) { CLIENT_ITER_SEND sendUS1Bytes( it->second, usval, data, datalen ); REPRECATOR_ITER_SEND sendUS1Bytes( it->second, usval, data, datalen ); } void RemoteHead::broadcastUS1UI1Bytes( uint16_t usval, uint32_t uival, const char *data, size_t datalen ) { CLIENT_ITER_SEND sendUS1UI1Bytes( it->second, usval, uival, data, datalen ); REPRECATOR_ITER_SEND sendUS1UI1Bytes( it->second, usval, uival, data, datalen ); } void RemoteHead::broadcastUS1UI1( uint16_t usval, uint32_t uival ) { CLIENT_ITER_SEND sendUS1UI1( it->second, usval, uival ); REPRECATOR_ITER_SEND sendUS1UI1( it->second, usval, uival ); } void RemoteHead::broadcastUS1UI2( uint16_t usval, uint32_t ui0, uint32_t ui1, bool reprecator_only ) { if(!reprecator_only) CLIENT_ITER_SEND sendUS1UI2( it->second, usval, ui0, ui1 ); REPRECATOR_ITER_SEND sendUS1UI2( it->second, usval, ui0, ui1 ); } void RemoteHead::broadcastUS1UI3( uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2 ) { CLIENT_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 ); REPRECATOR_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 ); } void RemoteHead::broadcastUS1UI4( uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3 ) { CLIENT_ITER_SEND sendUS1UI4( it->second, usval, ui0, ui1, ui2, ui3 ); REPRECATOR_ITER_SEND sendUS1UI4( it->second, usval, ui0, ui1, ui2, ui3 ); } void RemoteHead::broadcastUS1UI1Wstr( uint16_t usval, uint32_t uival, wchar_t *wstr, int wstr_num_letters ) { CLIENT_ITER_SEND sendUS1UI1Wstr( it->second, usval, uival, wstr, wstr_num_letters ); REPRECATOR_ITER_SEND sendUS1UI1Wstr( it->second, usval, uival, wstr, wstr_num_letters ); } void RemoteHead::broadcastUS1UI1F4( uint16_t usval, uint32_t uival, float f0, float f1, float f2, float f3 ) { CLIENT_ITER_SEND sendUS1UI1F4( it->second, usval, uival, f0, f1, f2, f3 ); REPRECATOR_ITER_SEND sendUS1UI1F4( it->second, usval, uival, f0, f1, f2, f3 ); } void RemoteHead::broadcastUS1UI1F2( uint16_t usval, uint32_t uival, float f0, float f1 ) { CLIENT_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 ); REPRECATOR_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 ); } void RemoteHead::broadcastUS1UI2F2( uint16_t usval, uint32_t ui0, uint32_t ui1, float f0, float f1 ) { CLIENT_ITER_SEND sendUS1UI2F2( it->second, usval, ui0, ui1, f0, f1 ); REPRECATOR_ITER_SEND sendUS1UI2F2( it->second, usval, ui0, ui1, f0, f1 ); } void RemoteHead::broadcastUS1UI1UC1( uint16_t usval, uint32_t uival, uint8_t ucval ) { CLIENT_ITER_SEND sendUS1UI1UC1( it->second, usval, uival, ucval ); REPRECATOR_ITER_SEND sendUS1UI1UC1( it->second, usval, uival, ucval ); } void RemoteHead::nearcastUS1UI1F2( Prop2D *p, uint16_t usval, uint32_t uival, float f0, float f1 ) { POOL_SCAN(cl_pool,Client) { Client *cl = it->second; if(cl->canSee(p)==false) continue; sendUS1UI1F2( cl, usval, uival, f0, f1 ); } REPRECATOR_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 ); } void RemoteHead::nearcastUS1UI3( Prop2D *p, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, bool reprecator_only ) { if(!reprecator_only) { POOL_SCAN(cl_pool,Client) { Client *cl = it->second; if(cl->canSee(p)==false) continue; sendUS1UI3( cl, usval, ui0, ui1, ui2 ); } } REPRECATOR_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 ); } void RemoteHead::nearcastUS1UI3F2( Prop2D *p, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, float f0, float f1 ) { POOL_SCAN(cl_pool,Client) { Client *cl = it->second; if(cl->canSee(p)==false) continue; sendUS1UI3F2( cl, usval, ui0, ui1, ui2, f0,f1 ); } REPRECATOR_ITER_SEND sendUS1UI3F2( it->second, usval, ui0, ui1, ui2, f0, f1 ); } void RemoteHead::broadcastUS1UI1F1( uint16_t usval, uint32_t uival, float f0 ) { CLIENT_ITER_SEND sendUS1UI1F1( it->second, usval, uival, f0 ); REPRECATOR_ITER_SEND sendUS1UI1F1( it->second, usval, uival, f0 ); } bool RemoteHead::appendNonlinearChangelist(Prop2D *p, PacketProp2DSnapshot *pkt) { if( changelist_used == elementof(changelist) )return false; changelist[changelist_used] = ChangeEntry(p,pkt); changelist_used++; return true; } void RemoteHead::broadcastSortedChangelist() { static SorterEntry tosort[elementof(changelist)]; for(int i=0;i<changelist_used;i++) { tosort[i].val = changelist[i].p->loc_sync_score; tosort[i].ptr = &changelist[i]; } quickSortF( tosort, 0, changelist_used-1); // print("sortChangelist:%d",changelist_used); int max_send_num = sorted_changelist_max_send_num; if( sorted_changelist_max_send_num > changelist_used ) max_send_num = changelist_used; int sent_n=0; for(int i=changelist_used-1;i>=0;i--) { // reverse order: biggest first ChangeEntry *e = (ChangeEntry*)tosort[i].ptr; if( e->p->loc_sync_score > sort_sync_thres ) { nearcastUS1UI3( e->p, PACKETTYPE_S2C_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y ); e->p->loc_sync_score=0; e->p->loc_changed=false; sent_n++; if( sent_n >= max_send_num)break; } else if( e->p->target_client_id > 0 ) { Client *cl = cl_pool.get(e->p->target_client_id); if(cl) { sendUS1UI3( cl, PACKETTYPE_S2C_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y ); } nearcastUS1UI3( e->p, PACKETTYPE_S2R_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y, true ); } } // print("broadcastChangelist: tot:%d sent:%d max:%d", changelist_used, sent_n, max_send_num); } /////////////////// int calcModkeyBits(bool shift, bool ctrl, bool alt ) { int out=0; if(shift) out |= MODKEY_BIT_SHIFT; if(ctrl) out |= MODKEY_BIT_CONTROL; if(alt) out |= MODKEY_BIT_ALT; return out; } void getModkeyBits(int val, bool *shift, bool *ctrl, bool *alt ) { *shift = val & MODKEY_BIT_SHIFT; *ctrl = val & MODKEY_BIT_CONTROL; *alt = val & MODKEY_BIT_ALT; } /////////////////// char sendbuf_work[1024*1024*16]; #define SET_RECORD_LEN_AND_US1 \ assert(totalsize<=sizeof(sendbuf_work));\ set_u32( sendbuf_work+0, totalsize - 4 ); \ set_u16( sendbuf_work+4, usval ); int pushDataToStream( Stream *s, char *buf, size_t sz ) { #if 0 // for debugging if(sz>=6){ uint16_t funcid = get_u16((const char*)buf+4); print("[%.4f] SEND %s ARGLEN:%d", now(), RemoteHead::funcidToString( (PACKETTYPE)funcid), sz-4-2 ); } #endif int ret = s->sendbuf.push(buf,sz); if(ret) return sz; else return 0; } int sendUS1RawArgs( Stream *s, uint16_t usval, const char *data, uint32_t datalen ) { size_t totalsize = 4 + 2 + datalen; SET_RECORD_LEN_AND_US1; memcpy( sendbuf_work+4+2,data, datalen); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1( Stream *s, uint16_t usval ) { size_t totalsize = 4 + 2; SET_RECORD_LEN_AND_US1; return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1Bytes( Stream *s, uint16_t usval, const char *bytes, uint16_t byteslen ) { size_t totalsize = 4 + 2 + (4+byteslen); SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, byteslen ); memcpy( sendbuf_work+4+2+4, bytes, byteslen ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1Bytes( Stream *s, uint16_t usval, uint32_t uival, const char *bytes, uint32_t byteslen ) { size_t totalsize = 4 + 2 + 4 + (4+byteslen); SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); set_u32( sendbuf_work+4+2+4, byteslen ); memcpy( sendbuf_work+4+2+4+4, bytes, byteslen ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI2Bytes( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, const char *bytes, uint32_t byteslen ) { size_t totalsize = 4 + 2 + 4 + 4+ (4+byteslen); SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival0 ); set_u32( sendbuf_work+4+2+4, uival1 ); set_u32( sendbuf_work+4+2+4+4, byteslen ); memcpy( sendbuf_work+4+2+4+4+4, bytes, byteslen ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1( Stream *s, uint16_t usval, uint32_t uival ) { size_t totalsize = 4 + 2 + 4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI2( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1 ) { size_t totalsize = 4 + 2 + 4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, ui0 ); set_u32( sendbuf_work+4+2+4, ui1 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI3( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2 ) { size_t totalsize = 4 + 2 + 4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, ui0 ); set_u32( sendbuf_work+4+2+4, ui1 ); set_u32( sendbuf_work+4+2+4+4, ui2 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI4( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3 ) { size_t totalsize = 4 + 2 + 4+4+4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, ui0 ); set_u32( sendbuf_work+4+2+4, ui1 ); set_u32( sendbuf_work+4+2+4+4, ui2 ); set_u32( sendbuf_work+4+2+4+4+4, ui3 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI5( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3, uint32_t ui4 ) { size_t totalsize = 4 + 2 + 4+4+4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, ui0 ); set_u32( sendbuf_work+4+2+4, ui1 ); set_u32( sendbuf_work+4+2+4+4, ui2 ); set_u32( sendbuf_work+4+2+4+4+4, ui3 ); set_u32( sendbuf_work+4+2+4+4+4+4, ui4 ); return pushDataToStream(s,sendbuf_work,totalsize); } // not an array int sendUS1UIn( Stream *s, uint16_t usval, uint32_t *ui, size_t ui_n ) { size_t totalsize = 4 + 2 + 4*ui_n; SET_RECORD_LEN_AND_US1; for(int i=0;i<ui_n;i++) set_u32( sendbuf_work+4+2+i*4, ui[i]); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1USn( Stream *s, uint16_t usval, uint16_t *us, size_t us_n ) { size_t totalsize = 4 + 2 + 2*us_n; SET_RECORD_LEN_AND_US1; for(int i=0;i<us_n;i++) set_u16( sendbuf_work+4+2+i*2, us[i]); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1F1( Stream *s, uint16_t usval, uint32_t uival, float f0 ) { size_t totalsize = 4 + 2 + 4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); memcpy( sendbuf_work+4+2+4, &f0, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1F2( Stream *s, uint16_t usval, uint32_t uival, float f0, float f1 ) { size_t totalsize = 4 + 2 + 4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); memcpy( sendbuf_work+4+2+4, &f0, 4 ); memcpy( sendbuf_work+4+2+4+4, &f1, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI2F2( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, float f0, float f1 ) { size_t totalsize = 4 + 2 + 4+4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival0 ); set_u32( sendbuf_work+4+2+4, uival1 ); memcpy( sendbuf_work+4+2+4+4, &f0, 4 ); memcpy( sendbuf_work+4+2+4+4+4, &f1, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI3F2( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, uint32_t uival2, float f0, float f1 ) { size_t totalsize = 4 + 2 + 4+4+4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival0 ); set_u32( sendbuf_work+4+2+4, uival1 ); set_u32( sendbuf_work+4+2+4+4, uival2 ); memcpy( sendbuf_work+4+2+4+4+4, &f0, 4 ); memcpy( sendbuf_work+4+2+4+4+4+4, &f1, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1F4( Stream *s, uint16_t usval, uint32_t uival, float f0, float f1, float f2, float f3 ) { size_t totalsize = 4 + 2 + 4+4+4+4+4; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); memcpy( sendbuf_work+4+2+4, &f0, 4 ); memcpy( sendbuf_work+4+2+4+4, &f1, 4 ); memcpy( sendbuf_work+4+2+4+4+4, &f2, 4 ); memcpy( sendbuf_work+4+2+4+4+4+4, &f3, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1UC1( Stream *s, uint16_t usval, uint32_t uival, uint8_t ucval ) { size_t totalsize = 4 + 2 + 4+1; SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); sendbuf_work[4+2+4] = ucval; return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1F2( Stream *s, uint16_t usval, float f0, float f1 ) { size_t totalsize = 4 + 2 + 4+4; SET_RECORD_LEN_AND_US1; memcpy( sendbuf_work+4+2, &f0, 4 ); memcpy( sendbuf_work+4+2+4, &f1, 4 ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI1Str( Stream *s, uint16_t usval, uint32_t uival, const char *cstr ) { int cstrlen = strlen(cstr); assert( cstrlen <= 255 ); size_t totalsize = 4 + 2 + 4 + (1+cstrlen); SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, uival ); set_u8( sendbuf_work+4+2+4, (unsigned char) cstrlen ); memcpy( sendbuf_work+4+2+4+1, cstr, cstrlen ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1UI2Str( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, const char *cstr ) { int cstrlen = strlen(cstr); assert( cstrlen <= 255 ); size_t totalsize = 4 + 2 + 4+4 + (1+cstrlen); SET_RECORD_LEN_AND_US1; set_u32( sendbuf_work+4+2, ui0 ); set_u32( sendbuf_work+4+2+4, ui1 ); set_u8( sendbuf_work+4+2+4+4, (unsigned char) cstrlen ); memcpy( sendbuf_work+4+2+4+4+1, cstr, cstrlen ); return pushDataToStream(s,sendbuf_work,totalsize); } int sendUS1Str( Stream *s, uint16_t usval, const char *cstr ) { int cstrlen = strlen(cstr); assert( cstrlen <= 255 ); size_t totalsize = 4 + 2 + (1+cstrlen); SET_RECORD_LEN_AND_US1; set_u8( sendbuf_work+4+2, (unsigned char) cstrlen ); memcpy( sendbuf_work+4+2+1, cstr, cstrlen ); return pushDataToStream(s,sendbuf_work,totalsize); } // [record-len:16][usval:16][cstr-len:8][cstr-body][data-len:32][data-body] int sendUS1StrBytes( Stream *s, uint16_t usval, const char *cstr, const char *data, uint32_t datalen ) { int cstrlen = strlen(cstr); assert( cstrlen <= 255 ); size_t totalsize = 4 + 2 + (1+cstrlen) + (4+datalen); SET_RECORD_LEN_AND_US1; set_u8( sendbuf_work+4+2, (unsigned char) cstrlen ); memcpy( sendbuf_work+4+2+1, cstr, cstrlen ); set_u32( sendbuf_work+4+2+1+cstrlen, datalen ); memcpy( sendbuf_work+4+2+1+cstrlen+4, data, datalen ); // print("send_packet_str_bytes: cstrlen:%d datalen:%d totallen:%d", cstrlen, datalen, totalsize ); return pushDataToStream(s,sendbuf_work,totalsize); } void parsePacketStrBytes( char *inptr, char *outcstr, char **outptr, size_t *outsize ) { uint8_t slen = get_u8(inptr); char *s = inptr + 1; uint32_t datalen = get_u32(inptr+1+slen); *outptr = inptr + 1 + slen + 4; memcpy( outcstr, s, slen ); outcstr[slen]='\0'; *outsize = (size_t) datalen; } // convert wchar_t to int sendUS1UI1Wstr( Stream *s, uint16_t usval, uint32_t uival, wchar_t *wstr, int wstr_num_letters ) { // lock is correctly handled by sendUS1UI1Bytes later in this func #if defined(__APPLE__) || defined(__linux__) assert( sizeof(wchar_t) == sizeof(int32_t) ); size_t bufsz = wstr_num_letters * sizeof(int32_t); UTF8 *outbuf = (UTF8*) MALLOC( bufsz + 1); assert(outbuf); UTF8 *orig_outbuf = outbuf; const UTF32 *inbuf = (UTF32*) wstr; ConversionResult r = ConvertUTF32toUTF8( &inbuf, inbuf+wstr_num_letters, &outbuf, outbuf+bufsz, strictConversion ); assertmsg(r==conversionOK, "ConvertUTF32toUTF8 failed:%d bufsz:%d", r, bufsz ); #else assert( sizeof(wchar_t) == sizeof(int16_t) ); size_t bufsz = wstr_num_letters * sizeof(int16_t) * 2; // utf8 gets bigger than utf16 UTF8 *outbuf = (UTF8*) MALLOC( bufsz + 1); assert(outbuf); UTF8 *orig_outbuf = outbuf; const UTF16 *inbuf = (UTF16*) wstr; ConversionResult r = ConvertUTF16toUTF8( &inbuf, inbuf+wstr_num_letters, &outbuf, outbuf+bufsz, strictConversion ); assertmsg(r==conversionOK, "ConvertUTF16toUTF8 failed:%d bufsz:%d", r, bufsz ); #endif size_t outlen = outbuf - orig_outbuf; // print("ConvertUTF32toUTF8 result utf8 len:%d out:'%s'", outlen, orig_outbuf ); int ret = sendUS1UI1Bytes( s, usval, uival, (const char*) orig_outbuf, outlen ); FREE(orig_outbuf); return ret; } void sendFile( Stream *s, const char *filename ) { const size_t MAXBUFSIZE = 1024*1024*16; char *buf = (char*) MALLOC(MAXBUFSIZE); assert(buf); size_t sz = MAXBUFSIZE; bool res = readFile( filename, buf, &sz ); assertmsg(res, "sendFile: file '%s' read error", filename ); int r = sendUS1StrBytes( s, PACKETTYPE_S2C_FILE, filename, buf, sz ); assert(r>0); print("sendFile: path:%s len:%d data:%x %x %x %x sendres:%d", filename, sz, buf[0], buf[1], buf[2], buf[3], r ); FREE(buf); } void sendPing( Stream *s ) { double t = now(); uint32_t sec = (uint32_t)t; uint32_t usec = (t - sec)*1000000; sendUS1UI2( s, PACKETTYPE_PING, sec, usec ); } void sendWindowSize( Stream *outstream, int w, int h ) { sendUS1UI2( outstream, PACKETTYPE_S2C_WINDOW_SIZE, w,h ); } void sendViewportCreateScale( Stream *outstream, Viewport *vp ) { sendUS1UI1( outstream, PACKETTYPE_S2C_VIEWPORT_CREATE, vp->id ); sendUS1UI1F2( outstream, PACKETTYPE_S2C_VIEWPORT_SCALE, vp->id, vp->scl.x, vp->scl.y ); } void sendCameraCreateLoc( Stream *outstream, Camera *cam ) { sendUS1UI1( outstream, PACKETTYPE_S2C_CAMERA_CREATE, cam->id ); sendUS1UI1F2( outstream, PACKETTYPE_S2C_CAMERA_LOC, cam->id, cam->loc.x, cam->loc.y ); } void sendLayerSetup( Stream *outstream, Layer *l ) { sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_CREATE, l->id, l->priority ); if( l->viewport ) sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_VIEWPORT, l->id, l->viewport->id); if( l->camera ) sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_CAMERA, l->id, l->camera->id ); } void sendImageSetup( Stream *outstream, Image *img ) { print("sending image_create id:%d", img->id ); sendUS1UI1( outstream, PACKETTYPE_S2C_IMAGE_CREATE, img->id ); if( img->last_load_file_path[0] ) { print("sending image_load_png: '%s'", img->last_load_file_path ); sendUS1UI1Str( outstream, PACKETTYPE_S2C_IMAGE_LOAD_PNG, img->id, img->last_load_file_path ); } if( img->width>0 && img->buffer) { // this image is not from file, maybe generated. sendUS1UI3( outstream, PACKETTYPE_S2C_IMAGE_ENSURE_SIZE, img->id, img->width, img->height ); } if( img->modified_pixel_num > 0 ) { // modified image (includes loadPNG case) sendUS1UI3( outstream, PACKETTYPE_S2C_IMAGE_ENSURE_SIZE, img->id, img->width, img->height ); sendUS1UI1Bytes( outstream, PACKETTYPE_S2C_IMAGE_RAW, img->id, (const char*) img->buffer, img->getBufferSize() ); } } void sendTextureCreateWithImage( Stream *outstream, Texture *tex ) { sendUS1UI1( outstream, PACKETTYPE_S2C_TEXTURE_CREATE, tex->id ); sendUS1UI2( outstream, PACKETTYPE_S2C_TEXTURE_IMAGE, tex->id, tex->image->id ); } void sendDeckSetup( Stream *outstream, Deck *dk ) { assertmsg(dk->getUperCell()>0, "only tiledeck is supported" ); // TODO: Support PackDeck TileDeck *td = (TileDeck*) dk; // print("sending tiledeck_create id:%d", td->id ); sendUS1UI1( outstream, PACKETTYPE_S2C_TILEDECK_CREATE, dk->id ); sendUS1UI2( outstream, PACKETTYPE_S2C_TILEDECK_TEXTURE, dk->id, td->tex->id ); // print("sendS2RTileDeckSize: id:%d %d,%d,%d,%d", td->id, sprw, sprh, cellw, cellh ); sendUS1UI5( outstream, PACKETTYPE_S2C_TILEDECK_SIZE, td->id, td->tile_width, td->tile_height, td->cell_width, td->cell_height ); } void sendFontSetupWithFile( Stream *outstream, Font *f ) { print("sending font id:%d path:%s", f->id, f->last_load_file_path ); sendUS1UI1( outstream, PACKETTYPE_S2C_FONT_CREATE, f->id ); // utf32toutf8 sendUS1UI1Wstr( outstream, PACKETTYPE_S2C_FONT_CHARCODES, f->id, f->charcode_table, f->charcode_table_used_num ); // sendFile( outstream, f->last_load_file_path ); sendUS1UI2Str( outstream, PACKETTYPE_S2C_FONT_LOADTTF, f->id, f->pixel_size, f->last_load_file_path ); } void sendColorReplacerShaderSetup( Stream *outstream, ColorReplacerShader *crs ) { print("sending col repl shader id:%d", crs->id ); PacketColorReplacerShaderSnapshot ss; setupPacketColorReplacerShaderSnapshot(&ss,crs); sendUS1Bytes( outstream, PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT, (const char*)&ss, sizeof(ss) ); } void sendSoundSetup( Stream *outstream, Sound *snd ) { if( snd->last_load_file_path[0] ) { // sendFile( outstream, snd->last_load_file_path ); print("sending sound load file: %d, '%s'", snd->id, snd->last_load_file_path ); sendUS1UI1Str( outstream, PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE, snd->id, snd->last_load_file_path ); } else if( snd->last_samples ){ sendUS1UI1Bytes( outstream, PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES, snd->id, (const char*) snd->last_samples, snd->last_samples_num * sizeof(snd->last_samples[0]) ); } sendUS1UI1F1( outstream, PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME, snd->id, snd->default_volume ); if(snd->isPlaying()) { sendUS1UI1F2( outstream, PACKETTYPE_S2C_SOUND_POSITION, snd->id, snd->getTimePositionSec(), snd->last_play_volume ); } } //////////////////// Buffer::Buffer() : buf(0), size(0), used(0) { } void Buffer::ensureMemory( size_t sz ) { if(!buf) { buf = (char*) MALLOC(sz); assert(buf); size = sz; used = 0; } } Buffer::~Buffer() { if(buf) { FREE(buf); } size = used = 0; } bool Buffer::push( const char *data, size_t datasz ) { if(datasz==0)return true; size_t left = size - used; if( left < datasz ) return false; memcpy( buf + used, data, datasz ); used += datasz; // fprintf(stderr, "buffer_push: pushed %d bytes, used: %d\n", (int)datasz, (int)b->used ); return true; } bool Buffer::pushWithNum32( const char *data, size_t datasz ) { size_t left = size - used; if( left < 4 + datasz ) return false; set_u32( buf + used, datasz ); used += 4; push( data, datasz ); return true; } bool Buffer::pushU32( unsigned int val ) { size_t left = size - used; if( left < 4 ) return false; set_u32( buf + used, val ); used += 4; // fprintf(stderr, "buffer_push_u32: pushed 4 bytes. val:%u\n",val ); return true; } bool Buffer::pushU16( unsigned short val ) { size_t left = size - used; if( left < 2 ) return false; set_u16( buf + used, val ); used += 2; return true; } bool Buffer::pushU8( unsigned char val ) { size_t left = size - used; if( left < 1 ) return false; set_u8( buf + used, val ); used += 1; return true; } // ALL or NOTHING. true when success bool Buffer::shift( size_t toshift ) { if( used < toshift ) return false; if( toshift == used ) { // most cases used = 0; return true; } // 0000000000 size=10 // uuuuu used=5 // ss shift=2 // mmm move=3 memmove( buf, buf + toshift, used - toshift ); used -= toshift; return true; } ////////////////// BufferArray::BufferArray( int maxnum ) { buffers = (Buffer**) MALLOC( maxnum * sizeof(Buffer*) ); assert(buffers); buffer_num = maxnum; buffer_used = 0; for(int i=0;i<maxnum;i++) buffers[i] = NULL; } BufferArray::~BufferArray() { for(unsigned int i=0;i<buffer_num;i++) { delete buffers[i]; FREE(buffers[i]); } } bool BufferArray::push(const char *data, size_t len) { if(buffer_used == buffer_num)return false; Buffer *b = new Buffer(); b->ensureMemory(len); b->push(data,len); buffers[buffer_used] = b; buffer_used++; return true; } Buffer *BufferArray::getTop() { if(buffer_used==0)return NULL; return buffers[0]; } void BufferArray::shift() { if(buffer_used==0)return; Buffer *top = buffers[0]; for(unsigned int i=0;i<buffer_used-1;i++) { buffers[i] = buffers[i+1]; } buffers[buffer_used]=NULL; buffer_used--; delete top; } ////////////////// int Stream::idgen = 1; Stream::Stream( uv_tcp_t *sk, size_t sendbufsize, size_t recvbufsize, bool compress ) : tcp(sk), use_compression(compress) { id = ++idgen; sendbuf.ensureMemory(sendbufsize); recvbuf.ensureMemory(recvbufsize); unzipped_recvbuf.ensureMemory(recvbufsize); } static void on_write_end( uv_write_t *req, int status ) { // print("on_write_end! st:%d",status); if(status<0) { print("on_write_end error: status:%d",status); } FREE(req->data); FREE(req); } size_t Stream::flushSendbuf(size_t unitsize) { if(uv_is_writable((uv_stream_t*)tcp) && sendbuf.used > 0 ) { size_t partsize = sendbuf.used; if(partsize>unitsize) partsize = unitsize; uv_write_t *write_req = (uv_write_t*)MALLOC(sizeof(uv_write_t)); size_t allocsize = use_compression ? partsize*2+64 : partsize; // Abs max size of snappy worst case size char *outbuf = (char*)MALLOC(allocsize); // need this because uv_write delays actual write after shifting sendbuf! if( use_compression ) { size_t headersize = 4+2; // print("partsize:%d allocsize:%d", partsize,allocsize); int compsz = memCompressSnappy( outbuf+headersize, allocsize-headersize, sendbuf.buf, partsize); assert(allocsize>=compsz+headersize); set_u32(outbuf+0,compsz+2); // size of funcid set_u16(outbuf+4,PACKETTYPE_ZIPPED_RECORDS); // print("compress: partsize:%d compd:%d", partsize, compsz); write_req->data = outbuf; uv_buf_t buf = uv_buf_init(outbuf,4+2+compsz); int r = uv_write( write_req, (uv_stream_t*)tcp, &buf, 1, on_write_end ); if(r) { print("uv_write fail. %d",r); return 0; } else { // print("uv_write ok, partsz:%d used:%d", partsize, sendbuf.used ); sendbuf.shift(partsize); return partsize; } } else { // print("nocompress used:%d", sendbuf.used ); memcpy(outbuf,sendbuf.buf,partsize); write_req->data = outbuf; uv_buf_t buf = uv_buf_init(outbuf,partsize); int r = uv_write( write_req, (uv_stream_t*)tcp, &buf, 1, on_write_end ); if(r) { print("uv_write fail. %d",r); return 0; } else { // print("uv_write ok, partsz:%d used:%d", partsize, sendbuf.used ); sendbuf.shift(partsize); return partsize; } } } return 0; } ////////////////// // normal headless client Client::Client( uv_tcp_t *sk, RemoteHead *rh, bool compress ) : Stream(sk,128*1024*1024,8*1024,compress){ init(); parent_rh = rh; } // clients connecting to reproxy Client::Client( uv_tcp_t *sk, ReprecationProxy *reproxy, bool compress ) : Stream(sk,128*1024*1024,8*1024,compress) { init(); parent_reproxy = reproxy; } // reproxies Client::Client( uv_tcp_t *sk, Reprecator *repr, bool compress ) : Stream(sk, 128*1024*1024,32*1024,compress){ init(); parent_reprecator = repr; } // creating logical clients in server Client::Client( RemoteHead *rh ) : Stream(NULL,0,0,false){ init(); parent_rh = rh; } Client *Client::createLogicalClient( Stream *reprecator_stream, RemoteHead *rh ) { Client *cl = new Client(rh); cl->reprecator_stream = reprecator_stream; print("createLogicalClient called. newclid:%d",cl->id); return cl; } void Client::init() { parent_rh = NULL; parent_reproxy = NULL; parent_reprecator = NULL; target_camera = NULL; target_viewport = NULL; initialized_at = now(); global_client_id = 0; reprecator_stream=NULL; accum_time=0; send_wait=0; } Client::~Client() { print("~Client called for %d", id ); if(target_camera) { POOL_SCAN(target_camera->target_layers,Layer){ it->second->delDynamicCamera(target_camera); } } if(target_viewport) { POOL_SCAN(target_viewport->target_layers,Layer) { it->second->delDynamicViewport(target_viewport); } } } size_t Client::flushSendbufToNetwork() { return getStream()->flushSendbuf(256*1024); } //////////////////////////// // return false when error(to close) bool parseRecord( Stream *s, Buffer *recvbuf, const char *data, size_t datalen, void (*funcCallback)( Stream *s, uint16_t funcid, char *data, uint32_t datalen ) ) { bool pushed = recvbuf->push( data, datalen ); // print("parseRecord: datalen:%d bufd:%d pushed:%d", datalen, recvbuf->used, pushed ); if(!pushed) { print("recv buf full? close."); return false; } // Parse RPC // fprintf(stderr, "recvbuf used:%zu\n", c->recvbuf->used ); while(true) { // process everything in one poll // print("recvbuf:%d", c->recvbuf->used ); if( recvbuf->used < (4+2) ) return true; // need more data from network // <---RECORDLEN------> // [RECORDLEN32][FUNCID32][..DATA..] size_t record_len = get_u32( recvbuf->buf ); unsigned int func_id = get_u16( recvbuf->buf + 4 ); if( recvbuf->used < (4+record_len) ) { // print("need. used:%d reclen:%d", recvbuf->used, record_len ); return true; // need more data from network } if( record_len < 2 ) { fprintf(stderr, "invalid packet format" ); return false; } // fprintf(stderr, "dispatching func_id:%d record_len:%lu\n", func_id, record_len ); // dump( recvbuf->buf, record_len-4); funcCallback( s, func_id, (char*) recvbuf->buf +4+2, record_len - 2 ); recvbuf->shift( 4 + record_len ); // fprintf(stderr, "after dispatch recv func: buffer used: %zu\n", c->recvbuf->used ); // if( c->recvbuf->used > 0 ) dump( c->recvbuf->buf, c->recvbuf->used ); } } bool Client::canSee(Prop2D*p) { if(!target_viewport) { return true; } Vec2 minv, maxv; target_viewport->getMinMax(&minv,&maxv); return p->isInView(&minv,&maxv,target_camera); } ////////////////////// static void reproxy_on_close_callback( uv_handle_t *s ) { print("reproxy_on_close_callback"); Client *cli = (Client*)s->data; if(cli->parent_reproxy->close_callback) cli->parent_reproxy->close_callback(cli); cli->parent_reproxy->delClient(cli); delete cli; } static void reproxy_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) { // print("reproxy_on_read_callback: nread:%d",nread); Client *cl = (Client*)s->data; if(nread>0) { ReprecationProxy *rp = cl->parent_reproxy; assert(rp); assert(rp->func_callback); bool res = parseRecord(cl, &cl->recvbuf, inbuf->base, nread, rp->func_callback ); if(!res) { uv_close( (uv_handle_t*)s, reproxy_on_close_callback ); return; } } else if( nread<0 ) { print("reproxy_on_read_callback EOF. clid:%d", cl->id ); uv_close( (uv_handle_t*)s, reproxy_on_close_callback ); } } void reproxy_on_accept_callback(uv_stream_t *listener, int status) { print("reproxy_on_accept_callback: status:%d",status); if(status!=0) { print("reproxy_on_accept_callback error status:%d",status); return; } uv_tcp_t *newsock = (uv_tcp_t*)MALLOC( sizeof(uv_tcp_t)); uv_tcp_init( uv_default_loop(), newsock ); if( uv_accept( listener, (uv_stream_t*)newsock) == 0 ) { uv_tcp_nodelay(newsock,1); ReprecationProxy *rp = (ReprecationProxy*)listener->data; Client *cl = new Client(newsock,rp,true); newsock->data = cl; cl->parent_reproxy->addClient(cl); print("reproxy_on_accept_callback. accepted"); int r = uv_read_start( (uv_stream_t*)newsock, moyai_libuv_alloc_buffer, reproxy_on_read_callback ); if(r) { print("uv_read_start: failed. ret:%d",r); return; } assert(rp->accept_callback); rp->accept_callback(cl); } } ReprecationProxy::ReprecationProxy(int portnum) : func_callback(NULL) { bool res = init_tcp_listener( &listener, (void*)this, portnum, reproxy_on_accept_callback ); assertmsg(res, "Reproxy: listen error"); print("Reproxy: listening on %d", portnum); } void ReprecationProxy::addClient( Client *cl) { Client *stored = cl_pool.get(cl->id); if(!stored) { cl->parent_reproxy = this; cl_pool.set(cl->id,cl); } } void ReprecationProxy::delClient(Client*cl) { cl_pool.del(cl->id); } void ReprecationProxy::broadcastUS1RawArgs(uint16_t funcid, const char*data, size_t datalen ) { POOL_SCAN(cl_pool,Client) { sendUS1RawArgs( it->second, funcid, data, datalen ); } } Client *ReprecationProxy::getClientByGlobalId(unsigned int gclid) { POOL_SCAN(cl_pool,Client) { if( it->second->global_client_id==gclid) { return it->second; } } return NULL; } void ReprecationProxy::heartbeat() { POOL_SCAN(cl_pool,Client) { it->second->flushSendbuf(256*1024); } }
41.548565
214
0.627326
01b2d5c9761b9d2cb889fb82409aab565a58c758
14,524
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGPathSegCurvetoCubicRel.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGPathSegCurvetoCubicRel.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGPathSegCurvetoCubicRel.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8SVGPathSegCurvetoCubicRel.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(SVGPathSegCurvetoCubicRel* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGPathSegCurvetoCubicRel::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::SVGPathSegCurvetoCubicRel* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8SVGPathSegCurvetoCubicRel::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGPathSegCurvetoCubicRel::domTemplate, V8SVGPathSegCurvetoCubicRel::derefObject, 0, 0, 0, V8SVGPathSegCurvetoCubicRel::installPerContextEnabledMethods, &V8SVGPathSeg::wrapperTypeInfo, WrapperTypeObjectPrototype, RefCountedObject }; namespace SVGPathSegCurvetoCubicRelV8Internal { template <typename T> void V8_USE(T) { } static void xAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->x()); } static void xAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::xAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void xAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setX(cppValue); } static void xAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::xAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void yAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->y()); } static void yAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::yAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void yAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setY(cppValue); } static void yAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::yAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void x1AttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->x1()); } static void x1AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::x1AttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void x1AttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setX1(cppValue); } static void x1AttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::x1AttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void y1AttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->y1()); } static void y1AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::y1AttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void y1AttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setY1(cppValue); } static void y1AttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::y1AttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void x2AttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->x2()); } static void x2AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::x2AttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void x2AttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setX2(cppValue); } static void x2AttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::x2AttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void y2AttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); v8SetReturnValue(info, impl->y2()); } static void y2AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); SVGPathSegCurvetoCubicRelV8Internal::y2AttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void y2AttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); SVGPathSegCurvetoCubicRel* impl = V8SVGPathSegCurvetoCubicRel::toNative(holder); TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue())); impl->setY2(cppValue); } static void y2AttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); SVGPathSegCurvetoCubicRelV8Internal::y2AttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } } // namespace SVGPathSegCurvetoCubicRelV8Internal static const V8DOMConfiguration::AttributeConfiguration V8SVGPathSegCurvetoCubicRelAttributes[] = { {"x", SVGPathSegCurvetoCubicRelV8Internal::xAttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::xAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"y", SVGPathSegCurvetoCubicRelV8Internal::yAttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::yAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"x1", SVGPathSegCurvetoCubicRelV8Internal::x1AttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::x1AttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"y1", SVGPathSegCurvetoCubicRelV8Internal::y1AttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::y1AttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"x2", SVGPathSegCurvetoCubicRelV8Internal::x2AttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::x2AttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"y2", SVGPathSegCurvetoCubicRelV8Internal::y2AttributeGetterCallback, SVGPathSegCurvetoCubicRelV8Internal::y2AttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static void configureV8SVGPathSegCurvetoCubicRelTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGPathSegCurvetoCubicRel", V8SVGPathSeg::domTemplate(isolate), V8SVGPathSegCurvetoCubicRel::internalFieldCount, V8SVGPathSegCurvetoCubicRelAttributes, WTF_ARRAY_LENGTH(V8SVGPathSegCurvetoCubicRelAttributes), 0, 0, 0, 0, isolate); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8SVGPathSegCurvetoCubicRel::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGPathSegCurvetoCubicRelTemplate); } bool V8SVGPathSegCurvetoCubicRel::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8SVGPathSegCurvetoCubicRel::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } SVGPathSegCurvetoCubicRel* V8SVGPathSegCurvetoCubicRel::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } v8::Handle<v8::Object> wrap(SVGPathSegCurvetoCubicRel* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8SVGPathSegCurvetoCubicRel>(impl, isolate)); return V8SVGPathSegCurvetoCubicRel::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8SVGPathSegCurvetoCubicRel::createWrapper(PassRefPtr<SVGPathSegCurvetoCubicRel> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8SVGPathSegCurvetoCubicRel>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8SVGPathSegCurvetoCubicRel>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent); return wrapper; } void V8SVGPathSegCurvetoCubicRel::derefObject(void* object) { fromInternalPointer(object)->deref(); } template<> v8::Handle<v8::Value> toV8NoInline(SVGPathSegCurvetoCubicRel* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
47.464052
326
0.774649
01b356052faac528613ddedb53d87ecf6305400a
96,356
cpp
C++
ref-impl/src/impl/ImplAAFDictionary.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFDictionary.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFDictionary.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= #include "ImplAAFDictionary.h" #include "ImplAAFMetaDictionary.h" #include "ImplAAFClassDef.h" #include "ImplEnumAAFClassDefs.h" #include "ImplAAFTypeDef.h" #include "ImplAAFPropertyDef.h" #include "ImplEnumAAFTypeDefs.h" #include "ImplAAFDataDef.h" #include "ImplEnumAAFDataDefs.h" #include "ImplAAFOperationDef.h" #include "ImplAAFParameterDef.h" #include "ImplEnumAAFOperationDefs.h" #include "ImplEnumAAFCodecDefs.h" #include "ImplEnumAAFPropertyDefs.h" #include "ImplAAFTypeDefRename.h" #include "ImplEnumAAFContainerDefs.h" #include "ImplEnumAAFInterpolationDefs.h" #include "ImplEnumAAFPluginDefs.h" #include "ImplEnumAAFKLVDataDefs.h" #include "ImplEnumAAFTaggedValueDefs.h" #include "AAFTypeDefUIDs.h" #include "ImplAAFBaseClassFactory.h" #include "ImplAAFBuiltinClasses.h" #include "ImplAAFBuiltinTypes.h" #include "ImplAAFDMS1Builtins.h" #include "ImplAAFMob.h" #include "AAFStoredObjectIDs.h" #include "AAFPropertyIDs.h" #include "ImplAAFObjectCreation.h" #include "ImplAAFBuiltinDefs.h" #include "AAFContainerDefs.h" #include "AAFClassDefUIDs.h" #include "OMVectorIterator.h" #include "OMAssertions.h" #include "OMExceptions.h" #include <string.h> #include "aafErr.h" #include "AAFUtils.h" #include "AAFDataDefs.h" #include "AAF.h" #include "AAFPrivate.h" #include "ImplAAFPluginManager.h" EXTERN_C const IID IID_IAAFRoot; #include "ImplAAFSmartPointer.h" typedef ImplAAFSmartPointer<ImplEnumAAFClassDefs> ImplEnumAAFClassDefsSP; typedef ImplAAFSmartPointer<ImplEnumAAFPropertyDefs> ImplEnumAAFPropertyDefsSP; extern "C" const aafClassID_t CLSID_EnumAAFCodecDefs; extern "C" const aafClassID_t CLSID_EnumAAFContainerDefs; extern "C" const aafClassID_t CLSID_EnumAAFDataDefs; extern "C" const aafClassID_t CLSID_EnumAAFDefObjects; extern "C" const aafClassID_t CLSID_EnumAAFInterpolationDefs; extern "C" const aafClassID_t CLSID_EnumAAFOperationDefs; extern "C" const aafClassID_t CLSID_EnumAAFParameterDefs; extern "C" const aafClassID_t CLSID_EnumAAFPluginDefs; extern "C" const aafClassID_t CLSID_EnumAAFKLVDataDefs; extern "C" const aafClassID_t CLSID_EnumAAFTaggedValueDefs; ImplAAFDictionary::ImplAAFDictionary () : _operationDefinitions(PID_Dictionary_OperationDefinitions, L"OperationDefinitions", PID_DefinitionObject_Identification), _parameterDefinitions(PID_Dictionary_ParameterDefinitions, L"ParameterDefinitions", PID_DefinitionObject_Identification), _dataDefinitions (PID_Dictionary_DataDefinitions, L"DataDefinitions", PID_DefinitionObject_Identification), _pluginDefinitions (PID_Dictionary_PluginDefinitions, L"PluginDefinitions", PID_DefinitionObject_Identification), _codecDefinitions(PID_Dictionary_CodecDefinitions, L"CodecDefinitions", PID_DefinitionObject_Identification), _containerDefinitions(PID_Dictionary_ContainerDefinitions, L"ContainerDefinitions", PID_DefinitionObject_Identification), _interpolationDefinitions (PID_Dictionary_InterpolationDefinitions, L"InterpolationDefinitions", PID_DefinitionObject_Identification), _klvDataDefinitions( PID_Dictionary_KLVDataDefinitions, L"KLVDataDefinitions", PID_DefinitionObject_Identification), _taggedValueDefinitions( PID_Dictionary_TaggedValueDefinitions, L"TaggedValueDefinitions", PID_DefinitionObject_Identification), _pBuiltinClasses (0), _pBuiltinTypes (0), _pBuiltinDefs (0), _pidSegmentsInitialised(false), _axiomaticTypes (0), _OKToAssurePropTypes (false), _defRegistrationAllowed (true), _metaDefinitionsInitialized(false), _metaDictionary(0) { _persistentProperties.put (_operationDefinitions.address()); _persistentProperties.put (_parameterDefinitions.address()); _persistentProperties.put(_dataDefinitions.address()); _persistentProperties.put(_pluginDefinitions.address()); _persistentProperties.put(_codecDefinitions.address()); _persistentProperties.put(_containerDefinitions.address()); _persistentProperties.put(_interpolationDefinitions.address()); _persistentProperties.put(_klvDataDefinitions.address()); _persistentProperties.put(_taggedValueDefinitions.address()); } ImplAAFDictionary::~ImplAAFDictionary () { // Release the _codecDefinitions OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFCodecDef>codecDefinitions(_codecDefinitions); while(++codecDefinitions) { ImplAAFCodecDef *pCodec = codecDefinitions.clearValue(); if (pCodec) { pCodec->ReleaseReference(); pCodec = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFContainerDef>containerDefinitions(_containerDefinitions); while(++containerDefinitions) { ImplAAFContainerDef *pContainer = containerDefinitions.clearValue(); if (pContainer) { pContainer->ReleaseReference(); pContainer = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFOperationDef>operationDefinitions(_operationDefinitions); while(++operationDefinitions) { ImplAAFOperationDef *pOp = operationDefinitions.clearValue(); if (pOp) { pOp->ReleaseReference(); pOp = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFParameterDef>parameterDefinitions(_parameterDefinitions); while(++parameterDefinitions) { ImplAAFParameterDef *pParm = parameterDefinitions.clearValue(); if (pParm) { pParm->ReleaseReference(); pParm = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFInterpolationDef>interpolateDefinitions(_interpolationDefinitions); while(++interpolateDefinitions) { ImplAAFInterpolationDef *pInterp = interpolateDefinitions.clearValue(); if (pInterp) { pInterp->ReleaseReference(); pInterp = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFPluginDef>pluginDefinitions(_pluginDefinitions); while(++pluginDefinitions) { ImplAAFPluginDef *pPlug = pluginDefinitions.clearValue(); if (pPlug) { pPlug->ReleaseReference(); pPlug = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFDataDef>dataDefinitions(_dataDefinitions); while(++dataDefinitions) { ImplAAFDataDef *pData = dataDefinitions.clearValue(); if (pData) { pData->ReleaseReference(); pData = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFKLVDataDefinition>klvDataDefinitions(_klvDataDefinitions); while(++klvDataDefinitions) { ImplAAFKLVDataDefinition *pKLVData = klvDataDefinitions.clearValue(); if (pKLVData) { pKLVData->ReleaseReference(); pKLVData = 0; } } OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFTaggedValueDefinition>taggedValueDefinitions(_taggedValueDefinitions); while(++taggedValueDefinitions) { ImplAAFTaggedValueDefinition *pTaggedValue = taggedValueDefinitions.clearValue(); if (pTaggedValue) { pTaggedValue->ReleaseReference(); pTaggedValue = 0; } } if (_pBuiltinClasses) { delete _pBuiltinClasses; _pBuiltinClasses = 0; } if (_pBuiltinTypes) { delete _pBuiltinTypes; _pBuiltinTypes = 0; } if (_pBuiltinDefs) { delete _pBuiltinDefs; _pBuiltinDefs = 0; } delete [] _axiomaticTypes; } // Return a pointer to the meta dictionary. ImplAAFMetaDictionary *ImplAAFDictionary::metaDictionary(void) const { // Return the dictionary for creating meta objects, classes, types and // properties. ASSERTU(NULL != _metaDictionary); return (_metaDictionary); } // Install the meta dictionary (i.e. the factory for creating // meta data: classes, properties and types). This method // can only be called once. void ImplAAFDictionary::setMetaDictionary(ImplAAFMetaDictionary *metaDictionary) { ASSERTU(!_metaDictionary); // do not reference count this pointer. _metaDictionary = metaDictionary; } // // Factory function for all built-in classes. // /*static*/ ImplAAFObject * ImplAAFDictionary::pvtCreateBaseClassInstance(const aafUID_t & auid) { // Lookup the code class id for the given stored object id. const aafClassID_t* id = ImplAAFBaseClassFactory::LookupClassID(auid); if (NULL == id) return NULL; // Attempt to create the corresponding storable object. ImplAAFRoot *impl = ::CreateImpl(*id); if (NULL == impl) { // This is a serious programming error. A stored object id was found in the file // with a known base class id but no base object could be created. ASSERTU(NULL != impl); return NULL; } // Make sure that the object we created was actually one of our // ImplAAFObject derived classes. ImplAAFObject* object = dynamic_cast<ImplAAFObject*>(impl); if (NULL == object) { // Not a valid object. Release the pointer so we don't leak memory. impl->ReleaseReference(); impl = 0; ASSERTU(NULL != object); return NULL; } return object; } // Factory method for creating a Dictionary. ImplAAFDictionary *ImplAAFDictionary::CreateDictionary(void) { // Create a dictionary. ImplAAFDictionary * pDictionary = NULL; pDictionary = static_cast<ImplAAFDictionary *>(pvtCreateBaseClassInstance(AUID_AAFDictionary)); ASSERTU(NULL != pDictionary); if (NULL != pDictionary) { // If we created a dictionary then give it a reference to a factory // (dictionary) to satisfy the OMStorable class invariant: Every OMStorabe // must have a reference to a factory. Since the dictionary is not created // by the OMClassFactory interface we just set the factory to "itself". // pDictionary->setClassFactory(pDictionary); } pDictionary->pvtSetSoid (AUID_AAFDictionary); return pDictionary; } bool ImplAAFDictionary::isRegistered(const OMClassId& classId) const { bool result; const aafUID_t* auid = reinterpret_cast<const aafUID_t*>(&classId); ImplAAFDictionary* pNonConstThis = const_cast<ImplAAFDictionary*>(this); ImplAAFClassDef* pClassDef = 0; HRESULT hr = pNonConstThis->LookupClassDef(*auid, &pClassDef); if (AAFRESULT_SUCCEEDED(hr)) { result = true; ASSERTU(pClassDef != 0); pClassDef->ReleaseReference(); pClassDef = 0; } else { result = false; } return result; } // // Create an instance of the appropriate derived class, given the class id. // This method implements the OMClassFactory interface. // OMStorable* ImplAAFDictionary::create(const OMClassId& classId) const { AAFRESULT hr; const aafUID_t * auid = reinterpret_cast<const aafUID_t*>(&classId); ImplAAFDictionary * pNonConstThis = (ImplAAFDictionary*) this; if (classId == AUID_AAFMetaDictionary) { // TEMPORARY: Set the factory of the meta dictionary to this dictionary. metaDictionary()->setClassFactory(this); // Do not bump the reference count. The meta dictionary is currently // not publicly available and it is owned by ImplAAFFile not be another // OMStorable or ImplAAFObject. return metaDictionary(); } else { // Call the sample top-level dictionary method that is called // by the API client to create objects. ImplAAFObject *pObject = NULL; hr = pNonConstThis->CreateInstance(*auid, &pObject); if (AAFRESULT_FAILED (hr)) { // This method is expected to always return a valid object. throw OMException(hr); } return pObject; } // ImplAAFClassDefSP pcd; // hr = pNonConstThis->LookupClassDef(*auid, &pcd); // ASSERTU (AAFRESULT_SUCCEEDED (hr)); // // return CreateAndInit (pcd); } void ImplAAFDictionary::destroy(OMStorable* victim) const { ImplAAFObject* v = fast_dynamic_cast<ImplAAFObject*>(victim); ASSERTU(v != 0); v->ReleaseReference(); } void ImplAAFDictionary::associate(const aafUID_t& id, const OMPropertyId propertyId) { ASSERTU (_pBuiltinClasses); if (propertyId >= 0x8000) { // Only remap dynamic pids OMPropertyId oldPid; AAFRESULT r = _pBuiltinClasses->LookupOmPid(id, oldPid); if (AAFRESULT_SUCCEEDED(r)) { r = _pBuiltinClasses->MapOmPid(id, propertyId); ASSERTU(AAFRESULT_SUCCEEDED(r)); } // else doesn't currently work for properties that aren't compiled-in } } ImplAAFObject * ImplAAFDictionary::CreateAndInit(ImplAAFClassDef * pClassDef) const { ASSERTU (pClassDef); AAFRESULT hr; aafUID_t auid; hr = pClassDef->GetAUID(&auid); ASSERTU (AAFRESULT_SUCCEEDED (hr)); ImplAAFObject * pNewObject = 0; pNewObject = pvtInstantiate (auid); if (pNewObject) { pNewObject->InitializeOMStorable (pClassDef); // Attempt to initialize any class extensions associated // with this object. Only the most derived extension that has an // associated plugin is created. // QUESTION: How should we "deal with" failure? We really need // an error/warning log file for this kind of information. pNewObject->InitializeExtensions(); } return pNewObject; } ImplAAFObject* ImplAAFDictionary::pvtInstantiate(const aafUID_t & auid) const { ImplAAFObject *result = 0; ImplAAFClassDef *parent; // Is this a request to create the dictionary? if (auid == AUID_AAFDictionary) { // The result is just this instance. result = const_cast<ImplAAFDictionary*>(this); // Bump the reference count. AcquireReference(); } else { // Create an instance of the class corresponsing to the given // stored object id. In other words, we instantiate an // implementation object which can represent this stored object // in code. In the case of built-in types, each one *has* a // code object which can represent it. However in the case of // client-defined classes, the best we can do is instantiate the // most-derived code object which is an inheritance parent of // the desired class. // First see if this is a built-in class. // result = pvtCreateBaseClassInstance(auid); //DAB+ 9-Sep-2001 Code corrected to REALLY iterate up the inheritance hierarchy aafUID_t parentAUID = auid; while (result == 0) { // aafUID_t parentAUID = auid; //DAB- 9-Sep-2001 Code corrected to REALLY iterate up the inheritance hierarchy aafBool isRoot; // Not a built-in class; find the nearest built-in parent. // That is, iterate up the inheritance hierarchy until we // find a class which we know how to instantiate. // ImplAAFClassDefSP pcd; AAFRESULT hr; hr = ((ImplAAFDictionary*)this)->LookupClassDef (parentAUID, &pcd); if (AAFRESULT_FAILED (hr)) { // AUID does not correspond to any class in the // dictionary; bail out with NULL result ASSERTU (0 == result); break; } hr = pcd->IsRoot(&isRoot); if (isRoot || hr != AAFRESULT_SUCCESS) { // Class was apparently registered, but no appropriate // parent class found! This should not happen, as every // registered class must have a registered parent class. // The only exception is AAFObject, which would have // been found by the earlier // pvtCreateBaseClassInstance() call. ASSERTU (0); } hr = pcd->GetParent (&parent); hr = parent->GetAUID(&parentAUID); parent->ReleaseReference(); result = pvtCreateBaseClassInstance(parentAUID); } } if (result) { if ((ImplAAFDictionary *)result != this) { // If we created an object then give it a reference to the // factory (dictionary) that was used to created it. // result->setClassFactory(this); // Set this object's stored ID. Be sure to set it to the // requested ID, not the instantiated one. (These will be // different if the requested ID is a client-supplied // extension class.) result->pvtSetSoid (auid); } } return result; } // Creates a single uninitialized AAF object of the class associated // with a specified stored object id. AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CreateInstance ( // Stored Object ID of the stored object to be created. aafUID_constref classId, // Address of output variable that receives the // object pointer requested in auid ImplAAFObject ** ppvObject) { if (NULL == ppvObject) return AAFRESULT_NULL_PARAM; // Lookup the class definition for the given classId. If the class // definition is one of the "built-in" class definitions then the // definition will be created and registered with the dictionary // if necessary. (TRR 2000-MAR-01) ImplAAFClassDefSP pClassDef; AAFRESULT hr; hr = LookupClassDef (classId, &pClassDef); if (AAFRESULT_FAILED (hr)) return hr; // We should not create an instance of a MetaDefinition with CreateInstance(). // CreateMetaInstance() should be used for that instead. if ( metaDictionary()->isMeta(*reinterpret_cast<const OMObjectIdentification *>(&classId) )) return AAFRESULT_INVALID_CLASS_ID; if (! pClassDef->pvtIsConcrete ()) return AAFRESULT_ABSTRACT_CLASS; *ppvObject = CreateAndInit (pClassDef); if (NULL == *ppvObject) return AAFRESULT_INVALID_CLASS_ID; else return AAFRESULT_SUCCESS; } //Creates a single uninitialized AAF meta definition associated // with a specified stored object id. AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CreateMetaInstance ( // Stored Object ID of the meta object to be created. aafUID_constref classId, // Address of output variable that receives the // object pointer requested in auid ImplAAFMetaDefinition ** ppMetaObject) { // Ask the meta dictionary to create the meta definition return (metaDictionary()->CreateMetaInstance(classId, ppMetaObject)); } AAFRESULT ImplAAFDictionary::dictLookupClassDef ( const aafUID_t & classID, ImplAAFClassDef ** ppClassDef) { // Ask the meta dictionary to see if the class has already in the set. return (metaDictionary()->LookupClassDef(classID, ppClassDef)); } bool ImplAAFDictionary::PvtIsClassPresent ( const aafUID_t & classID) { // Defer to the meta dictionary. return(metaDictionary()->containsClass(classID)); } bool ImplAAFDictionary::IsAxiomaticClass (const aafUID_t &classID) const { ImplAAFClassDef *pAxiomaticClass = metaDictionary()->findAxiomaticClassDefinition(classID); // return value NOT reference counted! if (pAxiomaticClass) return true; else return false; } bool ImplAAFDictionary::pvtLookupAxiomaticClassDef (const aafUID_t &classID, ImplAAFClassDef ** ppClassDef) { *ppClassDef = metaDictionary()->findAxiomaticClassDefinition(classID); // return value NOT reference counted! if (*ppClassDef) { (*ppClassDef)->AcquireReference(); // We will be returning this references! return true; } else { return false; } } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupClassDef ( const aafUID_t & classID, ImplAAFClassDef ** ppClassDef) { AAFRESULT status; // // TEMPORARY: // Initialize the built-in types and classes if necessary. // InitializeMetaDefinitions(); if (! ppClassDef) return AAFRESULT_NULL_PARAM; if (pvtLookupAxiomaticClassDef (classID, ppClassDef)) { ASSERTU (*ppClassDef); // Yes, this is an axiomatic class. classDef should be filled // in. Assure that it's in the dictionary, and return it. // here's where we assure it's in the dictionary. if(_defRegistrationAllowed) { ImplAAFClassDef *parent; // These classes fail with doubly-opened storages #if 0 if(memcmp(&classID, &kAAFClassID_ClassDefinition, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionCharacter, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionString, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionVariableArray, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionRecord, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionFixedArray, sizeof(aafUID_t)) != 0 && memcmp(&classID, &kAAFClassID_TypeDefinitionInteger, sizeof(aafUID_t)) != 0 ) #endif { if(!PvtIsClassPresent(classID)) { aafBool isRoot; aafUID_t uid; (*ppClassDef)->IsRoot(&isRoot); if(isRoot) { (*ppClassDef)->SetParent(*ppClassDef); } else { (*ppClassDef)->GetParent(&parent); // Uses bootstrap parent if set parent->GetAUID(&uid); parent->ReleaseReference(); parent = NULL; LookupClassDef (uid, &parent); (*ppClassDef)->SetParent(parent); parent->ReleaseReference(); } (*ppClassDef)->SetBootstrapParent(NULL); status = PvtRegisterClassDef(*ppClassDef); ASSERTU (AAFRESULT_SUCCEEDED (status)); } } } AssurePropertyTypes (*ppClassDef); return AAFRESULT_SUCCESS; } // Not axiomatic. Check to see if it's already in the dict. status = dictLookupClassDef (classID, ppClassDef); if (AAFRESULT_SUCCEEDED (status)) { // Yup, already here. Pass on the good news. AssurePropertyTypes (*ppClassDef); return status; } // Not found in the dict; check to see if it was due to failure // other than not being found if (AAFRESULT_NO_MORE_OBJECTS != status) { // Yup, some other failure. Pass on the bad news. return status; } // If we're here, it was not found in dict. Try it in builtins. status = _pBuiltinClasses->NewBuiltinClassDef (classID, ppClassDef); if (AAFRESULT_FAILED (status)) { // no recognized class guid return status; } // Yup, found it in builtins. Register it. ASSERTU (*ppClassDef); status = PvtRegisterClassDef (*ppClassDef); if (AAFRESULT_FAILED (status)) return status; AssurePropertyTypes (*ppClassDef); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CreateForwardClassReference ( aafUID_constref classId) { // Defer to the meta dictionary. return (metaDictionary()->CreateForwardClassReference(classId)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::HasForwardClassReference ( aafUID_constref classId, aafBoolean_t * pResult) { // Defer to the meta dictionary. return (metaDictionary()->HasForwardClassReference(classId, pResult)); } // Private class registration. This version does not perform any // initialization that requires other classes, types or properties or // types to be in the dictionary...it only adds the given class // to the set in the dictionary. AAFRESULT ImplAAFDictionary::PvtRegisterClassDef(ImplAAFClassDef * pClassDef) { ASSERTU (_defRegistrationAllowed); // Defer to the meta dictionary. return (metaDictionary()->PvtRegisterClassDef(pClassDef)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterClassDef ( ImplAAFClassDef * pClassDef) { ASSERTU (_defRegistrationAllowed); // Defer to the meta dictionary. return (metaDictionary()->RegisterClassDef(pClassDef)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetClassDefs ( ImplEnumAAFClassDefs ** ppEnum) { // Defer to the meta dictionary. return (metaDictionary()->GetClassDefs(ppEnum)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountClassDefs (aafUInt32 * pResult) { // Defer to the meta dictionary. return (metaDictionary()->CountClassDefs(pResult)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterTypeDef ( ImplAAFTypeDef * pTypeDef) { ASSERTU (_defRegistrationAllowed); // Defer to the meta dictionary. return(metaDictionary()->RegisterTypeDef(pTypeDef)); } AAFRESULT ImplAAFDictionary::dictLookupTypeDef ( const aafUID_t & typeID, ImplAAFTypeDef ** ppTypeDef) { // Defer to the meta dictionary. return (metaDictionary()->LookupTypeDef(typeID, ppTypeDef)); } bool ImplAAFDictionary::PvtIsTypePresent ( const aafUID_t & typeID) { // Defer to the meta dictionary. return(metaDictionary()->containsType(typeID)); } bool ImplAAFDictionary::pvtLookupAxiomaticTypeDef (const aafUID_t &typeID, ImplAAFTypeDef ** ppTypeDef) { *ppTypeDef = metaDictionary()->findAxiomaticTypeDefinition(typeID); // return value NOT reference counted! if (*ppTypeDef) { (*ppTypeDef)->AcquireReference (); // We will be returning this references! return true; } else { return false; } } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupTypeDef ( const aafUID_t & typeID, ImplAAFTypeDef ** ppTypeDef) { ImplAAFTypeDefSP typeDef; AAFRESULT status; // // TEMPORARY: // Initialize the built-in types and classes if necessary. // InitializeMetaDefinitions(); if (! ppTypeDef) return AAFRESULT_NULL_PARAM; if (pvtLookupAxiomaticTypeDef (typeID, &typeDef)) { if(_defRegistrationAllowed && !PvtIsTypePresent(typeID)) { status = RegisterTypeDef(typeDef); ASSERTU (AAFRESULT_SUCCEEDED (status)); } ASSERTU (ppTypeDef); *ppTypeDef = typeDef; ASSERTU (*ppTypeDef); (*ppTypeDef)->AcquireReference (); return AAFRESULT_SUCCESS; } // Not axiomatic. Check to see if it's already in the dict. status = dictLookupTypeDef (typeID, ppTypeDef); if (AAFRESULT_SUCCEEDED (status)) { // Yup, already here. Pass on the good news. return status; } // Not found in the dict; check to see if it was due to failure // other than not being found if (AAFRESULT_NO_MORE_OBJECTS != status) { // Yup, some other failure. Pass on the bad news. return status; } // If we're here, it was not found in dict. Try it in builtins. ASSERTU (0 == (ImplAAFTypeDef*) typeDef); status = _pBuiltinTypes->NewBuiltinTypeDef (typeID, &typeDef); if (AAFRESULT_FAILED (status)) { // no recognized type guid return AAFRESULT_NO_MORE_OBJECTS; } // Check again to see if it's in the dict. // The type we're looking for may have been recursively added // by NewBuiltinTypeDef() above. status = dictLookupTypeDef (typeID, ppTypeDef); if (AAFRESULT_SUCCEEDED (status)) { return status; } // Yup, found it in builtins. Register it. if(_defRegistrationAllowed) { ASSERTU (typeDef); status = RegisterTypeDef (typeDef); if (AAFRESULT_FAILED (status)) return status; } ASSERTU (ppTypeDef); *ppTypeDef = typeDef; ASSERTU (*ppTypeDef); (*ppTypeDef)->AcquireReference (); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetTypeDefs ( ImplEnumAAFTypeDefs ** ppEnum) { // Defer to the meta dictionary. return(metaDictionary()->GetTypeDefs(ppEnum)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountTypeDefs (aafUInt32 * pResult) { // Defer to the meta dictionary. return(metaDictionary()->CountTypeDefs(pResult)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterOpaqueTypeDef ( ImplAAFTypeDef * pTypeDef) { // Defer to the meta dictionary. return(metaDictionary()->RegisterOpaqueTypeDef(pTypeDef)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupOpaqueTypeDef ( const aafUID_t & typeID, ImplAAFTypeDef ** ppTypeDef) { // Defer to the meta dictionary. return(metaDictionary()->LookupOpaqueTypeDef(typeID, ppTypeDef)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetOpaqueTypeDefs ( ImplEnumAAFTypeDefs ** ppEnum) { // Defer to the meta dictionary. return(metaDictionary()->GetOpaqueTypeDefs(ppEnum)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountOpaqueTypeDefs (aafUInt32 * pResult) { // Defer to the meta dictionary. return(metaDictionary()->CountOpaqueTypeDefs(pResult)); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterKLVDataKey ( aafUID_t keyUID, ImplAAFTypeDef *underlyingType) { ImplAAFTypeDefRename *pRenameDef = NULL; XPROTECT() { CHECK(CreateMetaInstance(AUID_AAFTypeDefRename, (ImplAAFMetaDefinition **)&pRenameDef)); CHECK(pRenameDef->Initialize (keyUID, underlyingType, L"KLV Data")); CHECK(RegisterOpaqueTypeDef(pRenameDef)); pRenameDef->ReleaseReference(); pRenameDef = NULL; } XEXCEPT { if (pRenameDef) pRenameDef->ReleaseReference(); } XEND return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterDataDef ( ImplAAFDataDef *pDataDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pDataDef) return AAFRESULT_NULL_PARAM; // Get the AUID of the new type to register. aafUID_t newAUID; HRESULT hr = pDataDef->GetAUID(&newAUID); if (hr != AAFRESULT_SUCCESS) return hr; // Is this type already registered ? ImplAAFDataDef * pExistingDataDef = NULL; hr = LookupDataDef(newAUID, &pExistingDataDef); if (hr != AAFRESULT_SUCCESS) { // This type is not yet registered, add it to the dictionary. // first making sure it's being used somewhere else. if (pDataDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _dataDefinitions.appendValue(pDataDef); pDataDef->AcquireReference(); // Set up the (non-persistent) dictionary pointer. // // BobT 6/15/99: Remove ImplAAFDefObject::Get/SetDict() in favor of // ImplAAFObject::GetDictionary(). // pDataDef->SetDict(this); } else { // This type is already registered, probably because it was // already in the persisted dictionary. // Set up the (non-persistent) dictionary pointer. // // BobT 6/15/99: Remove ImplAAFDefObject::Get/SetDict() in favor of // ImplAAFObject::GetDictionary(). // pExistingDataDef->SetDict(this); pExistingDataDef->ReleaseReference(); pExistingDataDef = 0; } return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupDataDef ( const aafUID_t & dataDefinitionID, ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_dataDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&dataDefinitionID)), *ppDataDef)) { ASSERTU(NULL != *ppDataDef); (*ppDataDef)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetDataDefs ( ImplEnumAAFDataDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFDataDefs *theEnum = (ImplEnumAAFDataDefs *)CreateImpl (CLSID_EnumAAFDataDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFDataDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFDataDef>(_dataDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFDataDefs,this,iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountDataDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _dataDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterOperationDef ( ImplAAFOperationDef *pOperationDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pOperationDef) return AAFRESULT_NULL_PARAM; if (pOperationDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _operationDefinitions.appendValue(pOperationDef); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pOperationDef->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupOperationDef ( const aafUID_t & effectID, ImplAAFOperationDef **ppOperationDef) { if (!ppOperationDef) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_operationDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&effectID)), *ppOperationDef)) { ASSERTU(NULL != *ppOperationDef); (*ppOperationDef)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetOperationDefs ( ImplEnumAAFOperationDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFOperationDefs *theEnum = (ImplEnumAAFOperationDefs *)CreateImpl (CLSID_EnumAAFOperationDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFOperationDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFOperationDef>(_operationDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFOperationDefs, this, iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountOperationDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _operationDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterParameterDef ( ImplAAFParameterDef *pParameterDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pParameterDef) return AAFRESULT_NULL_PARAM; if (pParameterDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _parameterDefinitions.appendValue(pParameterDef); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pParameterDef->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupParameterDef ( const aafUID_t & parameterID, ImplAAFParameterDef **ppParameterDef) { if (!ppParameterDef) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_parameterDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&parameterID)), *ppParameterDef)) { ASSERTU(NULL != *ppParameterDef); (*ppParameterDef)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetParameterDefs ( ImplEnumAAFParameterDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFParameterDefs *theEnum = (ImplEnumAAFParameterDefs *)CreateImpl (CLSID_EnumAAFParameterDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFParameterDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFParameterDef>(_parameterDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFParameterDefs, this, iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountParameterDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _parameterDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterCodecDef ( ImplAAFCodecDef *pPlugDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pPlugDef) return AAFRESULT_NULL_PARAM; if (pPlugDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _codecDefinitions.appendValue(pPlugDef); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pPlugDef->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT ImplAAFDictionary::GetNumCodecDefs(aafUInt32 * pNumCodecDefs) { aafUInt32 siz; if(pNumCodecDefs == NULL) return AAFRESULT_NULL_PARAM; siz = _codecDefinitions.count(); *pNumCodecDefs = siz; return AAFRESULT_SUCCESS; } AAFRESULT ImplAAFDictionary::LookupCodecDef (const aafUID_t & defID, ImplAAFCodecDef **ppResult) { if (!ppResult) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_codecDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&defID)), *ppResult)) { ASSERTU(NULL != *ppResult); (*ppResult)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetCodecDefs ( ImplEnumAAFCodecDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFCodecDefs *theEnum = (ImplEnumAAFCodecDefs *)CreateImpl (CLSID_EnumAAFCodecDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFCodecDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFCodecDef>(_codecDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFCodecDefs,this,iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountCodecDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _codecDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterContainerDef ( ImplAAFContainerDef *pPlugDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pPlugDef) return AAFRESULT_NULL_PARAM; if (pPlugDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _containerDefinitions.appendValue(pPlugDef); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pPlugDef->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupContainerDef (const aafUID_t & defID, ImplAAFContainerDef **ppResult) { if (!ppResult) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_containerDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&defID)), *ppResult)) { ASSERTU(NULL != *ppResult); (*ppResult)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT ImplAAFDictionary::GetNumContainerDefs(aafUInt32 * pNumContainerDefs) { aafUInt32 siz; if(pNumContainerDefs == NULL) return AAFRESULT_NULL_PARAM; siz = _containerDefinitions.count(); *pNumContainerDefs = siz; return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetContainerDefs ( ImplEnumAAFContainerDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFContainerDefs *theEnum = (ImplEnumAAFContainerDefs *)CreateImpl (CLSID_EnumAAFContainerDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFContainerDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFContainerDef>(_containerDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFContainerDefs,this, iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountContainerDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _containerDefinitions.count(); return AAFRESULT_SUCCESS; } void ImplAAFDictionary::InitDataDefinition(const aafUID_t & dataDefinitionID, const aafCharacter *name, const aafCharacter *description) { ImplAAFDataDef *dataDef = NULL; AAFRESULT hr; hr = LookupDataDef (dataDefinitionID, &dataDef); if (AAFRESULT_FAILED (hr)) { // not already in dictionary hr = GetBuiltinDefs()->cdDataDef()-> CreateInstance ((ImplAAFObject **)&dataDef); hr = dataDef->Initialize (dataDefinitionID, name, description); hr = RegisterDataDef (dataDef); } dataDef->ReleaseReference(); dataDef = NULL; } void ImplAAFDictionary::InitContainerDefinition(const aafUID_t & defID, const aafCharacter *name, const aafCharacter *description) { ImplAAFContainerDef *containerDef = NULL; AAFRESULT hr; hr = LookupContainerDef (defID, &containerDef); if (AAFRESULT_FAILED (hr)) { // not already in dictionary hr = GetBuiltinDefs()->cdContainerDef()-> CreateInstance ((ImplAAFObject **)&containerDef); hr = containerDef->Initialize (defID, name, description); hr = RegisterContainerDef (containerDef); } containerDef->ReleaseReference(); containerDef = NULL; } void ImplAAFDictionary::InitBuiltins() { #include "ImplAAFDictionary.cpp_DataDefs" #include "ImplAAFDictionary.cpp_ContainerDefs" AssureClassPropertyTypes (); } #define check_result(result) \ if (AAFRESULT_FAILED (result)) \ return result; /* Note! Will modify argument... */ #define release_if_set(pIfc) \ { \ if (pIfc) \ { \ pIfc->ReleaseReference (); \ pIfc = 0; \ } \ } /* Note! Will modify argument... */ #define release_and_zero(pIfc) \ { \ ASSERTU (pIfc); \ pIfc->ReleaseReference (); \ pIfc = 0; \ } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterInterpolationDef ( ImplAAFInterpolationDef *pInterpolationDef) { ASSERTU (_defRegistrationAllowed); if (NULL == pInterpolationDef) return AAFRESULT_NULL_PARAM; if (pInterpolationDef->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _interpolationDefinitions.appendValue(pInterpolationDef); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pInterpolationDef->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupInterpolationDef ( const aafUID_t & interpolationID, ImplAAFInterpolationDef **ppInterpolationDef) { if (!ppInterpolationDef) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_interpolationDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&interpolationID)), *ppInterpolationDef)) { ASSERTU(NULL != *ppInterpolationDef); (*ppInterpolationDef)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetInterpolationDefs ( ImplEnumAAFInterpolationDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFInterpolationDefs *theEnum = (ImplEnumAAFInterpolationDefs *)CreateImpl (CLSID_EnumAAFInterpolationDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFInterpolationDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFInterpolationDef>(_interpolationDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFInterpolationDefs,this,iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountInterpolationDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _interpolationDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterPluginDef ( //!!! Bring this out through the IDL ImplAAFPluginDef *pDesc) { ASSERTU (_defRegistrationAllowed); if (NULL == pDesc) return AAFRESULT_NULL_PARAM; if (pDesc->attached()) return AAFRESULT_OBJECT_ALREADY_ATTACHED; _pluginDefinitions.appendValue(pDesc); // trr - We are saving a copy of pointer in _pluginDefinitions // so we need to bump its reference count. pDesc->AcquireReference(); return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupPluginDef ( //!!! Bring this out through the IDL const aafUID_t & interpolationID, ImplAAFPluginDef **ppPluginDesc) { if (!ppPluginDesc) return AAFRESULT_NULL_PARAM; AAFRESULT result = AAFRESULT_SUCCESS; // NOTE: The following type cast is temporary. It should be removed as soon // as the OM has a declarative sytax to include the type // of the key used in the set. (trr:2000-FEB-29) if (_pluginDefinitions.find((*reinterpret_cast<const OMObjectIdentification *>(&interpolationID)), *ppPluginDesc)) { ASSERTU(NULL != *ppPluginDesc); (*ppPluginDesc)->AcquireReference(); } else { // no recognized class guid in dictionary result = AAFRESULT_NO_MORE_OBJECTS; } return (result); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetPluginDefs ( //!!! Bring this out through the IDL ImplEnumAAFPluginDefs **ppEnum) { if (NULL == ppEnum) return AAFRESULT_NULL_PARAM; *ppEnum = 0; ImplEnumAAFPluginDefs *theEnum = (ImplEnumAAFPluginDefs *)CreateImpl (CLSID_EnumAAFPluginDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFPluginDef>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFPluginDef>(_pluginDefinitions); if(iter == 0) RAISE(AAFRESULT_NOMEMORY); CHECK(theEnum->Initialize(&CLSID_EnumAAFPluginDefs, this, iter)); *ppEnum = theEnum; } XEXCEPT { if (theEnum) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return(AAFRESULT_SUCCESS); } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountPluginDefs (aafUInt32 * pResult) { if (! pResult) return AAFRESULT_NULL_PARAM; *pResult = _pluginDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterKLVDataDef (ImplAAFKLVDataDefinition* pDef ) { ASSERTU (_defRegistrationAllowed); if ( NULL == pDef ) { return AAFRESULT_NULL_PARAM; } if ( pDef->attached() ) { return AAFRESULT_OBJECT_ALREADY_ATTACHED; } _klvDataDefinitions.appendValue(pDef); pDef->AcquireReference(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupKLVDataDef (aafUID_constref id, ImplAAFKLVDataDefinition ** ppDef ) { if ( !ppDef ) { return AAFRESULT_NULL_PARAM; } AAFRESULT result = AAFRESULT_SUCCESS; if ( _klvDataDefinitions.find( *reinterpret_cast<const OMObjectIdentification*>(&id), *ppDef) ) { ASSERTU( *ppDef ); (*ppDef)->AcquireReference(); } else { result = AAFRESULT_NO_MORE_OBJECTS; } return result; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetKLVDataDefs (ImplEnumAAFKLVDataDefs** ppEnum ) { if ( NULL == ppEnum ) { return AAFRESULT_NULL_PARAM; } *ppEnum = 0; ImplEnumAAFKLVDataDefs *theEnum = (ImplEnumAAFKLVDataDefs *)CreateImpl (CLSID_EnumAAFKLVDataDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFKLVDataDefinition>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFKLVDataDefinition>(_klvDataDefinitions); if ( !iter ) { RAISE(AAFRESULT_NOMEMORY); } CHECK( theEnum->Initialize(&CLSID_EnumAAFKLVDataDefs,this,iter) ); *ppEnum = theEnum; } XEXCEPT { if ( theEnum ) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountKLVDataDefs (aafUInt32 *pResult) { if(pResult == NULL) return AAFRESULT_NULL_PARAM; *pResult = _klvDataDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::RegisterTaggedValueDef (ImplAAFTaggedValueDefinition* pDef) { ASSERTU (_defRegistrationAllowed); if ( NULL == pDef ) { return AAFRESULT_NULL_PARAM; } if ( pDef->attached() ) { return AAFRESULT_OBJECT_ALREADY_ATTACHED; } _taggedValueDefinitions.appendValue(pDef); pDef->AcquireReference(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupTaggedValueDef (aafUID_constref id, ImplAAFTaggedValueDefinition ** ppDef ) { if ( !ppDef ) { return AAFRESULT_NULL_PARAM; } AAFRESULT result = AAFRESULT_SUCCESS; if ( _taggedValueDefinitions.find( *reinterpret_cast<const OMObjectIdentification*>(&id), *ppDef) ) { ASSERTU( *ppDef ); (*ppDef)->AcquireReference(); } else { result = AAFRESULT_NO_MORE_OBJECTS; } return result; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::GetTaggedValueDefs (ImplEnumAAFTaggedValueDefs** ppEnum) { if ( NULL == ppEnum ) { return AAFRESULT_NULL_PARAM; } *ppEnum = 0; ImplEnumAAFTaggedValueDefs *theEnum = (ImplEnumAAFTaggedValueDefs *)CreateImpl (CLSID_EnumAAFTaggedValueDefs); XPROTECT() { OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFTaggedValueDefinition>* iter = new OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFTaggedValueDefinition>(_taggedValueDefinitions); if ( !iter ) { RAISE(AAFRESULT_NOMEMORY); } CHECK( theEnum->Initialize(&CLSID_EnumAAFTaggedValueDefs,this,iter) ); *ppEnum = theEnum; } XEXCEPT { if ( theEnum ) { theEnum->ReleaseReference(); theEnum = 0; } } XEND; return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::CountTaggedValueDefs (aafUInt32* pResult) { if(pResult == NULL) return AAFRESULT_NULL_PARAM; *pResult = _taggedValueDefinitions.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupAuxiliaryDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Auxiliary, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupDescriptiveMetadataDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_DescriptiveMetadata, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupEdgecodeDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Edgecode, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupLegacyPictureDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_LegacyPicture, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupLegacySoundDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_LegacySound, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupLegacyTimecodeDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_LegacyTimecode, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupMatteDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Matte, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupPictureDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Picture, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupPictureWithMatteDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_PictureWithMatte, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupSoundDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Sound, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDictionary::LookupTimecodeDataDef ( ImplAAFDataDef **ppDataDef) { if (!ppDataDef) return AAFRESULT_NULL_PARAM; AAFRESULT hr = LookupDataDef( kAAFDataDef_Timecode, ppDataDef ); ASSERTU(AAFRESULT_SUCCEEDED (hr)); ASSERTU(NULL != *ppDataDef); return AAFRESULT_SUCCESS; } AAFRESULT ImplAAFDictionary::PvtIsPropertyDefDuplicate( aafUID_t propertyDefID, ImplAAFClassDef *correctClass, bool *isDuplicate) { ImplEnumAAFClassDefs *classEnum = NULL; ImplAAFClassDef *pClassDef = NULL; aafUID_t testClassID, correctClassID; bool foundDup = false; if (NULL == correctClass) return AAFRESULT_NULL_PARAM; if (NULL == isDuplicate) return AAFRESULT_NULL_PARAM; XPROTECT() { CHECK(correctClass->GetAUID(&correctClassID)); CHECK(GetClassDefs(&classEnum)); while((foundDup == false) && classEnum->NextOne(&pClassDef) == AAFRESULT_SUCCESS) { CHECK(pClassDef->GetAUID(&testClassID)); if(testClassID == correctClassID) { foundDup = pClassDef->PvtIsPropertyDefRegistered(propertyDefID); } pClassDef->ReleaseReference(); pClassDef = NULL; } classEnum->ReleaseReference(); classEnum = 0; } XEXCEPT { if (pClassDef) { pClassDef->ReleaseReference(); pClassDef = 0; } if (classEnum) { classEnum->ReleaseReference(); classEnum = 0; } } XEND; *isDuplicate = foundDup; return(AAFRESULT_SUCCESS); } bool ImplAAFDictionary::PIDSegment::operator==(const ImplAAFDictionary::PIDSegment& r) { return firstPid == r.firstPid && lastPid == r.lastPid; } AAFRESULT ImplAAFDictionary::GenerateOmPid ( const aafUID_t & rAuid, OMPropertyId & rOutPid ) { OMPropertyId result; AAFRESULT hr; ASSERTU(_pBuiltinClasses); hr = _pBuiltinClasses->LookupOmPid(rAuid, result); if (AAFRESULT_SUCCEEDED(hr) && result != 0) { rOutPid = result; } else { // Generate an om pid for user-extended properties (either in // user-extended classes, or from user-added properties to // existing classes). // // OM PID rules: // - guaranteed to be unique within this file // - not guaranteed to be unique across files // - all builtin properties have a fixed prop<->PID mapping // - all user properties not guaranted a mapping across files // - all builtin properties have *non-negative* PIDs // - all user properties have *negative* PIDs. // Specifics of this implementation: // A list of segments of continuous sequence of pids is maintained in the // _pidSegments variable. New pids are generated by filling in the gaps // starting from the top (0xffff). // The _pidSegments variable is initially empty, and is created by looping // through all the property definitions. if (!_pidSegmentsInitialised) { // initialise the pid segments vector using the properties // already registered in the dictionary // make sure it is clear in case there was a previous (failed) attempt _pidSegments.clear(); // add the dynamic pids already assigned in the file to the vector of pid segments OMSetIterator<aafUID_t, OMPropertyId> iter = _pBuiltinClasses->MappedOmPids(); while (++iter) { OMPropertyId pid = iter.value(); UseDynamicPid(pid); } ImplEnumAAFClassDefsSP enumClassDefs; hr = GetClassDefs(&enumClassDefs); if (AAFRESULT_FAILED(hr)) { return hr; } ImplAAFClassDefSP classDef; while (AAFRESULT_SUCCEEDED(enumClassDefs->NextOne(&classDef))) { ImplEnumAAFPropertyDefsSP enumPropDefs; hr = classDef->GetPropertyDefs(&enumPropDefs); if (AAFRESULT_FAILED(hr)) { return hr; } ImplAAFPropertyDefSP propDef; while (AAFRESULT_SUCCEEDED(enumPropDefs->NextOne(&propDef))) { OMPropertyId pid = propDef->OmPid(); if (pid < 0x8000) // static pid { continue; } // add the dynamic pid to the vector of pid segments UseDynamicPid(pid); } } _pidSegmentsInitialised = true; } // generate a new pid if (_pidSegments.count() == 0) { // this is the first dynamic pid; we start from the top rOutPid = 0xffff; PIDSegment newSegment; newSegment.firstPid = rOutPid; newSegment.lastPid = rOutPid; _pidSegments.append(newSegment); } else { // extend the last segment with a new pid OMVectorIterator<PIDSegment> iter(_pidSegments, OMAfter); --iter; PIDSegment& lastSegment = iter.value(); if (lastSegment.lastPid < 0xffff) { // the new pid becomes one above the last pid in the last segment lastSegment.lastPid++; rOutPid = lastSegment.lastPid; } else { // the new pid becomes one below the first pid in the last segment lastSegment.firstPid--; rOutPid = lastSegment.firstPid; // check whether the segment must be merged with the previous one if (--iter) { PIDSegment& prevSegment = iter.value(); if (prevSegment.lastPid + 1 >= lastSegment.firstPid) { // merge the segments and remove the previous segment lastSegment.firstPid = prevSegment.firstPid; _pidSegments.removeAt(iter.index()); } } } } ASSERTU(rOutPid >= 0x8000); } return AAFRESULT_SUCCESS; } void ImplAAFDictionary::UseDynamicPid(OMPropertyId pid) { // add the dynamic pid to the vector of pid segments bool haveProcessedPid = false; OMVectorIterator<PIDSegment> iter(_pidSegments, OMBefore); while (++iter) { PIDSegment& segment = iter.value(); if (pid >= segment.firstPid && pid <= segment.lastPid) { // this shouldn't happen - a pid should be unique within a file // ASSERTU(pid < segment.firstPid && pid > segment.lastPid); haveProcessedPid = true; break; } if (pid < segment.firstPid - 1) { // the pid is between this segment and the previous segment PIDSegment newSegment; newSegment.firstPid = pid; newSegment.lastPid = pid; _pidSegments.insertAt(newSegment, iter.index()); haveProcessedPid = true; break; } else if (pid == segment.firstPid - 1) { // extend the segment back 1 segment.firstPid = pid; haveProcessedPid = true; break; } else if (pid == segment.lastPid + 1) { // extend the segment forwards 1 segment.lastPid = pid; // check whether the extension takes us into the next segment if (++iter) { PIDSegment& nextSegment = iter.value(); if (pid + 1 >= nextSegment.firstPid) { // merge the segments and remove the next segment segment.lastPid = nextSegment.lastPid; _pidSegments.removeAt(iter.index()); } } haveProcessedPid = true; break; } } if (!haveProcessedPid) { // pid is beyond the last segment PIDSegment newSegment; newSegment.firstPid = pid; newSegment.lastPid = pid; _pidSegments.append(newSegment); } } void ImplAAFDictionary::pvtAttemptBuiltinSizeRegistration (ImplAAFTypeDefEnum * ptde) const { ImplAAFBuiltinTypes::RegisterExistingType (ptde); } void ImplAAFDictionary::pvtAttemptBuiltinSizeRegistration (ImplAAFTypeDefRecord * ptdr) const { ImplAAFBuiltinTypes::RegisterExistingType (ptdr); } void ImplAAFDictionary::AssurePropertyTypes (ImplAAFClassDef * pcd) { ASSERTU (pcd); // All axiomatic definitions have already been loaded all other // property and types can be loaded "lazily" if necessary. // Why do we need this stuff??? transdel 2000-DEC-20 if (_OKToAssurePropTypes) { pcd->AssurePropertyTypesLoaded (); } } void ImplAAFDictionary::AssureClassPropertyTypes () { AAFRESULT hr; ImplEnumAAFClassDefsSP enumClassDefs; ImplAAFClassDefSP classDef; _OKToAssurePropTypes = true; hr = GetClassDefs (&enumClassDefs); ASSERTU (AAFRESULT_SUCCEEDED (hr)); // do registered (normal) classes while (AAFRESULT_SUCCEEDED (enumClassDefs->NextOne (&classDef))) { ASSERTU (classDef); classDef->AssurePropertyTypesLoaded (); classDef = 0; } } bool ImplAAFDictionary::SetEnableDefRegistration (bool isEnabled) { bool retval = _defRegistrationAllowed; _defRegistrationAllowed = isEnabled; return retval; } ImplAAFBuiltinDefs * ImplAAFDictionary::GetBuiltinDefs () { if (! _pBuiltinDefs) { _pBuiltinDefs = new ImplAAFBuiltinDefs (this); } ASSERTU (_pBuiltinDefs); return _pBuiltinDefs; } // Initialize all of the axiomatic and required built-in definitions // have been initialized. This should be called after the file has been opened. void ImplAAFDictionary::InitializeMetaDefinitions(void) { if (!_metaDefinitionsInitialized) { _metaDefinitionsInitialized = true; // // TEMPORARY: // Initialize the built-in types and classes if necessary. // if (!_pBuiltinTypes) _pBuiltinTypes = new ImplAAFBuiltinTypes (this); ASSERTU (_pBuiltinTypes); if (!_pBuiltinClasses) _pBuiltinClasses = new ImplAAFBuiltinClasses (this); ASSERTU (_pBuiltinClasses); } } HRESULT ImplAAFDictionary::RegisterMetaDictionaries() { // Get an IAAFDictionary from this to pass to the plug-ins HRESULT hr; IUnknown* u = static_cast<IUnknown*>(GetContainer()); IAAFDictionary* pDictionary = 0; hr = u->QueryInterface(IID_IAAFDictionary, (void**)&pDictionary); if (!SUCCEEDED(hr)) return hr; // Get the plug-in manager IAAFPluginManager *pPluginManager = 0; hr = AAFGetPluginManager(&pPluginManager); if (!SUCCEEDED(hr)) { pDictionary->Release(); return hr; } // Get an enumerator over the dictionary extension plug-ins IEnumAAFLoadedPlugins* pEnumPlugins = 0; hr = pPluginManager->EnumLoadedPlugins(AUID_AAFDictionary, &pEnumPlugins); if (!SUCCEEDED(hr)) { pPluginManager->Release(); pDictionary->Release(); return hr; } // Get an ImplAAFPluginManager from the IAAFPluginManager because // CreateInstanceFromDefinition() is not public. IAAFRoot* pRoot = 0; hr = pPluginManager->QueryInterface(IID_IAAFRoot, (void**)&pRoot); if (!SUCCEEDED(hr)) { pEnumPlugins->Release(); pPluginManager->Release(); pDictionary->Release(); return hr; } ImplAAFPluginManager* pImplPluginManager = 0; hr = pRoot->GetImplRep((void**)&pImplPluginManager); if (!SUCCEEDED(hr)) { pRoot->Release(); pEnumPlugins->Release(); pPluginManager->Release(); pDictionary->Release(); return hr; } // Make sure that the built-ins are initialized before we // pass this to the plug-ins. InitBuiltins(); // Loop over the plug-ins akeing them to register their // extension definitions. aafUID_t pluginID; while(pEnumPlugins->NextOne (&pluginID) == AAFRESULT_SUCCESS) { IAAFDictionaryExtension *pDictionaryExtension = 0; hr = pImplPluginManager->CreateInstanceFromDefinition(pluginID, NULL, IID_IAAFDictionaryExtension, (void **)&pDictionaryExtension); if (!SUCCEEDED(hr)) continue; // Try next plugin (log this ?) hr = pDictionaryExtension->RegisterExtensionDefinitions(pDictionary); if (!SUCCEEDED(hr)) { pDictionaryExtension->Release(); continue; // Try next plugin (log this ?) } pDictionaryExtension->Release(); pDictionaryExtension = 0; } pRoot->Release(); pEnumPlugins->Release(); pPluginManager->Release(); pDictionary->Release(); return AAFRESULT_SUCCESS; } AAFRESULT ImplAAFDictionary::MergeTo( ImplAAFDictionary* pDestDictionary ) { ASSERTU( pDestDictionary ); AAFRESULT hr; ImplEnumAAFClassDefs* pEnumSrcClassDefs = NULL; hr = GetClassDefs( &pEnumSrcClassDefs ); if( AAFRESULT_SUCCEEDED(hr) ) { ImplAAFClassDef* pSrcClassDef = NULL; while( AAFRESULT_SUCCEEDED(pEnumSrcClassDefs->NextOne(&pSrcClassDef)) ) { #if 1 // DMS1SUPPORT aafUID_t classID; pSrcClassDef->GetAUID( &classID ); if( ! IsDMS1ClassDefinition( classID ) ) { hr = pSrcClassDef->MergeTo( pDestDictionary ); } #else hr = pSrcClassDef->MergeTo( pDestDictionary ); #endif pSrcClassDef->ReleaseReference(); pSrcClassDef = NULL; if( AAFRESULT_FAILED(hr) ) break; } pEnumSrcClassDefs->ReleaseReference(); pEnumSrcClassDefs = NULL; } // Copy all Type Definitions to the destination Dictionary. // // A Type Definition that is not explicitly referenced by // Property Definitions will not get copied with Class Definitions. // A Type Definition, however, may be referenced by other objects, // such as an indirect property value, and needs to be present in // the destination Dictionary. ImplEnumAAFTypeDefs* pEnumSrcTypeDefs = NULL; hr = GetTypeDefs( &pEnumSrcTypeDefs ); if( AAFRESULT_SUCCEEDED(hr) ) { ImplAAFTypeDef* pSrcTypeDef = NULL; while( AAFRESULT_SUCCEEDED(pEnumSrcTypeDefs->NextOne(&pSrcTypeDef)) ) { #if 1 // DMS1SUPPORT aafUID_t typeID; pSrcTypeDef->GetAUID( &typeID ); if( ! IsDMS1TypeDefinition( typeID ) ) { hr = pSrcTypeDef->MergeTo( pDestDictionary ); } #else hr = pSrcTypeDef->MergeTo( pDestDictionary ); #endif pSrcTypeDef->ReleaseReference(); pSrcTypeDef = NULL; if( AAFRESULT_FAILED(hr) ) break; } pEnumSrcTypeDefs->ReleaseReference(); pEnumSrcTypeDefs = NULL; } // // Copy Parameter Definitions to the destination Dictionary // // Issue #1: // // It is possible for a Parameter object to not be contained within // an Operation Group but to belong to another kind of object. // An Operation Group has a weak reference to its Operation Definition, // which, in turn, has weak references to Parameter Definitions for // Parameter objects that may be present in the Operation Group. // By design or by mistake a Parameter object doesn't have a weak // reference to its Parameter Definition, but only specifies its UID. // // The above matters when copying objects from one file to another. // The copy process walks the object tree following strong and weak // references. Copying a Parameter will not copy its Definition because // there no explicit reference from one to the other. But if the Parameter // belongs to an Operation Group it's definition will be copied as part // of copying the Operation Group, by following references from // the Group to its Operation Definition and then to its Parameter // Definitions. // // If a Parameter belongs to an object other than Operation Group, // its Parameter Definition although present in the Dictionary is not // referenced by anybody. When such Parameters are copied into an external // file their Definitions are not followed by the copy process and end up // missing from the destination file. When reading such a file Parameters // without Definitions will not be restored. // // There are AAF files where Parameters are not contained within // Operation Groups but belong to other Parameters. In those cases // the corresponding Parameter Definitions although present in // the Dictionary are not weakly referenced by anybody. Parameter // itself only has an ID of it Definition. When such Parameters are // copied into an external file their Definitions are not followed by // the copy process and end up missing from the destination file. // // Issue #2: // // It is possible to create an Operation Definiton that does not specify, // i.e. has weak references to its Parameter Definitions. For the reason // described above these Parameter Definitions will not be copied to // an external file. // // The fix: // // Here we copy all the parameter definitions to as part of dictionary // merge. This approach has a downside of copying Parameter Definitions // that are not used in the destination file. // // An alternative approach is to use the OMStorable::onCopy() call back // in ImplAAFMob::CloneExternal() to find and copy Definitions for // Parameters that get copied to the destination file. // OMStrongReferenceSetIterator<OMUniqueObjectIdentification, ImplAAFParameterDef> iterator(_parameterDefinitions); while( ++iterator ) { const ImplAAFParameterDef* pSrcParamDef = iterator.value(); const OMUniqueObjectIdentification id = pSrcParamDef->identification(); if( !pDestDictionary->_parameterDefinitions.contains(id) ) { OMStorable* pNewStorable = pSrcParamDef->shallowCopy(pDestDictionary); ImplAAFParameterDef* pDestParamDef = dynamic_cast<ImplAAFParameterDef*>(pNewStorable); ASSERTU(pDestParamDef); // Instance created by shallowCopy() is already reference counted. pDestDictionary->_parameterDefinitions.appendValue(pDestParamDef); pDestParamDef->onCopy(0); pSrcParamDef->deepCopyTo(pDestParamDef, 0); } } return hr; } // Returns true if the passed in container definition ID is an ID of AAF // container definition. // // Container definition IDs are currently compiled in. /*static*/ bool ImplAAFDictionary::IsAAFContainerDefinitionID (const aafUID_t& containerDefID) { bool isAAFContainer = false; if (EqualAUID(&containerDefID, &ContainerAAF)) { isAAFContainer = true; } else if (EqualAUID(&containerDefID, &ContainerAAFMSS) ) { isAAFContainer = true; } else if (EqualAUID(&containerDefID, &ContainerAAFKLV) ) { isAAFContainer = true; } else if (EqualAUID(&containerDefID, &ContainerAAFXML) ) { isAAFContainer = true; } else { isAAFContainer = false; } return isAAFContainer; } /************************************************************************* aafLookupTypeDef() This helper function searches for specified type definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_typedef - type definition to look for. Returns: kAAFTrue - type definition found in given objects dictionary. kAAFFalse - type def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupTypeDef( ImplAAFObject *p_holder, ImplAAFTypeDef *p_typedef ) { ASSERTU( p_holder ); ASSERTU( p_typedef ); AAFRESULT hr = AAFRESULT_TYPE_NOT_FOUND; // Important init. aafUID_t typedef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the type def we're looking for. p_typedef->GetAUID( &typedef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFTypeDef *p_tmp_typedef = NULL; hr = p_dict->LookupTypeDef( typedef_id, &p_tmp_typedef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_typedef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupOperationDef() This helper function searches for specified operation definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_operdef - operation definition to look for. Returns: kAAFTrue - operation definition found in given objects dictionary. kAAFFalse - operation def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupOperationDef( ImplAAFObject *p_holder, ImplAAFOperationDef *p_operdef ) { ASSERTU( p_holder ); ASSERTU( p_operdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t operdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the operation def we're looking for. p_operdef->GetAUID( &operdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFOperationDef *p_tmp_operdef = NULL; hr = p_dict->LookupOperationDef( operdef_id, &p_tmp_operdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_operdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupParameterDef() This helper function searches for specified parameter definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_paramdef - parameter definition to look for. Returns: kAAFTrue - parameter definition found in given objects dictionary. kAAFFalse - parameter def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupParameterDef( ImplAAFObject *p_holder, ImplAAFParameterDef *p_paramdef ) { ASSERTU( p_holder ); ASSERTU( p_paramdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t paramdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the parameter def we're looking for. p_paramdef->GetAUID( &paramdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFParameterDef *p_tmp_paramdef = NULL; hr = p_dict->LookupParameterDef( paramdef_id, &p_tmp_paramdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_paramdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupClassDef() This helper function searches for specified class definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_classdef - class definition to look for. Returns: kAAFTrue - class definition found in given objects dictionary. kAAFFalse - class def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupClassDef( ImplAAFObject *p_holder, ImplAAFClassDef *p_classdef ) { ASSERTU( p_holder ); ASSERTU( p_classdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t classdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the class def we're looking for. p_classdef->GetAUID( &classdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFClassDef *p_tmp_classdef = NULL; hr = p_dict->LookupClassDef( classdef_id, &p_tmp_classdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_classdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupDataDef() This helper function searches for specified data definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_datadef - data definition to look for. Returns: kAAFTrue - data definition found in given objects dictionary. kAAFFalse - data def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupDataDef( ImplAAFObject *p_holder, ImplAAFDataDef *p_datadef ) { ASSERTU( p_holder ); ASSERTU( p_datadef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t datadef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the data def we're looking for. p_datadef->GetAUID( &datadef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFDataDef *p_tmp_datadef = NULL; hr = p_dict->LookupDataDef( datadef_id, &p_tmp_datadef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_datadef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupCodecDef() This helper function searches for specified codec definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_codecdef - codec definition to look for. Returns: kAAFTrue - codec definition found in given objects dictionary. kAAFFalse - codec def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupCodecDef( ImplAAFObject *p_holder, ImplAAFCodecDef *p_codecdef ) { ASSERTU( p_holder ); ASSERTU( p_codecdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t codecdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the codec def we're looking for. p_codecdef->GetAUID( &codecdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFCodecDef *p_tmp_codecdef = NULL; hr = p_dict->LookupCodecDef( codecdef_id, &p_tmp_codecdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_codecdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupContainerDef() This helper function searches for specified container definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_containerdef - container definition to look for. Returns: kAAFTrue - container definition found in given objects dictionary. kAAFFalse - container def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupContainerDef( ImplAAFObject *p_holder, ImplAAFContainerDef *p_containerdef ) { ASSERTU( p_holder ); ASSERTU( p_containerdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t containerdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the container def we're looking for. p_containerdef->GetAUID( &containerdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFContainerDef *p_tmp_containerdef = NULL; hr = p_dict->LookupContainerDef( containerdef_id, &p_tmp_containerdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_containerdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupInterpolationDef() This helper function searches for specified interpolation definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_interpoldef - interpolation definition to look for. Returns: kAAFTrue - interpolation definition found in given objects dictionary. kAAFFalse - interpolation def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupInterpolationDef( ImplAAFObject *p_holder, ImplAAFInterpolationDef *p_interpoldef ) { ASSERTU( p_holder ); ASSERTU( p_interpoldef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t interpoldef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the interpolation def we're looking for. p_interpoldef->GetAUID( &interpoldef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFInterpolationDef *p_tmp_interpoldef = NULL; hr = p_dict->LookupInterpolationDef( interpoldef_id, &p_tmp_interpoldef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_interpoldef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /****/ /************************************************************************* aafLookupTypeDef() This helper function searches for specified type definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_typedef - type definition to look for. Returns: kAAFTrue - type definition found in given objects dictionary. kAAFFalse - type def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupTypeDef( ImplAAFMetaDefinition *p_holder, ImplAAFTypeDef *p_typedef ) { ASSERTU( p_holder ); ASSERTU( p_typedef ); AAFRESULT hr = AAFRESULT_TYPE_NOT_FOUND; // Important init. aafUID_t typedef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the type def we're looking for. p_typedef->GetAUID( &typedef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFTypeDef *p_tmp_typedef = NULL; hr = p_dict->LookupTypeDef( typedef_id, &p_tmp_typedef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_typedef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupOperationDef() This helper function searches for specified operation definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_operdef - operation definition to look for. Returns: kAAFTrue - operation definition found in given objects dictionary. kAAFFalse - operation def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupOperationDef( ImplAAFMetaDefinition *p_holder, ImplAAFOperationDef *p_operdef ) { ASSERTU( p_holder ); ASSERTU( p_operdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t operdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the operation def we're looking for. p_operdef->GetAUID( &operdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFOperationDef *p_tmp_operdef = NULL; hr = p_dict->LookupOperationDef( operdef_id, &p_tmp_operdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_operdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupParameterDef() This helper function searches for specified parameter definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_paramdef - parameter definition to look for. Returns: kAAFTrue - parameter definition found in given objects dictionary. kAAFFalse - parameter def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupParameterDef( ImplAAFMetaDefinition *p_holder, ImplAAFParameterDef *p_paramdef ) { ASSERTU( p_holder ); ASSERTU( p_paramdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t paramdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the parameter def we're looking for. p_paramdef->GetAUID( &paramdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFParameterDef *p_tmp_paramdef = NULL; hr = p_dict->LookupParameterDef( paramdef_id, &p_tmp_paramdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_paramdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupClassDef() This helper function searches for specified class definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_classdef - class definition to look for. Returns: kAAFTrue - class definition found in given objects dictionary. kAAFFalse - class def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupClassDef( ImplAAFMetaDefinition *p_holder, ImplAAFClassDef *p_classdef ) { ASSERTU( p_holder ); ASSERTU( p_classdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t classdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the class def we're looking for. p_classdef->GetAUID( &classdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFClassDef *p_tmp_classdef = NULL; hr = p_dict->LookupClassDef( classdef_id, &p_tmp_classdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_classdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupDataDef() This helper function searches for specified data definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_datadef - data definition to look for. Returns: kAAFTrue - data definition found in given objects dictionary. kAAFFalse - data def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupDataDef( ImplAAFMetaDefinition *p_holder, ImplAAFDataDef *p_datadef ) { ASSERTU( p_holder ); ASSERTU( p_datadef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t datadef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the data def we're looking for. p_datadef->GetAUID( &datadef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFDataDef *p_tmp_datadef = NULL; hr = p_dict->LookupDataDef( datadef_id, &p_tmp_datadef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_datadef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupCodecDef() This helper function searches for specified codec definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_codecdef - codec definition to look for. Returns: kAAFTrue - codec definition found in given objects dictionary. kAAFFalse - codec def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupCodecDef( ImplAAFMetaDefinition *p_holder, ImplAAFCodecDef *p_codecdef ) { ASSERTU( p_holder ); ASSERTU( p_codecdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t codecdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the codec def we're looking for. p_codecdef->GetAUID( &codecdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFCodecDef *p_tmp_codecdef = NULL; hr = p_dict->LookupCodecDef( codecdef_id, &p_tmp_codecdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_codecdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupContainerDef() This helper function searches for specified container definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_containerdef - container definition to look for. Returns: kAAFTrue - container definition found in given objects dictionary. kAAFFalse - container def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupContainerDef( ImplAAFMetaDefinition *p_holder, ImplAAFContainerDef *p_containerdef ) { ASSERTU( p_holder ); ASSERTU( p_containerdef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t containerdef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the container def we're looking for. p_containerdef->GetAUID( &containerdef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFContainerDef *p_tmp_containerdef = NULL; hr = p_dict->LookupContainerDef( containerdef_id, &p_tmp_containerdef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_containerdef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); } /************************************************************************* aafLookupInterpolationDef() This helper function searches for specified interpolation definition in given object's dictionary. Inputs: p_holder - definition object to look in. p_interpoldef - interpolation definition to look for. Returns: kAAFTrue - interpolation definition found in given objects dictionary. kAAFFalse - interpolation def is not in a dictionary. *************************************************************************/ aafBoolean_t aafLookupInterpolationDef( ImplAAFMetaDefinition *p_holder, ImplAAFInterpolationDef *p_interpoldef ) { ASSERTU( p_holder ); ASSERTU( p_interpoldef ); AAFRESULT hr = AAFRESULT_OBJECT_NOT_FOUND; // Important init. aafUID_t interpoldef_id; ImplAAFDictionary *p_dict = NULL; // Get UID of the interpolation def we're looking for. p_interpoldef->GetAUID( &interpoldef_id ); if( p_holder->GetDictionary( &p_dict ) == AAFRESULT_SUCCESS ) { ImplAAFInterpolationDef *p_tmp_interpoldef = NULL; hr = p_dict->LookupInterpolationDef( interpoldef_id, &p_tmp_interpoldef ); if( hr == AAFRESULT_SUCCESS ) p_tmp_interpoldef->ReleaseReference(); p_dict->ReleaseReference(); } return (hr == AAFRESULT_SUCCESS ? kAAFTrue : kAAFFalse); }
27.720368
144
0.682708
01b3e55d56db4c26698eff448438f681cbfc80e6
1,473
cc
C++
chapter-acceleration/openmp/offload-case-studies/case5.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
1
2021-07-04T12:41:16.000Z
2021-07-04T12:41:16.000Z
chapter-acceleration/openmp/offload-case-studies/case5.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
null
null
null
chapter-acceleration/openmp/offload-case-studies/case5.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
null
null
null
#include <cmath> #include <cstdio> // static const int waveletsize = 3; // static const int size = 6; class HaarWavelet { public: static const int waveletsize = 3; static const int size = 6; double wavelet[waveletsize] = {0.0, 1.0 / 2.0, 1.0 / 2.0}; double sigmafactors[size + 1] = {1.00000000000, 7.07167810e-1, 5.00000000e-1, 3.53553391e-1, 2.50000000e-1, 1.76776695e-1, 1.25000000e-1}; int* arr; HaarWavelet() { int *a = new int[10]; arr = a; #pragma omp target enter data map(alloc:a) } ~HaarWavelet() { int *a = arr; #pragma omp target exit data map(delete:a) delete [] arr; } #pragma omp declare target int getNumScales(int length) { return 1 + int(log(double(length - 1) / double(size - 1)) / M_LN2); } #pragma omp end declare target #pragma omp declare target int getMaxSize(int scale) { return int(pow(2, scale - 1)) * (size - 1) + 1; } #pragma omp end declare target }; #pragma omp declare target void offload_driver(HaarWavelet *haar) { printf("Max Size: %d\n", haar->getMaxSize(1)); printf("Num Scales: %d\n", haar->getNumScales(400)); } #pragma omp end declare target void test_offload_class() { HaarWavelet haar; #pragma omp target map(to: haar.wavelet[:haar.waveletsize]) \ map(to:haar.sigmafactors[:haar.size + 1]) { printf("Scales %d\n", haar.getNumScales(10)); offload_driver(&haar); } }
26.781818
79
0.619823
01bdd4f02548e24a34c2e63f51fc3ff6bfc8f172
29,130
cpp
C++
boolean_network/cudd_bnet.cpp
tonyfloatersu/simulator
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
[ "MIT" ]
1
2020-10-28T15:15:03.000Z
2020-10-28T15:15:03.000Z
boolean_network/cudd_bnet.cpp
SJTU-ECTL/simulator
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
[ "MIT" ]
null
null
null
boolean_network/cudd_bnet.cpp
SJTU-ECTL/simulator
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
[ "MIT" ]
null
null
null
/** @file @ingroup nanotrav @brief Functions to read in a boolean network. @author Fabio Somenzi @copyright@parblock Copyright (c) 1995-2015, Regents of the University of Colorado 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 University of Colorado 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. @endparblock */ #include "cudd_bnet.h" /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ #include <map> #include <vector> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Constant declarations */ /*---------------------------------------------------------------------------*/ #define MAXLENGTH 131072 /*---------------------------------------------------------------------------*/ /* Stucture declarations */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Type declarations */ /*---------------------------------------------------------------------------*/ /* Type of comparison function for qsort. */ typedef int (*DD_QSFP)(const void *, const void *); /*---------------------------------------------------------------------------*/ /* Variable declarations */ /*---------------------------------------------------------------------------*/ static char BuffLine[MAXLENGTH]; static char *CurPos; static int newNameNumber = 0; /*---------------------------------------------------------------------------*/ /* Macro declarations */ /*---------------------------------------------------------------------------*/ /** \cond */ /*---------------------------------------------------------------------------*/ /* Static function prototypes */ /*---------------------------------------------------------------------------*/ static char * readString (FILE *fp); static char ** readList (FILE *fp, int *n); static void printList (char **list, int n); static char ** bnetGenerateNewNames (st_table *hash, int n); static int bnetSetLevel (_BnetNetwork *net); static int bnetLevelDFS (_BnetNetwork *net, _BnetNode *node); static _BnetNode ** bnetOrderRoots (_BnetNetwork *net, int *nroots); static int bnetLevelCompare (_BnetNode **x, _BnetNode **y); /** \endcond */ /*---------------------------------------------------------------------------*/ /* Definition of exported functions */ /*---------------------------------------------------------------------------*/ /** @brief Reads boolean network from blif file. @details A very restricted subset of blif is supported. Specifically: <ul> <li> The only directives recognized are: <ul> <li> .model <li> .inputs <li> .outputs <li> .latch <li> .names <li> .exdc <li> .wire_load_slope <li> .end </ul> <li> Latches must have an initial values and no other parameters specified. <li> Lines must not exceed MAXLENGTH-1 characters, and individual names must not exceed 1023 characters. </ul> Caveat emptor: There may be other limitations as well. One should check the syntax of the blif file with some other tool before relying on this parser. @return a pointer to the network if successful; NULL otherwise. @sideeffect None @see Bnet_PrintNetwork Bnet_FreeNetwork */ _BnetNetwork * Bnet_ReadNetwork( FILE * fp /**< pointer to the blif file */, int pr /**< verbosity level */) { char *savestring; char **list; int i, j, n; _BnetNetwork *net; _BnetNode *newnode; _BnetNode *lastnode = nullptr; BnetTabline *newline; BnetTabline *lastline; char ***latches = nullptr; int maxlatches = 0; int exdc = 0; _BnetNode *node; int count; /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ std::map<std::string, std::vector<std::string> > name_outputs; std::map<std::string, std::vector<std::string> >::iterator it; /*---------------------------------------------------------------------------*/ /* Allocate network object and initialize symbol table. */ net = ALLOC(_BnetNetwork,1); if (net == nullptr) goto failure; memset((char *) net, 0, sizeof(_BnetNetwork)); net->hash = st_init_table((st_compare_t) strcmp, st_strhash); if (net->hash == nullptr) goto failure; savestring = readString(fp); if (savestring == nullptr) goto failure; net->nlatches = 0; while (strcmp(savestring, ".model") == 0 || strcmp(savestring, ".inputs") == 0 || strcmp(savestring, ".outputs") == 0 || strcmp(savestring, ".latch") == 0 || strcmp(savestring, ".wire_load_slope") == 0 || strcmp(savestring, ".exdc") == 0 || strcmp(savestring, ".names") == 0 || strcmp(savestring,".end") == 0) { if (strcmp(savestring, ".model") == 0) { /* Read .model directive. */ FREE(savestring); /* Read network name. */ savestring = readString(fp); if (savestring == nullptr) goto failure; if (savestring[0] == '.') { net->name = ALLOC(char, 1); if (net->name == nullptr) goto failure; net->name[0] = '\0'; } else { net->name = savestring; } } else if (strcmp(savestring, ".inputs") == 0) { /* Read .inputs directive. */ FREE(savestring); /* Read input names. */ list = readList(fp,&n); if (list == nullptr) goto failure; if (pr > 2) printList(list,n); /* Expect at least one input. */ if (n < 1) { (void) fprintf(stdout,"Empty input list.\n"); goto failure; } if (exdc) { for (i = 0; i < n; i++) FREE(list[i]); FREE(list); savestring = readString(fp); if (savestring == nullptr) goto failure; continue; } if (net->ninputs) { net->inputs = REALLOC(char *, net->inputs, (net->ninputs + n) * sizeof(char *)); for (i = 0; i < n; i++) net->inputs[net->ninputs + i] = list[i]; } else net->inputs = list; /* Create a node for each primary input. */ for (i = 0; i < n; i++) { newnode = ALLOC(_BnetNode,1); memset((char *) newnode, 0, sizeof(_BnetNode)); if (newnode == nullptr) goto failure; newnode->name = list[i]; newnode->inputs = nullptr; /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ newnode->outputs = nullptr; /*---------------------------------------------------------------------------*/ newnode->type = BNET_INPUT_NODE; newnode->active = FALSE; newnode->nfo = 0; newnode->ninp = 0; newnode->f = nullptr; newnode->polarity = 0; newnode->next = nullptr; if (lastnode == nullptr) { net->nodes = newnode; } else { lastnode->next = newnode; } lastnode = newnode; } net->npis += n; net->ninputs += n; } else if (strcmp(savestring, ".outputs") == 0) { /* Read .outputs directive. We do not create nodes for the primary ** outputs, because the nodes will be created when the same names ** appear as outputs of some gates. */ FREE(savestring); /* Read output names. */ list = readList(fp,&n); if (list == nullptr) goto failure; if (pr > 2) printList(list,n); if (n < 1) { (void) fprintf(stdout,"Empty .outputs list.\n"); goto failure; } if (exdc) { for (i = 0; i < n; i++) FREE(list[i]); FREE(list); savestring = readString(fp); if (savestring == nullptr) goto failure; continue; } if (net->noutputs) { net->outputs = REALLOC(char *, net->outputs, (net->noutputs + n) * sizeof(char *)); for (i = 0; i < n; i++) net->outputs[net->noutputs + i] = list[i]; } else { net->outputs = list; } net->npos += n; net->noutputs += n; } else if (strcmp(savestring,".wire_load_slope") == 0) { FREE(savestring); savestring = readString(fp); net->slope = savestring; } else if (strcmp(savestring,".latch") == 0) { FREE(savestring); newnode = ALLOC(_BnetNode,1); if (newnode == nullptr) goto failure; memset((char *) newnode, 0, sizeof(_BnetNode)); newnode->type = BNET_PRESENT_STATE_NODE; list = readList(fp,&n); if (list == nullptr) goto failure; if (pr > 2) printList(list,n); /* Expect three names. */ if (n != 3) { (void) fprintf(stdout, ".latch not followed by three tokens.\n"); goto failure; } newnode->name = list[1]; newnode->inputs = nullptr; newnode->ninp = 0; newnode->f = nullptr; newnode->active = FALSE; newnode->nfo = 0; newnode->polarity = 0; newnode->next = nullptr; if (lastnode == nullptr) { net->nodes = newnode; } else { lastnode->next = newnode; } lastnode = newnode; /* Add next state variable to list. */ if (maxlatches == 0) { maxlatches = 20; latches = ALLOC(char **,maxlatches); } else if (maxlatches <= net->nlatches) { maxlatches += 20; latches = REALLOC(char **,latches,maxlatches); } latches[net->nlatches] = list; net->nlatches++; savestring = readString(fp); if (savestring == nullptr) goto failure; } else if (strcmp(savestring,".names") == 0) { FREE(savestring); newnode = ALLOC(_BnetNode,1); memset((char *) newnode, 0, sizeof(_BnetNode)); if (newnode == nullptr) goto failure; list = readList(fp,&n); if (list == nullptr) goto failure; if (pr > 2) printList(list,n); /* Expect at least one name (the node output). */ if (n < 1) { (void) fprintf(stdout,"Missing output name.\n"); goto failure; } newnode->name = list[n-1]; newnode->inputs = list; /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ newnode->outputs = nullptr; for(i = 0; i < n-1; i++) { std::string input(newnode->inputs[i]); std::string output(newnode->name); it = name_outputs.find(input); if(it == name_outputs.end()) { std::vector<std::string> outputs; outputs.push_back(output); name_outputs.insert( std::pair<std::string, std::vector<std::string>> (input, outputs)); } else it->second.push_back(output); } /*---------------------------------------------------------------------------*/ newnode->ninp = n-1; newnode->active = FALSE; newnode->nfo = 0; newnode->polarity = 0; if (newnode->ninp > 0) { newnode->type = BNET_INTERNAL_NODE; for (i = 0; i < net->noutputs; i++) { if (strcmp(net->outputs[i], newnode->name) == 0) { newnode->type = BNET_OUTPUT_NODE; break; } } } else { newnode->type = BNET_CONSTANT_NODE; } newnode->next = nullptr; if (lastnode == nullptr) { net->nodes = newnode; } else { lastnode->next = newnode; } lastnode = newnode; /* Read node function. */ newnode->f = nullptr; if (exdc) { newnode->exdc_flag = 1; node = net->nodes; while (node) { if (node->type == BNET_OUTPUT_NODE && strcmp(node->name, newnode->name) == 0) { node->exdc = newnode; break; } node = node->next; } } savestring = readString(fp); if (savestring == nullptr) goto failure; lastline = nullptr; while (savestring[0] != '.') { /* Reading a table line. */ newline = ALLOC(BnetTabline,1); if (newline == nullptr) goto failure; newline->next = nullptr; if (lastline == nullptr) { newnode->f = newline; } else { lastline->next = newline; } lastline = newline; if (newnode->type == BNET_INTERNAL_NODE || newnode->type == BNET_OUTPUT_NODE) { newline->values = savestring; /* Read output 1 or 0. */ savestring = readString(fp); if (savestring == nullptr) goto failure; } else { newline->values = nullptr; } if (savestring[0] == '0') newnode->polarity = 1; FREE(savestring); savestring = readString(fp); if (savestring == nullptr) goto failure; } } else if (strcmp(savestring,".exdc") == 0) { FREE(savestring); exdc = 1; } else if (strcmp(savestring,".end") == 0) { FREE(savestring); break; } if ((!savestring) || savestring[0] != '.') savestring = readString(fp); if (savestring == nullptr) goto failure; } /* Put nodes in symbol table. */ newnode = net->nodes; while (newnode != nullptr) { int retval = st_insert(net->hash,newnode->name,(char *) newnode); if (retval == ST_OUT_OF_MEM) { goto failure; } else if (retval == 1) { printf("Error: Multiple drivers for node %s\n", newnode->name); goto failure; } else { if (pr > 2) printf("Inserted %s\n",newnode->name); } newnode = newnode->next; } if (latches) { net->latches = latches; count = 0; net->outputs = REALLOC(char *, net->outputs, (net->noutputs + net->nlatches) * sizeof(char *)); for (i = 0; i < net->nlatches; i++) { for (j = 0; j < net->noutputs; j++) { if (strcmp(latches[i][0], net->outputs[j]) == 0) break; } if (j < net->noutputs) continue; savestring = ALLOC(char, strlen(latches[i][0]) + 1); strcpy(savestring, latches[i][0]); net->outputs[net->noutputs + count] = savestring; count++; if (st_lookup(net->hash, savestring, (void **) &node)) { if (node->type == BNET_INTERNAL_NODE) { node->type = BNET_OUTPUT_NODE; } } } net->noutputs += count; net->inputs = REALLOC(char *, net->inputs, (net->ninputs + net->nlatches) * sizeof(char *)); for (i = 0; i < net->nlatches; i++) { savestring = ALLOC(char, strlen(latches[i][1]) + 1); strcpy(savestring, latches[i][1]); net->inputs[net->ninputs + i] = savestring; } net->ninputs += net->nlatches; } /* Compute fanout counts. For each node in the linked list, fetch ** all its fanins using the symbol table, and increment the fanout of ** each fanin. */ newnode = net->nodes; while (newnode != nullptr) { _BnetNode *auxnd; for (i = 0; i < newnode->ninp; i++) { if (!st_lookup(net->hash,newnode->inputs[i],(void **)&auxnd)) { (void) fprintf(stdout,"%s not driven\n", newnode->inputs[i]); goto failure; } auxnd->nfo++; } newnode = newnode->next; } /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ for (newnode = net->nodes; newnode != nullptr; newnode = newnode->next) { std::string name_str(newnode->name); it = name_outputs.find(name_str); if(it != name_outputs.end() && newnode->nfo > 0) { std::vector<std::string> outputs = it->second; newnode->outputs = ALLOC(char *, outputs.size()); for(i = 0; i < outputs.size(); i++) { std::string str = outputs[i]; auto *cc = (char*)malloc(str.size()+1); int j; for(j = 0; j < str.size(); j++) cc[j] = str[j]; cc[str.size()] = '\0'; newnode->outputs[i] = cc; } } } /*---------------------------------------------------------------------------*/ if (!bnetSetLevel(net)) goto failure; return(net); failure: /* Here we should clean up the mess. */ (void) fprintf(stdout,"Error in reading network from file.\n"); return(nullptr); } /* end of Bnet_ReadNetwork */ /** @brief Prints to stdout a boolean network created by Bnet_ReadNetwork. @details Uses the blif format; this way, one can verify the equivalence of the input and the output with, say, sis. @sideeffect None @see Bnet_ReadNetwork */ void Bnet_PrintNetwork( _BnetNetwork * net /**< boolean network */) { _BnetNode *nd; BnetTabline *tl; int i; if (net == nullptr) return; (void) fprintf(stdout,".model %s\n", net->name); (void) fprintf(stdout,".inputs"); printList(net->inputs,net->npis); (void) fprintf(stdout,".outputs"); printList(net->outputs,net->npos); for (i = 0; i < net->nlatches; i++) { (void) fprintf(stdout,".latch"); printList(net->latches[i],3); } nd = net->nodes; while (nd != nullptr) { if (nd->type != BNET_INPUT_NODE && nd->type != BNET_PRESENT_STATE_NODE) { (void) fprintf(stdout,".names"); for (i = 0; i < nd->ninp; i++) { (void) fprintf(stdout," %s",nd->inputs[i]); } (void) fprintf(stdout," %s\n",nd->name); tl = nd->f; while (tl != nullptr) { if (tl->values != nullptr) { (void) fprintf(stdout,"%s %d\n",tl->values, 1 - nd->polarity); } else { (void) fprintf(stdout,"%d\n", 1 - nd->polarity); } tl = tl->next; } } nd = nd->next; } (void) fprintf(stdout,".end\n"); } /* end of Bnet_PrintNetwork */ /** @brief Frees a boolean network created by Bnet_ReadNetwork. @sideeffect None @see Bnet_ReadNetwork */ void Bnet_FreeNetwork( _BnetNetwork * net) { _BnetNode *node, *nextnode; BnetTabline *line, *nextline; int i; FREE(net->name); /* The input name strings are already pointed by the input nodes. ** Here we only need to free the latch names and the array that ** points to them. */ for (i = 0; i < net->nlatches; i++) { FREE(net->inputs[net->npis + i]); } FREE(net->inputs); /* Free the output name strings and then the array pointing to them. */ for (i = 0; i < net->noutputs; i++) { FREE(net->outputs[i]); } FREE(net->outputs); for (i = 0; i < net->nlatches; i++) { FREE(net->latches[i][0]); FREE(net->latches[i][1]); FREE(net->latches[i][2]); FREE(net->latches[i]); } if (net->nlatches) FREE(net->latches); node = net->nodes; while (node != nullptr) { nextnode = node->next; if (node->type != BNET_PRESENT_STATE_NODE) FREE(node->name); for (i = 0; i < node->ninp; i++) { FREE(node->inputs[i]); } if (node->inputs != nullptr) { FREE(node->inputs); } /*---------------------------------------------------------------------------*/ /* Implementation of BnetNode->outputs */ for (i = 0; i < node->nfo; i++) { FREE(node->outputs[i]); } if (node->outputs != nullptr) { FREE(node->outputs); } /*---------------------------------------------------------------------------*/ /* Free the function table. */ line = node->f; while (line != nullptr) { nextline = line->next; FREE(line->values); FREE(line); line = nextline; } FREE(node); node = nextnode; } st_free_table(net->hash); if (net->slope != nullptr) FREE(net->slope); FREE(net); } /* end of Bnet_FreeNetwork */ /*---------------------------------------------------------------------------*/ /* Definition of internal functions */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* Definition of static functions */ /*---------------------------------------------------------------------------*/ /** @brief Reads a string from a file. @details The string can be MAXLENGTH-1 characters at most. readString allocates memory to hold the string. @return a pointer to the result string if successful. It returns NULL otherwise. @sideeffect None @see readList */ static char * readString( FILE * fp /**< pointer to the file from which the string is read */) { char *savestring; int length; while (!CurPos) { if (!fgets(BuffLine, MAXLENGTH, fp)) return(nullptr); BuffLine[strlen(BuffLine) - 1] = '\0'; CurPos = strtok(BuffLine, " \t"); if (CurPos && CurPos[0] == '#') CurPos = (char *) nullptr; } length = strlen(CurPos); savestring = ALLOC(char,length+1); if (savestring == nullptr) return(nullptr); strcpy(savestring,CurPos); CurPos = strtok(nullptr, " \t"); return(savestring); } /* end of readString */ /** @brief Reads a list of strings from a line of a file. @details The strings are sequences of characters separated by spaces or tabs. The total length of the list, white space included, must not exceed MAXLENGTH-1 characters. readList allocates memory for the strings and creates an array of pointers to the individual lists. Only two pieces of memory are allocated by readList: One to hold all the strings, and one to hold the pointers to them. Therefore, when freeing the memory allocated by readList, only the pointer to the list of pointers, and the pointer to the beginning of the first string should be freed. @return the pointer to the list of pointers if successful; NULL otherwise. @sideeffect n is set to the number of strings in the list. @see readString printList */ static char ** readList( FILE * fp /**< pointer to the file from which the list is read */, int * n /**< on return, number of strings in the list */) { char *savestring; int length; char *stack[8192]; char **list; int i, count = 0; while (CurPos) { if (strcmp(CurPos, "\\") == 0) { CurPos = (char *) nullptr; while (!CurPos) { if (!fgets(BuffLine, MAXLENGTH, fp)) return(nullptr); BuffLine[strlen(BuffLine) - 1] = '\0'; CurPos = strtok(BuffLine, " \t"); } } length = strlen(CurPos); savestring = ALLOC(char,length+1); if (savestring == nullptr) return(nullptr); strcpy(savestring,CurPos); stack[count] = savestring; count++; CurPos = strtok(nullptr, " \t"); } list = ALLOC(char *, count); for (i = 0; i < count; i++) list[i] = stack[i]; *n = count; return(list); } /* end of readList */ /** @brief Prints a list of strings to the standard output. @details The list is in the format created by readList. @sideeffect None @see readList Bnet_PrintNetwork */ static void printList( char ** list /**< list of pointers to strings */, int n /**< length of the list */) { int i; for (i = 0; i < n; i++) { (void) fprintf(stdout," %s",list[i]); } (void) fprintf(stdout,"\n"); } /* end of printList */ /** @brief Generates n names not currently in a symbol table. @details The pointer to the symbol table may be NULL, in which case no test is made. The names generated by the procedure are unique. So, if there is no possibility of conflict with pre-existing names, NULL can be passed for the hash table. @return an array of names if succesful; NULL otherwise. @sideeffect None @see */ static char ** bnetGenerateNewNames( st_table * hash /* table of existing names (or NULL) */, int n /* number of names to be generated */) { char **list; char name[256]; int i; if (n < 1) return(nullptr); list = ALLOC(char *,n); if (list == nullptr) return(nullptr); for (i = 0; i < n; i++) { do { sprintf(name, "var%d", newNameNumber); newNameNumber++; } while (hash != nullptr && st_is_member(hash,name)); list[i] = util_strsav(name); } return(list); } /* bnetGenerateNewNames */ /** @brief Writes blif for the truth table of an n-input xnor. @return 1 if successful; 0 otherwise. @sideeffect None */ #if 0 static int bnetBlifXnorTable( FILE * fp /**< file pointer */, int n /**< number of inputs */) { int power; /* 2 to the power n */ int i,j,k; int nzeroes; int retval; char *line; line = ALLOC(char,n+1); if (line == NULL) return(0); line[n] = '\0'; for (i = 0, power = 1; i < n; i++) { power *= 2; } for (i = 0; i < power; i++) { k = i; nzeroes = 0; for (j = 0; j < n; j++) { if (k & 1) { line[j] = '1'; } else { line[j] = '0'; nzeroes++; } k >>= 1; } if ((nzeroes & 1) == 0) { retval = fprintf(fp,"%s 1\n",line); if (retval == 0) return(0); } } return(1); } /* end of bnetBlifXnorTable */ #endif /** @brief Sets the level of each node. @return 1 if successful; 0 otherwise. @sideeffect Changes the level and visited fields of the nodes it visits. @see bnetLevelDFS */ static int bnetSetLevel( _BnetNetwork * net) { _BnetNode *node; /* Recursively visit nodes. This is pretty inefficient, because we ** visit all nodes in this loop, and most of them in the recursive ** calls to bnetLevelDFS. However, this approach guarantees that ** all nodes will be reached ven if there are dangling outputs. */ node = net->nodes; while (node != nullptr) { if (!bnetLevelDFS(net,node)) return(0); node = node->next; } /* Clear visited flags. */ node = net->nodes; while (node != nullptr) { node->visited = 0; node = node->next; } return(1); } /* end of bnetSetLevel */ /** @brief Does a DFS from a node setting the level field. @return 1 if successful; 0 otherwise. @sideeffect Changes the level and visited fields of the nodes it visits. @see bnetSetLevel */ static int bnetLevelDFS( _BnetNetwork * net, _BnetNode * node) { int i; _BnetNode *auxnd; if (node->visited == 1) { return(1); } node->visited = 1; /* Graphical sources have level 0. This is the final value if the ** node has no fan-ins. Otherwise the successive loop will ** increase the level. */ node->level = 0; for (i = 0; i < node->ninp; i++) { if (!st_lookup(net->hash, node->inputs[i], (void **) &auxnd)) { return(0); } if (!bnetLevelDFS(net,auxnd)) { return(0); } if (auxnd->level >= node->level) node->level = 1 + auxnd->level; } return(1); } /* end of bnetLevelDFS */ /** @brief Orders network roots for variable ordering. @return an array with the ordered outputs and next state variables if successful; NULL otherwise. @sideeffect None */ static _BnetNode ** bnetOrderRoots( _BnetNetwork * net, int * nroots) { int i, noutputs; _BnetNode *node; _BnetNode **nodes = nullptr; /* Initialize data structures. */ noutputs = net->noutputs; nodes = ALLOC(_BnetNode *, noutputs); if (nodes == nullptr) goto endgame; /* Find output names and levels. */ for (i = 0; i < net->noutputs; i++) { if (!st_lookup(net->hash,net->outputs[i],(void **)&node)) { goto endgame; } nodes[i] = node; } util_qsort(nodes, noutputs, sizeof(_BnetNode *), (DD_QSFP)bnetLevelCompare); *nroots = noutputs; return(nodes); endgame: if (nodes != nullptr) FREE(nodes); return(nullptr); } /* end of bnetOrderRoots */ /** @brief Comparison function used by qsort. @details Used to order the variables according to the number of keys in the subtables. @return the difference in number of keys between the two variables being compared. @sideeffect None */ static int bnetLevelCompare( _BnetNode ** x, _BnetNode ** y) { return((*y)->level - (*x)->level); } /* end of bnetLevelCompare */
28.199419
79
0.545383
01c16f4db4d5265ce125f3556cb43e5b3dc33ea8
2,068
cpp
C++
src/Socket.cpp
vhyz/requests
5937c84f9c9e0fe6d24641126ddfc09ebaed6469
[ "MIT" ]
null
null
null
src/Socket.cpp
vhyz/requests
5937c84f9c9e0fe6d24641126ddfc09ebaed6469
[ "MIT" ]
null
null
null
src/Socket.cpp
vhyz/requests
5937c84f9c9e0fe6d24641126ddfc09ebaed6469
[ "MIT" ]
null
null
null
// // Created by vhyz on 19-5-12. // #include "Socket.h" #include <strings.h> #include <zconf.h> void Socket::send(const std::string &s) { send(s.c_str(), s.size()); } void Socket::send(const char *msg, ssize_t n) { buffer.writeNBytes((void *)msg, n); } int Socket::recv(char *p, ssize_t n) { return buffer.readBuffer(p, n); } std::string Socket::recv() { char buf[MAXLINE]; int n = buffer.readBuffer(buf, MAXLINE); return std::string(buf, n); } Socket::Socket(const std::string &addr, int port) : Socket(addr.c_str(), port) {} Socket::Socket(const char *addr, int port) { sockfd_init(addr, port); auto readCallBack = std::bind(::read, sockfd, std::placeholders::_1, std::placeholders::_2); auto writeCallBack = std::bind(::write, sockfd, std::placeholders::_1, std::placeholders::_2); buffer.setCallBack(readCallBack, writeCallBack); } bool Socket::connect() { if (::connect(sockfd, (sockaddr *)&sockaddrIn, sizeof sockaddrIn) == 0) return true; else return false; } void Socket::shutdownClose() { close(sockfd); } void Socket::sockfd_init(const char *addr, int port) { sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&sockaddrIn, sizeof sockaddrIn); sockaddrIn.sin_family = AF_INET; sockaddrIn.sin_port = htons(port); inet_pton(AF_INET, addr, &sockaddrIn.sin_addr); } std::string Socket::readLine() { std::string res; char buf[MAXLINE]; while (true) { int n = buffer.readLine(buf, MAXLINE); if (n == 0 || n == -1) break; res += std::string(buf, n - 1); if (buf[n - 1] == '\n') { if (*res.rbegin() == '\r') res.pop_back(); break; } } return res; } std::string Socket::readNBytes(int n) { /* * C++17 std::string::data() is char*,it can be modified */ std::string s(n, 0); buffer.readNBytes(s.data(), n); return s; } int Socket::readNBytes(char *p, size_t n) { return buffer.readNBytes(p, n); }
26.177215
80
0.591876
01c21c7a16d17914f565eb5eccb68e4788672333
9,864
cpp
C++
src/utils/BCSimConvenience.cpp
sigurdstorve/OpenBCSim
500025c1b63bc6ff083cbd649771d1b98e3f7314
[ "BSD-3-Clause" ]
17
2016-05-27T13:09:19.000Z
2022-03-21T07:08:47.000Z
src/utils/BCSimConvenience.cpp
rojsc/OpenBCSim
53773172974ad42fc3faceb7b36611573abf1c4c
[ "BSD-3-Clause" ]
63
2015-09-10T11:22:56.000Z
2021-05-21T14:52:39.000Z
src/utils/BCSimConvenience.cpp
rojsc/OpenBCSim
53773172974ad42fc3faceb7b36611573abf1c4c
[ "BSD-3-Clause" ]
15
2016-07-26T14:52:18.000Z
2022-01-02T15:52:28.000Z
/* Copyright (c) 2015, Sigurd Storve All rights reserved. Licensed under the BSD license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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 <algorithm> #include <stdexcept> #include <cmath> #include <stdexcept> #include "BCSimConvenience.hpp" #include "../core/bspline.hpp" #include "rotation3d.hpp" namespace bcsim { std::vector<std::vector<float> > decimate_frame(const std::vector<std::vector<float> >& frame, int rad_decimation) { if (rad_decimation < 1) throw std::runtime_error("Invalid decimation value"); auto num_beams = frame.size(); auto num_samples = frame[0].size(); auto num_samples_dec = num_samples / rad_decimation; std::vector<std::vector<float> > decimated_frame(num_beams); for (size_t beam_no = 0; beam_no < num_beams; beam_no++) { decimated_frame[beam_no].resize(num_samples_dec); for (size_t sample_no = 0; sample_no < num_samples_dec; sample_no++) { decimated_frame[beam_no][sample_no] = frame[beam_no][sample_no*rad_decimation]; } } return decimated_frame; } float get_max_value(const std::vector<std::vector<float> >& image_lines) { std::vector<float> max_values; for (const auto& image_line : image_lines) { max_values.push_back(*std::max_element(image_line.begin(), image_line.end())); } return *std::max_element(max_values.begin(), max_values.end()); } void log_compress_frame(std::vector<std::vector<float> >& image_lines, float dyn_range, float normalize_factor, float gain_factor) { auto num_beams = image_lines.size(); auto num_samples = image_lines[0].size(); for (auto& beam : image_lines) { std::transform(beam.begin(), beam.end(), beam.begin(), [=](float pixel) { // log-compression pixel = static_cast<float>(20.0*std::log10(gain_factor*pixel/normalize_factor)); pixel = (255.0/dyn_range)*(pixel + dyn_range); // clamp to [0, 255] if (pixel < 0.0f) pixel = 0.0f; if (pixel >= 255.0f) pixel = 255.0f; return pixel; }); } } Scatterers::s_ptr render_fixed_scatterers(SplineScatterers::s_ptr spline_scatterers, float timestamp) { // TODO: can parts of this code be put in a separate function and used both // here and in the CPU spline algoritm to reduce code duplication? auto res = FixedScatterers::s_ptr(new FixedScatterers); const auto num_scatterers = spline_scatterers->num_scatterers(); if (num_scatterers == 0) { throw std::runtime_error("No spline scatterers"); } // precompute basis functions const auto num_cs = spline_scatterers->get_num_control_points(); std::vector<float> basis_fn(num_cs); for (size_t i = 0; i < num_cs; i++) { basis_fn[i] = bspline_storve::bsplineBasis(i, spline_scatterers->spline_degree, timestamp, spline_scatterers->knot_vector); } // evaluate using cached basis functions res->scatterers.resize(num_scatterers); for (size_t spline_no = 0; spline_no < num_scatterers; spline_no++) { PointScatterer scatterer; scatterer.pos = vector3(0.0f, 0.0f, 0.0f); scatterer.amplitude = spline_scatterers->amplitudes[spline_no]; for (size_t i = 0; i < num_cs; i++) { scatterer.pos += spline_scatterers->control_points[spline_no][i]*basis_fn[i]; } res->scatterers[spline_no] = scatterer; } return res; } ScanSequence CreateScanSequence(std::shared_ptr<SectorScanGeometry> geometry, size_t num_lines, float timestamp) { const auto line_length = geometry->depth; ScanSequence res(line_length); // Will be transformed by a rotation into lateral and radial unit vectors. // NOTE: Need to use double to avoid "not orthonormal" error (maybe the test is to strict for floats?) const auto unit_vector_x = unit_x<double>(); const auto unit_vector_z = unit_z<double>(); const vector3 origin(0.0f, 0.0f, 0.0f); for (int line_no = 0; line_no < static_cast<int>(num_lines); line_no++) { const float angle = -0.5f*geometry->width + geometry->tilt + line_no*geometry->width/(num_lines-1); const auto ROT_MATRIX = rotation_matrix_y<double>(angle); const auto temp_radial_direction = boost::numeric::ublas::prod(ROT_MATRIX, unit_vector_z); const auto temp_lateral_direction = boost::numeric::ublas::prod(ROT_MATRIX, unit_vector_x); // Copy to vector3 vectors. TODO: deduplicate const vector3 direction ((float)temp_radial_direction(0), (float)temp_radial_direction(1), (float)temp_radial_direction(2)); const vector3 lateral_dir((float)temp_lateral_direction(0), (float)temp_lateral_direction(1), (float)temp_lateral_direction(2)); try { auto sl = Scanline(origin, direction, lateral_dir, timestamp); res.add_scanline(sl); } catch (std::runtime_error& e) { throw std::runtime_error(std::string("failed creating scan line: ") + e.what()); } } return res; } ScanSequence CreateScanSequence(std::shared_ptr<LinearScanGeometry> geometry, size_t num_lines, float timestamp) { const auto line_length = geometry->range_max; ScanSequence res(line_length); const auto unit_vector_x = unit_x<double>(); const auto unit_vector_z = unit_z<double>(); // Copy to vector3 vectors. TODO: deduplicate const vector3 direction (unit_vector_z(0), unit_vector_z(1), unit_vector_z(2)); const vector3 lateral_dir(unit_vector_x(0), unit_vector_x(1), unit_vector_x(2)); for (int line_no = 0; line_no < static_cast<int>(num_lines); line_no++) { try { const vector3 scanline_origin(-0.5f*geometry->width + line_no*geometry->width/(static_cast<int>(num_lines)-1), 0.0f, 0.0f); auto sl = Scanline(scanline_origin, direction, lateral_dir, timestamp); res.add_scanline(sl); } catch (std::runtime_error& e) { throw std::runtime_error(std::string("failed creating scan line: ") + e.what()); } } return res; } // probe_origin is position of probe's origin in world coordinate system. ScanSequence CreateScanSequence(ScanGeometry::ptr geometry, size_t num_lines, float timestamp) { auto sector_geo = std::dynamic_pointer_cast<SectorScanGeometry>(geometry); auto linear_geo = std::dynamic_pointer_cast<LinearScanGeometry>(geometry); if (sector_geo) { return CreateScanSequence(sector_geo, num_lines, timestamp); } else if (linear_geo) { return CreateScanSequence(linear_geo, num_lines, timestamp); } else { throw std::runtime_error("unable to cast scan geometry"); } } namespace detail { // Apply a 3x3 rotation matrix to a vector3; template <typename T> vector3 TransformVector(const vector3& v, const boost::numeric::ublas::matrix<T>& matrix33) { boost::numeric::ublas::vector<T> temp_v(3); temp_v(0) = static_cast<T>(v.x); temp_v(1) = static_cast<T>(v.y); temp_v(2) = static_cast<T>(v.z); const auto transformed = boost::numeric::ublas::prod(matrix33, temp_v); return vector3(static_cast<float>(transformed(0)), static_cast<float>(transformed(1)), static_cast<float>(transformed(2))); } } ScanSequence::s_ptr OrientScanSequence(const ScanSequence& scan_seq, const vector3& rot_angles, const vector3& probe_origin) { const auto rot_matrix = rotation_matrix_xyz(rot_angles.x, rot_angles.y, rot_angles.z); const auto line_length = scan_seq.line_length; auto num_lines = scan_seq.get_num_lines(); auto res = new ScanSequence(line_length); for (int i = 0; i < num_lines; i++) { const auto old_line = scan_seq.get_scanline(i); const auto rotated_origin = detail::TransformVector(old_line.get_origin(), rot_matrix); const auto rotated_direction = detail::TransformVector(old_line.get_direction(), rot_matrix); const auto rotated_lateral_dir = detail::TransformVector(old_line.get_lateral_dir(), rot_matrix); res->add_scanline(Scanline(rotated_origin + probe_origin, rotated_direction, rotated_lateral_dir, old_line.get_timestamp())); } return ScanSequence::s_ptr(res); } } // end namespace
44.233184
136
0.686942
01c4459a7f9bb4ac7d43ac46f2adf3af5b923cde
3,241
cpp
C++
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/test/unittest/font/ui_font_unit_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/test/unittest/font/ui_font_unit_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/test/unittest/font/ui_font_unit_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-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 "font/ui_font.h" #include "font/ui_font_vector.h" #include <climits> #include <gtest/gtest.h> using namespace testing::ext; namespace OHOS { namespace { constexpr uint8_t FONT_ERROR_RET = 0xFF; } class UIFontTest : public testing::Test { public: UIFontTest() {} virtual ~UIFontTest() {} static void SetUpTestCase() {}; static void TearDownTestCase() {}; }; /** * @tc.name: Graphic_Font_Test_GetInstance_001 * @tc.desc: Verify UIFont::GetInstance function, not nullptr. * @tc.type: FUNC * @tc.require: SR000F3PEK */ HWTEST_F(UIFontTest, Graphic_Font_Test_GetInstance_001, TestSize.Level0) { UIFont* font = UIFont::GetInstance(); EXPECT_NE(font, nullptr); } /** * @tc.name: Graphic_Font_Test_GetInstance_002 * @tc.desc: Verify UIFont::GetInstance function, equal. * @tc.type: FUNC * @tc.require: SR000F3PEK */ HWTEST_F(UIFontTest, Graphic_Font_Test_GetInstance_002, TestSize.Level0) { UIFont* font = UIFont::GetInstance(); bool ret = UIFont::GetInstance()->IsVectorFont(); EXPECT_EQ(ret, true); } /** * @tc.name: Graphic_Font_Test_RegisterFontInfo_001 * @tc.desc: Verify UIFont::RegisterFontInfo function, error font name. * @tc.type: FUNC * @tc.require: AR000F3R7C */ HWTEST_F(UIFontTest, Graphic_Font_Test_RegisterFontInfo_001, TestSize.Level0) { uint8_t ret = UIFont::GetInstance()->RegisterFontInfo("error"); EXPECT_EQ(ret, FONT_ERROR_RET); } /** * @tc.name: Graphic_Font_Test_RegisterFontInfo_002 * @tc.desc: Verify UIFont::RegisterFontInfo function, error font file path. * @tc.type: FUNC * @tc.require: AR000F3R7C */ HWTEST_F(UIFontTest, Graphic_Font_Test_RegisterFontInfo_002, TestSize.Level0) { uint8_t ret = UIFont::GetInstance()->RegisterFontInfo("ui-font.ttf"); EXPECT_EQ(ret, FONT_ERROR_RET); } /** * @tc.name: Graphic_Font_Test_UnregisterFontInfo_001 * @tc.desc: Verify UIFont::UnregisterFontInfo function, error font name. * @tc.type: FUNC * @tc.require: AR000F3R7C */ HWTEST_F(UIFontTest, Graphic_Font_Test_UnregisterFontInfo_001, TestSize.Level0) { uint8_t ret = UIFont::GetInstance()->UnregisterFontInfo("error font name"); EXPECT_EQ(ret, FONT_ERROR_RET); } /** * @tc.name: Graphic_Font_Test_UnregisterFontInfo_002 * @tc.desc: Verify UIFont::UnregisterFontInfo function, unregister fontsTable. * @tc.type: FUNC * @tc.require: AR000F3R7C */ HWTEST_F(UIFontTest, Graphic_Font_Test_UnregisterFontInfo_002, TestSize.Level0) { const UITextLanguageFontParam* fontsTable = nullptr; uint8_t ret = UIFont::GetInstance()->UnregisterFontInfo(fontsTable, 0); EXPECT_EQ(ret, 0); } } // namespace OHOS
29.733945
79
0.73465
01c4bb3f0706119a5b8d4925a18a5d136aad9c19
160
cpp
C++
11Libraries/HelloLibrary.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
3
2016-01-27T18:12:40.000Z
2016-02-03T20:27:19.000Z
11Libraries/HelloLibrary.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
3
2016-03-21T02:18:52.000Z
2016-03-21T03:02:51.000Z
11Libraries/HelloLibrary.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
16
2016-01-27T18:12:41.000Z
2019-09-15T01:42:28.000Z
#include "HelloLibrary.h" #include <iostream> #include <string> using namespace std; void HelloWorld() { cout << "Hello My Library" << endl; }
12.307692
39
0.63125
01c6da2cde6ed9650ca85e0e289e61c18db9f890
6,289
cpp
C++
DiligentSamples/Samples/SampleBase/src/Android/SampleAppAndroid.cpp
raptoravis/defpr
7335474b09dde91710d7bb2725c06e88d95b86f3
[ "Apache-2.0" ]
null
null
null
DiligentSamples/Samples/SampleBase/src/Android/SampleAppAndroid.cpp
raptoravis/defpr
7335474b09dde91710d7bb2725c06e88d95b86f3
[ "Apache-2.0" ]
null
null
null
DiligentSamples/Samples/SampleBase/src/Android/SampleAppAndroid.cpp
raptoravis/defpr
7335474b09dde91710d7bb2725c06e88d95b86f3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "AndroidFileSystem.h" #include "EngineFactoryOpenGL.h" #include "SampleApp.h" #include "RenderDeviceGLES.h" #include "ImGuiImplAndroid.h" namespace Diligent { class SampleAppAndroid final : public SampleApp { public: SampleAppAndroid() { m_DeviceType = DeviceType::OpenGLES; } virtual void Initialize()override final { GetEngineFactoryOpenGL()->InitAndroidFileSystem(app_->activity, native_activity_class_name_.c_str()); AndroidFileSystem::Init(app_->activity, native_activity_class_name_.c_str()); SampleApp::Initialize(); InitializeDiligentEngine(app_->window); const auto& SCDesc = m_pSwapChain->GetDesc(); m_pImGui.reset(new ImGuiImplAndroid(m_pDevice, SCDesc.ColorBufferFormat, SCDesc.DepthBufferFormat, SCDesc.Width, SCDesc.Height)); m_RenderDeviceGLES = RefCntAutoPtr<IRenderDeviceGLES>(m_pDevice, IID_RenderDeviceGLES); InitializeSample(); } virtual int Resume(ANativeWindow* window)override final { return m_RenderDeviceGLES->Resume(window); } virtual void TermDisplay()override final { // Tear down the EGL context currently associated with the display. m_RenderDeviceGLES->Suspend(); } virtual void TrimMemory()override final { LOGI( "Trimming memory" ); m_RenderDeviceGLES->Invalidate(); } virtual int32_t HandleInput( AInputEvent* event )override final { if( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_MOTION ) { ndk_helper::GESTURE_STATE doubleTapState = doubletap_detector_.Detect( event ); ndk_helper::GESTURE_STATE dragState = drag_detector_.Detect( event ); ndk_helper::GESTURE_STATE pinchState = pinch_detector_.Detect( event ); //Double tap detector has a priority over other detectors if( doubleTapState == ndk_helper::GESTURE_STATE_ACTION ) { //Detect double tap //tap_camera_.Reset( true ); } else { //Handle drag state if( dragState & ndk_helper::GESTURE_STATE_START ) { //Otherwise, start dragging ndk_helper::Vec2 v; drag_detector_.GetPointer( v ); float fX = 0, fY = 0; v.Value(fX, fY); auto Handled = static_cast<ImGuiImplAndroid*>(m_pImGui.get())->BeginDrag(fX, fY); if (!Handled) { m_TheSample->GetInputController().BeginDrag(fX, fY); } } else if( dragState & ndk_helper::GESTURE_STATE_MOVE ) { ndk_helper::Vec2 v; drag_detector_.GetPointer( v ); float fX = 0, fY = 0; v.Value(fX, fY); auto Handled = static_cast<ImGuiImplAndroid*>(m_pImGui.get())->DragMove(fX, fY); if (!Handled) { m_TheSample->GetInputController().DragMove(fX, fY); } } else if( dragState & ndk_helper::GESTURE_STATE_END ) { static_cast<ImGuiImplAndroid*>(m_pImGui.get())->EndDrag(); m_TheSample->GetInputController().EndDrag(); } //Handle pinch state if( pinchState & ndk_helper::GESTURE_STATE_START ) { //Start new pinch ndk_helper::Vec2 v1; ndk_helper::Vec2 v2; pinch_detector_.GetPointers( v1, v2 ); float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0; v1.Value(fX1, fY1); v2.Value(fX2, fY2); m_TheSample->GetInputController().StartPinch(fX1, fY1, fX2, fY2); //tap_camera_.BeginPinch( v1, v2 ); } else if( pinchState & ndk_helper::GESTURE_STATE_MOVE ) { //Multi touch //Start new pinch ndk_helper::Vec2 v1; ndk_helper::Vec2 v2; pinch_detector_.GetPointers( v1, v2 ); float fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0; v1.Value(fX1, fY1); v2.Value(fX2, fY2); m_TheSample->GetInputController().PinchMove(fX1, fY1, fX2, fY2); //tap_camera_.Pinch( v1, v2 ); } else if( pinchState & ndk_helper::GESTURE_STATE_END ) { m_TheSample->GetInputController().EndPinch(); } } return 1; } return 0; } private: RefCntAutoPtr<IRenderDeviceGLES> m_RenderDeviceGLES; }; NativeAppBase* CreateApplication() { return new SampleAppAndroid; } }
38.115152
137
0.575608
01c7a3a7f5792c81fd3eb2eb886f2c784d0d78bd
1,170
hpp
C++
include/cutee/macros.hpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
null
null
null
include/cutee/macros.hpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
12
2018-06-18T12:56:33.000Z
2020-09-08T10:29:29.000Z
include/cutee/macros.hpp
IanHG/cutee
b3b3eba5d78b4871847a5251d311b588e7ba97c0
[ "MIT" ]
null
null
null
#pragma once #ifndef CUTEE_MACROS_HPP_INCLUDED #define CUTEE_MACROS_HPP_INCLUDED #include "suite.hpp" #include "float_eq.hpp" /** * Assertion Macros **/ #define UNIT_ASSERT(a, b) \ cutee::asserter::assertt(a, cutee::info{b, __FILE__, __LINE__}); #define UNIT_ASSERT_NOT(a, b) \ cutee::asserter::assert_not(a, cutee::info{b, __FILE__, __LINE__}); #define UNIT_ASSERT_EQUAL(a, b, c) \ cutee::asserter::assert_equal(a, b, cutee::info{c, __FILE__, __LINE__}); #define UNIT_ASSERT_NOT_EQUAL(a, b, c) \ cutee::asserter::assert_not_equal(a, b, cutee::info{c, __FILE__, __LINE__}); #define UNIT_ASSERT_FEQUAL(a, b, c) \ cutee::asserter::assert_float_equal_prec(a, b, 2u, cutee::info{c, __FILE__, __LINE__}); #define UNIT_ASSERT_FEQUAL_PREC(a, b, c, d) \ cutee::asserter::assert_float_equal_prec(a, b, c, cutee::info{d, __FILE__, __LINE__}); #define UNIT_ASSERT_FZERO(a,b,c) \ cutee::asserter::assert_float_numeq_zero_prec(a, b, 2u, cutee::info{c, __FILE__, __LINE__}); #define UNIT_ASSERT_FZERO_PREC(a,b,c,d) \ cutee::asserter::assert_float_numeq_zero_prec(a, b, c, cutee::info{d, __FILE__, __LINE__}); #endif /* CUTEE_MACROS_HPP_INCLUDED */
32.5
95
0.722222
01c817ed00701072add5f6d11fe4fc2d0ae003cf
592
cpp
C++
cpp/triangle/triangle.cpp
homembaixinho/exercism
fe145381365c101f8e0c5998180ef4973cd9f4ee
[ "MIT" ]
null
null
null
cpp/triangle/triangle.cpp
homembaixinho/exercism
fe145381365c101f8e0c5998180ef4973cd9f4ee
[ "MIT" ]
null
null
null
cpp/triangle/triangle.cpp
homembaixinho/exercism
fe145381365c101f8e0c5998180ef4973cd9f4ee
[ "MIT" ]
null
null
null
#include "triangle.h" #include <algorithm> #include <stdexcept> #include <vector> using namespace std; namespace triangle { flavor kind(double a, double b, double c) { // checks for invalid triangles double smallest = min(min(a,b), c); double largest = max(max(a,b), c); if (a + b + c - 2*largest <= 0 || smallest < 0) throw domain_error("invalid triangle"); if (a == b) { if (a == c) return flavor::equilateral; return flavor::isosceles; } if (b == c || a == c) return flavor::isosceles; return flavor::scalene; } }
19.733333
51
0.589527
01ca1ad888864e8ce50fb68689971ab6ad88eb15
115,748
cpp
C++
AStyleTest/src/AStyleTest_Format.cpp
a-w/astyle
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
[ "MIT" ]
null
null
null
AStyleTest/src/AStyleTest_Format.cpp
a-w/astyle
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
[ "MIT" ]
null
null
null
AStyleTest/src/AStyleTest_Format.cpp
a-w/astyle
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
[ "MIT" ]
null
null
null
// AStyleTest_Format.cpp // Copyright (c) 2016 by Jim Pattee <jimp03@email.com>. // Licensed under the MIT license. // License.txt describes the conditions under which this software may be distributed. //---------------------------------------------------------------------------- // headers //---------------------------------------------------------------------------- #include "AStyleTest.h" //---------------------------------------------------------------------------- // anonymous namespace //---------------------------------------------------------------------------- namespace { // //------------------------------------------------------------------------- // AStyle Break Closing Brackets // Additional tests are in the Brackets tests //------------------------------------------------------------------------- TEST(BreakClosingBrackets, LongOption) { // test NONE_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, ShortOption) { // test NONE_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "-y"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, Break) { // test BREAK_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo)\n" "{\n" " if (isFoo)\n" " {\n" " bar();\n" " }\n" " else\n" " {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=allman, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, Attach) { // test ATTACH_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=java, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, Linux) { // test LINUX_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=kr, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, Stroustrup) { // test STROUSTRUP_MODE brackets with break closing headers char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=stroustrup, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, KeepBlocks) { // test break closing headers with keep one line blocks // it shouldn't make any difference char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=java, break-closing-brackets, keep-one-line-blocks"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, ElseSans) { // test if/else without break closing brackets // else statement should be attached to the closing bracket char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " }\n" " else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " if (isFoo) {\n" " bar();\n" " } else {\n" " anotherBar();\n" " }\n" "}\n" "\n"; char options[] = "style=java"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, Catch) { // test try/catch with break closing brackets char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " try {\n" " bar();\n" " } catch (int i) {\n" " cout << i << endl;\n" " }\n" "}\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " try {\n" " bar();\n" " }\n" " catch (int i) {\n" " cout << i << endl;\n" " }\n" "}\n"; char options[] = "style=java, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, CatchSans) { // test try/catch without break closing brackets // catch statement should be attached to the closing bracket char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " try {\n" " bar();\n" " }\n" " catch (int i) {\n" " cout << i << endl;\n" " }\n" "}\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " try {\n" " bar();\n" " } catch (int i) {\n" " cout << i << endl;\n" " }\n" "}\n"; char options[] = "style=java"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, While) { // test do/while with break closing brackets char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " do {\n" " bar();\n" " } while (int x < 9);\n" "}\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " do {\n" " bar();\n" " }\n" " while (int x < 9);\n" "}\n"; char options[] = "style=java, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakClosingBrackets, WhileSans) { // test do/while without break closing brackets // while statement should be attached to the closing bracket char textIn[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " do {\n" " bar();\n" " }\n" " while (int x < 9);\n" "}\n"; char text[] = "\nvoid FooClass::Foo(bool isFoo) {\n" " do {\n" " bar();\n" " } while (int x < 9);\n" "}\n"; char options[] = "style=java"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Break Else If //------------------------------------------------------------------------- TEST(BreakElseIfs, LongOption) { // test break else/if // else/if statements should be broken char textIn[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if 0\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "}\n"; char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if 0\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "}\n"; char options[] = "break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, ShortOption) { // test break else/if short options // else/if statements should be broken char textIn[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if 0\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "}\n"; char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if 0\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "}\n"; char options[] = "-e"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Sans1) { // test without break else/if // else/if statements should be joined // but do NOT join #else char textIn[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else\n" " if (isBar) {\n" " anotherBar();\n" " } else if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if fooDef1\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "# if fooDef2\n" " foo();\n" "# else\n" " fooBar();\n" "# endif\n" "}\n"; char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo) {\n" " bar();\n" " } else if (isBar) {\n" " anotherBar();\n" " } else if (isBar) {\n" " anotherBar();\n" " } else {\n" " if (isBar) {\n" " anotherBar();\n" " }\n" " }\n" "\n" " if (isFoo) {\n" " bar();\n" " } else anotherBar();\n" " if (isFoo)\n" " bar();\n" "\n" "#if fooDef1\n" " foo();\n" "#else\n" " if (bar)\n" " fooBar();\n" "#endif\n" "# if fooDef2\n" " foo();\n" "# else\n" " fooBar();\n" "# endif\n" "}\n"; char options[] = ""; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Sans2) { // test without break else/if // but do NOT join to #else following an else char text[] = "\nvoid Foo()\n" "{\n" "#ifdef sun\n" " if (isUDP(mSettings)) {\n" " UDPSingleServer();\n" " }\n" " else\n" "#else\n" " if (isSingleUDP(mSettings)) {\n" " UDPSingleServer();\n" " }\n" " else\n" "#endif\n" " {\n" " thread_Settings *tempSettings = NULL;\n" " }\n" "}\n"; char options[] = ""; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(BreakElseIfs, KeepOneLineBlocks) { // test break else/if with keep one line blocks // else/if statements remain the same with breaking/attaching char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " { bar(); if (isBar1) anotherBar1(); else if (isBar2) anotherBar2(); }\n" " { if (isBar1) anotherBar1(); else if (isBar2) anotherBar2(); }\n" "}\n"; char options[] = "break-elseifs, keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, KeepOneLineStatements) { // test break else/if with keep one line statements // else/if statements remain the same with breaking/attaching char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " bar(); if (isBar1) anotherBar1(); else if (isBar2) anotherBar2();\n" " if (isBar1) anotherBar1(); else if (isBar2) anotherBar2();\n" "}\n"; char options[] = "break-elseifs, keep-one-line-statements"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Comments1) { // Test break else/if with comments preceding the 'else'. // The should be indented the same as the following 'else'. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " // comment 2\n" " else if (isFoo2)\n" " bar2();\n" " // comment 3\n" " else if (isFoo3)\n" " bar3();\n" " // comment 4\n" " else bar4();\n" " // not else-if comment\n" " endBar();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " // comment 2\n" " else\n" " if (isFoo2)\n" " bar2();\n" " // comment 3\n" " else\n" " if (isFoo3)\n" " bar3();\n" " // comment 4\n" " else bar4();\n" " // not else-if comment\n" " endBar();\n" "}"; char options[] = "break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Comments2) { // Test break else/if with comments preceding the 'else'. // The should be indented the same as the following 'else'. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1(); /* comment 1A */\n" " /* comment 2 */\n" " else if (isFoo2) /* comment 2A */\n" " { bar2(); }\n" " /* comment 3 */\n" " else if (isFoo3)\n" " { bar3(); }\n" " /* comment 4 */\n" " else bar4();\n" " /* not else-if comment */\n" " endBar();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1(); /* comment 1A */\n" " /* comment 2 */\n" " else\n" " if (isFoo2) /* comment 2A */\n" " { bar2(); }\n" " /* comment 3 */\n" " else\n" " if (isFoo3)\n" " { bar3(); }\n" " /* comment 4 */\n" " else bar4();\n" " /* not else-if comment */\n" " endBar();\n" "}"; char options[] = "break-elseifs, keep-one-line-blocks"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Comments3) { // Test break else/if with comments IFs with no ELSE. char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " // comment 2\n" " if (isFoo2)\n" " // comment 3\n" " if (isFoo3)\n" " bar3();\n" " // not IF comment\n" " endBar();\n" "}"; char options[] = "break-elseifs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Comments4) { // Test break else/if with multiple-line comments preceding the 'else'. // The should be indented the same as the following 'else'. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" " // comment 4A\n" " // comment 4B\n" " // comment 4C\n" " else bar4();\n" " // not else-if commentA\n" " // not else-if commentB\n" " // not else-if commentC\n" " endBar();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else\n" " if (isFoo2)\n" " bar2();\n" " else\n" " if (isFoo3)\n" " bar3();\n" " // comment 4A\n" " // comment 4B\n" " // comment 4C\n" " else bar4();\n" " // not else-if commentA\n" " // not else-if commentB\n" " // not else-if commentC\n" " endBar();\n" "}"; char options[] = "break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, Comments5) { // Test break else/if with multiple-line comments preceding the 'else'. // The should be indented the same as the following 'else'. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else if (isFoo2)\n" " bar2();\n" " /** comment 3A\n" " * comment 3B\n" " * comment 3C */\n" " else if (isFoo3)\n" " bar3();\n" " /** comment 4A\n" " * comment 4B\n" " * comment 4C\n" " */\n" " else bar4();\n" " /* not else-if commentA\n" " * not else-if commentB\n" " * not else-if commentC\n" " */\n" " endBar();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else\n" " if (isFoo2)\n" " bar2();\n" " /** comment 3A\n" " * comment 3B\n" " * comment 3C */\n" " else\n" " if (isFoo3)\n" " bar3();\n" " /** comment 4A\n" " * comment 4B\n" " * comment 4C\n" " */\n" " else bar4();\n" " /* not else-if commentA\n" " * not else-if commentB\n" " * not else-if commentC\n" " */\n" " endBar();\n" "}"; char options[] = "break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, CommentsInPreprocessor) { // Test break else/if with comment in a preprocessor directive. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else if (isFoo4)\n" " bar4();\n" "#ifdef IS_GUI\n" " // Beg of options used by GUI\n" " else if (isFoo4A)\n" " bar4A();\n" "#else\n" " // Options used by only console\n" " else if (isFoo5)\n" " bar5();\n" "#endif\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else\n" " if (isFoo4)\n" " bar4();\n" "#ifdef IS_GUI\n" " // Beg of options used by GUI\n" " else\n" " if (isFoo4A)\n" " bar4A();\n" "#else\n" " // Options used by only console\n" " else\n" " if (isFoo5)\n" " bar5();\n" "#endif\n" "}"; char options[] = "break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, AddBrackets) { // Test break else/if with add-brackets. // The resulting closing brackets should align // with the 'if' instead of the 'else'. char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " bar1();\n" " else if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" " else bar4();\n" " endBar();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1) {\n" " bar1();\n" " }\n" " else\n" " if (isFoo2) {\n" " bar2();\n" " }\n" " else\n" " if (isFoo3) {\n" " bar3();\n" " }\n" " else {\n" " bar4();\n" " }\n" " endBar();\n" "}"; char options[] = "break-elseifs, add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, EndOfFileComments1) { // Test comments at the end of file. // Was causing an exception in call to PeekNextText(). char text[] = "\nvoid Foo()\n" "{\n" " endBar();\n" "}" "// end of line comment"; char options[] = "break-elseifs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, EndOfFileComments2) { // Test comments at the end of file. // Was causing an exception in call to PeekNextText(). char text[] = "\nvoid Foo()\n" "{\n" " endBar();\n" "}" "/* end of line comment */"; char options[] = "break-elseifs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, WithSwitch) { // test break else/if with a switch statement // should not separate the colon from the header char text[] = "\nvoid foo()\n" "{\n" " switch (Current_Led_Toggle)\n" " {\n" " case LED_TOGGLE_NORMAL:\n" " break;\n" " default:\n" " break;\n" " }\n" "}\n"; char options[] = "break-elseifs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(BreakElseIfs, WithMaxCodeLength) { // test break else/if with a max code length // should not have an empty line between the IF and the statement char textIn[] = "\nvoid foo()\n" "{\n" " if (config.chkAnnSource) param << _T(\" -A\") << config.txtAnnSource;\n" " if (config.chkMinCount) param << _T(\" -m\") << config.spnMinCount;\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (config.chkAnnSource)\n" " param << _T(\" -A\") << config.txtAnnSource;\n" " if (config.chkMinCount)\n" " param << _T(\" -m\") << config.spnMinCount;\n" "}\n"; char options[] = "break-elseifs, max-code-length=50"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Keep One Line Statements //------------------------------------------------------------------------- TEST(KeepOneLineStatements, LongOption) { // test keep one line statements char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " {\n" " isFoo=false; isBar=true;\n" " }\n" "}\n"; char options[] = "keep-one-line-statements"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, ShortOption) { // // test keep one line statements short option char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " {\n" " isFoo=false; isBar=true;\n" " }\n" "}\n"; char options[] = "-o"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, WithHeader) { // test keep one line statements with a header in one of the statements char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-statements"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, SansWithHeader1) { // test without keep-one-line statements // one-line statements with a header in one of the statements // should break the statements char textIn[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te);\n" " if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char options[] = ""; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, SansWithHeader2) { // test without keep-one-line statements but with break blocks // one-line statements with a header in one of the statements // should break the statements and the header block char textIn[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te);\n" "\n" " if (!te.IsAllowed()) return;\n" "\n" " CalculatePositions();\n" "}"; char options[] = "break-blocks=all"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, BreakBlocks1) { // test with break-blocks=all and a header as the SECOND statement // should not change the lines char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-statements, break-blocks=all"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, BreakBlocks2) { // Test with break-blocks=all and a header as the FIRST statement. // Should keep the one-line statements and break the block. // Adding keep-one-line-blocks would not break the block. // See the following test. char textIn[] = "\nvoid Foo()\n" "{\n" " if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te);\n" " CalculatePositions();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te);\n" "\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-statements, break-blocks"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, BreakBlocks3) { // Test with break-blocks and keep-one-line-statements. // Should not break the Block. // Without keep-one-line-statements it will break the block. // See the previous test. char text[] = "\nvoid Foo()\n" "{\n" " if ( getter ) mv.Get = _T ( \"Get\" ) + method;\n" " else mv.Get = wxEmptyString;\n" "}"; char options[] = "keep-one-line-statements, break-blocks, keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, BreakBlocksMaxCodeLength1) { // test with break-blocks=all and max code length // should break the IF statement and break the block char textIn[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te);\n" "\n" " if (!te.IsAllowed()) return;\n" "\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-statements, break-blocks=all, max-code-length=60"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineStatements, BreakBlocksMaxCodeLength2) { // test with break-blocks=all and without max code length // should NOT break the one line statement char text[] = "\nvoid Foo()\n" "{\n" " SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-statements, break-blocks=all"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Keep One Line Blocks //------------------------------------------------------------------------- TEST(KeepOneLineBlocks, LongOption) { // test keep one line blocks char text[] = "\nvoid foo()\n" "{\n" " if (!j) { j=1; i=i-10; }\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, ShortOption) { // test keep one line blocks short option char text[] = "\nvoid foo()\n" "{\n" " if (!j) { j=1; i=i-10; }\n" "}\n"; char options[] = "-O"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, StartOfLine) { // line beginning with one-line blocks do NOT get a extra indent char text[] = "\nclass Foo\n" "{\n" "public:\n" " int getFoo() const\n" " { return isFoo; }\n" "};\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, NoneBrackets) { // test keep one line blocks char text[] = "\nvoid foo()\n" "{\n" " if (comment&&code) { ++codecomments_lines; }\n" " else if (comment) { ++comment_lines; }\n" " else if (code) { ++code_lines; }\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakBrackets) { // test keep one line blocks char text[] = "\nvoid foo()\n" "{\n" " if (comment&&code) { ++codecomments_lines; }\n" " else if (comment) { ++comment_lines; }\n" " else if (code) { ++code_lines; }\n" "}\n"; char options[] = "keep-one-line-blocks, style=allman"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, AttachBrackets) { // test keep one line blocks char text[] = "\nvoid foo() {\n" " if (comment&&code) { ++codecomments_lines; }\n" " else if (comment) { ++comment_lines; }\n" " else if (code) { ++code_lines; }\n" "}\n"; char options[] = "keep-one-line-blocks, style=java"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, LinuxBrackets) { // test keep one line blocks char text[] = "\nvoid foo()\n" "{\n" " if (comment&&code) { ++codecomments_lines; }\n" " else if (comment) { ++comment_lines; }\n" " else if (code) { ++code_lines; }\n" "}\n"; char options[] = "keep-one-line-blocks, style=kr"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, RunInBrackets) { // test keep one line blocks char text[] = "\nvoid foo()\n" "{ if (comment&&code) { ++codecomments_lines; }\n" " else if (comment) { ++comment_lines; }\n" " else if (code) { ++code_lines; }\n" "}\n"; char options[] = "keep-one-line-blocks, style=horstmann"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakElseIf) { // test keep one line blocks and break elseifs char textIn[] = "\nvoid foo()\n" "{\n" " if (!j) { j=1; if (i) i=i-10; }\n" " if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n" " if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (!j) { j=1; if (i) i=i-10; }\n" " if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n" " if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n" "}\n"; char options[] = "keep-one-line-blocks, break-elseifs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, KeepOneLineStatementsAndBreakElseIf) { // test keep one line blocks and keep one line statements // with if statement and break elseifs char text[] = "\nvoid foo()\n" "{\n" " if (!j) { j=1; if (i) i=i-10; }\n" " if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n" " if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n" "}\n"; char options[] = "keep-one-line-blocks, keep-one-line-statements, break-elseifs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakBlocks1) { // test keep one line blocks and break blocks // should NOT break the block char text[] = "\nvoid foo()\n" "{\n" " { SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return; }\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-blocks, break-blocks=all"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakBlocks2) { // test keep one line blocks and break blocks // should NOT break the block char text[] = "\nvoid foo()\n" "{\n" " { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-blocks, break-blocks=all"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakBlocks3) { // test keep one line blocks and break blocks // should NOT break the one-line block // should break the other IF block char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n" " CalculatePositions();\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n" "\n" " CalculatePositions();\n" "}"; char options[] = "keep-one-line-blocks, break-blocks=all"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, MultipleBrackets) { // test keep one line blocks with multiple brackets char text[] = "\npublic class FooClass\n" "{\n" " public string FooName { get { return Foo; } set { Foo = value; } }\n" "\n" " public event EventHandler Cancelled { add { } remove { } }\n" "}\n"; char options[] = "keep-one-line-blocks, mode=cs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, Sans1) { // test without keep one line blocks // should not break {} when break brackets char text[] = "\nclass JipeConsole\n" "{\n" " public JipeConsole(Jipe parent)\n" " {\n" " jipeConsole.addKeyListener(new KeyListener()\n" " {\n" " public void keyReleased(KeyEvent e) {}\n" " public void keyTyped(KeyEvent e) {}\n" " });\n" " }\n" "}\n"; char options[] = "style=allman, mode=java"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, Sans2) { // test without keep one line blocks // test attach bracket inside comment on single line block char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) // comment\n" " { return false; }\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) { // comment\n" " return false;\n" " }\n" "}\n"; char options[] = "style=kr"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, SansMultipleBrackets) { // test without keep one line blocks with multiple brackets char textIn[] = "\npublic class FooClass\n" "{\n" " public string FooName { get { return Foo; } set { Foo = value; } }\n" "\n" " public event EventHandler Cancelled { add { } remove { } }\n" "}\n"; char text[] = "\npublic class FooClass\n" "{\n" " public string FooName {\n" " get {\n" " return Foo;\n" " }\n" " set {\n" " Foo = value;\n" " }\n" " }\n" "\n" " public event EventHandler Cancelled {\n" " add { } remove { }\n" " }\n" "}\n"; char options[] = "mode=cs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, NoneRunIn) { // test none brackets with keep one line blocks and run-in // should not indent the run-in char text[] = "\nvoid foo()\n" "{ if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, RunInRunIn) { // test run-in brackets with keep one line blocks and run-in // should not indent the run-in char text[] = "\nvoid foo()\n" "{ if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks, style=horstmann"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, NoneClosingHeader) { // test keep one line blocks followed by a closing header // should not attach header to the one line statement char text[] = "\nvoid foo() {\n" " if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, BreakClosingHeader) { // test keep one line blocks followed by a closing header // should not attach header to the one line statement char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks, style=allman"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, AttachClosingHeader) { // test keep one line blocks followed by a closing header // should not attach header to the one line statement char text[] = "\nvoid foo() {\n" " if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks, style=java"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, LinuxClosingHeader) { // test keep one line blocks followed by a closing header // should not attach header to the one line statement char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " {/*ok*/;}\n" " else {bar();}\n" "}\n"; char options[] = "keep-one-line-blocks, style=kr"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentSwitchBlock) { // test one-line blocks with switch blocks char text[] = "\nvoid Foo(int fooBar)\n" "{\n" " switch (fooBar)\n" " {\n" " case 1:\n" " fooBar = 1;\n" " break;\n" " case 2:\n" " { fooBar = 2; }\n" " break;\n" " default:\n" " { break; }\n" " }\n" " int bar = true;\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentSwitchBlock_IndentSwitches) { // test one-line blocks with indented switch blocks char text[] = "\nvoid Foo(int fooBar)\n" "{\n" " switch (fooBar)\n" " {\n" " case 1:\n" " fooBar = 1;\n" " break;\n" " case 2:\n" " { fooBar = 2; }\n" " break;\n" " default:\n" " { break; }\n" " }\n" " int bar = true;\n" "}\n"; char options[] = "keep-one-line-blocks, indent-switches"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentAfterHeader) { // test one line blocks indentation following a header char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " if (isFoo)\n" " { bar(); }\n" " else\n" " { anotherBar(); }\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentAfterHeaderSansBrackets) { // Test one line blocks indentation following a header // when the header does not contain brackets. char text[] = "\nvoid Foo(bool isFoo)\n" "{\n" " if (isBar1)\n" " if (isBar2)\n" " { return true; }\n" "\n" " if (isBar1)\n" " if (isBar2) { return true; }\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentSansHeader) { // test one line blocks indentation without a header char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " bar()\n" " { anotherBar(); }\n" "}\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, IndentWithConstMethod) { // Test one line blocks indentation following a header // when the header does not contain brackets. char text[] = "\nclass FooClass\n" "{\n" " virtual bool foo() const\n" " { return false; }\n" "};\n"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, WithAccessModifier) { // A one line block with an access modifier should not break after the modifier. char text[] = "\ntemplate<typename T>\n" "struct RunHelper<T> { public: int Run(TestCases<T>&) { return 0; } };"; char options[] = "keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(KeepOneLineBlocks, WithAccessModifierSans) { // A one line block with an access modifier should break if keep is NOT used. char textIn[] = "\ntemplate<typename T>\n" "struct RunHelper<T> { public: int Run(TestCases<T>&) { return 0; } };"; char text[] = "\ntemplate<typename T>\n" "struct RunHelper<T> {\n" "public:\n" " int Run(TestCases<T>&) {\n" " return 0;\n" " }\n" "};"; char options[] = ""; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Add Brackets //------------------------------------------------------------------------- TEST(AddBrackets, LongOption) { // test add brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, ShortOption) { // test add brackets short option char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" "}\n"; char options[] = "-j"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, All) { // test add brackets for all headers char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "\n" " for (int i = 0; i <= 12; ++i)\n" " bar &= ::FooBar();\n" "\n" " while (isFoo)\n" " bar();\n" "\n" " do\n" " bar();\n" " while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" "\n" " if (isFoo()) {\n" " return false;\n" " }\n" " else {\n" " return true;\n" " }\n" "\n" " for (int i = 0; i <= 12; ++i) {\n" " bar &= ::FooBar();\n" " }\n" "\n" " while (isFoo) {\n" " bar();\n" " }\n" "\n" " do {\n" " bar();\n" " }\n" " while (isFoo);\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, ElseIf) { // test add brackets for "else if" statements char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" " else if (isFoo()) {\n" " return false;\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, SemiFollows) { // test add brackets when a semi-colon follows the statement char textIn[] = "\nvoid foo()\n" "{\n" " if (a == 0) ; func1(); i++;\n" " while (isFoo) // comment\n" " ;\n" " while (isFoo); // comment\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (a == 0) ;\n" " func1();\n" " i++;\n" " while (isFoo) // comment\n" " ;\n" " while (isFoo); // comment\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Sharp) { // test add brackets to C# headers // 'delegate' statement contains brackets char textIn[] = "\nvoid Foo()\n" "{\n" " foreach (int i in fibarray)\n" " System.Console.WriteLine(i);\n" "\n" " if (isFoo)\n" " bar(delegate { fooBar* = null; });\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " foreach (int i in fibarray) {\n" " System.Console.WriteLine(i);\n" " }\n" "\n" " if (isFoo)\n" " bar(delegate {\n" " fooBar* = null;\n" " });\n" "}\n"; char options[] = "add-brackets, mode=cs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, KeepOneLiners) { // add brackets with keep one liners // should break the added brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "\n" " for (int i = 0; i <= 12; ++i)\n" " bar &= ::FooBar();\n" "\n" " while (isFoo)\n" " bar();\n" "\n" " do\n" " bar();\n" " while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" "\n" " if (isFoo()) {\n" " return false;\n" " }\n" " else {\n" " return true;\n" " }\n" "\n" " for (int i = 0; i <= 12; ++i) {\n" " bar &= ::FooBar();\n" " }\n" "\n" " while (isFoo) {\n" " bar();\n" " }\n" "\n" " do {\n" " bar();\n" " }\n" " while (isFoo);\n" "}\n"; char options[] = "add-brackets, keep-one-line-blocks, keep-one-line-statements"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, SingleLine) { // add brackets to one line statements // should break the statements char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) return false;\n" "\n" " if (isFoo()) return false; else return true;\n" "\n" " for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n" "\n" " while (isFoo) bar();\n" "\n" " do bar(); while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " }\n" "\n" " if (isFoo()) {\n" " return false;\n" " }\n" " else {\n" " return true;\n" " }\n" "\n" " for (int i = 0; i <= 12; ++i) {\n" " bar &= ::FooBar();\n" " }\n" "\n" " while (isFoo) {\n" " bar();\n" " }\n" "\n" " do {\n" " bar();\n" " }\n" " while (isFoo);\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, SingleLineKeepOneLiners) { // add brackets to one line statements with keep one liners // should keep one line blocks with added brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) return false;\n" "\n" " if (isFoo()) return false; else return true;\n" "\n" " for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n" "\n" " while (isFoo) bar();\n" "\n" " do bar(); while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) { return false; }\n" "\n" " if (isFoo()) { return false; } else { return true; }\n" "\n" " for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n" "\n" " while (isFoo) { bar(); }\n" "\n" " do { bar(); } while (isFoo);\n" "}\n"; char options[] = "add-brackets, keep-one-line-blocks, keep-one-line-statements"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Break) { // test add brackets for broken brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " {\n" " return false;\n" " }\n" " else\n" " {\n" " return true;\n" " }\n" "}\n"; char options[] = "add-brackets, style=allman"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Attach) { // test add brackets for attached brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) {\n" " return false;\n" " } else {\n" " return true;\n" " }\n" "}\n"; char options[] = "add-brackets, style=kr"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, RunIn) { // test add brackets for run-in brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{ if (isFoo())\n" " { return false;\n" " }\n" " else\n" " { return true;\n" " }\n" "}\n"; char options[] = "add-brackets, style=horstmann"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, ExtraSpaces) { // extra spaces should be removed char textIn[] = "\nvoid foo()\n" "{\n" " if ( str ) (*str) += \"<?xml \";\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if ( str ) {\n" " (*str) += \"<?xml \";\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, ElseParen) { // else statement with following paren char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) break;\n" " else (numBar)--;\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) {\n" " break;\n" " }\n" " else {\n" " (numBar)--;\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Quote) { // must bypass quote with semi-colons and escaped quote marks char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = '\\'';\n" " if (isFoo) bar = '\\\\';\n" " if (isBar) bar = \";;version=\";\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) {\n" " bar = '\\'';\n" " }\n" " if (isFoo) {\n" " bar = '\\\\';\n" " }\n" " if (isBar) {\n" " bar = \";;version=\";\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, QuoteSans) { // must bypass multi-line quote char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " char* bar = \"one \\\n" " two \\\n" " three\";\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Comment) { // must bypass comment before a semi-colon // the last statement should be bracketed char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = // comment\n" " foo2;\n" " if (isFoo) bar = /* comment */\n" " foo2;\n" " if (isFoo) bar = /* comment\n" " comment */\n" " foo2;\n" " if (isFoo) bar = /* comment */ foo2;\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = // comment\n" " foo2;\n" " if (isFoo) bar = /* comment */\n" " foo2;\n" " if (isFoo) bar = /* comment\n" " comment */\n" " foo2;\n" " if (isFoo) {\n" " bar = /* comment */ foo2;\n" " }\n" "}\n"; char options[] = "add-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddBrackets, Sans) { // brackets should be added to specified headers only char text[] = "\npublic unsafe int foo()\n" "{\n" " int readCount;\n" " fixed(byte* pBuffer = buffer)\n" " readCount = ReadMemory(size);\n" "}\n"; char options[] = "add-brackets, mode=cs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Add One Line Brackets // Implies keep-one-line-blocks //------------------------------------------------------------------------- TEST(AddOneLineBrackets, LongOption) { // test add one line brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, ShortOption) { // test add one line brackets short option char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" "}\n"; char options[] = "-J"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, All) { // test add one line brackets for all headers char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" "\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "\n" " for (int i = 0; i <= 12; ++i)\n" " bar &= ::FooBar();\n" "\n" " while (isFoo)\n" " bar();\n" "\n" " do\n" " bar();\n" " while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" "\n" " if (isFoo())\n" " { return false; }\n" " else\n" " { return true; }\n" "\n" " for (int i = 0; i <= 12; ++i)\n" " { bar &= ::FooBar(); }\n" "\n" " while (isFoo)\n" " { bar(); }\n" "\n" " do\n" " { bar(); }\n" " while (isFoo);\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, ElseIf) { // test add one line brackets for "else if" statements char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else if (isFoo())\n" " return false;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" " else if (isFoo())\n" " { return false; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, SemiFollows) { // test add brackets when a semi-colon follows the statement char textIn[] = "\nvoid foo()\n" "{\n" " if (a == 0) ; func1(); i++;\n" " while (isFoo) // comment\n" " ;\n" " while (isFoo); // comment\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (a == 0) ;\n" " func1();\n" " i++;\n" " while (isFoo) // comment\n" " ;\n" " while (isFoo); // comment\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Sharp) { // test add one line brackets to C# headers // 'delegate' statement contains brackets char textIn[] = "\nvoid Foo()\n" "{\n" " foreach (int i in fibarray)\n" " System.Console.WriteLine(i);\n" "\n" " if (isFoo)\n" " bar(delegate { fooBar* = null; });\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " foreach (int i in fibarray)\n" " { System.Console.WriteLine(i); }\n" "\n" " if (isFoo)\n" " bar(delegate { fooBar* = null; });\n" "}\n"; char options[] = "add-one-line-brackets, mode=cs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, SingleLine) { // add one line brackets to one line statements // should keep the one line statements char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) return false;\n" "\n" " if (isFoo()) return false; else return true;\n" "\n" " for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n" "\n" " while (isFoo) bar();\n" "\n" " do bar(); while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) { return false; }\n" "\n" " if (isFoo()) { return false; }\n" " else { return true; }\n" "\n" " for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n" "\n" " while (isFoo) { bar(); }\n" "\n" " do { bar(); }\n" " while (isFoo);\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, SingleLineKeepOneLiners) { // add one line brackets to one line statements with keep one liners // should keep the one liners (keep blocks is implied) char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) return false;\n" "\n" " if (isFoo()) return false; else return true;\n" "\n" " for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n" "\n" " while (isFoo) bar();\n" "\n" " do bar(); while (isFoo);\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo()) { return false; }\n" "\n" " if (isFoo()) { return false; } else { return true; }\n" "\n" " for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n" "\n" " while (isFoo) { bar(); }\n" "\n" " do { bar(); } while (isFoo);\n" "}\n"; char options[] = "add-one-line-brackets, keep-one-line-statements"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Break) { // test add one line brackets for broken brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" " else\n" " { return true; }\n" "}\n"; char options[] = "add-one-line-brackets, style=allman"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Attach) { // test add one line brackets for attached brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " { return false; }\n" " else\n" " { return true; }\n" "}\n"; char options[] = "add-one-line-brackets, style=kr"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, RunIn) { // test add one line brackets for run-in brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo())\n" " return false;\n" " else\n" " return true;\n" "}\n"; char text[] = "\nvoid Foo()\n" "{ if (isFoo())\n" " { return false; }\n" " else\n" " { return true; }\n" "}\n"; char options[] = "add-one-line-brackets, style=horstmann"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, ExtraSpaces) { // extra spaces should not be removed char textIn[] = "\nvoid foo()\n" "{\n" " if ( str ) (*str) += \"<?xml \";\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if ( str ) { (*str) += \"<?xml \"; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, ElseParen) { // else statement with following paren char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) break;\n" " else (numBar)--;\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) { break; }\n" " else { (numBar)--; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Quote) { // must bypass quote with semi-colons and escaped quote marks char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = '\\'';\n" " if (isFoo) bar = '\\\\';\n" " if (isBar) bar = \";;version=\";\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) { bar = '\\''; }\n" " if (isFoo) { bar = '\\\\'; }\n" " if (isBar) { bar = \";;version=\"; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, QuoteSans) { // must bypass multi-line quote char text[] = "\nvoid foo()\n" "{\n" " if (isFoo)\n" " char* bar = \"one \\\n" " two \\\n" " three\";\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Comment) { // must bypass comment before a semi-colon // the last statement should be bracketed char textIn[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = // comment\n" " foo2;\n" " if (isFoo) bar = /* comment */\n" " foo2;\n" " if (isFoo) bar = /* comment\n" " comment */\n" " foo2;\n" " if (isFoo) bar = /* comment */ foo2;\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " if (isFoo) bar = // comment\n" " foo2;\n" " if (isFoo) bar = /* comment */\n" " foo2;\n" " if (isFoo) bar = /* comment\n" " comment */\n" " foo2;\n" " if (isFoo) { bar = /* comment */ foo2; }\n" "}\n"; char options[] = "add-one-line-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(AddOneLineBrackets, Sans) { // brackets should be added to specified headers only char text[] = "\npublic unsafe int foo()\n" "{\n" " int readCount;\n" " fixed(byte* pBuffer = buffer)\n" " readCount = ReadMemory(size);\n" "}\n"; char options[] = "add-one-line-brackets, mode=cs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Remove Brackets //------------------------------------------------------------------------- TEST(RemoveBrackets, LongOption) { // test remove brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, ShortOption) { // test remove brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "}"; char options[] = "-xj"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, WithEmptyLine1) { // test with a preceding empty line char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" "\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " \n" " bar3();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" "\n" " bar2();\n" " else if (isFoo3)\n" "\n" " bar3();\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, WithEmptyLine2) { // test with a following empty line char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" "\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " \n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" "\n" " else if (isFoo3)\n" " bar3();\n" "\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, WithEmptyLine3) { // test attached brackets with a empty lines char textIn[] = "\nvoid Foo()\n" "{\n" " if (IsUsingTree()) {\n" "\n" " m_pTree->Delete();\n" "\n" " }\n" " else {\n" "\n" " m_pCommands->Clear();\n" " m_pCategories->Clear();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (IsUsingTree())\n" "\n" " m_pTree->Delete();\n" "\n" " else {\n" "\n" " m_pCommands->Clear();\n" " m_pCategories->Clear();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(RemoveBrackets, Sans) { // don't remove if not a single statement char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " bar2a();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " bar3a();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OneLineBlock1) { // test with a one line block and keep-one-line-blocks // should NOT break the one-line block char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " { bar2(); }\n" " else if (isFoo3) { bar3(); }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3) bar3();\n" "}"; char options[] = "remove-brackets, keep-one-line-blocks"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OneLineBlockSans1) { // test with a one line block and NOT keep-one-line-blocks // should break the one-line block char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " { bar2(); }\n" " else if (isFoo3) { bar3(); }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OneLineBlockSans2) { // test with a one line block to NOT remove brackets // with keep-one-line-blocks char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " { bar2(); bar4(); }\n" " else if (isFoo3) { bar3(); bar4(); }\n" "}"; char options[] = "remove-brackets, keep-one-line-blocks"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OneLineBlockSans3) { // test with a one line block to NOT remove brackets // without keep-one-line-blocks char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " { bar2(); bar4(); }\n" " else if (isFoo3) { bar3(); bar4(); }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " bar4();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " bar4();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BreakBlocks1) { // test remove brackets with break blocks char textIn[] = "\nvoid Foo()\n" "{\n" " bar5();\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" " bar6();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " bar5();\n" "\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "\n" " bar6();\n" "}"; char options[] = "remove-brackets, break-blocks"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BreakBlocks2) { // test remove brackets with break all blocks char textIn[] = "\nvoid Foo()\n" "{\n" " bar5();\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" " bar6();\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " bar5();\n" "\n" " if (isFoo2)\n" " bar2();\n" "\n" " else if (isFoo3)\n" " bar3();\n" "\n" " bar6();\n" "}"; char options[] = "remove-brackets, break-blocks=all"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, Comment1) { // remove one-line brackets with a comment char textIn[] = "\nvoid foo()\n" "{\n" " if (keycode == WXK_RETURN)\n" " { myidx = 0; } // Edit\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " if (keycode == WXK_RETURN)\n" " myidx = 0; // Edit\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(RemoveBrackets, Comment2) { // remove one-line brackets with a comment char textIn[] = "\nvoid foo()\n" "{\n" " if ( (target = Convert()) )\n" " {;}//ok\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " if ( (target = Convert()) )\n" " ; //ok\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(RemoveBrackets, Comment3) { // remove brackets with a comment following closing bracket char textIn[] = "\nvoid foo()\n" "{\n" " for(size_t i = 0; i < Count; ++i)\n" " {\n" " AppendToLog(Output[i]);\n" " } // end for : idx: i\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " for(size_t i = 0; i < Count; ++i)\n" " AppendToLog(Output[i]);\n" " // end for : idx: i\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(RemoveBrackets, Comment4) { // remove attached bracket with a comment char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo) { // comment\n" " bar();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo) // comment\n" " bar();\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete[] textOut; } TEST(RemoveBrackets, CommentSans1) { // don't remove if a preceding comment char text[] = "\nvoid Foo()\n" "{\n" " // comment" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " /* comment\n" " comment */\n" " bar3();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, CommentSans2) { // don't remove if a preceding column 1 comment char text[] = "\nvoid Foo() {\n" " if(result)\n" " {\n" "// Manager::Get()->GetLogManager();\n" " }\n" " else\n" " {\n" "// Manager::Get()->GetLogManager();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, FollowingHeaderSans) { // don't remove if a following header char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " {\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo1)\n" " {\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, AddBracketsSans) { // should NOT remove brackets if add brackets is also requested char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char options[] = "remove-brackets, add-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, AddOneLineBracketsSans) { // should NOT remove brackets if add one line brackets is also requested char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " }\n" " else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char options[] = "remove-brackets, add-one-line-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OtherHeaders) { // test remove brackets with other headers char textIn[] = "\nvoid Foo()\n" "{\n" " for (i = 0; i < 10; i++)\n" " {\n" " bar2();\n" " }\n" " while (i > 0 && i < 10)\n" " {\n" " bar3();\n" " }\n" " do {\n" // NOT removed from do-while " bar4();\n" " } while (int x < 9);\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " for (i = 0; i < 10; i++)\n" " bar2();\n" " while (i > 0 && i < 10)\n" " bar3();\n" " do {\n" // NOT removed from do-while " bar4();\n" " } while (int x < 9);\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, SharpOtherHeaders) { // test remove brackets with other C# headers char textIn[] = "\nprivate void Foo()\n" "{\n" " foreach (T x in list)\n" " {\n" " foo = bar;\n" " }\n" "}"; char text[] = "\nprivate void Foo()\n" "{\n" " foreach (T x in list)\n" " foo = bar;\n" "}"; char options[] = "remove-brackets, mode=cs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, OTBSSans) { // should NOT remove brackets if "One True Brace Style" is requested char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2) {\n" " bar2();\n" " } else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char options[] = "remove-brackets, style=otbs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BreakClosingBrackets) { // test remove brackets with break closing brackets char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " } else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "}"; char options[] = "remove-brackets, break-closing-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, UnbrokenElse) { // test remove brackets with a unbroken "else if" statement char textIn[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " {\n" " bar2();\n" " } else if (isFoo3) {\n" " bar3();\n" " }\n" "}"; char text[] = "\nvoid Foo()\n" "{\n" " if (isFoo2)\n" " bar2();\n" " else if (isFoo3)\n" " bar3();\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, Preprocessor) { // test remove brackets with a preprocessor directive // the brackets should NOT be removed char text[] = "\nvoid Foo() {\n" "#define if(_RET_SUCCEED(exp)) { result = (exp); }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BracketInQuote) { // test remove brackets within a quote // should not remove the bracket in the quotes char textIn[] = "\nprivate void Foo() {\n" " if (closingBrackets > 0) {\n" " wrapper.Append(new string('}', closingBrackets));\n" " }\n" "}"; char text[] = "\nprivate void Foo() {\n" " if (closingBrackets > 0)\n" " wrapper.Append(new string('}', closingBrackets));\n" "}"; char options[] = "remove-brackets, mode=cs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BracketInComment1) { // test remove with brackets within a line comment // should not remove the brackets char text[] = "\nprivate void Foo() {\n" " if (closingBrackets > 0) {\n" " wrapper.Append(closingBrackets); // }\n" " }\n" "}"; char options[] = "remove-brackets, mode=cs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, BracketInComment2) { // test remove with brackets within a comment // should not remove the brackets char text[] = "\nprivate void Foo() {\n" " if (closingBrackets > 0) {\n" " wrapper.Append(closingBrackets); /* } */\n" " }\n" "}"; char options[] = "remove-brackets, mode=cs"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveBrackets, HorstmannBracketWithComment) { // test remove horstmann bracket with a comment // should not remove the brackets char text[] = "\nvoid Foo()\n" "{ if (isFoo)\n" " { // comment\n" " bar();\n" " }\n" "}"; char options[] = "remove-brackets"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Convert Tabs //------------------------------------------------------------------------- TEST(ConvertTabs, LongOption) { // test convert tabs char textIn[] = "\nstatic FooBar foo1[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo2[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo3[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo4[] =\n" "{\n" " { 100, 0, 9 },\n" " { 200, 0, 9 },\n" " { 300, 0, 9 },\n" " { 400, 0, 9 },\n" "};\n"; char text[] = "\nstatic FooBar foo1[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo2[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo3[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar foo4[] =\n" "{\n" " { 100, 0, 9 },\n" " { 200, 0, 9 },\n" " { 300, 0, 9 },\n" " { 400, 0, 9 },\n" "};\n"; char options[] = "convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, ShortOption) { // test convert tabs short option char textIn[] = "\nstatic FooBar foo[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar fooTab[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "}\n"; char text[] = "\nstatic FooBar foo[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "};\n" "\n" "static FooBar fooTab[] =\n" "{\n" " { 10000, 0, 9 },\n" " { 20000, 0, 9 },\n" " { 30000, 0, 9 },\n" " { 40000, 0, 9 },\n" "}\n"; char options[] = "-c"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, CommentsPreprocessorQuotes) { // convert comments, line comments, preprocessor // do NOT convert quotes char textIn[] = "\nvoid foo()\n" "{\n" " /*\n" " * comment comment\n" " * comment comment\n" " * comment comment\n" " * comment comment\n" " */\n" "\n" "/*\n" " commentedCode();\n" "*/\n" "\n" " // line comment\n" " // line comment\n" " // line comment\n" " // line comment\n" "\n" "#ifdef foo\n" " #error is foo\n" " #endif // end of if\n" "\n" " char* quote =\n" " \"this is a quote \\\n" " quote continuation \\\n" " quote continuation\";\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " /*\n" " * comment comment\n" " * comment comment\n" " * comment comment\n" " * comment comment\n" " */\n" "\n" " /*\n" " commentedCode();\n" " */\n" "\n" " // line comment\n" " // line comment\n" " // line comment\n" " // line comment\n" "\n" "#ifdef foo\n" "#error is foo\n" "#endif // end of if\n" "\n" " char* quote =\n" " \"this is a quote \\\n" " quote continuation \\\n" " quote continuation\";\n" "}\n"; char options[] = "convert-tabs, indent=tab"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, Comments1) { // test convert-tabs with comments char textIn[] = "\nvoid foo()\n" "{\n" " /* comment1\n" " comment2\n" " */\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " /* comment1\n" " comment2\n" " */\n" "}\n"; char options[] = "convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, Comments2) { // test convert-tabs with comment continuation char textIn[] = "\nvoid foo()\n" "{\n" " int bar1; /* comment1 */\n" " int bar2; /* comment2\n" " comment3 */\n" " int bar3; /* comment3 */\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " int bar1; /* comment1 */\n" " int bar2; /* comment2\n" " comment3 */\n" " int bar3; /* comment3 */\n" "}\n"; char options[] = "convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, Comments3) { // test convert-tabs with line comments and tabbed output // should NOT convert the leading tabs in a non-indent comment char textIn[] = "\nvoid foo()\n" "{\n" "// comment1 comment1a\n" " // comment2 comment2a\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" "// comment1 comment1a\n" "// comment2 comment2a\n" "}\n"; char options[] = "convert-tabs, --indent=tab"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, Misc1) { // test convert-tabs with unpad-paren and pad-paren-in // should replace the tab after the opening paren char textIn[] = "\nvoid foo( bool isFoo )\n" "{\n" " if( isFoo )\n" " bar;\n" "}\n"; char text[] = "\nvoid foo( bool isFoo )\n" "{\n" " if( isFoo )\n" " bar;\n" "}\n"; char options[] = "convert-tabs, unpad-paren, pad-paren-in"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, Misc2) { // verify that tabs are still present within quotes // should NOT have been replaced when AStyle was run char text[] = "\nvoid foo()\n" "{\n" " char* quote = \"this is a quote \";\n" "}\n"; // just check for the tab characters EXPECT_EQ('\t', text[37]); EXPECT_EQ('\t', text[40]); EXPECT_EQ('\t', text[42]); } TEST(ConvertTabs, ForceTabX1) { // test convert-tabs in indent=force-tab-x char textIn[] = "\nvoid foo()\n" "{\n" " int bar1; // comment1\n" " int bar111; /* comment2 */\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " int bar1; // comment1\n" " int bar111; /* comment2 */\n" "}\n"; char options[] = "indent=force-tab-x, convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, ForceTabX2) { // test convert-tabs in indent=force-tab-x with comment continuation char textIn[] = "\nvoid foo()\n" "{\n" " int bar1; /* comment1 */\n" " int bar2; /* comment2\n" " comment3 */\n" " int bar3; /* comment3 */\n" "}\n"; char text[] = "\nvoid foo()\n" "{\n" " int bar1; /* comment1 */\n" " int bar2; /* comment2\n" " comment3 */\n" " int bar3; /* comment3 */\n" "}\n"; char options[] = "indent=force-tab-x, convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(ConvertTabs, PreprocessorIndent) { // Test convert-tabs in a preprocessor indent. // NOTE: The defines do NOT have a #endif closing the define. // This will cause a memory leak if the activeBeautifierStack and // waitingBeautifierStack are not deleted properly in ASBeautifier. char textIn[] = "\n#if (! defined (yyoverflow) \\\n" " && (! defined (__cplusplus) \\\n" "\t || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))\n"; char text[] = "\n#if (! defined (yyoverflow) \\\n" " && (! defined (__cplusplus) \\\n" " || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))\n"; char options[] = "indent-preproc-define, convert-tabs"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Close Templates Tabs //------------------------------------------------------------------------- TEST(CloseTemplates, LongOption) { // Test close-templates long option. char textIn[] = "\nvoid foo()\n" "{\n" " vector<string<int> > vec\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " vector<string<int>> vec\n" "}"; char options[] = "close-templates"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(CloseTemplates, ShortOption) { // Test close-templates short option. char textIn[] = "\nvoid foo()\n" "{\n" " vector<string<int> > vec;\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " vector<string<int>> vec;\n" "}"; char options[] = "-xy"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(CloseTemplates, Sans) { // Templates should NOT be closed without the option. char text[] = "\nvoid foo()\n" "{\n" " vector<string<int> > vec;\n" "}"; char options[] = ""; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(CloseTemplates, Padded) { // Test close-templates with padding inside the templates. char textIn[] = "\nvoid foo()\n" "{\n" " vector< string< int > > vec;\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " vector<string<int>> vec;\n" "}"; char options[] = "close-templates"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //------------------------------------------------------------------------- // AStyle Remove Comment Prefix //------------------------------------------------------------------------- TEST(RemoveCommentPrefix, LongOption) { // Test remove-comment-prefix long option. char textIn[] = "\n/* comment\n" " *\n" " */"; char text[] = "\n/* comment\n" "\n" "*/"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, ShortOption) { // Test remove-comment-prefix short option. char textIn[] = "\n/* comment\n" " *\n" " */"; char text[] = "\n/* comment\n" "\n" "*/"; char options[] = "-xp"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, SansMultiLine) { // Test remove-comment-prefix with single-line comments. // They should not be changed. char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " /* comment3 */\n" " /*xcomment4x*/\n" "}"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format1) { // Test remove-comment-prefix indentation. char textIn[] = "\nvoid foo(bool isFoo)\n" "{\n" " /* comment1\n" " *\n" " */\n" " if(isFoo) {\n" " /* comment2\n" " *\n" " */\n" " fooBar();\n" " }\n" "}"; char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " /* comment1\n" "\n" " */\n" " if(isFoo) {\n" " /* comment2\n" "\n" " */\n" " fooBar();\n" " }\n" "}"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format2) { // Test remove-comment-prefix option. // Beginning and ending '*' should be removed. // Text should be indented one indent. // The all '*' lines should not change char textIn[] = "\n" "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" " * This software is distributed WITHOUT ANY WARRANTY, even the implied *\n" " * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n" " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */"; char text[] = "\n" "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" " This software is distributed WITHOUT ANY WARRANTY, even the implied\n" " warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format3) { // Test remove-comment-prefix option without '*'. // Text should be indented one indent. char textIn[] = "\nvoid foo()\n" "{\n" " /* This file is a part of Artistic Style - an indentation and\n" " reformatting tool for C, C++, C# and Java source files.\n" " */\n" "}"; char text[] = "\nvoid foo()\n" "{\n" " /* This file is a part of Artistic Style - an indentation and\n" " reformatting tool for C, C++, C# and Java source files.\n" " */\n" "}"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format4) { // Test remove-comment-prefix option. // Beginning '*' should be removed. // Text should NOT be indented - it is greater than one indent. char textIn[] = "\n" "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" " * Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>\n" " * Copyright (C) 1998-2002 by Tal Davidson\n" " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" " */"; char text[] = "\n" "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" " Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>\n" " Copyright (C) 1998-2002 by Tal Davidson\n" " * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" "*/"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format5) { // Test remove-comment-prefix option. // Beginning '*' should be removed. // Text with tabs should NOT be indented - it is greater than one indent. // The '*' is ERASED and not replaced with a space. char textIn[] = "\n" "/*\n" " *\ttabbed comment\n" " */"; char text[] = "\n" "/*\n" " \ttabbed comment\n" "*/"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format6) { // Test remove-comment-prefix option. // Beginning '*' should be removed. // The tabbed text should be properly indented. // The '/*!' should not be separated. char textIn[] = "\n" "/*! \\brief Update manifest.xml with the latest version string.\n" " * \\author Gary Harris\n" " * \\date 03/03/10\n" " * \\return void\n" " */"; char text[] = "\n" "/*! \\brief Update manifest.xml with the latest version string.\n" " \\author Gary Harris\n" " \\date 03/03/10\n" " \\return void\n" "*/"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, Format7) { // Test remove-comment-prefix option. // Beginning '*' should be removed. // The text should be properly indented. // The '/**' should not be separated. char textIn[] = "\n" "/** @brief A file editor\n" " *\n" " * @param use If true tooltips are allowed\n" " */"; char text[] = "\n" "/** @brief A file editor\n" "\n" " @param use If true tooltips are allowed\n" "*/"; char options[] = "remove-comment-prefix, indent=spaces=6"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } TEST(RemoveCommentPrefix, CommentedCode1) { // Test remove-comment-prefix option with commented text. // The tabbed alignment should be maintained. char textIn[] = "\nvoid foo(bool isFoo)\n" "{\n" " /*if (client == NULL) {\n" " //int found = -1;\n" " for (int i=0; i < getCount(); i++)\n" " if ((Item(i)) == event.GetEventObject())\n" " client = m_arrAttachedWnd.Item(i);\n" " }*/\n" "}"; char text[] = "\nvoid foo(bool isFoo)\n" "{\n" " /* if (client == NULL) {\n" " //int found = -1;\n" " for (int i=0; i < getCount(); i++)\n" " if ((Item(i)) == event.GetEventObject())\n" " client = m_arrAttachedWnd.Item(i);\n" " }*/\n" "}"; char options[] = "remove-comment-prefix"; char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc); EXPECT_STREQ(text, textOut); delete [] textOut; } //---------------------------------------------------------------------------- } // namespace
27.170892
117
0.480276
01cb6824755f79a0a0032f5d4891e44773a82ac8
2,752
cc
C++
device/fido/hid/fido_hid_discovery.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/fido/hid/fido_hid_discovery.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/fido/hid/fido_hid_discovery.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/fido/hid/fido_hid_discovery.h" #include <utility> #include "base/bind.h" #include "base/no_destructor.h" #include "device/fido/hid/fido_hid_device.h" namespace device { namespace { FidoHidDiscovery::HidManagerBinder& GetHidManagerBinder() { static base::NoDestructor<FidoHidDiscovery::HidManagerBinder> binder; return *binder; } } // namespace FidoHidDiscovery::FidoHidDiscovery() : FidoDeviceDiscovery(FidoTransportProtocol::kUsbHumanInterfaceDevice) { // TODO(piperc@): Give this constant a name. filter_.SetUsagePage(0xf1d0); } FidoHidDiscovery::~FidoHidDiscovery() = default; // static void FidoHidDiscovery::SetHidManagerBinder(HidManagerBinder binder) { GetHidManagerBinder() = std::move(binder); } void FidoHidDiscovery::StartInternal() { const auto& binder = GetHidManagerBinder(); if (!binder) return; binder.Run(hid_manager_.BindNewPipeAndPassReceiver()); hid_manager_->GetDevicesAndSetClient( receiver_.BindNewEndpointAndPassRemote(), base::BindOnce(&FidoHidDiscovery::OnGetDevices, weak_factory_.GetWeakPtr())); } void FidoHidDiscovery::DeviceAdded( device::mojom::HidDeviceInfoPtr device_info) { // The init packet header is the larger of the headers so we only compare // against it below. static_assert( kHidInitPacketHeaderSize >= kHidContinuationPacketHeaderSize, "init header is expected to be larger than continuation header"); // Ignore non-U2F devices. if (filter_.Matches(*device_info) && // Check that the supported report sizes are sufficient for at least one // byte of non-header data per report and not larger than our maximum // size. device_info->max_input_report_size > kHidInitPacketHeaderSize && device_info->max_input_report_size <= kHidMaxPacketSize && device_info->max_output_report_size > kHidInitPacketHeaderSize && device_info->max_output_report_size <= kHidMaxPacketSize) { AddDevice(std::make_unique<FidoHidDevice>(std::move(device_info), hid_manager_.get())); } } void FidoHidDiscovery::DeviceRemoved( device::mojom::HidDeviceInfoPtr device_info) { // Ignore non-U2F devices. if (filter_.Matches(*device_info)) { RemoveDevice(FidoHidDevice::GetIdForDevice(*device_info)); } } void FidoHidDiscovery::OnGetDevices( std::vector<device::mojom::HidDeviceInfoPtr> device_infos) { for (auto& device_info : device_infos) DeviceAdded(std::move(device_info)); NotifyDiscoveryStarted(true); } } // namespace device
31.272727
78
0.731831
01cce684c5c58f1a380917ec02e2f24139c17f69
1,274
cpp
C++
src/segment.cpp
drjod/construct
0199baf8b56735869b28ae526f78dcca117b2060
[ "BSD-3-Clause" ]
null
null
null
src/segment.cpp
drjod/construct
0199baf8b56735869b28ae526f78dcca117b2060
[ "BSD-3-Clause" ]
null
null
null
src/segment.cpp
drjod/construct
0199baf8b56735869b28ae526f78dcca117b2060
[ "BSD-3-Clause" ]
2
2020-03-23T13:08:11.000Z
2020-04-15T11:27:31.000Z
#include "segment.h" #include "configuration.h" #include "utilities.h" #include <math.h> namespace contra { Resistances Segment::set_resistances(Configuration* configuration) { return configuration->set_resistances(casing.get_D(), casing.get_lambda_g()); } void Segment::set_functions(Piping* piping) { Configuration* configuration = piping->get_configuration(); greeks = configuration->set_greeks(piping); const double dgz = greeks.get_gamma() * casing.get_L() / casing.get_N(); double gz = dgz; for(int i=0; i<casing.get_N(); ++i) { configuration->set_functions(f1[i], f2[i], f3[i], gz, greeks); //LOG("z: " << gz/greeks.get_gamma()); //LOG(" f1: " << f1[i]); //LOG(" f2: " << f2[i]); //LOG(" f3: " << f3[i]); gz += dgz; } } void Segment::calculate_temperatures(Configuration* configuration) { const int N = casing.get_N(); for(int i=1; i<N; ++i) // last node from sceleton { const double dz = casing.get_L() / N; T_in[i] = T_in[0] * f1[i-1] + T_out[0] * f2[i-1]; T_out[i] = -T_in[0] * f2[i-1] + T_out[0] * f3[i-1]; for(int j=0; j<i; ++j) { T_in[i] += configuration->F4(i*dz, j*dz, (j+1)*dz, greeks)*(T_s[j]+T_s[j+1])/2; T_out[i] -= configuration->F5(i*dz, j*dz, (j+1)*dz, greeks)*(T_s[j]+T_s[j+1])/2; } } } }
22.75
83
0.616954
01cfe3d0f5b6974abb9d2c5adde1650821f94fe1
642
hpp
C++
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
//===----------------------------------------------------------------------===// // GuinsooDB // // guinsoodb/parser/statement/vacuum_statement.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "guinsoodb/parser/parsed_expression.hpp" #include "guinsoodb/parser/sql_statement.hpp" #include "guinsoodb/parser/parsed_data/vacuum_info.hpp" namespace guinsoodb { class VacuumStatement : public SQLStatement { public: VacuumStatement(); unique_ptr<VacuumInfo> info; public: unique_ptr<SQLStatement> Copy() const override; }; } // namespace guinsoodb
22.928571
80
0.549844
01d14832780c7094cd947006b67ddbae23b4e18a
1,535
cpp
C++
src/testlibjsapi_gtkmm/label.cpp
RipcordSoftware/libjsapi
57369128d9da6eb84ff3b9c5b9791aee4ae34ce4
[ "MIT" ]
17
2015-04-21T13:24:22.000Z
2022-01-23T07:17:56.000Z
src/testlibjsapi_gtkmm/label.cpp
RipcordSoftware/libjsapi
57369128d9da6eb84ff3b9c5b9791aee4ae34ce4
[ "MIT" ]
31
2015-03-17T16:28:54.000Z
2018-06-17T02:02:10.000Z
src/testlibjsapi_gtkmm/label.cpp
RipcordSoftware/libjsapi
57369128d9da6eb84ff3b9c5b9791aee4ae34ce4
[ "MIT" ]
4
2015-11-16T15:31:24.000Z
2021-12-28T17:03:53.000Z
#include "label.h" #include <cstring> Label::Label(rs::jsapi::Context& cx, Gtk::Label* label) : cx_(cx), obj_(cx), label_(label), widget_(label, obj_) { auto functions = widget_.GetFunctions(); functions.emplace_back("setText", std::bind(&Label::SetText, this, std::placeholders::_1, std::placeholders::_2)); functions.emplace_back("getText", std::bind(&Label::GetText, this, std::placeholders::_1, std::placeholders::_2)); rs::jsapi::Object::Create(cx, { "value", "innerHTML" }, std::bind(&Label::GetCallback, this, std::placeholders::_1, std::placeholders::_2), std::bind(&Label::SetCallback, this, std::placeholders::_1, std::placeholders::_2), functions, std::bind(&Label::Finalizer, this), obj_); } void Label::GetCallback(const char* name, rs::jsapi::Value& value) { if (std::strcmp(name, "value") == 0 || std::strcmp(name, "innerHTML") == 0) { GetText({}, value); } } void Label::SetCallback(const char* name, const rs::jsapi::Value& value) { if (std::strcmp(name, "value") == 0 || std::strcmp(name, "innerHTML") == 0) { std::vector<rs::jsapi::Value> args; args.push_back(value); rs::jsapi::Value result(cx_); SetText(args, result); } } void Label::SetText(const std::vector<rs::jsapi::Value>& args, rs::jsapi::Value& result) { label_->set_text(args[0].ToString()); result = *this; } void Label::GetText(const std::vector<rs::jsapi::Value>& args, rs::jsapi::Value& result) { result = label_->get_text(); }
39.358974
118
0.633225
01d3ad3ae93b6588103d7dd8e00ec56f2386f769
159
hh
C++
Statement/MySQLStatement.hh
decouple/dbal
ea94dcb215d9693ab81d3be5394ff7448e254380
[ "MIT" ]
null
null
null
Statement/MySQLStatement.hh
decouple/dbal
ea94dcb215d9693ab81d3be5394ff7448e254380
[ "MIT" ]
null
null
null
Statement/MySQLStatement.hh
decouple/dbal
ea94dcb215d9693ab81d3be5394ff7448e254380
[ "MIT" ]
null
null
null
<?hh // strict use Decouple\Common\Contract\DB\Statement; interface MySQLStatement extends Statement { public function fetchColumn(int $column=0) : mixed; }
26.5
53
0.773585
01d409fe2a659c8b80e8da3affb79979ccebb12c
5,638
cpp
C++
src/bridge.cpp
dudpray0220/C-ProxyServer
40038726b988b21055b17af90b9142fcad2a213c
[ "Apache-2.0" ]
1
2021-11-29T08:11:43.000Z
2021-11-29T08:11:43.000Z
src/bridge.cpp
dudpray0220/C-ProxyServer
40038726b988b21055b17af90b9142fcad2a213c
[ "Apache-2.0" ]
null
null
null
src/bridge.cpp
dudpray0220/C-ProxyServer
40038726b988b21055b17af90b9142fcad2a213c
[ "Apache-2.0" ]
1
2021-12-01T04:45:55.000Z
2021-12-01T04:45:55.000Z
#include "../inc/bridge.hpp" // public namespace yhbae { bridge::bridge(boost::asio::io_service &ios) // 생성자 : downstream_socket_(ios), upstream_socket_(ios) // 멤버변수 down, upstream_socket에 파라미터를 연결해줌. {}; bridge::socket_type &yhbae::bridge::downstream_socket() // &를 붙이면 주소가 된다. 멤버함수(Method), socket_type은 return값의 타입이다. { // Client socket return downstream_socket_; }; bridge::socket_type &yhbae::bridge::upstream_socket() { // Remote server socket return upstream_socket_; }; // start 함수 void bridge::start(const std::string &upstream_host, unsigned short upstream_port) { // void는 return이 없음. string&는 upstream_host의 메모리 주소를 참조하는 것. // Attempt connection to remote server (upstream side) upstream_socket_.async_connect( // async_connect는 소켓을 지정된 원격 엔드포인트로 비동기 연결하는데 사용 (비동기 연결을 시작한다.) ip::tcp::endpoint( boost::asio::ip::address::from_string(upstream_host), // async_connect의 첫번째 파라미터 upstream_port), // async_connect의 두번째 파라미터 // bind는 주어진 엔드포인터로 소켓을 바인드한다. boost::bind(&bridge::handle_upstream_connect, // boost::bind() 에게 첫번째로 들어갈 인자는 바인딩할 함수의 주소. handle_upstream_connect의 메모리 주소를 참조. // handle_upstream_connect함수를 start에 바인딩? shared_from_this(), // 그 다음의 인자들 바인딩될시 매핑될 매개 변수 리스트들 boost::asio::placeholders::error)); }; // handle_upstream_connect 함수 void bridge::handle_upstream_connect(const boost::system::error_code &error) { if (!error) { // Setup async read from remote server (upstream) upstream_socket_.async_read_some( // 비동기 읽기를 시작한다. 스트림 소켓에서 데이터를 비동기로 읽는데 사용된다. boost::asio::buffer(upstream_data_, max_data_length), boost::bind(&bridge::handle_upstream_read, // 서버로부터 데이터를 읽어옴 shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // Setup async read from client (downstream) downstream_socket_.async_read_some( // 비동기 읽기를 시작한다. 스트림 소켓에서 데이터를 비동기로 읽는데 사용된다. boost::asio::buffer(downstream_data_, max_data_length), boost::bind(&bridge::handle_downstream_read, // 클라이언트로부터 데이터를 읽어옴 shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else close(); // error시 종료 }; // private /* Section A: Remote Server --> Proxy --> Client (다운스트림) Process data recieved from remote sever then send to client. (서버로부터 데이터를 받아서 클라이언트에 보낸다) */ // Read from remote server complete, now send data to client (서버로부터 데이터를 읽기 complete, 클라이언트로 데이터를 보낸다) void bridge::handle_upstream_read(const boost::system::error_code &error, const size_t &bytes_transferred) { if (!error) { async_write(downstream_socket_, // async_write는 스트림에 제공된 모든 데이터를 쓰는 비동기 작업을 시작한다. boost::asio::buffer(upstream_data_, bytes_transferred), boost::bind(&bridge::handle_downstream_write, shared_from_this(), boost::asio::placeholders::error)); } else close(); }; // Write to client complete, Async read from remote server (클라이언트에 데이터를 쓰기 complete, 서버데이터를 비동기로 읽는다) void bridge::handle_downstream_write(const boost::system::error_code &error) { if (!error) { upstream_socket_.async_read_some( boost::asio::buffer(upstream_data_, max_data_length), boost::bind(&bridge::handle_upstream_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else close(); }; // *** End Of Section A *** (다운스트림 완료) /* Section B: Client --> Proxy --> Remove Server (업스트림) Process data recieved from client then write to remove server. (클라이언트로부터 데이터를 받아 서버에 쓴다) */ // Read from client complete, now send data to remote server (클라이언트로부터 데이터를 읽기 complete, 서버로 데이터를 보낸다) void bridge::handle_downstream_read(const boost::system::error_code &error, const size_t &bytes_transferred) { if (!error) { async_write(upstream_socket_, boost::asio::buffer(downstream_data_, bytes_transferred), boost::bind(&bridge::handle_upstream_write, shared_from_this(), boost::asio::placeholders::error)); } else close(); }; // Write to remote server complete, Async read from client (서버에 데이터를 쓰기 complete, 클라이언트데이터를 비동기로 읽는다) void bridge::handle_upstream_write(const boost::system::error_code &error) { if (!error) { downstream_socket_.async_read_some( boost::asio::buffer(downstream_data_, max_data_length), boost::bind(&bridge::handle_downstream_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else close(); }; // *** End Of Section B *** (업스트림 완료) void bridge::close() { // 종료함수 boost::mutex::scoped_lock lock(mutex_); if (downstream_socket_.is_open()) // 소켓이 만약 열려있으면 닫는다. downstream_socket_은 즉, client socket { downstream_socket_.close(); } if (upstream_socket_.is_open()) { // upstream_socket_은 즉, Remote server socket upstream_socket_.close(); } } } // namespace yhbae
41.455882
146
0.622206
01d72abac4cfe9609df0fbda7140cbaf0a1f800f
2,528
cpp
C++
async-io-linux-filesystem/AsyncFileReader.cpp
daank94/async-io-linux-filesystem
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
[ "MIT" ]
1
2019-12-26T21:07:22.000Z
2019-12-26T21:07:22.000Z
async-io-linux-filesystem/AsyncFileReader.cpp
daank94/async-io-linux-filesystem
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
[ "MIT" ]
null
null
null
async-io-linux-filesystem/AsyncFileReader.cpp
daank94/async-io-linux-filesystem
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
[ "MIT" ]
1
2020-01-02T01:27:42.000Z
2020-01-02T01:27:42.000Z
#include "AsyncFileReader.h" #include <sys/epoll.h> #include <unistd.h> #include <stdio.h> AsyncFileReader::AsyncFileReader() : epoll_fd_(epoll_create1(0)), stopped_(false) { static_assert(EVENT_BUFFER_SIZE > 0, "EVENT_BUFFER_SIZE must be greater than 0"); static_assert(READ_BUFFER_SIZE > 0, "READ_BUFFER_SIZE must be greater than 0"); } AsyncFileReader::~AsyncFileReader() { close(epoll_fd_); } void AsyncFileReader::addFileDescriptor(const int fd) { struct epoll_event epoll_event; epoll_event.events = EPOLLIN; epoll_event.data.fd = fd; epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &epoll_event); } void AsyncFileReader::removeFileDescriptor(const int fd) { struct epoll_event epoll_event; // For the sake of compatibility with older versions of Linux, this struct must exist (pointer to struct cannot be nullptr). epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &epoll_event); } void AsyncFileReader::runAsyncLoop() { struct epoll_event epoll_event_buffer[EVENT_BUFFER_SIZE]; while(!stopped_) { // Call epoll_wait with a timeout of 1000 milliseconds. const int fds_ready = epoll_wait(epoll_fd_, epoll_event_buffer, EVENT_BUFFER_SIZE, 1000); // Function epoll_wait returned. if(-1 == fds_ready) { // An error occured. stopped_ = true; continue; } // Handle any file descriptors with events. for(int i = 0; i < fds_ready; i++) { const struct epoll_event& epoll_event = epoll_event_buffer[i]; /* To use multiple CPUs, you could execute the handlers on (multiple) worker threads. For the sake of simplicity, polling and handling is done on the same thread now. */ handleEventOnFile(epoll_event); } } } void AsyncFileReader::stopAsyncLoop() { stopped_ = true; } bool AsyncFileReader::hasStopped() { return stopped_; } void AsyncFileReader::handleEventOnFile(const struct epoll_event& epoll_event) { const uint32_t events = epoll_event.events; const int fd = epoll_event.data.fd; if(EPOLLERR & events) { // An error occured on the file descriptor. Try to close it. removeFileDescriptor(fd); close(fd); } else if(EPOLLIN & events) { // Read is available, read in from the file descriptor and print the message. int read_result = read(fd, read_buffer_, READ_BUFFER_SIZE-1); if(-1 == read_result) { // An error occured while reading. removeFileDescriptor(fd); close(fd); return; } // Successfully read in some bytes. read_buffer_[read_result] = '\0'; printf("Read %d bytes\n", read_result); printf("%s", read_buffer_); } }
24.07619
172
0.730222
01daf20c9fab3925dd7c843fd491b5cfa35042df
977
cpp
C++
uva/chapter_3/10341.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
uva/chapter_3/10341.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
uva/chapter_3/10341.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include <cmath> #include <stdio.h> #include <iostream> using namespace std; int p, q, r, s, t, u; double f(double x) { return p * exp(-x) + q * sin(x) + r * cos(x) + s * tan(x) + t * x * x + u; } double fd(double x){ // the derivative of function f return -p*exp(-x) + q*cos(x) - r*sin(x) + s/(cos(x)*cos(x)) + 2*t*x; } int loops = 0; const double EPS = 1e-7; double newton(){ if (f(0)==0) return 0; for (double x=0.5; ;){ // initial guess x = 0.5 loops++; double x1 = x - f(x)/fd(x); // x1 = next guess if (round(x1 * 10000) == round(x * 10000)) return x; x = x1; } } int main() { while (scanf("%d%d%d%d%d%d", &p, &q, &r, &s, &t, &u) == 6) { double r = 1.0d; double l = 0.0d; double lv = f(l); double rv = f(r); if (lv * rv > 0) { printf("No solution\n"); continue; } printf("%.4lf\n", newton()); } cerr << loops; return 0; }
21.23913
78
0.468782
01dd7017a5734ed0acb9fa4079335c1f4ed723f2
1,504
cpp
C++
main_web.cpp
kooBH/Qt_File_IO
2a95289f295018ece13665e0bc3112efbe889d8a
[ "Unlicense" ]
null
null
null
main_web.cpp
kooBH/Qt_File_IO
2a95289f295018ece13665e0bc3112efbe889d8a
[ "Unlicense" ]
6
2019-03-14T11:57:03.000Z
2019-06-07T10:42:18.000Z
main_web.cpp
kooBH/Qt_File_IO
2a95289f295018ece13665e0bc3112efbe889d8a
[ "Unlicense" ]
null
null
null
#include <QtWebEngineCore> #include <QApplication> #include <QWebEngineView> #include <QVBoxLayout> #include <QPushButton> #include <QWidget> QUrl commandLineUrlArgument() { const QStringList args = QCoreApplication::arguments(); for (const QString &arg : args.mid(1)) { if (!arg.startsWith(QLatin1Char('-'))) return QUrl::fromUserInput(arg); } return QUrl(QStringLiteral("http://iip.sogang.ac.kr")); } int main(int argc, char *argv[]) { QCoreApplication::addLibraryPath("../lib"); QCoreApplication::setOrganizationName("QtExamples"); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication app(argc, argv); QWidget widget_main; QVBoxLayout layout_main; QPushButton btn_scroll("scroll to bottom"); QWebEngineView view_main; widget_main.setLayout(&layout_main); layout_main.addWidget(&btn_scroll); layout_main.addWidget(&view_main); view_main.setUrl(commandLineUrlArgument()); view_main.resize(1024, 750); widget_main.show(); QObject::connect(&btn_scroll, &QPushButton::clicked, [&](){ /* view_main.page()->runJavaScript("\ var scrollingElement = (document.scrollingElement || document.body);\ scrollingElement.scrollTop = scrollingElement.scrollHeight;\ "); */ view_main.page()->runJavaScript(" window.scrollTo(0,document.body.scrollHeight);"); // view_main.page()->runJavaScript( "window.scrollTo(500, 500);"); } ); app.exec(); return 0; }
24.258065
89
0.692154
01e23ec8197e816ffb8957afcc85f7b9973b60ef
3,163
hpp
C++
diffsim_torch3d/arcsim/src/physics.hpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
diffsim_torch3d/arcsim/src/physics.hpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
diffsim_torch3d/arcsim/src/physics.hpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright ©2013 The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #ifndef PHYSICS_HPP #define PHYSICS_HPP #include "cloth.hpp" #include "obstacle.hpp" #include "geometry.hpp" #include "simulation.hpp" #include "taucs.hpp" #include <vector> using torch::Tensor; template <Space s> Tensor internal_energy (const Cloth &cloth); Tensor constraint_energy (const std::vector<Constraint*> &cons); Tensor external_energy (const Cloth &cloth, const Tensor &gravity, const Wind &wind); // A += dt^2 dF/dx; b += dt F + dt^2 dF/dx v // also adds damping terms // if dt == 0, just does A += dF/dx; b += F instead, no damping template <Space s> void add_internal_forces (const Cloth &cloth, SpMat &A, Tensor &b, Tensor dt); void add_constraint_forces (const Cloth &cloth, const std::vector<Constraint*> &cons, SpMat &A, Tensor &b, Tensor dt); void add_external_forces (const Cloth &cloth, const Tensor &gravity, const Wind &wind, Tensor &fext, Tensor &Jext); void obs_add_external_forces (const Obstacle &obstacle, const Tensor &gravity, const Wind &wind, Tensor &fext, Tensor &Jext); void add_morph_forces (const Cloth &cloth, const Morph &morph, Tensor t, Tensor dt, Tensor &fext, Tensor &Jext); void implicit_update (Cloth &cloth, const Tensor &fext, const Tensor &Jext, const std::vector<Constraint*> &cons, Tensor dt, bool update_positions=true); void obs_implicit_update (Obstacle &obstacle, const vector<Mesh*> &obs_meshes, const Tensor &fext, const Tensor &Jext, const vector<Constraint*> &cons, Tensor dt, bool update_positions); #endif
39.5375
98
0.669617
01e2fc1419df585b6bbda0d311ec4e0ead3faa7e
2,287
cpp
C++
benchmarks/benchmark_ref_counted_ptr.cpp
abu-lib/mem
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
[ "Apache-2.0" ]
null
null
null
benchmarks/benchmark_ref_counted_ptr.cpp
abu-lib/mem
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
[ "Apache-2.0" ]
1
2021-09-26T14:15:33.000Z
2021-09-26T15:40:32.000Z
benchmarks/benchmark_ref_counted_ptr.cpp
abu-lib/mem
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
[ "Apache-2.0" ]
null
null
null
#include <benchmark/benchmark.h> #include <cstdlib> #include <ctime> #include <memory> #include "abu/mem.h" namespace { static void BM_shared_ptr_int_lifetime(benchmark::State& state) { std::srand(std::time(nullptr)); int v = std::rand(); for (auto _ : state) { (void)_; auto tmp = std::make_shared<int>(v); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_shared_ptr_int_lifetime); static void BM_shared_ptr_int_access(benchmark::State& state) { std::srand(std::time(nullptr)); int v = std::rand(); for (auto _ : state) { (void)_; auto tmp = std::make_shared<int>(v); int u = *tmp; benchmark::DoNotOptimize(u); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_shared_ptr_int_access); static void BM_ref_counted_int_lifetime(benchmark::State& state) { std::srand(std::time(nullptr)); int v = std::rand(); for (auto _ : state) { (void)_; auto tmp = abu::mem::make_ref_counted<int>(v); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_ref_counted_int_lifetime); static void BM_ref_counted_int_access(benchmark::State& state) { std::srand(std::time(nullptr)); int v = std::rand(); for (auto _ : state) { (void)_; auto tmp = abu::mem::make_ref_counted<int>(v); int u = *tmp; benchmark::DoNotOptimize(u); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_ref_counted_int_access); static void BM_shared_ptr_obj_lifetime(benchmark::State& state) { struct ObjType {}; for (auto _ : state) { auto tmp = std::make_shared<ObjType>(); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_shared_ptr_obj_lifetime); static void BM_ref_counted_obj_lifetime(benchmark::State& state) { struct ObjType {}; for (auto _ : state) { auto tmp = abu::mem::make_ref_counted<ObjType>(); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_ref_counted_obj_lifetime); static void BM_ref_counted_intrusive_obj_lifetime(benchmark::State& state) { struct ObjType : public abu::mem::ref_counted {}; for (auto _ : state) { auto tmp = abu::mem::make_ref_counted<ObjType>(); benchmark::DoNotOptimize(tmp); } } BENCHMARK(BM_ref_counted_intrusive_obj_lifetime); } // namespace BENCHMARK_MAIN();
25.131868
77
0.663314
01e399aae29a026843f9751f0769d04e8ba7dc2f
52,394
cpp
C++
source/equation.cpp
LiquidFenrir/CalculaThreeDS
1f87cdafa639e8289ebf886c6dd0e341c4da6279
[ "MIT" ]
10
2020-11-08T13:40:44.000Z
2021-05-19T09:40:53.000Z
source/equation.cpp
LiquidFenrir/CalculaThreeDS
1f87cdafa639e8289ebf886c6dd0e341c4da6279
[ "MIT" ]
2
2021-01-18T13:56:08.000Z
2021-03-11T13:45:05.000Z
source/equation.cpp
LiquidFenrir/CalculaThreeDS
1f87cdafa639e8289ebf886c6dd0e341c4da6279
[ "MIT" ]
null
null
null
#include "equation.h" #include "sprites.h" #include "text.h" #include "colors.h" #include <algorithm> #include <cmath> static const Number E_VAL(std::exp(1.0)); static const Number PI_VAL(M_PI); static const Number I_VAL(0.0, 1.0); Equation::Equation() : parts(3) { parts[0].meta.assoc = 2; parts[0].meta.special = Part::Specialty::Equation; parts[0].meta.position = Part::Position::Start; parts[0].meta.next = 1; parts[2].meta.assoc = 0; parts[2].meta.special = Part::Specialty::Equation; parts[2].meta.position = Part::Position::End; parts[2].meta.before = 1; parts[1].meta.before = 0; parts[1].meta.next = 2; } struct RenderInfo { int current_x; const int min_x, max_x, center_y; const int height; const int editing_part; const int editing_char; bool can_draw(const int vertical_offset) const { const bool x_correct = (min_x - (13 -1)) <= current_x && current_x < max_x; const bool y_correct = -(height/2 + 24/2) < (vertical_offset - center_y) && (vertical_offset - center_y) <= (height/2 + 24); return x_correct && y_correct; } int get_x() const { return current_x - min_x; } int get_y(const int vertical_offset) const { return center_y - vertical_offset + height/2 - 24/2; } }; struct RenderPart { int data{}; // in deviation from the previous, counted in half parts int middle_change{}; // in number of half parts, from the middle int y_start{}; // positive, up int y_end{}; // negative, down // only used for special parts int associated{}; int content_width{}; int content_middle_high{}; int paren_y_start{}; int paren_y_end{}; }; static void find_part_sizes(const std::vector<Part>& parts, std::vector<RenderPart>& part_sizes) { static std::vector<int> id_stack; const auto pop_id = []() -> int { const int i = id_stack.back(); id_stack.pop_back(); return i; }; enum CareAbout : int { CA_Width = 1, CA_HeightBelow = 2, CA_HeightAbove = 4, CA_All = 1 | 2 | 4, }; const auto add_content_info = [&](const RenderPart& ps, const CareAbout care = CA_All) -> void { if(!id_stack.empty()) { auto& container_size = part_sizes[id_stack.back()]; if(care & CA_Width) { container_size.content_width += ps.content_width; } if(care & (CA_HeightAbove | CA_HeightBelow)) { if(care & CA_HeightAbove) { container_size.y_start = std::max(container_size.y_start, ps.y_start + ps.middle_change); container_size.paren_y_start = std::max(container_size.paren_y_start, container_size.y_start); container_size.paren_y_start = std::max(container_size.paren_y_start, ps.paren_y_start); } if(care & CA_HeightBelow) { container_size.y_end = std::min(container_size.y_end, ps.y_end + ps.middle_change); container_size.paren_y_end = std::min(container_size.paren_y_end, container_size.y_end); container_size.paren_y_end = std::min(container_size.paren_y_end, ps.paren_y_end); } container_size.content_middle_high = std::max(container_size.content_middle_high, ps.middle_change + ps.content_middle_high); } } }; const auto do_part_basic = [&](const int idx) -> void { const auto& p = parts[idx]; auto& ps = part_sizes[idx]; ps.data = [&]() -> int {; if(p.meta.special == Part::Specialty::TempParen) { return 1; } else if(p.value.empty()) { const auto& prev_meta = parts[p.meta.before].meta; const auto& next_meta = parts[p.meta.next].meta; const bool sandwiched = (check_pos_is(prev_meta.position, Part::Position::Start) && check_pos_is(next_meta.position, Part::Position::End)) && prev_meta.special == next_meta.special; if( (sandwiched && ( prev_meta.special == Part::Specialty::Equation || prev_meta.special == Part::Specialty::Paren || prev_meta.special == Part::Specialty::Absolute )) || (!sandwiched && (prev_meta.special == Part::Specialty::TempParen || next_meta.special != Part::Specialty::Exponent || (next_meta.special == Part::Specialty::Exponent && next_meta.position != Part::Position::Start) || (next_meta.special == Part::Specialty::Exponent && prev_meta.special == Part::Specialty::Paren && prev_meta.position == Part::Position::End) )) ) { return 0; } return 1; } else { return p.value.size(); } }(); ps.content_width = ps.data; ps.y_start = 1; ps.y_end = -1; ps.paren_y_start = 1; ps.paren_y_end = -1; add_content_info(ps); }; int current_idx = 0; while(current_idx != -1) { const auto& part = parts[current_idx]; if(part.meta.special == Part::Specialty::None || part.meta.special == Part::Specialty::TempParen) { do_part_basic(current_idx); } else if(part.meta.special != Part::Specialty::Equation) { if(check_pos_is(part.meta.position, Part::Position::End)) { const int associated_id = pop_id(); const auto& ap = parts[associated_id]; auto& aps = part_sizes[associated_id]; auto& ps = part_sizes[current_idx]; if(part.meta.special == Part::Specialty::Exponent) { const int delta = (aps.y_start - aps.content_middle_high) - aps.y_end; aps.middle_change = delta; ps.middle_change = -delta; aps.associated = current_idx; ps.associated = associated_id; add_content_info(aps, CA_All); } else if(part.meta.special == Part::Specialty::Fraction) { if(check_pos_is(ap.meta.position, Part::Position::End)) // ending bottom part { ps.middle_change = aps.y_start + 1; aps.middle_change += -ps.middle_change; // middle aps.associated = current_idx; // middle.associated points to end ps.associated = associated_id; // end.associated points to middle RenderPart cp = aps; cp.content_width = std::max(aps.content_width, aps.data); cp.middle_change = -ps.middle_change; add_content_info(cp, CareAbout(CA_HeightBelow | CA_Width)); } else // ending top part { aps.middle_change = 2 + (-aps.y_end - 1); // start ps.middle_change = -aps.middle_change; aps.associated = current_idx; // start.associated points to middle ps.data = aps.content_width; // middle.data is start.content_width add_content_info(aps, CA_HeightAbove); } } else if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute) { aps.associated = current_idx; ps.associated = associated_id; ps.paren_y_start = aps.paren_y_start; ps.paren_y_end = aps.paren_y_end; aps.content_width += 2; add_content_info(aps, CA_All); } else if(part.meta.special == Part::Specialty::Root) { aps.associated = current_idx; ps.associated = associated_id; ps.paren_y_start = aps.paren_y_start + 1; ps.paren_y_end = aps.paren_y_end; aps.content_width += 2; add_content_info(aps, CA_All); } else if(part.meta.special == Part::Specialty::Conjugate) { aps.associated = current_idx; ps.associated = associated_id; aps.y_start += 1; ps.y_start = aps.y_start; aps.paren_y_start = aps.y_start; ps.paren_y_start = aps.paren_y_start; ps.paren_y_end = aps.paren_y_end; add_content_info(aps, CA_All); } } if(check_pos_is(part.meta.position, Part::Position::Start)) { id_stack.push_back(current_idx); } } current_idx = part.meta.next; } id_stack.clear(); } static void render_parts(const std::vector<Part>& parts, RenderInfo& info, Equation::RenderResult& out, PartPos* screen, C2D_SpriteSheet sprites) { static std::vector<RenderPart> part_sizes; part_sizes.resize(parts.size()); find_part_sizes(parts, part_sizes); int selected_multi_id = -1; int selected_multi_assoc = -1; if(info.editing_char == 0) { if(const auto& part_before = parts[parts[info.editing_part].meta.before]; part_before.meta.special == Part::Specialty::Paren || part_before.meta.special == Part::Specialty::Absolute) { selected_multi_id = parts[info.editing_part].meta.before; selected_multi_assoc = part_before.meta.assoc; } } int current_idx = 0; C2D_Image empty_img = C2D_SpriteSheetGetImage(sprites, sprites_empty_but_clickable_idx); C2D_Image lpa_sprites[] = { C2D_SpriteSheetGetImage(sprites, sprites_lparen_begin_idx), C2D_SpriteSheetGetImage(sprites, sprites_lparen_middle_idx), C2D_SpriteSheetGetImage(sprites, sprites_lparen_end_idx), }; C2D_Image rpa_sprites[] = { C2D_SpriteSheetGetImage(sprites, sprites_rparen_begin_idx), C2D_SpriteSheetGetImage(sprites, sprites_rparen_middle_idx), C2D_SpriteSheetGetImage(sprites, sprites_rparen_end_idx), }; C2D_Image abs_sprites[] = { C2D_SpriteSheetGetImage(sprites, sprites_abs_begin_idx), C2D_SpriteSheetGetImage(sprites, sprites_abs_middle_idx), C2D_SpriteSheetGetImage(sprites, sprites_abs_end_idx), }; C2D_Image sqrt_sprites[] = { C2D_SpriteSheetGetImage(sprites, sprites_sqrt_begin_idx), C2D_SpriteSheetGetImage(sprites, sprites_sqrt_middle_idx), C2D_SpriteSheetGetImage(sprites, sprites_sqrt_end_idx), }; C2D_ImageTint text_tint; C2D_PlainImageTint(&text_tint, COLOR_BLACK, 1.0f); C2D_ImageTint temp_tint; C2D_PlainImageTint(&temp_tint, COLOR_GRAY, 1.0f); C2D_ImageTint paren_selected_tint; C2D_PlainImageTint(&paren_selected_tint, COLOR_BLUE, 1.0f); const auto draw_paren = [&](const C2D_Image* sprites, const int vertical_offset, const int y_start, const int y_end, const C2D_ImageTint* tnt) -> void { const int span = (y_start - y_end) - 2; const int span_pixels = (span * 24 / 4) + 1; const int pixel_y = info.get_y(vertical_offset) - ((y_start - 1) * 24 / 4); const int x = info.get_x(); C2D_DrawImageAt(sprites[0], x, pixel_y, 0.0f, tnt); const int middle_y = pixel_y + sprites[0].subtex->height; C2D_DrawImageAt(sprites[1], x, middle_y, 0.0f, tnt, 1.0f, span_pixels); const int bottom_y = middle_y + span_pixels; C2D_DrawImageAt(sprites[2], x, bottom_y, 0.0f, tnt); }; const auto set_cursor = [&](const int y) -> void { out.cursor_x = info.get_x(); out.cursor_y = y; if(!(out.cursor_x <= -2 || out.cursor_x >= (320 - 2) || out.cursor_y <= (-24) || out.cursor_y >= EQU_REGION_HEIGHT)) { out.cursor_visible = true; } }; int vertical_offset = 0; int min_vert = 0; int max_vert = 0; PartPos pos; while(current_idx != -1) { const auto& part = parts[current_idx]; const auto& part_size = part_sizes[current_idx]; if(part.meta.special == Part::Specialty::None) { pos.part = current_idx; if(part.value.empty()) { if(part_size.data != 0 && info.can_draw(vertical_offset)) { const auto& img = empty_img; C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint); if(screen) { pos.pos = 0; for(int y = 0; y < 24; y++) { const int actual_y = info.get_y(vertical_offset) + y; if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT) { const int y_part = actual_y * 320; for(int x = 0; x < 13; x++) { const int actual_x = info.get_x() + x; if(actual_x >= 0 && actual_x < 320) { screen[actual_x + y_part] = pos; } } } } } } if(info.editing_part == current_idx && info.editing_char == 0) { set_cursor(info.get_y(vertical_offset)); } if(part_size.data != 0) info.current_x += 13; } else { int char_idx = 0; for(const char c : part.value) { if(info.can_draw(vertical_offset)) { const auto img = TextMap::char_to_sprite->equ.at(std::string_view(&c, 1)); C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint); if(screen) { pos.pos = char_idx + 1; for(int y = 0; y < 24; y++) { const int actual_y = info.get_y(vertical_offset) + y; if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT) { const int y_part = actual_y * 320; for(int x = 0; x < 13; x++) { const int actual_x = info.get_x() + x; if(actual_x >= 0 && actual_x < 320) { screen[actual_x + y_part] = pos; } } } } } } if(info.editing_part == current_idx && info.editing_char == char_idx) { set_cursor(info.get_y(vertical_offset)); } info.current_x += 13;; char_idx += 1; } if(info.editing_part == current_idx && info.editing_char == char_idx) { set_cursor(info.get_y(vertical_offset)); } } } else if(part.meta.special != Part::Specialty::Equation) { if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::TempParen || part.meta.special == Part::Specialty::Absolute) { pos.part = part.meta.next; const C2D_Image* sprs = nullptr; if(part.meta.special == Part::Specialty::Absolute) { sprs = abs_sprites; } else if(part.meta.position == Part::Position::Start) { sprs = lpa_sprites; } else if(part.meta.position == Part::Position::End) { sprs = rpa_sprites; } const C2D_ImageTint* tnt = &temp_tint; if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute) { if(current_idx == selected_multi_id || current_idx == selected_multi_assoc) { tnt = &paren_selected_tint; } else { tnt = &text_tint; } } draw_paren(sprs, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, tnt); if(screen) { const int h = ((part_size.paren_y_start - part_size.paren_y_end) * 24 / 2) + 1; for(int y = 0; y < h; y++) { const int actual_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 2) + y; if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT) { const int y_part = actual_y * 320; for(int x = 0; x < 13; x++) { const int actual_x = info.get_x() + x; if(actual_x >= 0 && actual_x < 320) { screen[actual_x + y_part] = pos; } } } } } info.current_x += 13; } else if(part.meta.special == Part::Specialty::Root) { if(part.meta.position == Part::Position::Start) { draw_paren(sqrt_sprites, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, &text_tint); const int pixel_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4); const int bar_x = info.get_x() + 10; const int bar_w = (part_size.content_width - 2) * 13 + 10; const int notch_x = bar_x + bar_w; C2D_DrawRectSolid(bar_x, pixel_y, 0.125f, bar_w, 2, COLOR_BLACK); C2D_DrawRectSolid(notch_x, pixel_y, 0.125f, 2, 10, COLOR_BLACK); } info.current_x += 13; } else if(part.meta.special == Part::Specialty::Conjugate) { if(part.meta.position == Part::Position::Start) { C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4), 0.125f, part_size.content_width * 13, 2, COLOR_BLACK); } } else if(part.meta.special == Part::Specialty::Fraction) { if(part.meta.position == Part::Position::Start) { const auto& middle_size = part_sizes[part_size.associated]; const int max_width = std::max(middle_size.content_width, part_size.content_width); C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) + 24 / 2 - 1, 0.0f, max_width * 13, 2.0f, COLOR_BLACK); info.current_x += ((max_width - part_size.content_width) * 13)/2; // top align } else if(part.meta.position == Part::Position::Middle) { const int max_width = std::max(part_size.content_width, part_size.data); info.current_x -= (part_size.data * 13); // top size info.current_x -= ((max_width - part_size.data) * 13)/2; // top align info.current_x += ((max_width - part_size.content_width) * 13)/2; // bottom align } else if(part.meta.position == Part::Position::End) { const auto& middle_size = part_sizes[part_size.associated]; const int max_width = std::max(middle_size.content_width, middle_size.data); info.current_x -= (middle_size.content_width * 13); // bottom size info.current_x -= ((max_width - middle_size.content_width) * 13)/2; // bottom align info.current_x += max_width * 13; // full size } } vertical_offset += (part_size.middle_change * 24) / 4; max_vert = std::max(max_vert, vertical_offset); min_vert = std::min(min_vert, vertical_offset); } current_idx = part.meta.next; } out.w = info.current_x; out.min_y = min_vert - 24 / 2; out.max_y = max_vert + 24 / 2; part_sizes.clear(); } Equation::RenderResult Equation::render_main(const int x, const int y, const int editing_part, const int editing_char, C2D_SpriteSheet sprites, PartPos* screen) { RenderResult out{0,0,0,-1,-1, false}; RenderInfo info{ 0, x, x + 320, y, EQU_REGION_HEIGHT, editing_part, editing_char, }; render_parts(parts, info, out, screen, sprites); return out; } Equation::RenderResult Equation::render_memory(const int x, const int y, C2D_SpriteSheet sprites) { RenderResult out{0,0,0,-1,-1, false}; RenderInfo info{ 0, x, x + 400, y, EQU_REGION_HEIGHT, -1, -1, }; render_parts(parts, info, out, nullptr, sprites); return out; } void Equation::optimize() { std::vector<Part> tmp; tmp.push_back(std::move(parts[0])); int prev_id = 0; int next_id_parts = tmp.back().meta.next; while(next_id_parts != -1) { int next_id_tmp = tmp.size(); tmp.back().meta.next = next_id_tmp; tmp.push_back(std::move(parts[next_id_parts])); next_id_parts = tmp.back().meta.next; tmp.back().meta.before = prev_id; prev_id = next_id_tmp; } parts = std::move(tmp); } std::pair<Number, bool> Equation::calculate(std::map<std::string, Number>& variables, int& error_part, int& error_position) { #define ERROR_AT(part, pos) { error_part = part; error_position = pos; return {}; } struct Token { enum class Type { Number, Variable, Function, Operator, ParenOpen, ParenClose, }; std::string_view value; int part, position; Type type; }; const auto base_tokens = [&, this]() -> std::vector<Token> { std::vector<Token> toks; int start = 0; int len = 0; int tmp_is_num = -1; int current_idx = 0; while(current_idx != -1) { const auto& p = parts[current_idx]; if(p.meta.special != Part::Specialty::None) { if(p.meta.special == Part::Specialty::TempParen) { ERROR_AT(p.meta.next, 0); } else if(p.meta.special == Part::Specialty::Absolute) { if(p.meta.position == Part::Position::Start) { toks.push_back(Token{"abs", p.meta.next, 0, Token::Type::Function}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } else if(p.meta.special == Part::Specialty::Root) { if(p.meta.position == Part::Position::Start) { if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number)) { toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator}); } toks.push_back(Token{"sqrt", p.meta.next, 0, Token::Type::Function}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } else if(p.meta.special == Part::Specialty::Conjugate) { if(p.meta.position == Part::Position::Start) { toks.push_back(Token{"conj", p.meta.next, 0, Token::Type::Function}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } else if(p.meta.special == Part::Specialty::Paren) { if(p.meta.position == Part::Position::Start) { if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number)) { toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator}); } toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } else if(p.meta.special == Part::Specialty::Exponent) { if(p.meta.position == Part::Position::Start) { if(toks.size() >= 1) { if(const auto b = toks.back(); b.value == "e" && b.type == Token::Type::Variable) { toks.pop_back(); if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number)) { toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator}); } toks.push_back(Token{"exp", b.part, b.position, Token::Type::Function}); } else toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator}); } else toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } else if(p.meta.special == Part::Specialty::Fraction) { if(p.meta.position == Part::Position::Start) { if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number)) { toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator}); } toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else if(p.meta.position == Part::Position::Middle) { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); toks.push_back(Token{"/", p.meta.next, 0, Token::Type::Operator}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen}); } else { toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose}); } } } else { int pos = 0; const char* beg = p.value.c_str(); for(const char c : p.value) { if(('0' <= c && c <= '9') || c == '.') { if(tmp_is_num == 1) { ++len; } else { if(len != 0) { if(toks.size() && toks.back().type == Token::Type::ParenClose) { toks.push_back(Token{"*", current_idx, start, Token::Type::Operator}); } toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable}); toks.push_back(Token{"*", current_idx, start, Token::Type::Operator}); } start = pos; len = 1; tmp_is_num = 1; } } else if(('a' <= c && c <= 'z') || c == 'P') { if(tmp_is_num == 0) { ++len; } else { if(len != 0) { if(toks.size() && toks.back().type == Token::Type::ParenClose) { toks.push_back(Token{"*", current_idx, start, Token::Type::Operator}); } toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number}); toks.push_back(Token{"*", current_idx, start, Token::Type::Operator}); } start = pos; len = 1; tmp_is_num = 0; } } else { if(len != 0) { toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, tmp_is_num ? Token::Type::Number : Token::Type::Variable}); } start = 0; len = 0; tmp_is_num = -1; toks.push_back(Token{{beg + pos, 1}, current_idx, pos, Token::Type::Operator}); } ++pos; } if(tmp_is_num == 0) { if(const auto& pn = parts[p.meta.next].meta; pn.position == Part::Position::Start && pn.special == Part::Specialty::Paren) { if(len == 1 || std::string_view{beg + start, size_t(len)} == "ans") // 1 letter names can only be variables { toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable}); toks.push_back(Token{"*", current_idx, start, Token::Type::Operator}); } else { toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Function}); } } else { toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable}); } } else if(tmp_is_num == 1) { toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number}); } start = 0; len = 0; tmp_is_num = -1; } current_idx = p.meta.next; } return toks; }(); if(base_tokens.empty()) return std::make_pair(Number{}, true); const auto final_rpn = [&]() -> std::vector<const Token*> { std::vector<const Token*> postfix; std::vector<const Token*> opstack; const auto get_prec = [](std::string_view op) -> int { switch(op.front()) { case '^': return 4; case '*': return 3; case '/': return 3; case '+': return 2; case '-': return 2; case '>': return 1; default: return 0; } }; const auto get_assoc = [](std::string_view op) -> bool { return op.front() == '^'; }; for(const Token& tok : base_tokens) { if(tok.type == Token::Type::Variable || tok.type == Token::Type::Number) { postfix.push_back(&tok); } else if(tok.type == Token::Type::ParenOpen) { opstack.push_back(&tok); } else if(tok.type == Token::Type::ParenClose) { while(opstack.size() && opstack.back()->type != Token::Type::ParenOpen) { postfix.push_back(opstack.back()); opstack.pop_back(); } opstack.pop_back(); // open paren (mismatch cannot happen) } else if(tok.type == Token::Type::Function) { opstack.push_back(&tok); } else if(tok.type == Token::Type::Operator) { auto prec = get_prec(tok.value); while(opstack.size()) { if(const Token* op = opstack.back(); op->type != Token::Type::ParenOpen && ( op->type == Token::Type::Function || get_prec(op->value) >= prec || (get_prec(op->value) == prec && get_assoc(op->value)) ) ) { postfix.push_back(op); opstack.pop_back(); } else break; } opstack.push_back(&tok); } } while(opstack.size()) { postfix.push_back(opstack.back()); opstack.pop_back(); } return postfix; }(); if(final_rpn.empty()) std::make_pair(Number{}, true); #undef ERROR_AT #define ERROR_AT(part, pos) { error_part = part; error_position = pos; return std::make_pair(Number{}, true); } struct Value { Number val; std::string_view assoc_variable; Value(std::string_view v) : val(v) { } Value(const Number& v) : val(v) { } Value(const Number& v, std::string_view a) : val(v), assoc_variable(a) { } }; const auto get_var = [&](std::string_view name) -> Value { if(auto it = variables.find(std::string(name)); it != variables.end()) { return {it->second, name}; } return {{}, name}; }; #define MK_WRAPPER_FN(fname, fn) {#fname, [](std::vector<Value>& vals) { \ vals.back() = Value(std::fn(vals.back().val.value)); \ }} #define MK_WRAPPER(fname) MK_WRAPPER_FN(fname, fname) const std::map<std::string_view, void(*)(std::vector<Value>&)> function_handlers{ MK_WRAPPER(abs), MK_WRAPPER(sqrt), MK_WRAPPER(conj), MK_WRAPPER(cos), MK_WRAPPER(sin), MK_WRAPPER(tan), MK_WRAPPER(acos), MK_WRAPPER(asin), MK_WRAPPER(atan), MK_WRAPPER(cosh), MK_WRAPPER(sinh), MK_WRAPPER(tanh), MK_WRAPPER(acosh), MK_WRAPPER(asinh), MK_WRAPPER(atanh), MK_WRAPPER(exp), MK_WRAPPER_FN(ln, log), MK_WRAPPER_FN(log, log10), }; std::vector<Value> value_stack; for(const Token* tok : final_rpn) { if(tok->type == Token::Type::Number) { if(tok->value.front() == '.' || tok->value.back() == '.') { ERROR_AT(tok->part, tok->position); } else { value_stack.emplace_back(tok->value); } } else if(tok->type == Token::Type::Variable) { if(tok->value == "P") { value_stack.emplace_back(PI_VAL); } else if(tok->value == "e") { value_stack.emplace_back(E_VAL); } else if(tok->value == "i") { value_stack.emplace_back(I_VAL); } else { value_stack.push_back(get_var(tok->value)); } } else if(tok->type == Token::Type::Operator) { #define OP_CASE(op) case #op[0] : { \ const Value left = value_stack.back(); \ value_stack.pop_back(); \ const Value right = value_stack.back(); \ value_stack.pop_back(); \ value_stack.emplace_back(right.val.value op left.val.value); \ } break; switch(tok->value.front()) { OP_CASE(+) OP_CASE(-) OP_CASE(*) OP_CASE(/) case '^': { const Value left = value_stack.back(); value_stack.pop_back(); const Value right = value_stack.back(); value_stack.pop_back(); value_stack.emplace_back(std::pow(right.val.value, left.val.value)); } break; case '>': { const Value left = value_stack.back(); value_stack.pop_back(); const Value right = value_stack.back(); value_stack.pop_back(); variables.insert_or_assign(std::string(left.assoc_variable), right.val.value); value_stack.push_back(right); } break; } } else if(tok->type == Token::Type::Function) { if(auto it = function_handlers.find(tok->value); it != function_handlers.end()) { it->second(value_stack); } } } return {value_stack.back().val, false}; #undef ERROR_AT } int Equation::set_special(const int current_part_id, const int at_position, const Part::Specialty special) { if(static_cast<size_t>(at_position) != parts[current_part_id].value.size()) return 0; const int next_id = parts[current_part_id].meta.next; if(next_id == -1) return 0; auto& p = parts[next_id]; if(p.meta.special != Part::Specialty::Paren || p.meta.position != Part::Position::Start) return 0; p.meta.special = special; parts[p.meta.assoc].meta.special = special; return 1; } void Equation::find_matching_tmp_paren(const int original_pos) { using HelperType = int(*)(Equation&, const int); const auto do_find = [](Equation& e, const int original_pos, int inc_on_start, HelperType get_following) { int current_count = 0; int prev_pos = original_pos; const Part::Position searching_for = !e.parts[original_pos].meta.position; int pos = get_following(e, prev_pos); while(current_count >= 0 /* && pos != -1 */) // second test redundant, since we have the Equation start and end chunks { if(current_count == 0 && e.parts[pos].meta.special == Part::Specialty::TempParen && e.parts[pos].meta.position == searching_for) { e.parts[pos].meta.special = Part::Specialty::Paren; e.parts[pos].meta.assoc = original_pos; e.parts[original_pos].meta.special = Part::Specialty::Paren; e.parts[original_pos].meta.assoc = pos; break; } if(check_pos_is(e.parts[pos].meta.position, Part::Position::End) && e.parts[pos].meta.special != Part::Specialty::TempParen) { current_count -= inc_on_start; } if(check_pos_is(e.parts[pos].meta.position, Part::Position::Start) && e.parts[pos].meta.special != Part::Specialty::TempParen) { current_count += inc_on_start; } prev_pos = pos; pos = get_following(e, pos); } }; if(parts[original_pos].meta.position == Part::Position::Start) { // go forward do_find(*this, original_pos, +1, [](Equation& e, const int pos) -> int { return e.parts[pos].meta.next; } ); } else if(parts[original_pos].meta.position == Part::Position::End) { // go backwards do_find(*this, original_pos, -1, [](Equation& e, const int pos) -> int { return e.parts[pos].meta.before; } ); } } std::pair<bool, bool> Equation::add_part_at(int& current_part_id, int& at_position, const Part::Specialty special, const Part::Position position, const int assoc) { std::string before_val = parts[current_part_id].value.substr(0, at_position); std::string after_val = parts[current_part_id].value.substr(at_position); const bool after_val_empty = after_val.empty(); const bool before_val_empty = before_val.empty(); const int new_part_id = parts.size(); if(after_val_empty) { parts.emplace_back(); auto& current_part = parts[current_part_id]; auto& new_part = parts[new_part_id]; new_part.meta.special = special; new_part.meta.position = position; new_part.meta.assoc = assoc; new_part.meta.before = current_part_id; new_part.meta.next = current_part.meta.next; parts[new_part.meta.next].meta.before = new_part_id; current_part.meta.next = new_part_id; } else if(before_val_empty) { parts.emplace_back(); auto& current_part = parts[current_part_id]; auto& new_part = parts[new_part_id]; new_part.meta.special = special; new_part.meta.position = position; new_part.meta.assoc = assoc; new_part.meta.before = current_part.meta.before; new_part.meta.next = current_part_id; parts[new_part.meta.before].meta.next = new_part_id; current_part.meta.before = new_part_id; } else { parts.emplace_back(); const int after_part_id = parts.size(); parts.emplace_back(); auto& current_part = parts[current_part_id]; auto& new_part = parts[new_part_id]; auto& after_part = parts[after_part_id]; new_part.meta.special = special; new_part.meta.position = position; new_part.meta.assoc = assoc; new_part.meta.before = current_part_id; new_part.meta.next = after_part_id; after_part.meta.before = new_part_id; after_part.meta.next = current_part.meta.next; current_part.meta.next = new_part_id; current_part.value = std::move(before_val); after_part.value = std::move(after_val); } current_part_id = new_part_id; at_position = 0; const auto& new_part = parts[new_part_id]; return {parts[new_part.meta.before].meta.special == Part::Specialty::None, parts[new_part.meta.next].meta.special == Part::Specialty::None}; } bool Equation::remove_at(int& current_part_id, int& at_position) { if(at_position == 0) { const auto merge_single_part = [this](Part::Meta single_meta) -> std::pair<int, int> { const int before_part_start_id = single_meta.before; const int after_part_start_id = single_meta.next; const int part_id = before_part_start_id; const int at_char = parts[part_id].value.size(); /* * equ_start -> A -> single -> B -> equ_end * append B to A * make A's next into B's next * make B's next's before into A * equ_start -> AB -> equ_end */ Part::Meta after_start_meta = parts[after_part_start_id].meta; parts[before_part_start_id].value.append(parts[after_part_start_id].value); parts[before_part_start_id].meta.next = after_start_meta.next; parts[after_start_meta.next].meta.before = before_part_start_id; return {part_id, at_char}; }; const auto merge_parts = [this](Part::Meta start_meta, Part::Meta end_meta) -> std::pair<int, int> { const int before_part_start_id = start_meta.before; const int after_part_start_id = start_meta.next; const int before_part_end_id = end_meta.before; const int after_part_end_id = end_meta.next; const int part_id = before_part_start_id; const int at_char = parts[part_id].value.size(); /* * if after_part_start_id != before_part_end_id: * equ_start -> A -> start -> B -> ... -> C -> end -> D -> equ_end * append D to C * make C's next into D's next * make C's new next's before into C * equ_start -> A -> start -> B -> ... -> CD -> equ_end * append B to A * make A's next into B's next * make CD's next's before into C * equ_start -> A -> start -> B -> ... -> CD -> equ_end */ /* * if after_part_start_id == before_part_end_id: * equ_start -> A -> start -> B -> end -> C -> equ_end * append C to B * make B's next into C's next * make B's new next's before into B * equ_start -> A -> start -> BC -> equ_end * append BC to A * make A's next into BC's next * make A's next's before into A * equ_start -> ABC -> equ_end */ Part::Meta after_end_meta = parts[after_part_end_id].meta; parts[before_part_end_id].value.append(parts[after_part_end_id].value); parts[before_part_end_id].meta.next = after_end_meta.next; parts[after_end_meta.next].meta.before = before_part_end_id; Part::Meta after_start_meta = parts[after_part_start_id].meta; parts[before_part_start_id].value.append(parts[after_part_start_id].value); parts[before_part_start_id].meta.next = after_start_meta.next; parts[after_start_meta.next].meta.before = before_part_start_id; return {part_id, at_char}; }; Part::Meta start_meta = parts[parts[current_part_id].meta.before].meta; // select the special chunk before the writing area we're in // Don't allow deleting the first chunk or chunks we're after the end of. chunks have to be deleted from the front of the inside if((!(start_meta.special == Part::Specialty::Paren || start_meta.special == Part::Specialty::TempParen) && check_pos_is(start_meta.position, Part::Position::End)) || start_meta.special == Part::Specialty::Equation) return false; if(start_meta.special == Part::Specialty::Fraction) { Part::Meta middle_meta = parts[start_meta.assoc].meta; Part::Meta end_meta = parts[middle_meta.assoc].meta; merge_parts(middle_meta, end_meta); const int before_part_start_id = start_meta.before; const int part_id = before_part_start_id; const int at_char = parts[part_id].value.size(); Part::Meta after_start_meta = parts[start_meta.next].meta; parts[before_part_start_id].value.append(parts[start_meta.next].value); parts[before_part_start_id].meta.next = after_start_meta.next; parts[after_start_meta.next].meta.before = before_part_start_id; current_part_id = part_id; at_position = at_char; return true; } else if(start_meta.special == Part::Specialty::Paren) { parts[start_meta.assoc].meta.assoc = -1; parts[start_meta.assoc].meta.special = Part::Specialty::TempParen; std::tie(current_part_id, at_position) = merge_single_part(start_meta); return true; } else if(start_meta.special == Part::Specialty::TempParen) { std::tie(current_part_id, at_position) = merge_single_part(start_meta); return true; } else { std::tie(current_part_id, at_position) = merge_parts(start_meta, parts[start_meta.assoc].meta); return true; } } else { at_position -= 1; parts[current_part_id].value.erase(at_position, 1); return true; } } bool Equation::left_of(int& current_part_id, int& at_position) { if(at_position != 0) { at_position--; return true; } if(parts[parts[current_part_id].meta.before].meta.special != Part::Specialty::Equation) { do { current_part_id = parts[current_part_id].meta.before; } while(parts[current_part_id].meta.special != Part::Specialty::None); at_position = parts[current_part_id].value.size(); return true; } return false; } bool Equation::right_of(int& current_part_id, int& at_position) { if(static_cast<size_t>(at_position) != parts[current_part_id].value.size()) { at_position++; return true; } if(parts[parts[current_part_id].meta.next].meta.special != Part::Specialty::Equation) { do { current_part_id = parts[current_part_id].meta.next; } while(parts[current_part_id].meta.special != Part::Specialty::None); at_position = 0; return true; } return false; }
38.83914
236
0.492881
01e39ce818b54c879e1b196b68ac199bd3856752
2,133
cpp
C++
Sources/AGEngine/Utils/Frustum.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Utils/Frustum.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Utils/Frustum.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#pragma once #include "Frustum.hh" #include <glm/glm.hpp> namespace AGE { void Frustum::buildPlanes() { _planes[PLANE_NEAR].setCoefficients( _viewProj[0][2] + _viewProj[0][3], _viewProj[1][2] + _viewProj[1][3], _viewProj[2][2] + _viewProj[2][3], _viewProj[3][2] + _viewProj[3][3]); _planes[PLANE_FAR].setCoefficients( -_viewProj[0][2] + _viewProj[0][3], -_viewProj[1][2] + _viewProj[1][3], -_viewProj[2][2] + _viewProj[2][3], -_viewProj[3][2] + _viewProj[3][3]); _planes[PLANE_BOTTOM].setCoefficients( _viewProj[0][1] + _viewProj[0][3], _viewProj[1][1] + _viewProj[1][3], _viewProj[2][1] + _viewProj[2][3], _viewProj[3][1] + _viewProj[3][3]); _planes[PLANE_TOP].setCoefficients( -_viewProj[0][1] + _viewProj[0][3], -_viewProj[1][1] + _viewProj[1][3], -_viewProj[2][1] + _viewProj[2][3], -_viewProj[3][1] + _viewProj[3][3]); _planes[PLANE_LEFT].setCoefficients( _viewProj[0][0] + _viewProj[0][3], _viewProj[1][0] + _viewProj[1][3], _viewProj[2][0] + _viewProj[2][3], _viewProj[3][0] + _viewProj[3][3]); _planes[PLANE_RIGHT].setCoefficients( -_viewProj[0][0] + _viewProj[0][3], -_viewProj[1][0] + _viewProj[1][3], -_viewProj[2][0] + _viewProj[2][3], -_viewProj[3][0] + _viewProj[3][3]); } void Frustum::setMatrix(const glm::mat4 &viewProj) { if (_viewProj != viewProj) { _viewProj = viewProj; buildPlanes(); } } bool Frustum::checkCollision(AABoundingBox const &aabb) const { for (int i = 0; i < PLANE_END; i++) { if (_planes[i].getPointDistance(aabb.getPositivePoint(_planes[i].getNormal())) < 0) return (false); } return (true); } bool Frustum::checkCollision(Sphere const &sphere) const { assert(!"Not implemented"); return (false); } bool Frustum::checkCollision(glm::vec4 const &sphere) const { for (int i = 0; i < PLANE_END; i++) { float dist = _planes[i].getPointDistance(glm::vec3(sphere)); if (dist + sphere.w < 0) return (false); } return (true); } bool Frustum::checkCollision(Frustum const &frustum) const { assert(!"Not implemented"); return (false); } }
23.966292
86
0.631036
01e7355d0093d04bd17cd74177abaa99133bd59e
20,259
cpp
C++
render_algorithms/ripgen-fbo/src/UI.cpp
itsermo/holovideo-algorithms
6b39f896a8c61d2a82a7314efc583940d685dd55
[ "BSD-3-Clause" ]
3
2018-02-26T19:53:10.000Z
2020-01-16T14:30:02.000Z
render_algorithms/ripgen-fbo/src/UI.cpp
itsermo/holovideo-algorithms
6b39f896a8c61d2a82a7314efc583940d685dd55
[ "BSD-3-Clause" ]
null
null
null
render_algorithms/ripgen-fbo/src/UI.cpp
itsermo/holovideo-algorithms
6b39f896a8c61d2a82a7314efc583940d685dd55
[ "BSD-3-Clause" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "setupglew.h" #include <GL/gl.h> #include <GL/glu.h> #include <GL/glxew.h> //#include <GL/glx.h> //for Nvida Framelock code #include <GL/glut.h> #include "JSharedMemory.h" #include "JSequencer.h" #include "JDisplayState.h" #include "RIP.h" #include "UI.h" #include "flyRender.h" #include "holoren.h" #include <sys/time.h> //headers for 3d mouse #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <X11/Xatom.h> #include <X11/keysym.h> #include "xdrvlib.h" #include <stdio.h> /* for printf and NULL */ #include <stdlib.h> /* for exit */ #include <string.h> #include <GL/gl.h> // The GL Header File #include <GL/glut.h> // The GL Utility Toolkit (Glut) Header //#include <GL/glx.h> //end 3d mouse headers static HoloRenderParams *holoRenParams = NULL; static HoloRenderParams *holoRenParams2 = NULL; static RIPHologram *ripParams = NULL; static RIPHologram *ripParams2 = NULL; //static int attributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None }; //JB: The only use of this was if'd out of Tyler's old code. static Display *dpy; //static Window win; //static XVisualInfo *vi; //not used //static XSetWindowAttributes swa; //not used static GLXContext cx; static JDisplayState statecopy; static JSharedMemory *sharedstate; float MASTER_GAIN = 0.7; //this is overridden by the external UI double MagellanSensitivity = 1.0; Display *dsp; Window root, drw; XEvent report; MagellanFloatEvent MagellanEvent; int fringeToUse = 0; bool freeSpin = false; // should object be sipinning for demo? static bool ismaster = false; // is this instance the one that has keyboard/mouse? For now, pick based on screen number & make sure 0 is opened last. static JSharedMemory* sharedFilename; static JSharedMemory* sharedDepthA; static JSharedMemory* sharedDepthB; static JSequencer* sequencer = NULL; //#define FILENAME_KEY 6624 //#define DEPTH_A_KEY 6625 //#define DEPTH_B_KEY 6626 void spaceball() { if(!dsp) return; XEvent report; report.type = 0; if(XPending(dsp) <= 0) return; XNextEvent( dsp, &report ); //BLOCKING. BOO. Hopefully checking for pending events above keeps this from blocking if (!XCheckTypedEvent(dsp, ClientMessage, &report)) { //no event return; } switch( report.type ) { case ClientMessage : switch( MagellanTranslateEvent( dsp, &report, &MagellanEvent, 1.0, 1.0 ) ) { case MagellanInputMotionEvent : MagellanRemoveMotionEvents( dsp ); printf( "x=%+5.0lf y=%+5.0lf z=%+5.0lf a=%+5.0lf b=%+5.0lf c=%+5.0lf \n", MagellanEvent.MagellanData[ MagellanX ], MagellanEvent.MagellanData[ MagellanY ], MagellanEvent.MagellanData[ MagellanZ ], MagellanEvent.MagellanData[ MagellanA ], MagellanEvent.MagellanData[ MagellanB ], MagellanEvent.MagellanData[ MagellanC ] ); ripParams->m_render->motion(MagellanEvent.MagellanData[ MagellanX ], -MagellanEvent.MagellanData[ MagellanZ ]); ripParams->m_render->spin(MagellanEvent.MagellanData[ MagellanA ]/100.0, MagellanEvent.MagellanData[ MagellanB ]/100.0); // XClearWindow( drw, drw ); // XDrawString( drw, drw, wingc, 10,40, //MagellanBuffer, (int)strlen(MagellanBuffer) ); // XFlush( display ); //tz= MagellanEvent.MagellanData[ MagellanZ]; break; switch( MagellanEvent.MagellanButton ) { case 5: MagellanSensitivity = MagellanSensitivity <= 1.0/32.0 ? 1.0/32.0 : MagellanSensitivity/2.0; break; case 6: MagellanSensitivity = MagellanSensitivity >= 32.0 ? 32.0 : MagellanSensitivity*2.0; break; } default : // another ClientMessage event break; }; break; }; } void loadModelIfChanged(char* newname) { if(strncmp(newname, ripParams2->m_render->loadedFile, 1024)) { ripParams2->m_render->config(newname); ripParams2->m_render->init(); //load the new configuration! //TODO: verify that this doesn't blow anything up. } } void display(void) { struct timeval tp; struct timezone tz; //uncomment to restore spaceball rotation (flaky?) //spaceball(); //JB: window gets reset somehow. Let's try fixing before we draw //if ((holoRenParams->m_framebufferNumber % 2) == 0) { // glutPositionWindow(0,hit); //} //glutReshapeWindow(wid,hit); #ifdef SCREEN_SIZE_DIAGNOSTICS //Some JB Diagnostics: { int screenHeight = glutGet(GLUT_SCREEN_HEIGHT); int screenWidth = glutGet(GLUT_SCREEN_WIDTH); int windowWidth = glutGet(GLUT_WINDOW_WIDTH); int windowHeight = glutGet(GLUT_WINDOW_HEIGHT); int windowXPos = glutGet(GLUT_WINDOW_X); int windowYPos = glutGet(GLUT_WINDOW_Y); printf("At top of display function,\n"); printf("The glut Current Window is %d\n", glutGetWindow()); printf("Screen is %d by %d\n", screenWidth, screenHeight); printf("OpenGL window is %d by %d\n", windowWidth, windowHeight); printf("Window is located at %d, %d\n",windowXPos, windowYPos); } #endif #ifdef XSCREENDUMP static int framect = 0; system("xwd -display localhost:0.0 -root -screen -silent | xwdtopnm 2>/dev/null | pnmtopng > ~/screendump.png"); printf("dumped screen to screendump.png\n"); if (framect++ == 5) exit(0); #endif //**** get current state from shared memory //get state from UI & update model #ifndef IGNORE_GUI sharedstate->getDataCopy(&statecopy); MASTER_GAIN = statecopy.gain; if(ripParams) { ripParams->m_render->models->orient->rotate[0] = statecopy.xrot; ripParams->m_render->models->orient->rotate[1] = statecopy.yrot; ripParams->m_render->models->orient->rotate[2] = statecopy.zrot; ripParams->m_render->models->orient->translate[0] = statecopy.xpos; ripParams->m_render->models->orient->translate[1] = statecopy.ypos; ripParams->m_render->models->orient->translate[2] = statecopy.zpos; if(ripParams->m_flatrender != statecopy.rendermode1) { ripParams->m_flatrender = statecopy.rendermode1; if(ripParams->m_flatrender == 0) //switch to RIP Method { ripParams->m_projectionPlaneDist = RIP_PROJ_PLANE; ripParams->recomputeGeometry(ripParams->m_holorenparams); } else //switch to planar method { ripParams->m_projectionPlaneDist = statecopy.flatdepth1; ripParams->recomputeGeometry(ripParams->m_holorenparams); } } if(ripParams->m_flatrender && (statecopy.flatdepth1 != ripParams->m_projectionPlaneDist)) { ripParams->m_projectionPlaneDist = statecopy.flatdepth1; ripParams->recomputeGeometry(ripParams->m_holorenparams); } } if(ripParams2) { ripParams2->m_render->models->orient->rotate[0] = statecopy.xrot; ripParams2->m_render->models->orient->rotate[1] = statecopy.yrot; ripParams2->m_render->models->orient->rotate[2] = statecopy.zrot; //ripParams2->m_render->models->orient->translate[0] = statecopy.xpos; //ripParams2->m_render->models->orient->translate[1] = statecopy.ypos; //ripParams2->m_render->models->orient->translate[2] = statecopy.zpos; if(ripParams2->m_flatrender != statecopy.rendermode2) { ripParams2->m_flatrender = statecopy.rendermode2; if(ripParams2->m_flatrender == 0) //switch to RIP Method { ripParams2->m_projectionPlaneDist = RIP_PROJ_PLANE; ripParams2->recomputeGeometry(ripParams2->m_holorenparams); } else //switch to planar method { ripParams2->m_projectionPlaneDist = statecopy.flatdepth2; ripParams2->recomputeGeometry(ripParams2->m_holorenparams); } } if(ripParams2->m_flatrender && (statecopy.flatdepth2 != ripParams2->m_projectionPlaneDist)) { ripParams2->m_projectionPlaneDist = statecopy.flatdepth2; ripParams2->recomputeGeometry(ripParams2->m_holorenparams); } } #endif /*char newname[1024]; if(sharedFilename->getDataCopyIfUnlocked(newname)) { loadModelIfChanged(newname); } float newdepthA; float newdepthB; sharedDepthA->getDataCopyIfUnlocked(&newdepthA); if(newdepthA != ripParams->m_projectionPlaneDist) { ripParams->m_projectionPlaneDist = newdepthA; ripParams->recomputeGeometry(ripParams->m_holorenparams); } sharedDepthB->getDataCopyIfUnlocked(&newdepthB); if(newdepthB != ripParams2->m_projectionPlaneDist) { ripParams2->m_projectionPlaneDist = newdepthB; ripParams2->recomputeGeometry(ripParams2->m_holorenparams); } */ //**** render //black the color buffer glClearColor(0.0,0.0,0.0,0.0); glClear (GL_COLOR_BUFFER_BIT); sequencer->update(); if(ripParams2 != NULL) { glPushAttrib(GL_ALL_ATTRIB_BITS); ripParams2->DisplayRIPHologramSingleFramebuffer(holoRenParams2); glPopAttrib(); } glPushAttrib(GL_ALL_ATTRIB_BITS); // calls RIPHologram::DisplayRIPHologramSingleFramebuffer (in RIP.cpp) ripParams->DisplayRIPHologramSingleFramebuffer(holoRenParams); glPopAttrib(); glFlush(); glutSwapBuffers(); //JB: Make it move #ifdef SPIN_OBJECT_HACK if(freeSpin) { if(ripParams) ripParams->m_render->spin(2, 0); if(ripParams2) ripParams2->m_render->spin(-1.5,0); } #endif //warp pointer back to center of screen if it isn't already there. int cx, cy; #ifndef LOCKED_UI cx = glutGet(GLUT_WINDOW_WIDTH)/2; cy = glutGet(GLUT_WINDOW_HEIGHT)/2; if(ripParams->m_render->mLX != cx || ripParams->m_render->mLY != cy) { glutWarpPointer(cx,cy); ripParams->m_render->mLX = cx; ripParams->m_render->mLY = cy; } #endif glutPostRedisplay(); //JB: This causes glut to continue to repeatedly execute display() #ifdef TIMING_DIAGNOSTICS { gettimeofday(&tp, &tz); printf("time now is: %ld sec %ld usec \n", tp.tv_sec, tp.tv_usec); printf("time now is: (tp.tv_sec*100000)/100000)\n"); } #endif #ifdef SCREEN_SIZE_DIAGNOSTICS int screenHeight = glutGet(GLUT_SCREEN_HEIGHT); int screenWidth = glutGet(GLUT_SCREEN_WIDTH); int windowWidth = glutGet(GLUT_WINDOW_WIDTH); int windowHeight = glutGet(GLUT_WINDOW_HEIGHT); int windowXPos = glutGet(GLUT_WINDOW_X); int windowYPos = glutGet(GLUT_WINDOW_Y); printf("After buffer swap,\n"); printf("The glut Current Window is %d\n", glutGetWindow()); printf("Screen is %d by %d\n", screenWidth, screenHeight); printf("OpenGL window is %d by %d\n", windowWidth, windowHeight); printf("Window is located at %d, %d\n",windowXPos, windowYPos); #endif #ifdef WRITE_FB_TO_FILE unsigned char *pic; unsigned char *bptr; FILE *fp; int allocfail = 0; printf("attempting to write framebuffer to file"); if ((pic = (unsigned char*)malloc(screenWidth*screenHeight*3 * sizeof(unsigned char))) == NULL) { printf("couldn't allocate memory for framebuffer dump.\n"); allocfail = 1; } if ( !allocfail) { char fname[255]; glReadBuffer(GL_FRONT); bptr = pic; glReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pic); printf("saving %dx%dx3 to file...\n", screenWidth,screenHeight); sprintf(fname, "FBcontents%d.raw", holoRenParams->m_framebufferNumber); if ( (fp = fopen (fname, "w")) == NULL) { printf("failure opening file.\n"); exit(0); } else { if (fwrite (pic, 1, 3*screenWidth*screenHeight, fp) != screenWidth*screenHeight*3) { printf("failure writing file.\n"); //exit(0); } fclose (fp); } free (pic); } exit(1); #endif } //called by GLUT on mouseup and mousedown void mouse(int button, int state, int x, int y) { // calls holoConf::mouse which sets cursor state and mousebutton state ripParams->m_render->mouse(button, state, x, y); } //called by GLUT on mouse move (buttons up only) //keep mouse at middle of screen void passiveMotion(int x, int y) { //TODO: check for recursive events? Dead zone? #ifndef LOCKED_UI glutWarpPointer(holoRenParams->m_xRes/2,holoRenParams->m_yRes); #endif } //called by GLUT on drag void motion(int x, int y) { // calls holoConf::motion() which appears to // translate the scene based on mouse movement. ripParams->m_render->motion(x, y); } void keyboard(unsigned char key, int x, int y) { printf("got key \"%c\" on screen %d\n", key, holoRenParams->m_framebufferNumber); sequencer->keypress(key); #ifndef LOCKED_UI switch(key) { case 'q': case 'Q': exit(0); break; case 'a': fringeToUse ++; if(fringeToUse >= NUM_PRECOMPUTED_FRINGES) fringeToUse = NUM_PRECOMPUTED_FRINGES-1; printf("using fringe %d\n", fringeToUse); ripParams->m_fringeToUse = fringeToUse; glutPostRedisplay(); break; case 'A': fringeToUse--; if(fringeToUse < 0) fringeToUse = 0; printf("using fringe %d\n", fringeToUse); ripParams->m_fringeToUse = fringeToUse; glutPostRedisplay(); break; case ' ': freeSpin = !freeSpin; glutPostRedisplay(); break; case 'd': ripParams->m_projectionPlaneDist += 1.0; printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist); ripParams->recomputeGeometry(ripParams->m_holorenparams); break; case 'D': ripParams->m_projectionPlaneDist -= 1.0; printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist); ripParams->recomputeGeometry(ripParams->m_holorenparams); break; case 'l' : //if(ismaster) { char fname[1024] = "/models/letters/SLOAN/C.xml"; sharedFilename->write(fname); loadModelIfChanged(fname); } break; case 'k' : //if(ismaster) { char fname[1024] = "/models/letters/SLOAN/K.xml"; sharedFilename->write(fname); loadModelIfChanged(fname); } break; }; // calls holoConf::keyboard() which adds other commands: // + = +ztranlate // - = -ztranslate // 4 = -xtranslate // 6 = +xtranslate // 8 = -ytranslate // 2 = +ytranslate ripParams->m_render->keyboard(key, x, y); #endif } //JB: for testing on desktop display: void reshape(int w, int h) { glViewport(0,0,(GLsizei)w, (GLsizei)h); glutPostRedisplay(); } // setup UI // uses structs holoRenParams. void InitGL(int &argc, char **&argv, HoloRenderParams *hrP, RIPHologram *ripP, HoloRenderParams *hrP2, RIPHologram *ripP2) { holoRenParams = hrP; ripParams = ripP; holoRenParams2 = hrP2; ripParams2 = ripP2; printf("initializing GL\n"); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL | GLUT_ACCUM); //instance on framebuffer 0 gets to interact with keyboard & send events to other instances. if(holoRenParams->m_framebufferNumber == 0) { ismaster = true; } else { ismaster = false; } //state for slaving to separate UI sharedstate = new JSharedMemory(sizeof(JDisplayState),ALL_STATE_KEY); sharedstate->getDataCopy(&statecopy); /* sharedFilename = new JSharedMemory(1024,FILENAME_KEY); sharedDepthA = new JSharedMemory(sizeof(float),DEPTH_A_KEY); sharedDepthB = new JSharedMemory(sizeof(float),DEPTH_B_KEY); */ /* char f[1024] = "/models/blankframe.xml"; sharedFilename->write(f); //initalize z-distance to first & second hologram. float pdA = 10; float pdB = 128; sharedDepthA->write(&pdA); sharedDepthB->write(&pdB); */ //TODO: get subject ID! // glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); //glutInitDisplayString("xvisual=250");//doesn't seem to work //glutInitDisplayString("depth=>1 rgba>1");//doesn't seem to work // set up window size to be (these are hardcoded in RIP.h) 2048x(2*1780) //(2 vertically stacked "framebuffers" worth per window) glutInitWindowSize(holoRenParams->m_xRes,holoRenParams->m_yRes*2); //glutInitWindowSize(2048,holoRenParams->m_yRes*2); // TODO: Update block comment for version 3.0. // Bottom line: each PC has 2 framebuffers, one window. // PCnumber = floor(framebufferNumber/2) has one window, with framebuffer // number PCnumber*2+1 on top and PCnumber*2 on bottom half of screen. // previously, we had one window per framebuffer, but the two windows on the // same video card liked to fight. // WJP's note from pre-3.0 version: // In holocomputation, we assume that hololines are apportioned // in logical order in FB0, FB1, FB2, FB3, FB4 and FB5, and comments // throughout the code reflect this. FB0 gets hololines 0,1,2, 18,19,20,... // and FB1 gets hololines 3,4,5, 21,22,23... and so on. And the // scripts: /home/holovideox/local/framebuffer1 and framebuffer2 return // 0 and 1 on holovideo1, 2 and 3 on holovideo2, and 4 and 5 on holovideo3 // respectively. // Here's what we've learned about the way framebuffers on // holovideo1, holovideo2, holovideo3 map to holoLines. // on holovideo1, framebufferNumber 1 has the top 3 hololines. // framebufferNumber 0 has the next 3 hololines. // on holovideo2, framebufferNumber 3 has the next 3 hololines. // framebufferNumber 2 has the next three lines. // on holovideo3, framebufferNumber 5 has the next three lines, and // framebufferNumber 4 has the bottom three lines. // our software assumes that lines are arranged from top to bottom // in framebufferNumber 0 - 5. So, we swap the position of the output // windows for FBs (0and1) (2and3) (4and5) in UI.cpp, // so that FB0's output window is at (0,m_viewYRes) and FB1's is at (0,0). // I hope this is understandable. //JB removed for version 3.0 //if((hrP->m_framebufferNumber % 2) == 1) //{ glutInitWindowPosition(0, 0); //} else { // glutInitWindowPosition(0, hrP->m_yRes); //} // specifies display, keyboard, mouse, motion callacks, // configures window and turns OFF the cursor! int winnum = glutCreateWindow("HoloLoadExec"); //title is hint to window manager to not decorate window GLenum glewerr = glewInit(); if(GLEW_OK != glewerr) { printf("Glew Init Failed! (%s) \n", glewGetErrorString(glewerr)); } glutDisplayFunc(display); GLuint numgroups,numbars; int ret; #ifdef USE_HARDWARE_GENLOCK //Code block to turn on buffer swap syncronization using genlock hardware ret = glXQueryMaxSwapGroupsNV(dsp,drw,&numgroups, &numbars); if (!ret) printf("Couldn't query swap group info\n"); ret = glXJoinSwapGroupNV(dsp,drw,1);//Make our drawable part of framelock group zero if (!ret) printf("Failed to start swap group\n"); ret = glXBindSwapBarrierNV(dsp,1,1);//make framelock group zero part of barrier zero if (!ret) printf("Failed to start swap barrier\n"); printf("System supports %d groups and %d barriers\n", numgroups, numbars); #endif #ifdef WORKSTATION_DEBUG glutReshapeFunc(reshape); #endif glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutMotionFunc(motion); glutPassiveMotionFunc(passiveMotion); //glutFullScreen(); glutSetCursor(GLUT_CURSOR_NONE); //TODO: This will probably need to change with three wimultaneous windows... glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH)/2, glutGet(GLUT_WINDOW_HEIGHT)/2); // move mouse to center of display //Set up Spaceball/SpaceNavigator support GLXDrawable drw = glXGetCurrentDrawable(); dsp = glXGetCurrentDisplay(); if ( !MagellanInit( dsp, drw ) ) { fprintf( stderr, "Can't find the spaceball driver. try running:\n sudo /etc/3DxWare/daemon/3dxsrv -d usb \n" ); } //testing GLX capabilities... int vid = glutGet(GLUT_WINDOW_FORMAT_ID); printf("Using openGL visual #%d. See visualinfo for more information\n", vid); XVisualInfo* newVisual = NULL; int visattrib[] = {GLX_RGBA, GLX_RED_SIZE, 64}; newVisual = glXChooseVisual(dsp, 0, visattrib); sequencer = new JSequencer("HoloLayerLetter", 0, holoRenParams->m_framebufferNumber, hrP, ripP, hrP2, ripP2); //Some JB Diagnostics: #ifdef SCREEN_SIZE_DIAGNOSTICS { int screenHeight = glutGet(GLUT_SCREEN_HEIGHT); int screenWidth = glutGet(GLUT_SCREEN_WIDTH); int windowWidth = glutGet(GLUT_WINDOW_WIDTH); int windowHeight = glutGet(GLUT_WINDOW_HEIGHT); int windowXPos = glutGet(GLUT_WINDOW_X); int windowYPos = glutGet(GLUT_WINDOW_Y); printf("Before starting main loop,\n"); printf("glutCreateWindow returned window ID %d\n", winnum); printf("The glut Current Window is %d\n", glutGetWindow()); printf("Screen is %d by %d\n", screenWidth, screenHeight); printf("OpenGL window is %d by %d\n", windowWidth, windowHeight); printf("Window is located at %d, %d\n",windowXPos, windowYPos); printf("swapped buffers: you should SEE something on the display now...\n"); } #endif } //I don't think this ever gets called (JB); void CloseGL() { // glXDestroyContext(dpy, cx); // XDestroyWindow(dpy, win); // XCloseDisplay(dpy); }
27.982044
149
0.710203
543527a510cb32554b395028916e54e8d894c42f
775
cpp
C++
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#include "../../../include/xtd/reflection/assembly_title_attribute.h" using namespace std; using namespace xtd; using namespace xtd::reflection; assembly_title_attribute::assembly_title_attribute(const ustring& title) : title_(title) { } assembly_title_attribute::assembly_title_attribute(const ustring& title, const object& executing_assembly) : title_(title) { __assembly_title_attribute__() = make_shared<xtd::reflection::assembly_title_attribute>(title); } shared_ptr<object> assembly_title_attribute::get_type_id() const { return xtd::guid::new_guid().memberwise_clone<xtd::guid>(); } shared_ptr<xtd::reflection::assembly_title_attribute>& __assembly_title_attribute__() { static shared_ptr<xtd::reflection::assembly_title_attribute> title; return title; }
35.227273
124
0.79871
543567ad7d0c1ef880e252e10dc15d03a3e809d8
29,672
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2004-2007, Ron Fedkiw, Eran Guendelman, Nipun Kwatra, Frank Losasso, Andrew Selle, Tamar Shinar, Jonathan Su, Jerry Talton. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Arrays_Computations/MAGNITUDE.h> #include <PhysBAM_Tools/Grids_Dyadic/OCTREE_GRID.h> #include <PhysBAM_Tools/Grids_Dyadic/QUADTREE_GRID.h> #include <PhysBAM_Tools/Grids_Uniform/GRID.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_NODE.h> #include <PhysBAM_Tools/Grids_Uniform_Arrays/FACE_ARRAYS.h> #include <PhysBAM_Tools/Grids_Uniform_Boundaries/BOUNDARY_UNIFORM.h> #include <PhysBAM_Tools/Krylov_Solvers/IMPLICIT_SOLVE_PARAMETERS.h> #include <PhysBAM_Tools/Log/LOG.h> #include <PhysBAM_Tools/Math_Tools/RANGE.h> #include <PhysBAM_Tools/Matrices/MATRIX_4X4.h> #include <PhysBAM_Tools/Parsing/PARSE_ARGS.h> #include <PhysBAM_Tools/Read_Write/Grids_Uniform/READ_WRITE_GRID.h> #include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_ARRAYS.h> #include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_FACE_ARRAYS.h> #include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_MATRIX_1X1.h> #include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_SYMMETRIC_MATRIX_2X2.h> #include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_SYMMETRIC_MATRIX_3X3.h> #include <PhysBAM_Tools/Read_Write/Point_Clouds/READ_WRITE_POINT_CLOUD.h> #include <PhysBAM_Geometry/Basic_Geometry/CYLINDER.h> #include <PhysBAM_Geometry/Basic_Geometry/SPHERE.h> #include <PhysBAM_Geometry/Collisions/RIGID_COLLISION_GEOMETRY.h> #include <PhysBAM_Geometry/Grids_Dyadic_Level_Sets/LEVELSET_OCTREE.h> #include <PhysBAM_Geometry/Grids_Dyadic_Level_Sets/LEVELSET_QUADTREE.h> #include <PhysBAM_Geometry/Grids_RLE_Level_Sets/LEVELSET_RLE.h> #include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_FACE_BINARY_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_FACE_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Collisions/GRID_BASED_COLLISION_GEOMETRY_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Level_Sets/FAST_LEVELSET.h> #include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_FAST_LEVELSET.h> #include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_1D.h> #include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_2D.h> #include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_3D.h> #include <PhysBAM_Geometry/Read_Write/Implicit_Objects_Uniform/READ_WRITE_LEVELSET_IMPLICIT_OBJECT.h> #include <PhysBAM_Geometry/Topology_Based_Geometry/TRIANGULATED_SURFACE.h> #include <PhysBAM_Solids/PhysBAM_Deformables/Collisions_And_Interactions/TRIANGLE_COLLISION_PARAMETERS.h> #include <PhysBAM_Solids/PhysBAM_Deformables/Deformable_Objects/DEFORMABLE_BODY_COLLECTION.h> #include <PhysBAM_Solids/PhysBAM_Rigids/Rigid_Bodies/RIGID_BODY.h> #include <PhysBAM_Solids/PhysBAM_Rigids/Rigid_Bodies/RIGID_BODY_EVOLUTION_PARAMETERS.h> #include <PhysBAM_Solids/PhysBAM_Solids/Solids/SOLID_BODY_COLLECTION.h> #include <PhysBAM_Solids/PhysBAM_Solids/Solids/SOLIDS_PARAMETERS.h> #include <PhysBAM_Solids/PhysBAM_Solids/Solids_Evolution/NEWMARK_EVOLUTION.h> #include <PhysBAM_Fluids/PhysBAM_Compressible/Euler_Equations/EULER_LAPLACE.h> #include <PhysBAM_Fluids/PhysBAM_Compressible/Euler_Equations/EULER_UNIFORM.h> #include <PhysBAM_Fluids/PhysBAM_Fluids/Coupled_Evolution/COMPRESSIBLE_INCOMPRESSIBLE_COUPLING_UTILITIES.h> #include <PhysBAM_Fluids/PhysBAM_Incompressible/Collisions_And_Interactions/DEFORMABLE_OBJECT_FLUID_COLLISIONS.h> #include <PhysBAM_Fluids/PhysBAM_Incompressible/Collisions_And_Interactions/FLUID_COLLISION_BODY_INACCURATE_UNION.h> #include <PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.h> #include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_COMPRESSIBLE_FLUID_COUPLING_UTILITIES.h> #include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_FLUID_COUPLED_EVOLUTION.h> #include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_FLUID_COUPLED_EVOLUTION_SLIP.h> #include <PhysBAM_Dynamics/Coupled_Evolution/UNIFORM_COLLISION_AWARE_ITERATOR_FACE_INFO.h> #include <PhysBAM_Dynamics/Forces_And_Torques/EULER_FLUID_FORCES.h> #include <PhysBAM_Dynamics/Geometry/GENERAL_GEOMETRY_FORWARD.h> #include <PhysBAM_Dynamics/Incompressible_Flows/INCOMPRESSIBLE_MULTIPHASE_UNIFORM.h> #include <PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_EVOLUTION_MULTIPLE_UNIFORM.h> #include <PhysBAM_Dynamics/Particles/PARTICLES_FORWARD.h> #include <PhysBAM_Dynamics/Solids_And_Fluids/SOLIDS_FLUIDS_PARAMETERS.h> #include <stdexcept> using namespace PhysBAM; //##################################################################### // Constructor //##################################################################### template<class TV_PFE> PLS_FSI_EXAMPLE<TV_PFE>:: PLS_FSI_EXAMPLE(const STREAM_TYPE stream_type,const int number_of_regions) :BASE((Initialize_Particles(),stream_type)),solids_parameters(*new SOLIDS_PARAMETERS<TV_PFE>),solids_fluids_parameters(*new SOLIDS_FLUIDS_PARAMETERS<TV_PFE>(this)), solid_body_collection(*new SOLID_BODY_COLLECTION<TV_PFE>(this,0)),solids_evolution(new NEWMARK_EVOLUTION<TV_PFE>(solids_parameters,solid_body_collection)), fluids_parameters(number_of_regions,fluids_parameters.WATER,incompressible_fluid_container),resolution(0),convection_order(1),use_pls_evolution_for_structure(false), two_phase(false) { Initialize_Read_Write_General_Structures(); Set_Minimum_Collision_Thickness(); Set_Write_Substeps_Level(-1); } //##################################################################### // Destructor //##################################################################### template<class TV_PFE> PLS_FSI_EXAMPLE<TV_PFE>:: ~PLS_FSI_EXAMPLE() { fluids_parameters.projection=0; delete solids_evolution; delete &solid_body_collection; delete &solids_parameters; delete &solids_fluids_parameters; } //##################################################################### // Function Register_Options //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Register_Options() { if(!parse_args) return; BASE::Register_Options(); parse_args->Add_String_Argument("-params","","parameter file"); parse_args->Add_Double_Argument("-solidscfl",.9,"solids CFL"); parse_args->Add_Option_Argument("-solidscg","Use CG for time integration"); parse_args->Add_Option_Argument("-solidscr","Use CONJUGATE_RESIDUAL for time integration"); parse_args->Add_Option_Argument("-solidssymmqmr","Use SYMMQMR for time integration"); parse_args->Add_Double_Argument("-rigidcfl",.5,"rigid CFL"); parse_args->Add_Option_Argument("-skip_debug_data","turn off file io for debug data"); parse_args->Add_Integer_Argument("-resolution",1); } //##################################################################### // Function Parse_Options //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Parse_Options() { BASE::Parse_Options(); if(parse_args->Is_Value_Set("-skip_debug_data")) fluids_parameters.write_debug_data=false; resolution=parse_args->Get_Integer_Value("-resolution"); } //##################################################################### // Function Add_Volumetric_Body_To_Fluid_Simulation //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Add_Volumetric_Body_To_Fluid_Simulation(RIGID_BODY<TV_PFE>& rigid_body,bool add_collision,bool add_coupling) { RIGID_COLLISION_GEOMETRY<TV_PFE>* collision_geometry=new RIGID_COLLISION_GEOMETRY<TV_PFE>(rigid_body); if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(collision_geometry,rigid_body.particle_index,true); if(add_coupling) if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution)) coupled_evolution->iterator_info.coupling_bodies.Append(collision_geometry); if(rigid_body.simplicial_object) rigid_body.simplicial_object->Initialize_Hierarchy(); } //##################################################################### // Function Add_Thin_Shell_To_Fluid_Simulation //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Add_Thin_Shell_To_Fluid_Simulation(RIGID_BODY<TV_PFE>& rigid_body,bool add_collision,bool add_coupling) { RIGID_COLLISION_GEOMETRY<TV_PFE>* collision_geometry=new RIGID_COLLISION_GEOMETRY<TV_PFE>(rigid_body); if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(collision_geometry,rigid_body.particle_index,true); if(add_coupling) if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution)) coupled_evolution->iterator_info.coupling_bodies.Append(collision_geometry); rigid_body.thin_shell=true; if(collision_geometry->collision_thickness<minimum_collision_thickness) collision_geometry->Set_Collision_Thickness(minimum_collision_thickness); if(rigid_body.simplicial_object) rigid_body.simplicial_object->Initialize_Hierarchy(); } //##################################################################### // Function Add_To_Fluid_Simulation //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Add_To_Fluid_Simulation(DEFORMABLE_OBJECT_FLUID_COLLISIONS<TV_PFE>& deformable_collisions,bool add_collision,bool add_coupling) { if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(&deformable_collisions,0,false); if(add_coupling) if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution)) coupled_evolution->iterator_info.coupling_bodies.Append(&deformable_collisions); if(deformable_collisions.collision_thickness<minimum_collision_thickness) deformable_collisions.Set_Collision_Thickness(minimum_collision_thickness); deformable_collisions.Initialize_For_Thin_Shells_Fluid_Coupling(); } //##################################################################### // Function Get_Source_Velocities //##################################################################### template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>:: Get_Source_Velocities(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source,const TV_PFE& constant_source_velocity) { for(UNIFORM_GRID_ITERATOR_FACE<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()) if(source.Lazy_Inside(world_to_source.Homogeneous_Times(iterator.Location()))){ int axis=iterator.Axis();fluids_parameters.incompressible->projection.elliptic_solver->psi_N.Component(axis)(iterator.Face_Index())=true; incompressible_fluid_container.face_velocities.Component(axis)(iterator.Face_Index())=constant_source_velocity[axis];} } //##################################################################### // Function Get_Source_Velocities //##################################################################### template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>:: Get_Source_Velocities(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source,const TV_PFE& constant_source_velocity,const ARRAY<bool,FACE_INDEX<TV_PFE::m> >& invalid_mask) { for(UNIFORM_GRID_ITERATOR_FACE<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){const int axis=iterator.Axis();const TV_INT face_index=iterator.Face_Index(); if(!invalid_mask(axis,face_index) && source.Lazy_Inside(world_to_source.Homogeneous_Times(iterator.Location()))){ fluids_parameters.incompressible->projection.elliptic_solver->psi_N.Component(axis)(face_index)=true; incompressible_fluid_container.face_velocities.Component(axis)(face_index)=constant_source_velocity[axis];}} } //##################################################################### // Function Adjust_Phi_With_Source //##################################################################### template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>:: Adjust_Phi_With_Source(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source) { for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){TV_PFE source_X=world_to_source.Homogeneous_Times(iterator.Location()); if(source.Lazy_Inside(source_X)) fluids_parameters.particle_levelset_evolution->phi(iterator.Cell_Index())=min(fluids_parameters.particle_levelset_evolution->phi(iterator.Cell_Index()), source.Signed_Distance(source_X));} } //##################################################################### // Function Adjust_Phi_With_Source //##################################################################### template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>:: Adjust_Phi_With_Source(const GEOMETRY& source,const int region,const T_TRANSFORMATION_MATRIX& world_to_source) { T bandwidth=3*fluids_parameters.grid->Minimum_Edge_Length(); ARRAY<ARRAY<T,TV_INT> >& phis=fluids_parameters.particle_levelset_evolution_multiple->phis; for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){ TV_PFE source_X=world_to_source.Homogeneous_Times(iterator.Location()); if(source.Inside(source_X,-bandwidth)){ T source_signed_distance=source.Signed_Distance(source_X); for(int i=1;i<=fluids_parameters.number_of_regions;i++){ if(i==region) phis(i)(iterator.Cell_Index())=min(phis(i)(iterator.Cell_Index()),source_signed_distance); else phis(i)(iterator.Cell_Index())=max(phis(i)(iterator.Cell_Index()),-source_signed_distance);}}} } //##################################################################### // Function Revalidate_Fluid_Scalars //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Revalidate_Fluid_Scalars() { T_FAST_LEVELSET& levelset=fluids_parameters.particle_levelset_evolution->Levelset(1); T_FAST_LEVELSET_ADVECTION& levelset_advection=fluids_parameters.particle_levelset_evolution->Levelset_Advection(1); if(levelset_advection.nested_semi_lagrangian_collidable) levelset_advection.nested_semi_lagrangian_collidable->Average_To_Invalidated_Cells(*fluids_parameters.grid,fluids_parameters.collidable_phi_replacement_value,levelset.phi); } //##################################################################### // Function Revalidate_Phi_After_Modify_Levelset //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Revalidate_Phi_After_Modify_Levelset() { T_FAST_LEVELSET& levelset=fluids_parameters.particle_levelset_evolution->Levelset(1); T_FAST_LEVELSET_ADVECTION& levelset_advection=fluids_parameters.particle_levelset_evolution->Levelset_Advection(1); if(levelset_advection.nested_semi_lagrangian_collidable){ levelset_advection.nested_semi_lagrangian_collidable->cell_valid_points_current=levelset_advection.nested_semi_lagrangian_collidable->cell_valid_points_next; levelset_advection.nested_semi_lagrangian_collidable->Average_To_Invalidated_Cells(*fluids_parameters.grid,fluids_parameters.collidable_phi_replacement_value,levelset.phi);} } //##################################################################### // Function Revalidate_Fluid_Velocity //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Revalidate_Fluid_Velocity(ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities) { if(fluids_parameters.incompressible->nested_semi_lagrangian_collidable) fluids_parameters.incompressible->nested_semi_lagrangian_collidable->Average_To_Invalidated_Face(*fluids_parameters.grid,face_velocities); } //##################################################################### // Function Get_Object_Velocities //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Get_Object_Velocities(LAPLACE_UNIFORM<GRID<TV_PFE> >* elliptic_solver,ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities,const T dt,const T time) { if(fluids_parameters.solid_affects_fluid && (fluids_parameters.fluid_affects_solid || fluids_parameters.use_slip)){ if(!fluids_parameters.use_slip){ SOLID_FLUID_COUPLED_EVOLUTION<TV_PFE>& coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION<TV_PFE>&>(*solids_evolution); coupled_evolution.Apply_Solid_Boundary_Conditions(time,false,face_velocities);} else{ SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>& coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>&>(*solids_evolution); coupled_evolution.Get_Coupled_Faces_And_Interpolated_Solid_Velocities(time,elliptic_solver->psi_N,face_velocities);}} else fluids_parameters.collision_bodies_affecting_fluid->Compute_Psi_N(elliptic_solver->psi_N,&face_velocities); } //##################################################################### // Function Get_Levelset_Velocity //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Get_Levelset_Velocity(const GRID<TV_PFE>& grid,LEVELSET_MULTIPLE_UNIFORM<GRID<TV_PFE> >& levelset_multiple,ARRAY<T,FACE_INDEX<TV_PFE::m> >& V_levelset,const T time) const { ARRAY<T,FACE_INDEX<TV_PFE::m> >::Put(incompressible_fluid_container.face_velocities,V_levelset); } //##################################################################### // Function Initialize_Swept_Occupied_Blocks_For_Advection //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Initialize_Swept_Occupied_Blocks_For_Advection(const T dt,const T time,const ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities) { GRID<TV_PFE>& grid=*fluids_parameters.grid; T maximum_fluid_speed=face_velocities.Maxabs().Max(),maximum_particle_speed=0; PARTICLE_LEVELSET_UNIFORM<GRID<TV_PFE> >& particle_levelset=fluids_parameters.particle_levelset_evolution->Particle_Levelset(1); if(particle_levelset.use_removed_negative_particles) for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(particle_levelset.levelset.grid);iterator.Valid();iterator.Next()){ PARTICLE_LEVELSET_REMOVED_PARTICLES<TV_PFE>* particles=particle_levelset.removed_negative_particles(iterator.Cell_Index()); if(particles) maximum_particle_speed=max(maximum_particle_speed,ARRAYS_COMPUTATIONS::Maximum_Magnitude(particles->V));} if(particle_levelset.use_removed_positive_particles) for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(particle_levelset.levelset.grid);iterator.Valid();iterator.Next()){ PARTICLE_LEVELSET_REMOVED_PARTICLES<TV_PFE>* particles=particle_levelset.removed_positive_particles(iterator.Cell_Index()); if(particles) maximum_particle_speed=max(maximum_particle_speed,ARRAYS_COMPUTATIONS::Maximum_Magnitude(particles->V));} T max_particle_collision_distance=0; max_particle_collision_distance=max(max_particle_collision_distance,fluids_parameters.particle_levelset_evolution->Particle_Levelset(1).max_collision_distance_factor*grid.dX.Max()); fluids_parameters.collision_bodies_affecting_fluid->Compute_Occupied_Blocks(true, dt*max(maximum_fluid_speed,maximum_particle_speed)+2*max_particle_collision_distance+(T).5*fluids_parameters.p_grid.dX.Max(),10); } //##################################################################### // Function Delete_Particles_Inside_Objects //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Delete_Particles_Inside_Objects(PARTICLE_LEVELSET_PARTICLES<TV_PFE>& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T time) {} //##################################################################### // Function Read_Output_Files_Fluids //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Read_Output_Files_Fluids(const int frame) { fluids_parameters.Read_Output_Files(stream_type,output_directory,frame); incompressible_fluid_container.Read_Output_Files(stream_type,output_directory,frame); std::string f=STRING_UTILITIES::string_sprintf("%d",frame); } //##################################################################### // Function Write_Output_Files //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Write_Output_Files(const int frame) const { FILE_UTILITIES::Create_Directory(output_directory); std::string f=STRING_UTILITIES::string_sprintf("%d",frame); FILE_UTILITIES::Create_Directory(output_directory+"/"+f); FILE_UTILITIES::Create_Directory(output_directory+"/common"); Write_Frame_Title(frame); solid_body_collection.Write(stream_type,output_directory,frame,first_frame,solids_parameters.write_static_variables_every_frame, solids_parameters.rigid_body_evolution_parameters.write_rigid_bodies,solids_parameters.write_deformable_body,solids_parameters.write_from_every_process, solids_parameters.triangle_collision_parameters.output_interaction_pairs); if(NEWMARK_EVOLUTION<TV_PFE>* newmark=dynamic_cast<NEWMARK_EVOLUTION<TV_PFE>*>(solids_evolution)) newmark->Write_Position_Update_Projection_Data(stream_type,output_directory+"/"+f+"/"); fluids_parameters.Write_Output_Files(stream_type,output_directory,first_frame,frame); incompressible_fluid_container.Write_Output_Files(stream_type,output_directory,frame); } //##################################################################### // Function Log_Parameters //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Log_Parameters() const { LOG::SCOPE scope("PLS_FSI_EXAMPLE parameters"); BASE::Log_Parameters(); std::stringstream ss; ss<<"minimum_collision_thickness="<<minimum_collision_thickness<<std::endl; LOG::filecout(ss.str()); fluids_parameters.Log_Parameters(); } //##################################################################### // Function Read_Output_Files_Solids //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Read_Output_Files_Solids(const int frame) { solid_body_collection.Read(stream_type,output_directory,frame,frame,solids_parameters.write_static_variables_every_frame,solids_parameters.rigid_body_evolution_parameters.write_rigid_bodies, solids_parameters.write_deformable_body,solids_parameters.write_from_every_process); std::string f=STRING_UTILITIES::string_sprintf("%d",frame); //if(NEWMARK_EVOLUTION<TV_PFE>* newmark=dynamic_cast<NEWMARK_EVOLUTION<TV_PFE>*>(solids_evolution)) // newmark->Read_Position_Update_Projection_Data(stream_type,output_directory+"/"+f+"/"); } //##################################################################### // Function Parse_Late_Options //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Parse_Late_Options() { if(!parse_args) return; BASE::Parse_Late_Options(); if(parse_args->Is_Value_Set("-solidscfl")) solids_parameters.cfl=(T)parse_args->Get_Double_Value("-solidscfl"); if(parse_args->Is_Value_Set("-rigidcfl")) solids_parameters.rigid_body_evolution_parameters.rigid_cfl=(T)parse_args->Get_Double_Value("-rigidcfl"); if(parse_args->Is_Value_Set("-solidscg")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_cg; if(parse_args->Is_Value_Set("-solidscr")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_cr; if(parse_args->Is_Value_Set("-solidssymmqmr")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_symmqmr; } //##################################################################### // Function Adjust_Particle_For_Domain_Boundaries //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Adjust_Particle_For_Domain_Boundaries(PARTICLE_LEVELSET_PARTICLES<TV_PFE>& particles,const int index,TV_PFE& V,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time) { // remove this for speed - don't call the function for the other particles if(particle_type==PARTICLE_LEVELSET_POSITIVE || particle_type==PARTICLE_LEVELSET_REMOVED_POSITIVE) return; TV_PFE& X=particles.X(index);TV_PFE X_new=X+dt*V; T max_collision_distance=fluids_parameters.particle_levelset_evolution->particle_levelset.Particle_Collision_Distance(particles.quantized_collision_distance(index)); T min_collision_distance=fluids_parameters.particle_levelset_evolution->particle_levelset.min_collision_distance_factor*max_collision_distance; TV_PFE min_corner=fluids_parameters.grid->domain.Minimum_Corner(),max_corner=fluids_parameters.grid->domain.Maximum_Corner(); for(int axis=1;axis<=TV_PFE::m;axis++){ if(fluids_parameters.domain_walls[axis][1] && X_new[axis]<min_corner[axis]+max_collision_distance){ T collision_distance=X[axis]-min_corner[axis]; if(collision_distance>max_collision_distance)collision_distance=X_new[axis]-min_corner[axis]; collision_distance=max(min_collision_distance,collision_distance); X_new[axis]+=max((T)0,min_corner[axis]-X_new[axis]+collision_distance); V[axis]=max((T)0,V[axis]);X=X_new-dt*V;} if(fluids_parameters.domain_walls[axis][2] && X_new[axis]>max_corner[axis]-max_collision_distance){ T collision_distance=max_corner[axis]-X[axis]; if(collision_distance>max_collision_distance) collision_distance=max_corner[axis]-X_new[axis]; collision_distance=max(min_collision_distance,collision_distance); X_new[axis]-=max((T)0,X_new[axis]-max_corner[axis]+collision_distance); V[axis]=min((T)0,V[axis]);X=X_new-dt*V;}} } //##################################################################### // Function Update_Fluid_Parameters //##################################################################### template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>:: Update_Fluid_Parameters(const T dt,const T time) { fluids_parameters.incompressible->Set_Gravity(fluids_parameters.gravity,fluids_parameters.gravity_direction); fluids_parameters.incompressible->Set_Body_Force(fluids_parameters.use_body_force); fluids_parameters.incompressible->projection.Use_Non_Zero_Divergence(fluids_parameters.use_non_zero_divergence); fluids_parameters.incompressible->projection.elliptic_solver->Solve_Neumann_Regions(fluids_parameters.solve_neumann_regions); fluids_parameters.incompressible->projection.elliptic_solver->solve_single_cell_neumann_regions=fluids_parameters.solve_single_cell_neumann_regions; fluids_parameters.incompressible->Use_Explicit_Part_Of_Implicit_Viscosity(fluids_parameters.use_explicit_part_of_implicit_viscosity); if(fluids_parameters.implicit_viscosity && fluids_parameters.implicit_viscosity_iterations) fluids_parameters.incompressible->Set_Maximum_Implicit_Viscosity_Iterations(fluids_parameters.implicit_viscosity_iterations); fluids_parameters.incompressible->Use_Variable_Vorticity_Confinement(fluids_parameters.use_variable_vorticity_confinement); fluids_parameters.incompressible->Set_Surface_Tension(fluids_parameters.surface_tension); fluids_parameters.incompressible->Set_Variable_Surface_Tension(fluids_parameters.variable_surface_tension); fluids_parameters.incompressible->Set_Viscosity(fluids_parameters.viscosity); fluids_parameters.incompressible->Set_Variable_Viscosity(fluids_parameters.variable_viscosity); fluids_parameters.incompressible->projection.Set_Density(fluids_parameters.density); } //##################################################################### template class PLS_FSI_EXAMPLE<VECTOR<float,1> >; template class PLS_FSI_EXAMPLE<VECTOR<float,2> >; template class PLS_FSI_EXAMPLE<VECTOR<float,3> >; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class PLS_FSI_EXAMPLE<VECTOR<double,1> >; template class PLS_FSI_EXAMPLE<VECTOR<double,2> >; template class PLS_FSI_EXAMPLE<VECTOR<double,3> >; #endif
71.155875
194
0.722365
54358998b03fceb71efcc8fb2e66032bb7240d54
857
cpp
C++
CodeForces/1624/B_Make_AP.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
CodeForces/1624/B_Make_AP.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
CodeForces/1624/B_Make_AP.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // freopen("input.in", "r", stdin); ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int t; cin >> t; while(t--) { int a, b, c; cin >> a >> b >> c; if (a > c) swap(a, c); int ret = c - a; int d = (c-a)/2; int p = c - b; int p2 = b - a; if (p == p2) { cout << "YES\n";continue; } if (!((a+c)%(2*b))) { cout << "YES\n"; continue; } int f = b - c; int g = b + f; if (g > 0 && !(g%a)) { cout << "YES\n"; continue; } f = b - a; g = b + f; if (g > 0 && !(g%c)) { cout << "YES\n"; continue; } cout << "NO\n"; } return 0; }
23.162162
74
0.347725
543614d4379119294edb2d06606b2e4da4f4ceee
755
cpp
C++
p636/p636_2.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
1
2019-10-07T05:00:21.000Z
2019-10-07T05:00:21.000Z
p636/p636_2.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
p636/p636_2.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
class Solution { public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> res(n); stack<int> st; int preTime = 0; for (int i = 0; i < logs.size(); ++i) { int pos = logs[i].find(':'); int id = atoi(logs[i].substr(0, pos).c_str()); pos = logs[i].find(':', pos+1); int curTime = atoi(logs[i].substr(pos+1).c_str()); if (!st.empty()) res[st.top()] += curTime - preTime; preTime = curTime; if (logs[i][pos-1] == 't') st.push(id); else { ++res[st.top()]; st.pop(); ++preTime; } } return res; } };
23.59375
62
0.403974
543fa89656496c552e0840f549271c1541df4c4e
865
cpp
C++
src/state_vector/state_vector.cpp
libtangle/tools
4362e5312bcfbe93c912c3f8df9159816003b66e
[ "MIT" ]
1
2019-10-14T05:41:58.000Z
2019-10-14T05:41:58.000Z
src/state_vector/state_vector.cpp
libtangle/tools
4362e5312bcfbe93c912c3f8df9159816003b66e
[ "MIT" ]
1
2019-09-15T17:57:43.000Z
2019-09-16T06:36:19.000Z
src/state_vector/state_vector.cpp
libtangle/tools
4362e5312bcfbe93c912c3f8df9159816003b66e
[ "MIT" ]
null
null
null
#include "state_vector.h" #include "omp.h" #include <iostream> #include <stdlib.h> StateVector::StateVector(int num_qubits) { this->num_qubits = num_qubits; this->num_amps = 1L << num_qubits; // Allocate the required memory for the state vector std::size_t bytes = num_amps * sizeof(complex); state = (complex *)malloc(bytes); // Initialize the state vector state[0] = complex(1); #pragma omp parallel for for (std::size_t i = 1; i < num_amps; i++) { state[i] = complex(0); } } void StateVector::print() { for (std::size_t i = 0; i < num_amps; i++) { complex amp = state[i]; std::cout << i << ": " << std::real(amp) << (std::imag(amp) >= 0.0 ? " + " : " - ") << std::abs(std::imag(amp)) << "i" << std::endl; } }
22.179487
56
0.523699
5440b08301628ef96e197bf93542acbaa63f2f0f
1,490
hpp
C++
include/prog/sym/func_def.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
include/prog/sym/func_def.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
include/prog/sym/func_def.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#pragma once #include "prog/expr/node.hpp" #include "prog/sym/const_decl_table.hpp" #include "prog/sym/func_decl_table.hpp" #include <vector> namespace prog::sym { // Function definition. Contains the body of a user-function. class FuncDef final { friend class FuncDefTable; public: enum class Flags : unsigned int { None = 0U, NoInline = 1U << 0U, // Hint to the optmizer that it should not inline this function. }; FuncDef() = delete; FuncDef(const FuncDef& rhs) = delete; FuncDef(FuncDef&& rhs) = default; ~FuncDef() = default; auto operator=(const FuncDef& rhs) -> FuncDef& = delete; auto operator=(FuncDef&& rhs) noexcept -> FuncDef& = delete; [[nodiscard]] auto getId() const noexcept -> const FuncId&; [[nodiscard]] auto getFlags() const noexcept -> Flags; [[nodiscard]] auto hasFlags(Flags flags) const noexcept -> bool; [[nodiscard]] auto getConsts() const noexcept -> const sym::ConstDeclTable&; [[nodiscard]] auto getBody() const noexcept -> const expr::Node&; [[nodiscard]] auto getOptArgInitializer(unsigned int i) const -> expr::NodePtr; private: sym::FuncId m_id; sym::ConstDeclTable m_consts; expr::NodePtr m_body; std::vector<expr::NodePtr> m_optArgInitializers; Flags m_flags; FuncDef( sym::FuncId id, sym::ConstDeclTable consts, expr::NodePtr body, std::vector<expr::NodePtr> optArgInitializers, Flags flags); }; } // namespace prog::sym
29.8
89
0.672483
5445fbb01d0b541ba8265c0941408dadaf0ef837
226
hpp
C++
source/platform/windows/defines.hpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
source/platform/windows/defines.hpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
source/platform/windows/defines.hpp
ameisen/gcgg
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cassert> #define OS Windows #define __likely(c) (c) #define __unlikely(c) (c) #define __unreachable __assume(0) #define nodefault default: { __unreachable; } #define xassert(c) assert(c)
17.384615
46
0.69469
5446676bcffd729b260e4aba4e25c442da814dc9
2,705
cxx
C++
src/shared/init_models.cxx
solomonik/ctf
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
[ "BSD-2-Clause" ]
56
2015-02-28T08:19:58.000Z
2021-11-04T16:46:17.000Z
src/shared/init_models.cxx
solomonik/ctf
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
[ "BSD-2-Clause" ]
40
2015-04-08T14:58:42.000Z
2017-11-17T20:57:26.000Z
src/shared/init_models.cxx
solomonik/ctf
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
[ "BSD-2-Clause" ]
17
2015-04-03T00:57:43.000Z
2018-03-30T20:46:14.000Z
namespace CTF_int{ double seq_tsr_spctr_cst_off_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_cst_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_cst_off_k2_init[] = {-2.1996E-04, 3.1883E-09, 3.8743E-11}; double seq_tsr_spctr_off_k0_init[] = {8.6970E-06, 4.5598E-11, 1.1544E-09}; double seq_tsr_spctr_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_off_k2_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_cst_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_cst_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_cst_k2_init[] = {-8.8459E-08, 8.1207E-10, -2.8486E-12}; double seq_tsr_spctr_cst_k3_init[] = {1.8504E-08, 2.9154E-11, 2.1973E-11}; double seq_tsr_spctr_cst_k4_init[] = {2.0948E-05, 1.2294E-09, 8.0037E-10}; double seq_tsr_spctr_k0_init[] = {2.2620E-08, -5.7494E-10, 2.2146E-09}; double seq_tsr_spctr_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_spctr_k2_init[] = {3.0917E-08, 5.2181E-11, 4.1634E-12}; double seq_tsr_spctr_k3_init[] = {7.2456E-08, 1.5128E-10, -1.5528E-12}; double seq_tsr_spctr_k4_init[] = {1.6880E-07, 4.9411E-10, 9.2847E-13}; double pin_keys_mdl_init[] = {3.1189E-09, 6.6717E-08}; double seq_tsr_ctr_mdl_cst_init[] = {5.1626E-06, -6.3215E-11, 3.9638E-09}; double seq_tsr_ctr_mdl_ref_init[] = {4.9138E-08, 5.8290E-10, 4.8575E-11}; double seq_tsr_ctr_mdl_inr_init[] = {2.0647E-08, 1.9721E-10, 2.9948E-11}; double seq_tsr_ctr_mdl_off_init[] = {6.2925E-05, 1.7449E-11, 1.7211E-12}; double seq_tsr_ctr_mdl_cst_inr_init[] = {1.3863E-04, 2.0119E-10, 9.8820E-09}; double seq_tsr_ctr_mdl_cst_off_init[] = {8.4844E-04, -5.9246E-11, 3.5247E-10}; double long_contig_transp_mdl_init[] = {2.9158E-10, 3.0501E-09}; double shrt_contig_transp_mdl_init[] = {1.3427E-08, 4.3168E-09}; double non_contig_transp_mdl_init[] = {4.0475E-08, 4.0463E-09}; double dgtog_res_mdl_init[] = {2.9786E-05, 2.4335E-04, 1.0845E-08}; double blres_mdl_init[] = {1.0598E-05, 7.2741E-08}; double alltoall_mdl_init[] = {1.0000E-06, 1.0000E-06, 5.0000E-10}; double alltoallv_mdl_init[] = {2.7437E-06, 2.2416E-05, 1.0469E-08}; double red_mdl_init[] = {6.2935E-07, 4.6276E-06, 9.2245E-10}; double red_mdl_cst_init[] = {5.7302E-07, 4.7347E-06, 6.0191E-10}; double allred_mdl_init[] = {8.4416E-07, 6.8651E-06, 3.5845E-08}; double allred_mdl_cst_init[] = {-3.3754E-04, 2.1343E-04, 3.0801E-09}; double bcast_mdl_init[] = {1.5045E-06, 1.4485E-05, 3.2876E-09}; double spredist_mdl_init[] = {1.2744E-04, 1.0278E-03, 7.6837E-08}; double csrred_mdl_init[] = {3.7005E-05, 1.1854E-04, 5.5165E-09}; double csrred_mdl_cst_init[] = {-1.8323E-04, 1.3076E-04, 2.8732E-09}; }
65.97561
79
0.721257
54480537ce43bf919f9db44aa9af3ca8e5844ec5
1,009
cpp
C++
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
paulmoon/csc460
a432cfccef97fca5820cb0fc006112bb773cda0f
[ "MIT" ]
null
null
null
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
paulmoon/csc460
a432cfccef97fca5820cb0fc006112bb773cda0f
[ "MIT" ]
null
null
null
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
paulmoon/csc460
a432cfccef97fca5820cb0fc006112bb773cda0f
[ "MIT" ]
null
null
null
#ifdef USE_TEST_012 /* Testing RR tasks subscribing to another RR publisher. Desired Trace: T012;0;0;1;1;2;2;3;3;4;4;5;5;6;6;7;7;8;8;9;9; */ #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "os.h" #include "uart/uart.h" #include "trace/trace.h" #include "../profiler.h" #include "../error_code.h" SERVICE* services[3]; int g_count = 0; void r(){ int16_t v; while( g_count < 20){ Service_Subscribe(services[0], &v); add_to_trace(v); g_count += 1; } } void r2(){ int16_t count = 0; for(;;){ Service_Publish(services[0],count++); Task_Next(); if( g_count >= 20){ print_trace(); } } } extern int r_main(){ uart_init(); set_trace_test(12); services[0] = Service_Init(); Task_Create_RR(r,0); Task_Create_RR(r,0); Task_Create_RR(r2,0); Task_Terminate(); return 0; } #endif
18.017857
54
0.54113
544d01213eb9ec71ae3a48c1140790d960edc11c
6,585
cpp
C++
src/maglev/MagLevNull.cpp
mindpowered/maglev-cpp
8383ed7576202d6d61fcdfb6723a2baa74b8e010
[ "MIT" ]
null
null
null
src/maglev/MagLevNull.cpp
mindpowered/maglev-cpp
8383ed7576202d6d61fcdfb6723a2baa74b8e010
[ "MIT" ]
null
null
null
src/maglev/MagLevNull.cpp
mindpowered/maglev-cpp
8383ed7576202d6d61fcdfb6723a2baa74b8e010
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.1 #include <hxcpp.h> #ifndef INCLUDED_maglev_MagLevAny #include <maglev/MagLevAny.h> #endif #ifndef INCLUDED_maglev_MagLevNull #include <maglev/MagLevNull.h> #endif #ifndef INCLUDED_maglev_MagLevString #include <maglev/MagLevString.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_25586abe6b76e172_662_new,"maglev.MagLevNull","new",0xb2260507,"maglev.MagLevNull.new","maglev/MagLev.hx",662,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_665_getType,"maglev.MagLevNull","getType",0x2072b697,"maglev.MagLevNull.getType","maglev/MagLev.hx",665,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_671_isEqual,"maglev.MagLevNull","isEqual",0x0fef8791,"maglev.MagLevNull.isEqual","maglev/MagLev.hx",671,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_679_toJson,"maglev.MagLevNull","toJson",0x070a9afc,"maglev.MagLevNull.toJson","maglev/MagLev.hx",679,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_659_create,"maglev.MagLevNull","create",0x06f854b5,"maglev.MagLevNull.create","maglev/MagLev.hx",659,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_668_getStaticType,"maglev.MagLevNull","getStaticType",0x365a7225,"maglev.MagLevNull.getStaticType","maglev/MagLev.hx",668,0x5b19476f) HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_682_wrap,"maglev.MagLevNull","wrap",0x351b1743,"maglev.MagLevNull.wrap","maglev/MagLev.hx",682,0x5b19476f) namespace maglev{ void MagLevNull_obj::__construct(){ HX_STACKFRAME(&_hx_pos_25586abe6b76e172_662_new) HXDLIN( 662) super::__construct(); } Dynamic MagLevNull_obj::__CreateEmpty() { return new MagLevNull_obj; } void *MagLevNull_obj::_hx_vtable = 0; Dynamic MagLevNull_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< MagLevNull_obj > _hx_result = new MagLevNull_obj(); _hx_result->__construct(); return _hx_result; } bool MagLevNull_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x7cdfae7b) { return inClassId==(int)0x00000001 || inClassId==(int)0x7cdfae7b; } else { return inClassId==(int)0x7fdb9bc4; } } int MagLevNull_obj::getType(){ HX_STACKFRAME(&_hx_pos_25586abe6b76e172_665_getType) HXDLIN( 665) return 1; } bool MagLevNull_obj::isEqual( ::maglev::MagLevAny other){ HX_STACKFRAME(&_hx_pos_25586abe6b76e172_671_isEqual) HXDLIN( 671) int _hx_tmp = other->getType(); HXDLIN( 671) if ((_hx_tmp == this->getType())) { HXLINE( 672) return true; } else { HXLINE( 675) return false; } HXLINE( 671) return false; } ::maglev::MagLevString MagLevNull_obj::toJson(){ HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_679_toJson) HXDLIN( 679) return ::maglev::MagLevString_obj::__alloc( HX_CTX ,HX_("null",87,9e,0e,49)); } ::maglev::MagLevNull MagLevNull_obj::create(){ HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_659_create) HXDLIN( 659) return ::maglev::MagLevNull_obj::__alloc( HX_CTX ); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(MagLevNull_obj,create,return ) int MagLevNull_obj::getStaticType(){ HX_STACKFRAME(&_hx_pos_25586abe6b76e172_668_getStaticType) HXDLIN( 668) return 1; } STATIC_HX_DEFINE_DYNAMIC_FUNC0(MagLevNull_obj,getStaticType,return ) ::maglev::MagLevAny MagLevNull_obj::wrap( ::maglev::MagLevAny o){ HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_682_wrap) HXDLIN( 682) if (::hx::IsNull( o )) { HXLINE( 683) return ::maglev::MagLevNull_obj::__alloc( HX_CTX ); } else { HXLINE( 685) return o; } HXLINE( 682) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(MagLevNull_obj,wrap,return ) ::hx::ObjectPtr< MagLevNull_obj > MagLevNull_obj::__new() { ::hx::ObjectPtr< MagLevNull_obj > __this = new MagLevNull_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< MagLevNull_obj > MagLevNull_obj::__alloc(::hx::Ctx *_hx_ctx) { MagLevNull_obj *__this = (MagLevNull_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(MagLevNull_obj), false, "maglev.MagLevNull")); *(void **)__this = MagLevNull_obj::_hx_vtable; __this->__construct(); return __this; } MagLevNull_obj::MagLevNull_obj() { } ::hx::Val MagLevNull_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"toJson") ) { return ::hx::Val( toJson_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"getType") ) { return ::hx::Val( getType_dyn() ); } if (HX_FIELD_EQ(inName,"isEqual") ) { return ::hx::Val( isEqual_dyn() ); } } return super::__Field(inName,inCallProp); } bool MagLevNull_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"wrap") ) { outValue = wrap_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"create") ) { outValue = create_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"getStaticType") ) { outValue = getStaticType_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *MagLevNull_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *MagLevNull_obj_sStaticStorageInfo = 0; #endif static ::String MagLevNull_obj_sMemberFields[] = { HX_("getType",70,a2,8b,1f), HX_("isEqual",6a,73,08,0f), HX_("toJson",43,ad,21,7c), ::String(null()) }; ::hx::Class MagLevNull_obj::__mClass; static ::String MagLevNull_obj_sStaticFields[] = { HX_("create",fc,66,0f,7c), HX_("getStaticType",be,46,27,0b), HX_("wrap",ca,39,ff,4e), ::String(null()) }; void MagLevNull_obj::__register() { MagLevNull_obj _hx_dummy; MagLevNull_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("maglev.MagLevNull",95,75,57,ef); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &MagLevNull_obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(MagLevNull_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(MagLevNull_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< MagLevNull_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = MagLevNull_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = MagLevNull_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace maglev
34.296875
179
0.731815
544ebc8e13e44f1a9d4d382557bc3bffc28f7cfe
1,933
cpp
C++
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
FirstLoveLife/Rider-Faiz
ffa1ec3b335b836bd81600fb67587734325b2ce6
[ "MIT" ]
3
2019-01-18T08:36:03.000Z
2020-10-29T08:30:59.000Z
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
FirstLoveLife/Faiz
ffa1ec3b335b836bd81600fb67587734325b2ce6
[ "MIT" ]
null
null
null
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
FirstLoveLife/Faiz
ffa1ec3b335b836bd81600fb67587734325b2ce6
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // type_traits // is_trivially_copy_assignable // XFAIL: gcc-4.9 #include "test-utilities.hpp" #include <catch2/catch.hpp> #include "rider/faiz/type_traits.hpp" namespace { template<class T> void test_has_trivially_copy_assignable() { STATIC_REQUIRE(Rider::Faiz::is_trivially_copy_assignable<T>::value); #if TEST_STD_VER > 14 STATIC_REQUIRE(Rider::Faiz::is_trivially_copy_assignable_v<T>); #endif } template<class T> void test_has_not_trivially_copy_assignable() { STATIC_REQUIRE(!Rider::Faiz::is_trivially_copy_assignable<T>::value); #if TEST_STD_VER > 14 STATIC_REQUIRE(!Rider::Faiz::is_trivially_copy_assignable_v<T>); #endif } class Empty {}; class NotEmpty { virtual ~NotEmpty(); }; union Union {}; struct bit_zero { int : 0; }; class Abstract { virtual ~Abstract() = 0; }; struct A { A& operator=(const A&); }; } // namespace TEST_CASE("is_trivially_copy_assignable.libcxx: ") { test_has_trivially_copy_assignable<int&>(); test_has_trivially_copy_assignable<Union>(); test_has_trivially_copy_assignable<Empty>(); test_has_trivially_copy_assignable<int>(); test_has_trivially_copy_assignable<double>(); test_has_trivially_copy_assignable<int*>(); test_has_trivially_copy_assignable<const int*>(); test_has_trivially_copy_assignable<bit_zero>(); test_has_not_trivially_copy_assignable<void>(); test_has_not_trivially_copy_assignable<A>(); test_has_not_trivially_copy_assignable<NotEmpty>(); test_has_not_trivially_copy_assignable<Abstract>(); test_has_not_trivially_copy_assignable<const Empty>(); }
21.719101
80
0.691154
5450373884e4d7eeae4d4c943765a34f77388329
650
cpp
C++
dlls/ADM/Physics/PhysManager.cpp
BlueNightHawk4906/HL-ADM-Custom
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
[ "Unlicense" ]
1
2020-12-11T17:52:33.000Z
2020-12-11T17:52:33.000Z
dlls/ADM/Physics/PhysManager.cpp
BlueNightHawk4906/HL-ADM-Custom
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
[ "Unlicense" ]
7
2021-07-09T09:19:14.000Z
2021-07-20T19:35:21.000Z
dlls/ADM/Physics/PhysManager.cpp
phoenixprojectsoftware/phoenixADM
5f170a34739e64111dbe161d9ab9e0baa219512b
[ "Unlicense" ]
null
null
null
#include "Base/ExtDLL.h" #include "Util.h" #include "Base/CBase.h" #include "PhysManager.h" #include "../shared/ADM/Physics/PhysicsWorld.h" LINK_ENTITY_TO_CLASS( phys_manager, CPhysManager ); void CPhysManager::Spawn() { pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NONE; // pev->flags |= FL_ALWAYSTHINK; SetThink( &CPhysManager::PhysManagerThink ); pev->nextthink = gpGlobals->time + 1.5f; } void CPhysManager::PhysManagerThink() { g_Physics.StepSimulation( 1.f / 64.f, 16 ); pev->nextthink = gpGlobals->time + 1.f / 64.f; //ALERT( at_console, "CPhysManager::Think() time %3.2f\n", pev->nextthink ); }
22.413793
78
0.673846
545343e4b425c92a160ff5ae232d07b35cfc5e73
846
cpp
C++
MoveAndCard.cpp
misaka15565/Doudizhu_CanJu
6bf4827ff79f523760df1362d2b746138eb0f7c5
[ "Apache-2.0" ]
null
null
null
MoveAndCard.cpp
misaka15565/Doudizhu_CanJu
6bf4827ff79f523760df1362d2b746138eb0f7c5
[ "Apache-2.0" ]
null
null
null
MoveAndCard.cpp
misaka15565/Doudizhu_CanJu
6bf4827ff79f523760df1362d2b746138eb0f7c5
[ "Apache-2.0" ]
null
null
null
#include <vector> using namespace std; //sc means 单张牌 typedef char sc; const int TYPE_0_PASS = 0; const int TYPE_1_SINGLE = 1; const int TYPE_2_PAIR = 2; const int TYPE_3_TRIPLE = 3; const int TYPE_4_BOMB = 4; const int TYPE_5_KING_BOMB = 5; const int TYPE_6_3_1 = 6; const int TYPE_7_3_2 = 7; const int TYPE_8_SERIAL_SINGLE = 8; const int TYPE_9_SERIAL_PAIR = 9; const int TYPE_10_SERIAL_TRIPLE = 10; const int TYPE_11_SERIAL_3_1 = 11; const int TYPE_12_SERIAL_3_2 = 12; const int TYPE_13_4_2 = 13; const int TYPE_14_4_2_2 = 14; const int TYPE_99_WRONG = 99; class theMove { public: vector<sc> main; //主要牌,从小到大排 vector<sc> sub; //次要牌 int type; int size() { if (main.size() == 0) { return -1; } return main[0]; } }; class theCard{ public: vector<sc>cards; };
18.391304
37
0.65721
54571cf0e13f22a286b8c650a63c535529550a82
35,187
hpp
C++
include/ext/net/http/http_server.hpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
1
2018-05-14T13:46:59.000Z
2018-05-14T13:46:59.000Z
include/ext/net/http/http_server.hpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
null
null
null
include/ext/net/http/http_server.hpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
null
null
null
#pragma once #include <memory> #include <string> #include <vector> #include <functional> #include <iterator> #include <thread> #include <mutex> #include <condition_variable> #include <boost/container/flat_set.hpp> #include <boost/container/flat_map.hpp> #include <ext/config.hpp> #include <ext/future.hpp> #include <ext/thread_pool.hpp> #include <ext/intrusive_ptr.hpp> #include <ext/library_logger/logger.hpp> #include <ext/stream_filtering/filter_types.hpp> #include <ext/openssl.hpp> #include <ext/net/socket_stream.hpp> #include <ext/net/socket_queue.hpp> #include <ext/net/http_parser.hpp> #include <ext/net/http/http_types.hpp> #include <ext/net/http/http_server_handler.hpp> #include <ext/net/http/http_server_filter.hpp> #include <ext/net/http/nonblocking_http_parser.hpp> #include <ext/net/http/nonblocking_http_writer.hpp> namespace ext::net::http { /// Simple embedded http server. /// Listens for incoming connections on given listener sockets, /// parses http requests, calls registered handler that accepts that request /// /// supports: /// * SSL /// * http_handlers: sync and async(result is returned via ext::future) /// * http_filters /// * thread_pool executor /// /// have 2 working modes(those should not be mixed): /// * work on current thread(join/interrupt), useful when you want start simple http_server on main thread /// * work on internal background thread(start/stop), useful when you do not want block main thread in http_server /// /// NOTE: by default there no preinstalled filters or handlers class http_server { using self_type = http_server; public: using handle_type = socket_queue::handle_type; using duration_type = socket_queue::duration_type; using time_point = socket_queue::time_point; using handler_result_type = http_server_handler::result_type; using simple_handler_result_type = simple_http_server_handler::result_type; using simple_handler_body_function_type = simple_http_server_handler::body_function_types; using simple_handler_request_function_type = simple_http_server_handler::request_function_type; #ifdef EXT_ENABLE_OPENSSL using SSL = ::SSL; using ssl_ctx_iptr = ext::openssl::ssl_ctx_iptr; using ssl_iptr = ext::openssl::ssl_iptr; #else using SSL = std::nullptr_t; using ssl_ctx_iptr = std::nullptr_t; using ssl_iptr = std::nullptr_t; #endif // Internally sockets(both regular and listeners) are handled by ext::net::socket_queue, this class is not thread safe // (system calls select/poll used by ext::net::socket_queue do not affected by any pthread related functions). // So we have background thread(internal or joined) running ext::net::socket_queue, whenever some action is performed via public method // it's submitted into internal task queue -> socket_queue interrupted and all pending queued actions are executed on background thread. // See m_sock_queue, m_tasks, m_delayed // // http_request/socket processing: // When there is ready socket in socket_queue - it's taken, http_request is read, then action handler is searched and invoked, // http_response is written back, socket is placed back into the queue or closed. // // This whole http processing can be done on executor or, if unset, in background thread. // http action handlers can be async - return ext::future<http_response>, sync - return ready http_response // // Currently http request and response are synchronously processed in executor or background thread - // while whole http request will not be read, action handler invoked, http response written back - socket will not be placed back into queue, // and background thread will be busy working with current request/socket, unless processing executor is set. // // In case of async special continuation is attached to returned future, it submits special task when http_result future become ready. // This task continues processing of this http request, writes back response, etc(see m_delayed) // // There also pre/post http filters, currently those can't be async, but maybe changed in future. // Those can be used for some common functionality: zlib processing, authentication, CORS, other. // // processing_context: // When http request is processed - processing context is allocated for it, it holds registered filters, handlers and some helper members. // Some minimal numbers of contexts are cached and only reinitialized if needed, if there no cached contexts are available - one is allocated. // When maximum number exceeds - server busy is returned as http answer. // // handle_* group: // http request is handled by handle_* method group. All methods can be overridden, also to allow more customization, each method returns what must be done next: // handle_request -> handle_prefilters -> .... -> handle_finish protected: using process_result = http_server_handler::result_type; using async_process_result = std::variant<ext::future<http_response>, ext::future<null_response_type>>; using hook_type = boost::intrusive::list_base_hook< boost::intrusive::link_mode<boost::intrusive::link_mode_type::normal_link> >; class task_base; // inherits hook_type template <class Functor, class ResultType> class task_impl; // implements task_base class delayed_async_executor_task_continuation; class processing_executor; template <class ExecutorPtr> class processing_executor_impl; class async_http_body_source_impl; class http_body_streambuf_impl; protected: using list_option = boost::intrusive::base_hook<hook_type>; using task_list = boost::intrusive::list<task_base, list_option, boost::intrusive::constant_time_size<false>>; using delayed_async_executor_task_continuation_list = boost::intrusive::list<delayed_async_executor_task_continuation, list_option, boost::intrusive::constant_time_size<false>>; protected: class closable_http_body; struct processing_context; class http_server_control; /// sort of union of bellow methods; class handle_method_type; using regular_handle_methed = auto (http_server::*)(processing_context * context) -> handle_method_type ; using finalizer_handle_method = void (http_server::*)(processing_context * context); protected: using streaming_context = ext::stream_filtering::streaming_context < std::vector<std::unique_ptr<ext::stream_filtering::filter>>, // FilterVector std::vector<ext::stream_filtering::data_context>, // DataContextVector std::vector<std::vector<char>> // BuffersVector >; /// holds some listener context configuration struct listener_context { unsigned backlog; ssl_ctx_iptr ssl_ctx; ext::net::listener listener; // valid until it placed into sock_queue }; struct config_context; struct filtering_context; struct filtering_context { streaming_context request_streaming_ctx, response_streaming_ctx; boost::container::flat_map<std::string, http::http_server_control::property> property_map; }; /// groups some context parameters for processing http request struct processing_context { socket_streambuf sock; // socket where http request came from ssl_iptr ssl_ptr = nullptr; // ssl session, created from listener ssl context // socket waiting socket_queue::wait_type wait_type; // next method after socket waiting is complete regular_handle_methed next_method; // current method that is executed regular_handle_methed cur_method; // state used by some handle_methods, value for switch unsigned async_state = 0; // should this connection be closed after request processed, determined by Connection header, // but also - were there errors while processing request. connection_action_type conn_action = connection_action_type::close; // byte counters, used in various scenarios std::size_t read_count; // number of bytes read from socket std::size_t written_count; // number of bytes written socket http_server_utils::nonblocking_http_parser parser; // http parser with state http_server_utils::nonblocking_http_writer writer; // http writer with state // buffers for filtered and non filtered parsing and writting std::vector<char> request_raw_buffer, request_filtered_buffer; std::vector<char> response_raw_buffer, response_filtered_buffer; std::string chunk_prefix; // buffer for preparing and holding chunk prefix(chunked transfer encoding) // contexts for filtering request/reply http_body; std::unique_ptr<filtering_context> filter_ctx; ext::stream_filtering::processing_parameters filter_params; http_request request; // current http request, valid after is was parsed process_result response = null_response; // current http response, valid after handler was called std::shared_ptr<const config_context> config; // config snapshot const http_server_handler * handler; // found handler for request bool expect_extension; // request with Expect: 100-continue header, see RFC7231 section 5.1.1. bool continue_answer; // context holds answer 100 Continue bool first_response_written; // wrote first 100-continue bool final_response_written; // wrote final(possibly second) response bool response_is_final; // response was marked as final, see http_server_filter_control std::atomic<ext::shared_state_basic *> executor_state = nullptr; // holds current pending processing execution task state, used for internal synchronization std::atomic<ext::shared_state_basic *> async_task_state = nullptr; // holds current pending async operation(from handlers), used for internal synchronization // async_http_body_source/http_body_streambuf closing closer // allowed values: // 0x00 - no body closer // 0x01 - http_server is closing, already set body closer is taken, new should not be installed // other - some body closer std::atomic_uintptr_t body_closer = 0; }; /// holds some configuration parameters sharable by processing contexts struct config_context { /// http filters, handlers can added when http server already started. What if we already processing some request and handler is added? /// When processing starts - context holds snapshot of currently registered handlers, filters and only they are used; it also handles multithreaded issues. /// whenever filters, handlers or anything config related changes -> new context is config_context as copy of current is created with dirty set to true. /// sort of copy on write unsigned dirty = true; std::vector<const http_server_handler *> handlers; // http handlers registered in server std::vector<const http_prefilter *> prefilters; // http prefilters registered in server, sorted by order std::vector<const http_postfilter *> postfilters; // http postfilters registered in server, sorted by order /// Maximum bytes read from socket while parsing HTTP request headers, -1 - unlimited. /// If request headers are not parsed yet, and server read from socket more than maximum_http_headers_size, BAD request is returned std::size_t maximum_http_headers_size = -1; /// Maximum bytes read from socket while parsing HTTP body, -1 - unlimited. /// This affects only simple std::vector<char>/std::string bodies, and never affects stream/async bodies. /// If server read from socket more than maximum_http_body_size, BAD request is returned std::size_t maximum_http_body_size = -1; /// Maximum bytes read from socket while parsing discarded HTTP request, -1 - unlimited. /// If there is no handler for this request, or some other error code is answered(e.g. unauthorized), /// this request is considered to be discarded - in this case we still might read it's body, /// but no more than maximum_discarded_http_body_size, otherwise connection is forcibly closed. std::size_t maximum_discarded_http_body_size = -1; }; protected: socket_queue m_sock_queue; // intenal socket and listener queue boost::container::flat_map<socket_handle_type, listener_context> m_listener_contexts; // listener contexts map by listener handle // sharable cow config context, see config_context description std::shared_ptr<config_context> m_config_context = std::make_shared<config_context>(); ext::library_logger::logger * m_logger = nullptr; // log level on which http request and reply headers are logged unsigned m_request_logging_level = -1; // log level on which http request and reply body are logger, overrides m_request_logging_level if bigger unsigned m_request_body_logging_level = -1; // log level on which every read from socket operation buffer is logged unsigned m_read_buffer_logging_level = -1; // log level on which every write to socket operation buffer is logged unsigned m_write_buffer_logging_level = -1; // processing_contexts std::size_t m_minimum_contexts = 10; std::size_t m_maximum_contexts = 128; // set of existing contexts for which sockets are waiting for read/write state boost::container::flat_map<socket_streambuf::handle_type, processing_context *> m_pending_contexts; // set of existing contexts boost::container::flat_set<processing_context *> m_processing_contexts; // free contexts that can be reused std::vector<processing_context *> m_free_contexts; mutable std::mutex m_mutex; mutable std::condition_variable m_event; mutable std::thread m_thread; std::thread::id m_threadid; // id of thread running tasks and socket queue // linked list of task task_list m_tasks; // delayed tasks are little tricky, for every one - we create a service continuation, // which when fired, adds task to task_list. // Those can work and fire when we are being destructed, // http_server lifetime should not linger on delayed_task - they should become abandoned. // Nevertheless we have lifetime problem. // // So we store those active service continuations in a list: // - When continuation is fired it checks if it's taken(future internal helper flag): // * if yes - http_server is gone, nothing to do; // * if not - http_server is still there - we should add task to a list; // // - When destructing we are checking each continuation if it's taken(future internal helper flag): // * if successful - service continuation is sort of cancelled and it will not access http_server // * if not - continuation is firing right now somewhere in the middle, // so destructor must wait until it finishes and then complete destruction. delayed_async_executor_task_continuation_list m_delayed; // how many delayed_continuations were not "taken/cancelled" at destruction, // and how many we must wait - it's sort of a semaphore. std::size_t m_delayed_count = 0; // optional http request processing executor std::shared_ptr<processing_executor> m_processing_executor; // http_server running state variables bool m_running = false; // http_server is in running state bool m_started = false; // http_server is started either by start or join bool m_joined = false; // used only by join/interrupt pair methods bool m_interrupted = false; // used only by join/interrupt pair methods // listeners default backlog int m_default_backlog = 10; /// socket HTTP request processing operations(read/write) timeout duration_type m_socket_timeout = std::chrono::seconds(10); /// how long socket can be kept open awaiting new incoming HTTP requests duration_type m_keep_alive_timeout = m_sock_queue.get_default_timeout(); /// timeout for socket operations when closing, basicly affects SSL shutdown static constexpr duration_type m_close_socket_timeout = std::chrono::milliseconds(100); static constexpr auto chunkprefix_size = sizeof(int) * CHAR_BIT / 4 + (CHAR_BIT % 4 ? 1 : 0); // in hex static constexpr std::string_view crlf = "\r\n"; protected: /// Performs actual startup of http server, blocking virtual void do_start(std::unique_lock<std::mutex> & lk); /// Performs actual stopping of http server, blocking virtual void do_stop (std::unique_lock<std::mutex> & lk); /// Resets http server to default state: closes all sockets, deletes handlers, filters. /// Some properties are not reset virtual void do_reset(std::unique_lock<std::mutex> & lk); /// clears m_config_context virtual void do_clear_config(std::unique_lock<std::mutex> & lk); public: /// Starts http_server: internal background thread + listeners start listen virtual void start(); /// Stops http_server: background thread stopped, all sockets are closed, all http handlers, filters are deleted virtual void stop(); /// Similar to start, but callers thread becomes background one and caller basicly joins it. /// Useful for simple configurations were you start https_server from main thread virtual void join(); /// Similar to stop, but must be called if http_server was started via join. /// Can be called from signal handler. virtual void interrupt(); protected: /// Main background thread function, started_promise can be used to propagate exceptions to caller, and notify when actual startup is complete virtual void run_proc(ext::promise<void> & started_promise); /// Runs socket_queue until it interrupted. virtual void run_sockqueue(); /// Reads, parses, process http request and writes http_response back, full cycle for single http request on socket. virtual void run_socket(processing_context * context); /// Runs handle_* circuit, updates context->cur_method for regular methods virtual void executor_handle_runner(handle_method_type next_method, processing_context * context); /// Submits and schedules processing of async result virtual void submit_async_executor_task(ext::intrusive_ptr<ext::shared_state_basic> handle, handle_method_type method, processing_context * context); /// Helper method for creating async handle_method static auto async_method(ext::intrusive_ptr<ext::shared_state_basic> future_handle, regular_handle_methed async_method) -> handle_method_type; static auto async_method(socket_queue::wait_type wait, regular_handle_methed async_method) -> handle_method_type; /// non blocking recv with MSG_PEEK: /// * if successfully reads something - returns nullptr /// * if read would block - returns wait_connection operation, /// * if some error occurs sets it into sock, logs it and returns handle_finish virtual auto peek(processing_context * context, char * data, int len, int & read) const -> handle_method_type; /// non blocking recv method: /// * if successfully reads something - returns nullptr /// * if read would block - returns wait_connection operation, /// * if some error occurs sets it into sock, logs it and returns handle_finish virtual auto recv(processing_context * context, char * data, int len, int & read) const -> handle_method_type; /// non blocking send method: /// * if successfully sends something - returns nullptr /// * if send would block - returns wait_connection operation, /// * if some error occurs sets it into sock, logs it and returns handle_finish virtual auto send(processing_context * context, const char * data, int len, int & written) const -> handle_method_type; /// returns socket send buffer size getsockopt(..., SOL_SOCKET, SO_SNDBUF, ...), but no more that 10 * 1024 virtual std::size_t sendbuf_size(processing_context * context) const; /// non blocking recv method, read data is parsed with http parser, /// result is stored in whatever parser body destination is set /// * if successfully reads something - returns nullptr /// * if read would block - returns wait_connection operation, /// * if some error occurs sets it into sock, logs it and returns handle_finish. virtual auto recv_and_parse(processing_context * context) const -> handle_method_type; /// same as recv_and_parse, but no more than limit is ever read from socket in total, /// otherwise bad response is created and http_server::handle_response is returned, connection is closed. virtual auto recv_and_parse(processing_context * context, std::size_t limit) const -> handle_method_type; protected: // http_request processing parts virtual auto handle_start(processing_context * context) -> handle_method_type; virtual auto handle_close(processing_context * context) -> handle_method_type; virtual void handle_finish(processing_context * context); virtual auto handle_ssl_configuration(processing_context * context) -> handle_method_type; virtual auto handle_ssl_start_handshake(processing_context * context) -> handle_method_type; virtual auto handle_ssl_continue_handshake(processing_context * context) -> handle_method_type; virtual auto handle_ssl_finish_handshake(processing_context * context) -> handle_method_type; virtual auto handle_ssl_shutdown(processing_context * context) -> handle_method_type; virtual auto handle_request_headers_parsing(processing_context * context) -> handle_method_type; virtual auto handle_request_normal_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_request_filtered_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_discarded_request_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_request_normal_async_source_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_request_filtered_async_source_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_parsed_headers(processing_context * context) -> handle_method_type; virtual auto handle_prefilters(processing_context * context) -> handle_method_type; virtual auto handle_find_handler(processing_context * context) -> handle_method_type; virtual auto handle_request_header_processing(processing_context * context) -> handle_method_type; virtual auto handle_request_init_body_parsing(processing_context * context) -> handle_method_type; virtual auto handle_parsed_request(processing_context * context) -> handle_method_type; virtual auto handle_processing(processing_context * context) -> handle_method_type; virtual auto handle_processing_result(processing_context * context) -> handle_method_type; virtual auto handle_postfilters(processing_context * context) -> handle_method_type; virtual auto handle_response(processing_context * context) -> handle_method_type; virtual auto handle_response_headers_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_headers_written(processing_context * context) -> handle_method_type; virtual auto handle_response_normal_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_filtered_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_lstream_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_normal_stream_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_filtered_stream_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_normal_async_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_filtered_async_body_writting(processing_context * context) -> handle_method_type; virtual auto handle_response_written(processing_context * context) -> handle_method_type; protected: // filtering virtual void prepare_request_http_body_filtering(processing_context * context); virtual void filter_request_http_body(processing_context * context); virtual void prepare_response_http_body_filtering(processing_context * context); virtual void filter_response_http_body(processing_context * context); protected: /// Acquires processing context, one of cached ones, or creates one if allowed. If exhausted - returns null virtual auto acquire_context() -> processing_context *; /// Release processing context after http request processed, this method should place this context to cache or delete it, if cache is full virtual void release_context(processing_context * context); /// Prepares processing context, called each time new http request should be processed. /// Makes http handlers and filters snapshots if needed. virtual void prepare_context(processing_context * context, const socket_streambuf & sock, bool newconn); /// Called when processing context is created, default implementation does nothing virtual void construct_context(processing_context * context); /// Called when processing context is deleted, default implementation does nothing virtual void destruct_context(processing_context * context); /// Checks if there is pending context for this socket and returns it, otherwise returns new context via acquire_context() /// Can return null if maximum number of contexts are created. virtual auto acquire_context(socket_streambuf & sock) -> processing_context *; /// Checks if there is pending context for this socket and release it, otherwise does nothing virtual void release_context(socket_streambuf & sock); /// Submits socket into internal socket_queue for waiting socket event(readable/writable). /// When socket will become ready, processing will continue from where it stopped. /// Should be called from server background thread virtual void wait_connection(processing_context * context); /// Submits connection into socket_queue, also sets m_keep_alive_timeout on socket. Should be called from server background thread virtual void submit_connection(socket_streambuf sock); /// Closes connection, logs, does some internal cleanup. Should be called from server background thread virtual void close_connection(socket_streambuf sock); /// Writes http response to socket, if errors occurs, logs it and returns false virtual bool write_response(socket_streambuf & sock, const http_response & resp) const; /// Postprocess ready http response, can be used to do some http headers machinery, /// called after all http filter are handled, just before writting response. /// Also called for special answers created via create_*_response. /// Default implementation tweaks Close and Content-Length virtual void postprocess_response(http_response & resp) const; virtual void postprocess_response(processing_context * context) const; /// Does some response checking, default implementation checks if request http body was fully parsed /// NOTE: postprocess_response is called separately virtual void check_response(processing_context * context) const; /// Exception wrapper for handler.process(request), on exception returns create_internal_server_error_response(sock, request, ex) virtual auto process_request(socket_streambuf & sock, const http_server_handler & handler, http_request & request) -> process_result; /// Exception wrapper for getting result from ext::future<http_response>, on exception returns create_internal_server_error_response(sock, request, ex). /// Also checks if future is cancelled or abandoned. virtual auto process_ready_response(async_process_result result, socket_streambuf & sock, http_request & request) -> process_result; /// Searches listener context by listener handle virtual const listener_context & get_listener_context(socket_handle_type listener_handle) const; /// Searches acceptable http handler, nullptr if not found virtual const http_server_handler * find_handler(processing_context & context) const; protected: template <class Lock> void process_tasks(Lock & lock); template <class Lock, class Task> auto submit_task(Lock & lk, Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>; template <class Task> auto submit_task(Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>; /// submits task for running handle_* circuit void submit_handler(handle_method_type next_method, processing_context * context); template <class Lock> void submit_handler(Lock & lk, handle_method_type next_method, processing_context * context); protected: /// obtains current config context, copying one if needed config_context & current_config(); protected: virtual auto do_add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx) -> ext::future<void>; virtual void do_add_handler(std::unique_ptr<const http_server_handler> handler); virtual void do_add_filter(ext::intrusive_ptr<http_filter_base> filter); //virtual void do_remove_handler(std::string uri, std::vector<std::string> methods); protected: /// Logs http request, checks log levels virtual void log_request(const http_request & request) const; /// Logs http response, checks log levels virtual void log_response(const http_response & response) const; /// Formats error from error codes, in case of SSL error reads and formats all SSL errors from OpenSSL error queue virtual std::string format_error(std::error_code errc) const; /// logs read buffer in hex dump format virtual void log_read_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const; /// logs write buffer in hex dump format virtual void log_write_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const; /// parses Accept header and returns text/plain and text/html weights static std::pair<double, double> parse_accept(const http_request & request); /// Creates HTTP 400 BAD REQUEST answer virtual http_response create_bad_request_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const; /// Creates HTTP 503 Service Unavailable answer virtual http_response create_server_busy_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const; /// Creates HTTP 404 Not found answer virtual http_response create_unknown_request_response(const socket_streambuf & sock, const http_request & request) const; /// Creates HTTP 500 Internal Server Error answer, body = Request processing abandoned virtual http_response create_processing_abondoned_response(const socket_streambuf & sock, const http_request & request) const; /// Creates HTTP 404 Canceled, body = Request processing cancelled virtual http_response create_processing_cancelled_response(const socket_streambuf & sock, const http_request & request) const; /// Creates HTTP 500 Internal Server Error answer virtual http_response create_internal_server_error_response(const socket_streambuf & sock, const http_request & request, std::exception * ex) const; /// Creates HTTP 417 Expectation Failed answer virtual http_response create_expectation_failed_response(const processing_context * context) const; /// Creates HTTP 100 Continue response virtual http_response create_continue_response(const processing_context * context) const; public: /// Adds http filter(both pre and post if applicable) virtual void add_filter(ext::intrusive_ptr<http_filter_base> filter); /// Adds listener with optional SSL configuration virtual void add_listener(listener listener, ssl_ctx_iptr ssl_ctx = nullptr); /// Adds opens listener with given backlog with optional SSL configuration virtual void add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx = nullptr); /// Adds and opens listener by port number with optional SSL configuration virtual void add_listener(unsigned short port, ssl_ctx_iptr ssl_ctx = nullptr); /// Adds http handler virtual void add_handler(std::unique_ptr<const http_server_handler> handler); /// Adds simple http handler virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_body_function_type function); /// Adds simple http handler virtual void add_handler(std::string url, simple_handler_body_function_type function); /// Adds simple http handler virtual void add_handler(std::string method, std::string url, simple_handler_body_function_type function); /// Adds simple http handler virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string); /// Adds simple http handler virtual void add_handler(std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string); /// Adds simple http handler virtual void add_handler(std::string method, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string); public: /// Configures processing context limits virtual void set_processing_context_limits(std::size_t minimum, std::size_t maximum); /// Sets http processing executor virtual void set_processing_executor(std::shared_ptr<processing_executor> executor); /// Sets http processing executor to given thread_pool virtual void set_thread_pool(std::shared_ptr<ext::thread_pool> pool); public: void set_socket_timeout(duration_type timeout); auto get_socket_timeout() const -> duration_type; void set_keep_alive_timeout(duration_type timeout); auto get_keep_alive_timeout() const -> duration_type; public: // limits void set_maximum_http_headers_size(std::size_t size); auto get_maximum_http_headers_size() -> std::size_t; void set_maximum_http_body_size(std::size_t size); auto get_maximum_http_body_size() -> std::size_t; void set_maximum_discarded_http_body_size(std::size_t size); auto get_maximum_discarded_http_body_size() -> std::size_t; public: void set_logger(ext::library_logger::logger * logger) { m_logger = logger; m_sock_queue.set_logger(logger); } auto get_logger() const noexcept { return m_logger; } void set_request_logging_level(unsigned log_level) noexcept { m_request_logging_level = log_level; } auto get_request_logging_level() const noexcept { return m_request_logging_level; } void set_request_body_logging_level(unsigned log_level) noexcept { m_request_body_logging_level = log_level; } auto get_request_body_logging_level() const noexcept { return m_request_body_logging_level; } void set_read_buffer_logging_level(unsigned log_level) noexcept { m_read_buffer_logging_level = log_level; } auto get_read_buffer_logging_level() const noexcept { return m_read_buffer_logging_level; } void set_write_buffer_logging_level(unsigned log_level) noexcept { m_write_buffer_logging_level = log_level; } auto get_write_buffer_logging_level() const noexcept { return m_write_buffer_logging_level; } public: http_server(); virtual ~http_server(); http_server(http_server && ) = delete; http_server & operator =(http_server && ) = delete; }; }
55.412598
191
0.772729
54576dde40f92e2115e8513477ef33ee1b106a31
673
cpp
C++
campion-era/control.cpp/control.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
1
2021-07-05T16:32:14.000Z
2021-07-05T16:32:14.000Z
campion-era/control.cpp/control.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
null
null
null
campion-era/control.cpp/control.cpp
GeorgianBadita/algorithmic-problems
6b260050b7a1768b5e47a1d7d4ef7138a52db210
[ "MIT" ]
1
2021-05-14T15:40:09.000Z
2021-05-14T15:40:09.000Z
#include<fstream> using namespace std; int x[100]; int main() { ifstream f("control.in"); ofstream g("control.out"); int ok,aux,i,n,v[101],ap=0,s=0; f>>n; for(i=1;i<=n;i++) { f>>v[i]; } do { ok=1; for(i=1;i<=n-1;i++) { if(v[i]>v[i+1]) { ok=0; aux=v[i]; v[i]=v[i+1]; v[i+1]=aux; } } }while(ok==0); for(i=1;i<=n;i++) { } }
20.393939
40
0.2526
546385e4c80aaa2894a8b262692e2894d57c4c14
5,774
cpp
C++
test/indenter/test_indenter_python.cpp
SammyEnigma/qutepart-cpp
3c5401c7d2856697171c4331099e2fa05ef0c49b
[ "WTFPL" ]
5
2019-11-02T15:36:38.000Z
2021-11-01T21:17:32.000Z
test/indenter/test_indenter_python.cpp
SammyEnigma/qutepart-cpp
3c5401c7d2856697171c4331099e2fa05ef0c49b
[ "WTFPL" ]
1
2021-02-11T23:11:00.000Z
2021-02-11T23:11:00.000Z
test/indenter/test_indenter_python.cpp
SammyEnigma/qutepart-cpp
3c5401c7d2856697171c4331099e2fa05ef0c49b
[ "WTFPL" ]
3
2020-01-29T17:55:34.000Z
2021-12-23T11:38:41.000Z
#include <QtTest/QtTest> #include "base_indenter_test.h" class Test: public BaseTest { Q_OBJECT private slots: void python_data() { addColumns(); QTest::newRow("dedent return") << "def some_function():\n" " return" << std::make_pair(1, 8) << "\npass" << "def some_function():\n" " return\n" "pass"; QTest::newRow("dedent continue") << "while True:\n" " continue" << std::make_pair(1, 10) << "\npass" << "while True:\n" " continue\n" "pass"; QTest::newRow("keep indent 1") << "def some_function(param, param2):\n" " a = 5\n" " b = 7" << std::make_pair(2, 7) << "\npass" << "def some_function(param, param2):\n" " a = 5\n" " b = 7\n" " pass"; QTest::newRow("keep indent 2") << "class my_class():\n" " def my_fun():\n" " print \"Foo\"\n" " print 3" << std::make_pair(3, 11) << "\npass" << "class my_class():\n" " def my_fun():\n" " print \"Foo\"\n" " print 3\n" " pass"; QTest::newRow("keep indent 3") << "while True:\n" " returnFunc()\n" " myVar = 3" << std::make_pair(2, 11) << "\npass" << "while True:\n" " returnFunc()\n" " myVar = 3\n" " pass"; QTest::newRow("keep indent 4") << "def some_function():" << std::make_pair(0, 20) << "\npass\n\npass" << "def some_function():\n" " pass\n" "\n" "pass"; QTest::newRow("dedent raise") << "try:\n" " raise" << std::make_pair(1, 7) << "\nexcept:" << "try:\n" " raise\n" "except:"; QTest::newRow("indent colon 1") << "def some_function(param, param2):" << std::make_pair(0, 33) << "\npass" << "def some_function(param, param2):\n" " pass"; QTest::newRow("indent colon 2") << "def some_function(1,\n" " 2):" << std::make_pair(1, 21) << "\npass" << "def some_function(1,\n" " 2):\n" " pass"; QTest::newRow("indent colon 3") // do not indent colon if hanging indentation used << " a = {1:" << std::make_pair(0, 11) << "\nx" << " a = {1:\n" " x"; QTest::newRow("dedent pass") << "def some_function():\n" " pass" << std::make_pair(1, 6) << "\npass" << "def some_function():\n" " pass\n" "pass"; QTest::newRow("dedent return") << "def some_function():\n" " return" << std::make_pair(1, 8) << "\npass" << "def some_function():\n" " return\n" "pass"; QTest::newRow("autoindent after empty") << "while True:\n" " returnFunc()\n" "\n" " myVar = 3" << std::make_pair(2, 0) << "\n\tx" << "while True:\n" " returnFunc()\n" "\n" " x\n" " myVar = 3"; QTest::newRow("hanging indentation") << " return func (something," << std::make_pair(0, 28) << "\nx" << " return func (something,\n" " x"; QTest::newRow("hanging indentation 2") << " return func (\n" " something," << std::make_pair(1, 18) << "\nx" << " return func (\n" " something,\n" " x"; QTest::newRow("hanging indentation 3") << " a = func (\n" " something)" << std::make_pair(1, 20) << "\nx" << " a = func (\n" " something)\n" " x"; QTest::newRow("hanging indentation 4") << " return func(a,\n" " another_func(1,\n" " 2)," << std::make_pair(2, 33) << "\nx" << " return func(a,\n" " another_func(1,\n" " 2),\n" " x"; QTest::newRow("hanging indentation 5") << " return func(another_func(1,\n" " 2)," << std::make_pair(1, 33) << "\nx" << " return func(another_func(1,\n" " 2),\n" " x"; } void python() { qpart.setIndentAlgorithm(Qutepart::INDENT_ALG_PYTHON); qpart.setIndentWidth(2); runDataDrivenTest(); } }; QTEST_MAIN(Test) #include "test_indenter_python.moc"
29.762887
91
0.336682
5463d9bb199bab6956d3a9ba142fbd22002a67a9
3,707
hpp
C++
hydra/vulkan/pipeline_layout.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
2
2016-09-15T22:29:46.000Z
2017-11-30T11:16:12.000Z
hydra/vulkan/pipeline_layout.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
hydra/vulkan/pipeline_layout.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
// // file : pipeline_layout.hpp // in : file:///home/tim/projects/hydra/hydra/vulkan/pipeline_layout.hpp // // created by : Timothée Feuillet // date: Sun Aug 14 2016 13:43:28 GMT+0200 (CEST) // // // Copyright (c) 2016 Timothée Feuillet // // 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 __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__ #define __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__ #include <vulkan/vulkan.h> #include "../hydra_exception.hpp" #include "device.hpp" #include "descriptor_set_layout.hpp" namespace neam { namespace hydra { namespace vk { /// \brief Wraps a VkPipelineLayout and its creation /// \note This class is far from being complete class pipeline_layout { public: // advanced public: /// \brief Create an empty pipeline layout pipeline_layout(device &_dev) : dev(_dev) { VkPipelineLayoutCreateInfo plci { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0, 0, nullptr, 0, nullptr }; check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout)); } /// \brief Create a pipeline layout (without push constants) pipeline_layout(device &_dev, const std::vector<descriptor_set_layout *> &dsl_vct, const std::vector<VkPushConstantRange> &pc_range_vct = {}) : dev(_dev) { std::vector<VkDescriptorSetLayout> vk_dsl_vct; vk_dsl_vct.reserve(dsl_vct.size()); for (descriptor_set_layout *it : dsl_vct) vk_dsl_vct.push_back(it->_get_vk_descriptor_set_layout()); VkPipelineLayoutCreateInfo plci { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0, (uint32_t)vk_dsl_vct.size(), vk_dsl_vct.data(), (uint32_t)pc_range_vct.size(), pc_range_vct.data() }; check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout)); } ~pipeline_layout() { if (vk_playout) dev._vkDestroyPipelineLayout(vk_playout, nullptr); } public: // advanced /// \brief Return the VkPipelineLayout VkPipelineLayout _get_vk_pipeline_layout() const { return vk_playout; } private: device &dev; VkPipelineLayout vk_playout = nullptr; }; } // namespace vk } // namespace hydra } // namespace neam #endif // __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
36.70297
151
0.671702
5463e2b117bb725c57e7be31f033e82e3e782a5d
30,428
cpp
C++
src/topology/TMR_TACSTopoCreator.cpp
peekwez/tmr
3ac41d8edd9b65c833f55940c451ee87019c5f55
[ "Apache-2.0" ]
null
null
null
src/topology/TMR_TACSTopoCreator.cpp
peekwez/tmr
3ac41d8edd9b65c833f55940c451ee87019c5f55
[ "Apache-2.0" ]
null
null
null
src/topology/TMR_TACSTopoCreator.cpp
peekwez/tmr
3ac41d8edd9b65c833f55940c451ee87019c5f55
[ "Apache-2.0" ]
null
null
null
/* This file is part of the package TMR for adaptive mesh refinement. Copyright (C) 2015 Georgia Tech Research Corporation. Additional copyright (C) 2015 Graeme Kennedy. All rights reserved. TMR is licensed under the Apache License, Version 2.0 (the "License"); you may not use this software 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 "TMR_TACSTopoCreator.h" #include "TMROctStiffness.h" #include "TMRQuadStiffness.h" #include "FElibrary.h" #include "Solid.h" #include "PlaneStressQuad.h" /* Compare integers for sorting */ static int compare_integers( const void *a, const void *b ){ return (*(int*)a - *(int*)b); } /* Set up a creator class for the given filter problem */ TMROctTACSTopoCreator::TMROctTACSTopoCreator( TMRBoundaryConditions *_bcs, TMROctForest *_filter ): TMROctTACSCreator(_bcs){ // Reference the filter filter = _filter; filter->incref(); int mpi_rank; MPI_Comm comm = filter->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); // Create the nodes within the filter filter->createNodes(); // Get the node range for the filter design variables const int *filter_range; filter->getOwnedNodeRange(&filter_range); // Set up the variable map for the design variable numbers int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank]; filter_map = new TACSVarMap(comm, num_filter_local); filter_map->incref(); // Set the filter indices to NULL filter_indices = NULL; } /* Free the creator object */ TMROctTACSTopoCreator::~TMROctTACSTopoCreator(){ filter->decref(); filter_map->decref(); if (filter_indices){ filter_indices->decref(); } } // Get the underlying information about the filter void TMROctTACSTopoCreator::getFilter( TMROctForest **_filter ){ *_filter = filter; } void TMROctTACSTopoCreator::getMap( TACSVarMap **_map ){ *_map = filter_map; } void TMROctTACSTopoCreator::getIndices( TACSBVecIndices **_indices ){ *_indices = filter_indices; } void TMROctTACSTopoCreator::computeWeights( const int mesh_order, const double *knots, TMROctant *node, TMROctant *oct, TMRIndexWeight *weights, double *tmp ){ // Find the side length of the octant in the filter that contains // the element octant const int32_t h = 1 << (TMR_MAX_LEVEL - node->level); const int32_t hoct = 1 << (TMR_MAX_LEVEL - oct->level); // Compute the i, j, k location of the nod const int i = node->info % mesh_order; const int j = (node->info % (mesh_order*mesh_order))/mesh_order; const int k = node->info/(mesh_order*mesh_order); // Get the u/v/w values within the filter octant double pt[3]; pt[0] = -1.0 + 2.0*((node->x % hoct) + 0.5*h*(1.0 + knots[i]))/hoct; pt[1] = -1.0 + 2.0*((node->y % hoct) + 0.5*h*(1.0 + knots[j]))/hoct; pt[2] = -1.0 + 2.0*((node->z % hoct) + 0.5*h*(1.0 + knots[k]))/hoct; // Get the Lagrange shape functions double *N = tmp; filter->evalInterp(pt, N); // Get the dependent node information for this mesh const int *dep_ptr, *dep_conn; const double *dep_weights; filter->getDepNodeConn(&dep_ptr, &dep_conn, &dep_weights); // Get the mesh order const int order = filter->getMeshOrder(); // Get the connectivity const int *conn; filter->getNodeConn(&conn); const int *c = &conn[oct->tag*order*order*order]; // Loop over the adjacent nodes within the filter int nweights = 0; for ( int kk = 0; kk < order; kk++ ){ for ( int jj = 0; jj < order; jj++ ){ for ( int ii = 0; ii < order; ii++ ){ // Set the weights int offset = ii + jj*order + kk*order*order; double weight = N[offset]; // Get the tag number if (c[offset] >= 0){ weights[nweights].index = c[offset]; weights[nweights].weight = weight; nweights++; } else { int node = -c[offset]-1; for ( int jp = dep_ptr[node]; jp < dep_ptr[node+1]; jp++ ){ weights[nweights].index = dep_conn[jp]; weights[nweights].weight = weight*dep_weights[jp]; nweights++; } } } } } // Sort and sum the array of weights - there are only 8 nodes // per filter point at most nweights = TMRIndexWeight::uniqueSort(weights, nweights); } /* Create all of the elements for the topology optimization problem */ void TMROctTACSTopoCreator::createElements( int order, TMROctForest *forest, int num_elements, TACSElement **elements ){ // Get the MPI communicator int mpi_rank, mpi_size; MPI_Comm comm = forest->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); MPI_Comm_size(comm, &mpi_size); // Get the octants associated with the forest TMROctantArray *octants; forest->getOctants(&octants); // Get the array of octants from the forest int num_octs; TMROctant *octs; octants->getArray(&octs, &num_octs); // Create a queue for the external octants TMROctantQueue *queue = new TMROctantQueue(); // The number of weights/element const int filter_order = filter->getMeshOrder(); const int nweights = filter_order*filter_order*filter_order; // Allocate temp space double *tmp = new double[ nweights ]; TMRIndexWeight *wtmp = new TMRIndexWeight[ nweights*filter_order*filter_order ]; // Allocate the weights for all of the local elements TMRIndexWeight *weights = new TMRIndexWeight[ nweights*num_octs ]; // Fake the information as if we have a third-order and we are // searching for the centeral node const int node_info = 13; const double node_knots[] = {-1.0, 0.0, 1.0}; const int node_order = 3; for ( int i = 0; i < num_octs; i++ ){ // Get the original octant from the forest TMROctant node = octs[i]; node.info = node_info; // Find the enclosing central node int mpi_owner = 0; TMROctant *oct = filter->findEnclosing(node_order, node_knots, &node, &mpi_owner); if (!oct){ // Push the octant to the external queue. We will handle these // cases seperately after a collective communication. node.tag = mpi_owner; queue->push(&node); weights[nweights*i].index = -1; } else { computeWeights(node_order, node_knots, &node, oct, wtmp, tmp); memcpy(&weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight)); } } // Create a list of octants that are external TMROctantArray *nodes = queue->toArray(); delete queue; // Distribute the nodes to the processors that own them int use_tags = 1; int *send_ptr, *recv_ptr; TMROctantArray *dist_nodes = filter->distributeOctants(nodes, use_tags, &send_ptr, &recv_ptr); delete nodes; // Get the external nodes that are local to this processor and // compute their weights int dist_size; TMROctant *dist_array; dist_nodes->getArray(&dist_array, &dist_size); // Create the distributed weights TMRIndexWeight *dist_weights = new TMRIndexWeight[ nweights*dist_size ]; for ( int i = 0; i < dist_size; i++ ){ TMROctant *oct = filter->findEnclosing(node_order, node_knots, &dist_array[i]); if (oct){ computeWeights(node_order, node_knots, &dist_array[i], oct, wtmp, tmp); memcpy(&dist_weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight)); } else { fprintf(stderr, "[%d] TMROctTACSTopoCreator: Node not found\n", mpi_rank); } } // Free the temporary space delete [] wtmp; delete [] tmp; // The distributed nodes are no longer required delete dist_nodes; // Compute the number of sends and recvs that were performed. int nsends = 0, nrecvs = 0; for ( int i = 0; i < mpi_size; i++ ){ if (i != mpi_rank){ if (send_ptr[i+1] - send_ptr[i] > 0){ nsends++; } if (recv_ptr[i+1] - recv_ptr[i] > 0){ nrecvs++; } } } // Now prepare to reverse the communication to distribute the // weights back to the processors that need them. First allocate // space for the requests MPI_Request *send_request = new MPI_Request[ nrecvs ]; // Allocate space for the new weights TMRIndexWeight *new_weights = new TMRIndexWeight[ nweights*send_ptr[mpi_size] ]; // Loop over all the ranks and send for ( int i = 0, j = 0; i < mpi_size; i++ ){ if (i != mpi_rank && recv_ptr[i+1] - recv_ptr[i] > 0){ // Post the send to the destination int count = nweights*(recv_ptr[i+1] - recv_ptr[i]); MPI_Isend(&dist_weights[nweights*recv_ptr[i]], count, TMRIndexWeight_MPI_type, i, 0, comm, &send_request[j]); j++; } } // Loop over the recieve calls for ( int i = 0; i < mpi_size; i++ ){ if (i != mpi_rank && send_ptr[i+1] > send_ptr[i]){ int count = nweights*(send_ptr[i+1] - send_ptr[i]); MPI_Recv(&new_weights[nweights*send_ptr[i]], count, TMRIndexWeight_MPI_type, i, 0, comm, MPI_STATUS_IGNORE); } } // Wait for any remaining sends to complete MPI_Waitall(nrecvs, send_request, MPI_STATUSES_IGNORE); // Now place the weights back into their original locations for ( int i = 0, j = 0; i < num_octs && j < send_ptr[mpi_size]; i++ ){ if (weights[nweights*i].index == -1){ memcpy(&weights[nweights*i], &new_weights[nweights*j], nweights*sizeof(TMRIndexWeight)); j++; } } delete [] new_weights; delete [] send_request; delete [] send_ptr; delete [] recv_ptr; delete [] dist_weights; // The node numbers within the weights are global. Convert them to a // local node ordering and create a list of the external node // numbers referenced by the weights. // Get the node range for the filter design variables const int *filter_range; filter->getOwnedNodeRange(&filter_range); // The number of local nodes int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank]; // Get the external numbers from the filter itself const int *filter_ext; int num_filter_ext = filter->getNodeNumbers(&filter_ext); // Count up all the external nodes int num_ext = 0; int max_ext_nodes = nweights*num_octs + num_filter_ext; int *ext_nodes = new int[ max_ext_nodes ]; // Add the external nodes from the filter for ( int i = 0; i < num_filter_ext; i++ ){ int node = filter_ext[i]; if (node >= 0 && (node < filter_range[mpi_rank] || node >= filter_range[mpi_rank+1])){ ext_nodes[num_ext] = node; num_ext++; } } // Add the external nodes from the element-level connectivity for ( int i = 0; i < nweights*num_octs; i++ ){ int node = weights[i].index; if (node < filter_range[mpi_rank] || node >= filter_range[mpi_rank+1]){ ext_nodes[num_ext] = node; num_ext++; } } // Sort the external array of nodes qsort(ext_nodes, num_ext, sizeof(int), compare_integers); // Remove duplicates from the array int len = 0; for ( int i = 0; i < num_ext; i++, len++ ){ while ((i < num_ext-1) && (ext_nodes[i] == ext_nodes[i+1])){ i++; } if (i != len){ ext_nodes[len] = ext_nodes[i]; } } // Truncate the array and delete the old array int num_ext_nodes = len; int *ext_node_nums = new int[ len ]; memcpy(ext_node_nums, ext_nodes, len*sizeof(int)); delete [] ext_nodes; // Set up the external filter indices for this filter. The indices // objects steals the array for the external nodes. filter_indices = new TACSBVecIndices(&ext_node_nums, num_ext_nodes); filter_indices->incref(); filter_indices->setUpInverse(); // Scan through all of the weights and convert them to the local // ordering for ( int i = 0; i < nweights*num_octs; i++ ){ int node = weights[i].index; if (node >= filter_range[mpi_rank] && node < filter_range[mpi_rank+1]){ node = node - filter_range[mpi_rank]; } else { node = num_filter_local + filter_indices->findIndex(node); } weights[i].index = node; } // Loop over the octants octants->getArray(&octs, &num_octs); for ( int i = 0; i < num_octs; i++ ){ // Allocate the stiffness object elements[i] = createElement(order, &octs[i], &weights[nweights*i], nweights); } delete [] weights; } /* Set up a creator class for the given filter problem */ TMRQuadTACSTopoCreator::TMRQuadTACSTopoCreator( TMRBoundaryConditions *_bcs, TMRQuadForest *_filter ): TMRQuadTACSCreator(_bcs){ // Reference the filter filter = _filter; filter->incref(); int mpi_rank; MPI_Comm comm = filter->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); // Create the nodes within the filter filter->createNodes(); // Get the node range for the filter design variables const int *filter_range; filter->getOwnedNodeRange(&filter_range); // Set up the variable map for the design variable numbers int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank]; filter_map = new TACSVarMap(comm, num_filter_local); filter_map->incref(); // Set the filter indices to NULL filter_indices = NULL; } /* Free the creator object */ TMRQuadTACSTopoCreator::~TMRQuadTACSTopoCreator(){ filter->decref(); filter_map->decref(); if (filter_indices){ filter_indices->decref(); } } // Get the underlying information about the problem void TMRQuadTACSTopoCreator::getFilter( TMRQuadForest **_filter ){ *_filter = filter; } void TMRQuadTACSTopoCreator::getMap( TACSVarMap **_map ){ *_map = filter_map; } void TMRQuadTACSTopoCreator::getIndices( TACSBVecIndices **_indices ){ *_indices = filter_indices; } /* Compute the weights associated with the given quadrant */ void TMRQuadTACSTopoCreator::computeWeights( const int mesh_order, const double *knots, TMRQuadrant *node, TMRQuadrant *quad, TMRIndexWeight *weights, double *tmp, int sort ){ // Find the side length of the octant in the filter that contains // the element octant const int32_t h = 1 << (TMR_MAX_LEVEL - node->level); const int32_t hquad = 1 << (TMR_MAX_LEVEL - quad->level); // Compute the i, j, k location of the node const int i = node->info % mesh_order; const int j = node->info/mesh_order; // Get the u/v values within the filter octant double pt[3]; pt[0] = -1.0 + 2.0*((node->x % hquad) + 0.5*h*(1.0 + knots[i]))/hquad; pt[1] = -1.0 + 2.0*((node->y % hquad) + 0.5*h*(1.0 + knots[j]))/hquad; // Get the shape functions double *N = tmp; filter->evalInterp(pt, N); // Get the dependent node information for this mesh const int *dep_ptr, *dep_conn; const double *dep_weights; filter->getDepNodeConn(&dep_ptr, &dep_conn, &dep_weights); // Get the mesh order const int order = filter->getMeshOrder(); // Get the connectivity const int *conn; filter->getNodeConn(&conn); const int *c = &conn[quad->tag*order*order]; // Loop over the adjacent nodes within the filter int nweights = 0; for ( int jj = 0; jj < order; jj++ ){ for ( int ii = 0; ii < order; ii++ ){ // Set the weights int offset = ii + jj*order; double weight = N[offset]; // Get the tag number if (c[offset] >= 0){ weights[nweights].index = c[offset]; weights[nweights].weight = weight; nweights++; } else { int node = -c[offset]-1; for ( int jp = dep_ptr[node]; jp < dep_ptr[node+1]; jp++ ){ weights[nweights].index = dep_conn[jp]; weights[nweights].weight = weight*dep_weights[jp]; nweights++; } } } } if (sort){ // Sort and sum the array of weights - there are only 8 nodes // per filter point at most nweights = TMRIndexWeight::uniqueSort(weights, nweights); } } /* Create all of the elements for the topology optimization problem */ void TMRQuadTACSTopoCreator::createElements( int order, TMRQuadForest *forest, int num_elements, TACSElement **elements ){ // Get the MPI communicator int mpi_rank, mpi_size; MPI_Comm comm = forest->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); MPI_Comm_size(comm, &mpi_size); // Get the quadrants associated with the forest TMRQuadrantArray *quadrants; forest->getQuadrants(&quadrants); // Get the array of quadrants from the forest int num_quads; TMRQuadrant *quads; quadrants->getArray(&quads, &num_quads); // Create a queue for the external octants TMRQuadrantQueue *queue = new TMRQuadrantQueue(); // The number of weights/element const int filter_order = filter->getMeshOrder(); const int nweights = filter_order*filter_order; // Allocate temp space double *tmp = new double[ nweights ]; TMRIndexWeight *wtmp = new TMRIndexWeight[ nweights*filter_order*filter_order ]; // Allocate the weights for all of the local elements TMRIndexWeight *weights = new TMRIndexWeight[ nweights*num_quads ]; // Fake the information as if we have a third-order and we are // searching for the centeral node const int node_info = 4; const double node_knots[] = {-1.0, 0.0, 1.0}; const int node_order = 3; for ( int i = 0; i < num_quads; i++ ){ // Get the original quadrant from the forest TMRQuadrant node = quads[i]; node.info = node_info; // Find the central node int mpi_owner = 0; TMRQuadrant *quad = filter->findEnclosing(node_order, node_knots, &node, &mpi_owner); if (!quad){ // Push the quadrant to the external queue. We will handle these // cases seperately after a collective communication. node.tag = mpi_owner; queue->push(&node); weights[nweights*i].index = -1; } else { computeWeights(node_order, node_knots, &node, quad, wtmp, tmp); memcpy(&weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight)); } } // Create a list of quadrants that are external TMRQuadrantArray *nodes = queue->toArray(); delete queue; // Distribute the nodes to the processors that own them int use_tags = 1; int *send_ptr, *recv_ptr; TMRQuadrantArray *dist_nodes = filter->distributeQuadrants(nodes, use_tags, &send_ptr, &recv_ptr); delete nodes; // Get the external nodes that are local to this processor and // compute their weights int dist_size; TMRQuadrant *dist_array; dist_nodes->getArray(&dist_array, &dist_size); // Create the distributed weights TMRIndexWeight *dist_weights = new TMRIndexWeight[ nweights*dist_size ]; for ( int i = 0; i < dist_size; i++ ){ TMRQuadrant *quad = filter->findEnclosing(node_order, node_knots, &dist_array[i]); if (quad){ computeWeights(node_order, node_knots, &dist_array[i], quad, wtmp, tmp); memcpy(&dist_weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight)); } } // Free the tmporary space delete [] wtmp; delete [] tmp; // The distributed nodes are no longer required delete dist_nodes; // Compute the number of sends and recvs that were performed. int nsends = 0, nrecvs = 0; for ( int i = 0; i < mpi_size; i++ ){ if (i != mpi_rank){ if (send_ptr[i+1] - send_ptr[i] > 0){ nsends++; } if (recv_ptr[i+1] - recv_ptr[i] > 0){ nrecvs++; } } } // Now prepare to reverse the communication to distribute the // weights back to the processors that need them. First allocate // space for the requests MPI_Request *send_request = new MPI_Request[ nrecvs ]; // Allocate space for the new weights TMRIndexWeight *new_weights = new TMRIndexWeight[ nweights*send_ptr[mpi_size] ]; // Loop over all the ranks and send for ( int i = 0, j = 0; i < mpi_size; i++ ){ if (i != mpi_rank && recv_ptr[i+1] - recv_ptr[i] > 0){ // Post the send to the destination int count = nweights*(recv_ptr[i+1] - recv_ptr[i]); MPI_Isend(&dist_weights[nweights*recv_ptr[i]], count, TMRIndexWeight_MPI_type, i, 0, comm, &send_request[j]); j++; } } // Loop over the recieve calls for ( int i = 0; i < mpi_size; i++ ){ if (i != mpi_rank && send_ptr[i+1] > send_ptr[i]){ int count = nweights*(send_ptr[i+1] - send_ptr[i]); MPI_Recv(&new_weights[nweights*send_ptr[i]], count, TMRIndexWeight_MPI_type, i, 0, comm, MPI_STATUS_IGNORE); } } // Wait for any remaining sends to complete MPI_Waitall(nrecvs, send_request, MPI_STATUSES_IGNORE); // Now place the weights back into their original locations for ( int i = 0, j = 0; i < num_quads && j < send_ptr[mpi_size]; i++ ){ if (weights[nweights*i].index == -1){ memcpy(&weights[nweights*i], &new_weights[nweights*j], nweights*sizeof(TMRIndexWeight)); j++; } } delete [] new_weights; delete [] send_request; delete [] send_ptr; delete [] recv_ptr; delete [] dist_weights; // The node numbers within the weights are global. Convert them into // a local node ordering and create a list of the external node // numbers referenced by the weights. // Get the node range for the filter design variables const int *filter_range; filter->getOwnedNodeRange(&filter_range); // The number of local nodes int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank]; // Get the external numbers from the filter itself const int *filter_ext; int num_filter_ext = filter->getNodeNumbers(&filter_ext); // Count up all the external nodes int num_ext = 0; int max_ext_nodes = nweights*num_quads + num_filter_ext; int *ext_nodes = new int[ max_ext_nodes ]; // Add the external nodes from the filter for ( int i = 0; i < num_filter_ext; i++ ){ int node = filter_ext[i]; if (node >= 0 && (node < filter_range[mpi_rank] || node >= filter_range[mpi_rank+1])){ ext_nodes[num_ext] = node; num_ext++; } } // Add the external nodes from the element-level connectivity for ( int i = 0; i < nweights*num_quads; i++ ){ int node = weights[i].index; if (node < filter_range[mpi_rank] || node >= filter_range[mpi_rank+1]){ ext_nodes[num_ext] = node; num_ext++; } } // Sort the external array of nodes qsort(ext_nodes, num_ext, sizeof(int), compare_integers); // Remove duplicates from the array int len = 0; for ( int i = 0; i < num_ext; i++, len++ ){ while ((i < num_ext-1) && (ext_nodes[i] == ext_nodes[i+1])){ i++; } if (i != len){ ext_nodes[len] = ext_nodes[i]; } } // Truncate the array and delete the old array int num_ext_nodes = len; int *ext_node_nums = new int[ len ]; memcpy(ext_node_nums, ext_nodes, len*sizeof(int)); delete [] ext_nodes; // Set up the external filter indices for this filter. The indices // objects steals the array for the external nodes. filter_indices = new TACSBVecIndices(&ext_node_nums, num_ext_nodes); filter_indices->incref(); filter_indices->setUpInverse(); // Scan through all of the weights and convert them to the local // ordering for ( int i = 0; i < nweights*num_quads; i++ ){ int node = weights[i].index; if (node >= filter_range[mpi_rank] && node < filter_range[mpi_rank+1]){ node = node - filter_range[mpi_rank]; } else { node = num_filter_local + filter_indices->findIndex(node); } weights[i].index = node; } // Loop over the octants quadrants->getArray(&quads, &num_quads); for ( int i = 0; i < num_quads; i++ ){ // Allocate the stiffness object elements[i] = createElement(order, &quads[i], &weights[nweights*i], nweights); } // Free the weights delete [] weights; } /* Set up a creator class for the given forest problem */ TMROctConformTACSTopoCreator::TMROctConformTACSTopoCreator( TMRBoundaryConditions *_bcs, TMROctForest *_forest, int order, TMRInterpolationType interp_type ): TMROctTACSCreator(_bcs){ // Use the forest as the filter in these cases if (order < 0 || (order == _forest->getMeshOrder() && interp_type == _forest->getInterpType())){ filter = _forest; } else { filter = _forest->duplicate(); order = filter->getMeshOrder()-1; if (order < 2){ order = 2; } filter->setMeshOrder(order, interp_type); } filter->incref(); // Create the nodes within the filter filter->createNodes(); } /* Free the creator object */ TMROctConformTACSTopoCreator::~TMROctConformTACSTopoCreator(){ filter->decref(); } // Get the underlying information about the problem void TMROctConformTACSTopoCreator::getFilter( TMROctForest **_filter ){ *_filter = filter; } /* Create all of the elements for the topology optimization problem */ void TMROctConformTACSTopoCreator::createElements( int order, TMROctForest *forest, int num_elements, TACSElement **elements ){ // Get the MPI communicator int mpi_rank, mpi_size; MPI_Comm comm = forest->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); MPI_Comm_size(comm, &mpi_size); // Get the quadrants associated with the forest TMROctantArray *octants; forest->getOctants(&octants); // Get the array of quadrants from the forest int num_octs; TMROctant *octs; octants->getArray(&octs, &num_octs); // The number of weights/element const int filter_order = filter->getMeshOrder(); const int nweights = filter_order*filter_order*filter_order; // Allocate the weights for all of the local elements int *index = new int[ nweights*num_octs ]; // Loop over the nodes and convert to the local numbering scheme const int *conn; filter->getNodeConn(&conn); // Get the local node index on this processor for ( int i = 0; i < nweights*num_octs; i++ ){ index[i] = filter->getLocalNodeNumber(conn[i]); } // Loop over the octants octants->getArray(&octs, &num_octs); for ( int i = 0; i < num_octs; i++ ){ // Allocate the stiffness object elements[i] = createElement(order, &octs[i], &index[nweights*i], nweights, filter); } } /* Set up a creator class for the given forest problem */ TMRQuadConformTACSTopoCreator::TMRQuadConformTACSTopoCreator( TMRBoundaryConditions *_bcs, TMRQuadForest *_forest, int order, TMRInterpolationType interp_type ): TMRQuadTACSCreator(_bcs){ // Create and reference the filter if (order < 0 || (order == _forest->getMeshOrder() && interp_type == _forest->getInterpType())){ filter = _forest; } else { filter = _forest->duplicate(); order = filter->getMeshOrder()-1; if (order < 2){ order = 2; } filter->setMeshOrder(order, interp_type); } filter->incref(); // Create the nodes within the filter filter->createNodes(); } /* Free the creator object */ TMRQuadConformTACSTopoCreator::~TMRQuadConformTACSTopoCreator(){ filter->decref(); } // Get the underlying information about the problem void TMRQuadConformTACSTopoCreator::getFilter( TMRQuadForest **_filter ){ *_filter = filter; } /* Create all of the elements for the topology optimization problem */ void TMRQuadConformTACSTopoCreator::createElements( int order, TMRQuadForest *forest, int num_elements, TACSElement **elements ){ // Get the MPI communicator int mpi_rank, mpi_size; MPI_Comm comm = forest->getMPIComm(); MPI_Comm_rank(comm, &mpi_rank); MPI_Comm_size(comm, &mpi_size); // Get the quadrants associated with the forest TMRQuadrantArray *quadrants; forest->getQuadrants(&quadrants); // Get the array of quadrants from the forest int num_quads; TMRQuadrant *quads; quadrants->getArray(&quads, &num_quads); // The number of weights/element const int filter_order = filter->getMeshOrder(); const int nweights = filter_order*filter_order; // Allocate the weights for all of the local elements int *index = new int[ nweights*num_quads ]; // Loop over the nodes and convert to the local numbering scheme const int *conn; filter->getNodeConn(&conn); // Get the local node index on this processor for ( int i = 0; i < nweights*num_quads; i++ ){ index[i] = filter->getLocalNodeNumber(conn[i]); } // Loop over the octants quadrants->getArray(&quads, &num_quads); for ( int i = 0; i < num_quads; i++ ){ // Allocate the stiffness object elements[i] = createElement(order, &quads[i], &index[nweights*i], nweights, filter); } }
31.401445
97
0.627021
546a11c1b2fb0ea64885541a70df951ecaf43844
1,136
hpp
C++
src/common/naive.hpp
TNishimoto/rlbwt_iterator
f2a4ae0276cb756d2724570def84641449da2f87
[ "MIT" ]
null
null
null
src/common/naive.hpp
TNishimoto/rlbwt_iterator
f2a4ae0276cb756d2724570def84641449da2f87
[ "MIT" ]
null
null
null
src/common/naive.hpp
TNishimoto/rlbwt_iterator
f2a4ae0276cb756d2724570def84641449da2f87
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <iostream> #include <list> #include <memory> #include <random> #include <exception> #include <algorithm> #include <fstream> #include <chrono> #include <time.h> //#include <stdio.h> namespace stool { class NaiveAlgorithms { template <typename INDEX> static std::vector<INDEX> naive_sa(std::string &text) { std::vector<INDEX> sa; INDEX n = text.size(); sa.resize(n); for (INDEX i = 0; i < n; i++) { sa[i] = i; } std::sort(sa.begin(), sa.end(), [&](const INDEX &x, const INDEX &y) { INDEX size = x < y ? text.size() - y : text.size() - x; for (INDEX i = 0; i < size; i++) { if ((uint8_t)text[x + i] != (uint8_t)text[y + i]) { return (uint8_t)text[x + i] < (uint8_t)text[y + i]; } } return x <= y ? false : true; }); return sa; } }; } // namespace stool
27.047619
81
0.43662
54720cd912f3adf5ecc237fbb8e1ef36829439c1
773
hpp
C++
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_EngramEntry_Toilet_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C // 0x0000 (0x0090 - 0x0090) class UEngramEntry_Toilet_C : public UPrimalEngramEntry { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C"); return ptr; } void ExecuteUbergraph_EngramEntry_Toilet(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
19.820513
106
0.626132
54722c53866980373235710947a1645834cb2bd8
18,465
cpp
C++
ums1/ums1.cpp
codepilot/UMS1
e89332f613c0306cc8ff20e232c9e7d15b7672df
[ "MIT" ]
1
2016-07-20T18:40:42.000Z
2016-07-20T18:40:42.000Z
ums1/ums1.cpp
codepilot/UMS1
e89332f613c0306cc8ff20e232c9e7d15b7672df
[ "MIT" ]
null
null
null
ums1/ums1.cpp
codepilot/UMS1
e89332f613c0306cc8ff20e232c9e7d15b7672df
[ "MIT" ]
null
null
null
#include "stdafx.h" LPFN_DISCONNECTEX DisconnectEx=0; SOCKET sListen; char *status200HelloWorld = "HTTP/1.1 200 Ok\r\nContent-Length: 12\r\nConnection: close\r\n\r\nHello World!"; #if 0 #include <km\Ntifs.h> #include <km\Fltkernel.h> #else /* START OF LIBUV SOURCE MATERIAL (SEE LIBUV-LICENSE) */ namespace WinInternal { typedef struct _FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; DWORD FileAttributes; } FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION; typedef struct _FILE_STANDARD_INFORMATION { LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG NumberOfLinks; BOOLEAN DeletePending; BOOLEAN Directory; } FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; typedef struct _FILE_INTERNAL_INFORMATION { LARGE_INTEGER IndexNumber; } FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION; typedef struct _FILE_EA_INFORMATION { ULONG EaSize; } FILE_EA_INFORMATION, *PFILE_EA_INFORMATION; typedef struct _FILE_ACCESS_INFORMATION { ACCESS_MASK AccessFlags; } FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION; typedef struct _FILE_POSITION_INFORMATION { LARGE_INTEGER CurrentByteOffset; } FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; typedef struct _FILE_MODE_INFORMATION { ULONG Mode; } FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION; typedef struct _FILE_ALIGNMENT_INFORMATION { ULONG AlignmentRequirement; } FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION; typedef struct _FILE_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; } FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION; typedef struct _FILE_ALL_INFORMATION { FILE_BASIC_INFORMATION BasicInformation; FILE_STANDARD_INFORMATION StandardInformation; FILE_INTERNAL_INFORMATION InternalInformation; FILE_EA_INFORMATION EaInformation; FILE_ACCESS_INFORMATION AccessInformation; FILE_POSITION_INFORMATION PositionInformation; FILE_MODE_INFORMATION ModeInformation; FILE_ALIGNMENT_INFORMATION AlignmentInformation; FILE_NAME_INFORMATION NameInformation; } FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION; typedef struct _FILE_FS_VOLUME_INFORMATION { LARGE_INTEGER VolumeCreationTime; ULONG VolumeSerialNumber; ULONG VolumeLabelLength; BOOLEAN SupportsObjects; WCHAR VolumeLabel[1]; } FILE_FS_VOLUME_INFORMATION, *PFILE_FS_VOLUME_INFORMATION; typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; PVOID Pointer; } DUMMYUNIONNAME; ULONG_PTR Information; } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; typedef enum _FILE_INFORMATION_CLASS { FileDirectoryInformation = 1, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileAttributeCacheInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileMaximumInformation } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; #endif typedef enum _FS_INFORMATION_CLASS { FileFsVolumeInformation = 1, FileFsLabelInformation = 2, FileFsSizeInformation = 3, FileFsDeviceInformation = 4, FileFsAttributeInformation = 5, FileFsControlInformation = 6, FileFsFullSizeInformation = 7, FileFsObjectIdInformation = 8, FileFsDriverPathInformation = 9, FileFsVolumeFlagsInformation = 10, FileFsSectorSizeInformation = 11 } FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS; typedef NTSTATUS (NTAPI *sNtQueryInformationFile) (HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass); typedef NTSTATUS (NTAPI *sNtQueryVolumeInformationFile) (HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation, ULONG Length, FS_INFORMATION_CLASS FsInformationClass); //sRtlNtStatusToDosError pRtlNtStatusToDosError; //sNtDeviceIoControlFile pNtDeviceIoControlFile; sNtQueryInformationFile pNtQueryInformationFile; //sNtSetInformationFile pNtSetInformationFile; sNtQueryVolumeInformationFile pNtQueryVolumeInformationFile; //sNtQueryDirectoryFile pNtQueryDirectoryFile; //sNtQuerySystemInformation pNtQuerySystemInformation; //#include <Winternl.h> typedef BOOLEAN (WINAPI *sRtlTimeToSecondsSince1970) (_In_ PLARGE_INTEGER Time, _Out_ PULONG ElapsedSeconds); sRtlTimeToSecondsSince1970 pRtlTimeToSecondsSince1970; }; __forceinline int fs__stat_handle(HANDLE handle) { WinInternal::FILE_ALL_INFORMATION file_info; WinInternal::FILE_FS_VOLUME_INFORMATION volume_info; NTSTATUS nt_status; WinInternal::IO_STATUS_BLOCK io_status; nt_status = WinInternal::pNtQueryInformationFile(handle, &io_status, &file_info, sizeof file_info, WinInternal::FileAllInformation); /* Buffer overflow (a warning status code) is expected here. */ /* if (NT_ERROR(nt_status)) { SetLastError(pRtlNtStatusToDosError(nt_status)); return -1; } */ nt_status = WinInternal::pNtQueryVolumeInformationFile(handle, &io_status, &volume_info, sizeof volume_info, WinInternal::FileFsVolumeInformation); /* Buffer overflow (a warning status code) is expected here. */ /* if (io_status.Status == STATUS_NOT_IMPLEMENTED) { statbuf->st_dev = 0; } else if (NT_ERROR(nt_status)) { SetLastError(pRtlNtStatusToDosError(nt_status)); return -1; } else { statbuf->st_dev = volume_info.VolumeSerialNumber; } */ /* Todo: st_mode should probably always be 0666 for everyone. We might also * want to report 0777 if the file is a .exe or a directory. * * Currently it's based on whether the 'readonly' attribute is set, which * makes little sense because the semantics are so different: the 'read-only' * flag is just a way for a user to protect against accidental deletion, and * serves no security purpose. Windows uses ACLs for that. * * Also people now use uv_fs_chmod() to take away the writable bit for good * reasons. Windows however just makes the file read-only, which makes it * impossible to delete the file afterwards, since read-only files can't be * deleted. * * IOW it's all just a clusterfuck and we should think of something that * makes slightly more sense. * * And uv_fs_chmod should probably just fail on windows or be a total no-op. * There's nothing sensible it can do anyway. */ if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { //statbuf->st_mode |= S_IFLNK; //if (fs__readlink_handle(handle, NULL, &statbuf->st_size) != 0) return -1; } else if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //statbuf->st_mode |= _S_IFDIR; //statbuf->st_size = 0; } else { //statbuf->st_mode |= _S_IFREG; //statbuf->st_size = file_info.StandardInformation.EndOfFile.QuadPart; } //if (file_info.BasicInformation.FileAttributes & FILE_ATTRIBUTE_READONLY) //statbuf->st_mode |= _S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6); //else //statbuf->st_mode |= (_S_IREAD | _S_IWRITE) | ((_S_IREAD | _S_IWRITE) >> 3) | // ((_S_IREAD | _S_IWRITE) >> 6); //FILETIME_TO_TIMESPEC(statbuf->st_atim, file_info.BasicInformation.LastAccessTime); //FILETIME_TO_TIMESPEC(statbuf->st_ctim, file_info.BasicInformation.ChangeTime); //FILETIME_TO_TIMESPEC(statbuf->st_mtim, file_info.BasicInformation.LastWriteTime); //FILETIME_TO_TIMESPEC(statbuf->st_birthtim, file_info.BasicInformation.CreationTime); //statbuf->st_ino = file_info.InternalInformation.IndexNumber.QuadPart; /* st_blocks contains the on-disk allocation size in 512-byte units. */ //statbuf->st_blocks = // file_info.StandardInformation.AllocationSize.QuadPart >> 9ULL; //statbuf->st_nlink = file_info.StandardInformation.NumberOfLinks; /* The st_blksize is supposed to be the 'optimal' number of bytes for reading * and writing to the disk. That is, for any definition of 'optimal' - it's * supposed to at least avoid read-update-write behavior when writing to the * disk. * * However nobody knows this and even fewer people actually use this value, * and in order to fill it out we'd have to make another syscall to query the * volume for FILE_FS_SECTOR_SIZE_INFORMATION. * * Therefore we'll just report a sensible value that's quite commonly okay * on modern hardware. */ //statbuf->st_blksize = 2048; /* Todo: set st_flags to something meaningful. Also provide a wrapper for * chattr(2). */ //statbuf->st_flags = 0; /* Windows has nothing sensible to say about these values, so they'll just * remain empty. */ //statbuf->st_gid = 0; //statbuf->st_uid = 0; //statbuf->st_rdev = 0; //statbuf->st_gen = 0; return 0; } __forceinline void fs_stat() { HANDLE handle = CreateFileW( L".", FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if(INVALID_HANDLE_VALUE == handle) { DebugBreak(); } fs__stat_handle(handle); CloseHandle(handle); } /* END OF LIBUV SOURCE MATERIAL (SEE LIBUV-LICENSE) */ __declspec(align(64)) __int64 volatile dequeuedRequestCount{0}; __declspec(align(64)) unsigned __int64 volatile firstRequestStarted{0}; __declspec(align(64)) unsigned __int64 volatile lastRequestFinished{0}; __declspec(align(64)) unsigned __int64 volatile WaitVariable{0}; __declspec(align(64)) unsigned __int64 CompareVariable{0}; __declspec(align(64)) unsigned __int64 UndesiredValue{0}; __declspec(noinline) bool benchmark_sync_fs_stat() { for(int r = 0; r < numBenchmarkRepetitions; r++) { auto start = __rdtsc(); for(int i = 0; i < numRequests; i++) { fs_stat(); } auto finish = __rdtsc(); wprintf(L"start to finish: %f seconds\n", static_cast<double_t>(finish - start) / 3300000000.0); } return false; } __declspec(noinline) int64_t getTsc1970epoch() { //auto ftSpacing = KeQueryTimeIncrement(); FILETIME ftNowPrecise{0,0}; GetSystemTimePreciseAsFileTime(&ftNowPrecise); std::array<int64_t, 10000> ftList; std::array<int64_t, 10000> tscList; std::array<int64_t, 10000> ftSpacing; std::array<int64_t, 10000> tscSpacing; double_t averageFtSpacing{0}; double_t averageTscSpacing{0}; int64_t lastTick{*reinterpret_cast<volatile int64_t *>(0x7FFE0014ui32)}; for(int i = 0; i < 10000; i++) { int64_t curTick; do { curTick = *reinterpret_cast<volatile int64_t *>(0x7FFE0014ui32); } while(curTick == lastTick); ftList[i] = curTick; tscList[i] = __rdtsc(); lastTick = curTick; } for(int i = 1; i < 10000; i++) { ftSpacing[i] = ftList[i] - ftList[i - 1]; averageFtSpacing += ftSpacing[i]; tscSpacing[i] = tscList[i] - tscList[i - 1]; averageTscSpacing += tscSpacing[i]; } averageFtSpacing /= 9999.0; averageTscSpacing /= 9999.0; return 0; } //int64_t Tsc1970epoch{getTsc1970epoch()}; __forceinline int64_t fileTimeFromUTC() { #if 1 FILETIME sSystemTimeAsFileTime{0,0}; //GetSystemTimeAsFileTime(&sSystemTimeAsFileTime); uint64_t start = __rdtsc(); uint64_t middle = __rdtsc(); //GetSystemTimePreciseAsFileTime(&sSystemTimeAsFileTime); uint64_t finish = __rdtsc(); printf("start to finish = %I64u\n", finish - start); LARGE_INTEGER liSysFileTime{sSystemTimeAsFileTime.dwLowDateTime, sSystemTimeAsFileTime.dwHighDateTime}; return liSysFileTime.QuadPart; #else return *reinterpret_cast<volatile int64_t *>(0x7FFE0014ui32); #endif } __forceinline int64_t fileTimeFromSystemTime() { SYSTEMTIME sysTime1970{1970,1,4,1,0,0,0,0}; FILETIME fileType1970{0,0}; macroDebugLastError(SystemTimeToFileTime(&sysTime1970, &fileType1970)); LARGE_INTEGER liFileType1970{fileType1970.dwLowDateTime, fileType1970.dwHighDateTime}; return liFileType1970.QuadPart; } const int64_t fileTimeEpoch1970{fileTimeFromSystemTime()}; __forceinline double_t msSince1970perf() { double_t retC = static_cast<double_t>(fileTimeFromUTC() - fileTimeEpoch1970) * 1.0e-4; return retC; } int64_t msSince1970() { //FILETIME sSystemTimeAsFileTime{0,0}; //GetSystemTimeAsFileTime(&sSystemTimeAsFileTime); //ULONG ulSecondsA{0}; //LARGE_INTEGER liSysFileTime{sSystemTimeAsFileTime.dwLowDateTime, sSystemTimeAsFileTime.dwHighDateTime}; //macroDebugLastError(pRtlTimeToSecondsSince1970(&liSysFileTime, &ulSecondsA)); //int64_t retA = static_cast<int64_t>(ulSecondsA) * 1000; //SYSTEMTIME sysTime1970{1970,1,4,1,0,0,0,0}; //FILETIME fileType1970{0,0}; //macroDebugLastError(SystemTimeToFileTime(&sysTime1970, &fileType1970)); //LARGE_INTEGER liFileType1970{fileType1970.dwLowDateTime, fileType1970.dwHighDateTime}; //ULONG ulSecondsB{0}; //macroDebugLastError(pRtlTimeToSecondsSince1970(&liFileType1970, &ulSecondsB)); //int64_t retB = static_cast<int64_t>(ulSecondsB) * 1000; int64_t retC = (fileTimeFromUTC() - fileTimeEpoch1970) / 10000i64; return retC; } #if 0 __declspec(noinline) void smallestTSC_old1() { SetThreadAffinityMask(GetCurrentThread(), 1); uint64_t smallest = 0xFFFFFFFFFFFFFFFFui64; for(;;) { auto start = __rdtsc(); auto finish = __rdtsc(); auto diff = finish - start; if(diff < smallest) { smallest = diff; printf("smallest %I64u\n", smallest); if(smallest < 10) { break; } } } } __declspec(noinline) void smallestTSC_old2() { SetThreadAffinityMask(GetCurrentThread(), 1); int32_t smallest = 0x7FFFFFFFi32; for(;;) { int32_t start = __rdtsc(); int32_t finish = __rdtsc(); int32_t diff = finish - start; if(diff < smallest) { smallest = diff; printf("smallest %d\n", smallest); if(smallest < 10) { break; } } } } __declspec(noinline) void smallestTSC() { //SetThreadAffinityMask(GetCurrentThread(), 1); uint64_t smallest = 0xFFFFFFFFFFFFFFFFui64; for(;;) { SwitchToThread(); uint64_t start = __rdtsc(); uint64_t finish = __rdtsc(); uint64_t diff = finish - start; if(diff < smallest) { smallest = diff; printf("smallest %I64u\n", smallest); if(smallest < 10) { break; } } } } #endif int __cdecl _tmain(int argc, _TCHAR* argv[]) { //smallestTSC(); HMODULE ntdll_module; // HMODULE kernel32_module; ntdll_module = GetModuleHandleA("ntdll.dll"); WinInternal::pNtQueryInformationFile = (WinInternal::sNtQueryInformationFile) GetProcAddress(ntdll_module, "NtQueryInformationFile"); WinInternal::pNtQueryVolumeInformationFile = (WinInternal::sNtQueryVolumeInformationFile) GetProcAddress(ntdll_module, "NtQueryVolumeInformationFile"); WinInternal::pRtlTimeToSecondsSince1970 = (WinInternal::sRtlTimeToSecondsSince1970) GetProcAddress(ntdll_module, "RtlTimeToSecondsSince1970"); if(0) { std::array<double_t, 1000> counts; for(int i = 0; i < 1000; i++) { counts[i] = msSince1970perf(); } for(int i = 0; i < 1000; i++) { printf("msSince1970perf(): %f\n", counts[i]); } } #ifdef USE_SYNCHRONOUS wprintf(TEXT("benchmark_sync_fs_stat started\n")); benchmark_sync_fs_stat(); wprintf(TEXT("benchmark_sync_fs_stat finished\n")); #endif #ifdef USE_NEW_THREAD_POOL #ifdef USE_TEST_WEBSERVER wprintf(TEXT("test_new_thread_pool started\n")); test_new_thread_pool(); wprintf(TEXT("test_new_thread_pool finished\n")); #endif wprintf(TEXT("benchmark_ntp_workQueue_fs_stat started\n")); benchmark_ntp_workQueue_fs_stat(); wprintf(TEXT("benchmark_ntp_workQueue_fs_stat finished\n")); wprintf(TEXT("benchmark_ntp_trySubmit_fs_stat started\n")); benchmark_ntp_trySubmit_fs_stat(); wprintf(TEXT("benchmark_ntp_trySubmit_fs_stat finished\n")); #endif #ifdef USE_DIRECT_THREAD_POOL #ifdef USE_TEST_WEBSERVER wprintf(TEXT("test_direct_thread_pool started\n")); test_direct_thread_pool(); wprintf(TEXT("test_direct_thread_pool finished\n")); #endif wprintf(TEXT("benchmark_dtp_fs_stat started\n")); benchmark_dtp_fs_stat(); wprintf(TEXT("benchmark_dtp_fs_stat finished\n")); #endif #ifdef USE_USER_MODE_SCHEDULING #ifdef USE_TEST_WEBSERVER wprintf(TEXT("test_user_mode_scheduling started\n")); test_user_mode_scheduling(); wprintf(TEXT("test_user_mode_scheduling finished\n")); #endif wprintf(TEXT("benchmark_ums_fs_stat started\n")); benchmark_ums_fs_stat(); wprintf(TEXT("benchmark_ums_fs_stat finished\n")); #endif #ifdef USE_OLD_THREAD_POOL #ifdef USE_TEST_WEBSERVER wprintf(TEXT("test_old_thread_pool started\n")); test_old_thread_pool(); wprintf(TEXT("test_old_thread_pool finished\n")); #endif wprintf(TEXT("benchmark_otp_fs_stat started\n")); benchmark_otp_fs_stat(); wprintf(TEXT("benchmark_opt_fs_stat finished\n")); #endif #ifdef _DEBUG wprintf(L"Press any key to quit..."); getchar(); #endif return 0; }
32.973214
153
0.746548
5472d4010d1eaeaf62637e439bd939e07cee465d
28,590
cpp
C++
src/Renderer.cpp
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
src/Renderer.cpp
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
src/Renderer.cpp
smithy545/engine
1818a1acafdbc2550b10ef74a215aa41d94edf0f
[ "MIT" ]
null
null
null
// // Created by Philip Smith on 10/17/2020. // #include <engine/Renderer.h> #include <engine/OrbitCam.h> #include <engine/InstanceList.h> #include <engine/mesh/Mesh.h> #include <engine/sprite/ShapeSprite.h> #include <engine/sprite/TextSprite.h> #include <engine/sprite/TextureSprite.h> #include <fmt/format.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <iostream> #include <utils/file_util.h> namespace engine { Renderer::Renderer(entt::registry& registry) { m_context_entity = registry.create(); registry.emplace<RenderContext>(m_context_entity); } bool Renderer::init(entt::registry &registry) { // init config auto& context = registry.get<RenderContext>(m_context_entity); context.screen_width = 800; context.screen_height = 600; context.fovy = 45.0f; context.z_near = 0.1f; context.z_far = 10000.0f; json requested_textures; json requested_fonts; try { // load override from config file if available auto config_json = utils::file::read_json_file("../res/renderer.json"); if (config_json.contains("width")) context.screen_width = config_json["width"]; if (config_json.contains("height")) context.screen_height = config_json["height"]; if(config_json.contains("fovy")) context.fovy = config_json["fovy"]; if(config_json.contains("z_near")) context.z_near = config_json["z_near"]; if(config_json.contains("z_far")) context.z_far = config_json["z_far"]; if(config_json.contains("textures")) requested_textures = config_json["textures"]; if(config_json.contains("fonts")) requested_fonts = config_json["fonts"]; } catch (nlohmann::detail::parse_error& e) { std::cout << "Error reading config file: " << e.what() << std::endl; } //init subsystems if(!init_glfw()) { std::cerr << "Failed to init GLFW" << std::endl; return false; } if(!init_window(context)) { std::cerr << "Failed to init window" << std::endl; return false; } if(!init_glew()) { std::cerr << "Failed to init glew" << std::endl; return false; } if(!init_shaders(context)) { std::cerr << "Failed to init shaders" << std::endl; return false; } if(!init_fonts(requested_fonts)) { std::cerr << "Failed to init fonts" << std::endl; return false; } // cull triangles facing away from camera glEnable(GL_CULL_FACE); // enable depth buffer glEnable(GL_DEPTH_TEST); // background glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // load textures from config for(auto info: requested_textures) { std::string path = info["filepath"]; std::string name = info["name"]; std::cout << "Loading texture '" << name << "' at '" << path << "'" << std::endl; m_loaded_textures.insert({name, utils::file::read_png_file_to_texture(path)}); } registry.on_construct<Mesh>().connect<&load_mesh>(); registry.on_construct<ShapeSprite>().connect<&load_shape_sprite>(); registry.on_construct<TextureSprite>().connect<&Renderer::load_texture_sprite>(this); registry.on_construct<TextSprite>().connect<&Renderer::load_text_sprite>(); registry.on_update<Mesh>().connect<&update_mesh>(); registry.on_update<ShapeSprite>().connect<&update_shape_sprite>(); registry.on_update<TextureSprite>().connect<&Renderer::update_texture_sprite>(this); registry.on_update<TextSprite>().connect<&Renderer::update_text_sprite>( ); registry.on_destroy<VertexArrayObject>().connect<&destroy_vao>(); registry.on_destroy<InstanceList>().connect<&destroy_instances>(); return true; } bool Renderer::init_glfw() { if (!glfwInit()) return false; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif return true; } bool Renderer::init_glew() { glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { glfwTerminate(); return false; } return true; } bool Renderer::init_fonts(const nlohmann::json& fonts) { FT_Library ft; if(FT_Init_FreeType(&ft)) { std::cerr << "Could not initialize FreeType library" << std::endl; return false; } // enable blending for text transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for(auto font: fonts) { auto glyphs = load_font(ft, font["path"], font["size"]); if(glyphs.empty()) std::cerr << "Could not initialize font from '" << font["path"] << "'" << std::endl; else m_loaded_fonts[font["name"]] = glyphs; } FT_Done_FreeType(ft); return true; } bool Renderer::init_window(RenderContext& context) { // Open a window and create its OpenGL context context.window = glfwCreateWindow(context.screen_width, context.screen_height, "Civil War", nullptr, nullptr); if (context.window == nullptr) { std::cerr << "Failed to open GLFW window" << std::endl; glfwTerminate(); return false; } glfwMakeContextCurrent(context.window); return true; } bool Renderer::init_shaders(RenderContext& context) { auto color_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/color_vert.glsl"); auto color_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/color_vert2d.glsl"); auto color_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/color_frag.glsl"); auto tex_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/tex_vert.glsl"); auto tex_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/tex_vert2d.glsl"); auto tex_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/tex_frag.glsl"); auto text_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/text_vert.glsl"); auto text_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/text_frag.glsl"); try { context.color_shader2d = load_shader(color_vshader_src2d.c_str(), color_fshader_src.c_str()); } catch (std::runtime_error& e) { std::cout << "2d color shader failed to init: " << e.what() << std::endl; return false; } try { context.color_shader3d = load_shader(color_vshader_src.c_str(), color_fshader_src.c_str()); } catch (std::runtime_error& e) { std::cout << "3d color shader failed to init: " << e.what() << std::endl; return false; } try { context.tex_shader2d = load_shader(tex_vshader_src2d.c_str(), tex_fshader_src.c_str()); } catch (std::runtime_error& e) { std::cout << "2d texture shader failed to init: " << e.what() << std::endl; return false; } try { context.tex_shader3d = load_shader(tex_vshader_src.c_str(), tex_fshader_src.c_str()); } catch (std::runtime_error& e) { std::cout << "3d texture shader failed to init: " << e.what() << std::endl; return false; } try { context.text_shader = load_shader(text_vshader_src.c_str(), text_fshader_src.c_str()); } catch (std::runtime_error& e) { std::cout << "Text shader failed to init: " << e.what() << std::endl; return false; } return true; } void Renderer::load_mesh(entt::registry &registry, entt::entity entity) { auto sizeof_vec4 = sizeof(glm::vec4); auto sizeof_vec3 = sizeof(glm::vec3); auto& mesh = registry.get<Mesh>(entity); // setup vertex array object glGenVertexArrays(1, &mesh.vao); glBindVertexArray(mesh.vao); // verts glGenBuffers(1, &mesh.vbo); glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // colors glGenBuffers(1, &mesh.cbo); glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // indices glGenBuffers(1, &mesh.ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0], GL_STATIC_DRAW); // instance buffer (initially empty) GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ARRAY_BUFFER, ibo); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4)); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4)); glVertexAttribDivisor(2, 1); glVertexAttribDivisor(3, 1); glVertexAttribDivisor(4, 1); glVertexAttribDivisor(5, 1); mesh.num_indices = mesh.indices.size(); registry.emplace<InstanceList>(entity, ibo); glBindVertexArray(0); } void Renderer::load_shape_sprite(entt::registry &registry, entt::entity entity) { auto sizeof_vec4 = sizeof(glm::vec4); auto& sprite = registry.get<ShapeSprite>(entity); // setup vertex array object glGenVertexArrays(1, &sprite.vao); glBindVertexArray(sprite.vao); // verts glGenBuffers(1, &sprite.vbo); glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // colors glGenBuffers(1, &sprite.cbo); glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); // indices glGenBuffers(1, &sprite.ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0], GL_STATIC_DRAW); // instance buffer (initially empty) GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ARRAY_BUFFER, ibo); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4)); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4)); glVertexAttribDivisor(2, 1); glVertexAttribDivisor(3, 1); glVertexAttribDivisor(4, 1); glVertexAttribDivisor(5, 1); glBindVertexArray(0); sprite.num_indices = sprite.indices.size(); registry.emplace<InstanceList>(entity, ibo); } void Renderer::load_texture_sprite(entt::registry &registry, entt::entity entity) { auto sizeof_vec2 = sizeof(glm::vec2); auto sizeof_vec4 = sizeof(glm::vec4); auto& sprite = registry.get<TextureSprite>(entity); // setup vertex array object glGenVertexArrays(1, &sprite.vao); glBindVertexArray(sprite.vao); // verts glGenBuffers(1, &sprite.vbo); glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // uvs glGenBuffers(1, &sprite.tex_uvs); glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs); glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); // indices glGenBuffers(1, &sprite.ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0], GL_STATIC_DRAW); // texture sampler sprite.tex_id = m_loaded_textures[sprite.name]; // instance buffer (initially empty) GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ARRAY_BUFFER, ibo); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4)); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4)); glVertexAttribDivisor(2, 1); glVertexAttribDivisor(3, 1); glVertexAttribDivisor(4, 1); glVertexAttribDivisor(5, 1); glBindVertexArray(0); sprite.num_indices = sprite.indices.size(); registry.emplace<InstanceList>(entity, ibo); } void Renderer::load_text_sprite(entt::registry &registry, entt::entity entity) { auto& sprite = registry.get<TextSprite>(entity); glGenVertexArrays(1, &sprite.vao); glGenBuffers(1, &sprite.vbo); glBindVertexArray(sprite.vao); glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, nullptr, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Renderer::update_mesh(entt::registry &registry, entt::entity entity) { auto sizeof_vec3 = sizeof(glm::vec3); auto& mesh = registry.get<Mesh>(entity); glBindVertexArray(mesh.vao); // verts glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW); // colors glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW); // indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0], GL_STATIC_DRAW); glBindVertexArray(0); } void Renderer::update_shape_sprite(entt::registry &registry, entt::entity entity) { auto sizeof_vec3 = sizeof(glm::vec3); auto sizeof_vec2 = sizeof(glm::vec2); auto& sprite = registry.get<ShapeSprite>(entity); glBindVertexArray(sprite.vao); // verts glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW); // colors glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW); // indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0], GL_STATIC_DRAW); glBindVertexArray(0); } void Renderer::update_texture_sprite(entt::registry &registry, entt::entity entity) { auto sizeof_vec2 = sizeof(glm::vec2); auto& sprite = registry.get<TextureSprite>(entity); glBindVertexArray(sprite.vao); // verts glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW); // uvs glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs); glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW); // indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0], GL_STATIC_DRAW); // texture sampler sprite.tex_id = m_loaded_textures[sprite.name]; glBindVertexArray(0); } void Renderer::update_text_sprite(entt::registry &registry, entt::entity entity) {} void Renderer::destroy_vao(entt::registry &registry, entt::entity entity) { auto vao = registry.get<VertexArrayObject>(entity); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); if(vao.vao) glDeleteVertexArrays(1, &vao.vao); if(vao.vbo) glDeleteBuffers(1, &vao.vbo); if(vao.ebo) glDeleteBuffers(1, &vao.ebo); if(vao.cbo) glDeleteBuffers(1, &vao.cbo); if(vao.tex_id) glDeleteTextures(1, &vao.tex_id); if(vao.tex_uvs) glDeleteBuffers(1, &vao.tex_uvs); } void Renderer::destroy_instances(entt::registry &registry, entt::entity entity) { auto instances = registry.get<InstanceList>(entity); if(instances.id) glDeleteBuffers(1, &instances.id); } void Renderer::render(entt::registry &registry, const Camera::Ptr& camera) { const auto& ctx = registry.get<RenderContext>(m_context_entity); glm::mat4 vp; // 3D rendering if(camera != nullptr) { vp = glm::perspective(ctx.fovy, ctx.screen_width / ctx.screen_height, ctx.z_near, ctx.z_far) * camera->get_view(); glUseProgram(ctx.color_shader3d); glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader3d, "VP"), 1, GL_FALSE, &vp[0][0]); auto view3d = registry.view<Mesh, InstanceList>(); for (const auto &entity: view3d) { auto[mesh, ilist] = view3d.get(entity); if (mesh.visible) { glBindVertexArray(mesh.vao); glDrawElementsInstanced(ilist.render_strategy, mesh.num_indices, GL_UNSIGNED_INT, 0, ilist.instances.size()); } } } // 2D rendering (TODO: Add occlusion culling to prevent drawing 3D entities that are covered by 2D elements) vp = glm::ortho(0.f, ctx.screen_width, ctx.screen_height, 0.f); glUseProgram(ctx.color_shader2d); glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]); auto color_view = registry.view<ShapeSprite, InstanceList>(); for(const auto &entity: color_view) { auto [sprite, ilist] = color_view.get(entity); if(sprite.visible) { glBindVertexArray(sprite.vao); glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0, ilist.instances.size()); } } // texture rendering glUseProgram(ctx.tex_shader2d); glUniformMatrix4fv(glGetUniformLocation(ctx.tex_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]); glUniform1i(glGetUniformLocation(ctx.tex_shader2d, "texSampler"), 0); auto tex_view = registry.view<TextureSprite, InstanceList>(); for(const auto &entity: tex_view) { auto [sprite, ilist] = tex_view.get(entity); if(sprite.visible) { glBindVertexArray(sprite.vao); glBindTexture(GL_TEXTURE_2D, sprite.tex_id); glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0, ilist.instances.size()); glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); } } // text rendering glUseProgram(ctx.text_shader); glUniformMatrix4fv(glGetUniformLocation(ctx.text_shader, "VP"), 1, GL_FALSE, &vp[0][0]); glUniform1i(glGetUniformLocation(ctx.text_shader, "texSampler"), 0); auto text_view = registry.view<TextSprite>(); for(const auto &entity: text_view) { auto [sprite] = text_view.get(entity); if(sprite.visible) { if(!m_loaded_fonts.contains(sprite.font)) std::cerr << "Can't render sprite with unloaded font '" << sprite.font << "'" << std::endl; else { glUniform3f(glGetUniformLocation(ctx.text_shader, "textColor"), sprite.color.x, sprite.color.y, sprite.color.z); auto x = sprite.x; for(std::string::const_iterator c = sprite.text.begin(); c != sprite.text.end(); c++) { if(!m_loaded_fonts[sprite.font].contains(*c)) { std::cerr << "Todo: add 404 texture. Error on '" << *c << "'"<< std::endl; continue; } auto glyph = m_loaded_fonts[sprite.font][*c]; float xpos = x + glyph.bearing.x * sprite.scale; float ypos = sprite.y - (glyph.size.y - glyph.bearing.y) * sprite.scale; float w = glyph.size.x * sprite.scale; float h = glyph.size.y * sprite.scale; // update VBO for each character float vertices[6][4] = { { xpos, ypos - h, 0.0f, 0.0f }, { xpos, ypos, 0.0f, 1.0f }, { xpos + w, ypos, 1.0f, 1.0f }, { xpos, ypos - h, 0.0f, 0.0f }, { xpos + w, ypos, 1.0f, 1.0f }, { xpos + w, ypos - h, 1.0f, 0.0f } }; glBindVertexArray(sprite.vao); // render glyph texture over quad glBindTexture(GL_TEXTURE_2D, glyph.tex_id); // update content of VBO memory glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); glBindBuffer(GL_ARRAY_BUFFER, 0); // render quad glDrawArrays(GL_TRIANGLES, 0, 6); // now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (glyph.advance >> 6) * sprite.scale; // bitshift by 6 to get value in pixels (2^6 = 64) glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); } } } } glUseProgram(0); } void Renderer::cleanup(entt::registry &registry) { const auto& ctx = registry.get<RenderContext>(m_context_entity); glDeleteProgram(ctx.color_shader2d); glDeleteProgram(ctx.color_shader3d); glDeleteProgram(ctx.tex_shader2d); glDeleteProgram(ctx.tex_shader3d); glDeleteProgram(ctx.text_shader); glfwTerminate(); } const RenderContext& Renderer::get_context(entt::registry& registry) const { return registry.get<RenderContext>(m_context_entity); } GLuint Renderer::load_shader(const char* vertex_source, const char* frag_source) { int vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source, nullptr); glCompileShader(vertex_shader); int success; char infoLog[512]; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex_shader, 512, nullptr, infoLog); std::string message = fmt::format("Error on vertex compilation ", infoLog); throw std::runtime_error(message.c_str()); } int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &frag_source, nullptr); glCompileShader(fragment_shader); glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment_shader, 512, nullptr, infoLog); std::string message = fmt::format("Error on fragment compilation ", infoLog); throw std::runtime_error(message.c_str()); } auto shader = glCreateProgram(); glAttachShader(shader, vertex_shader); glAttachShader(shader, fragment_shader); glLinkProgram(shader); glValidateProgram(shader); glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 512, nullptr, infoLog); std::string message = fmt::format("Error linking program ", infoLog); throw std::runtime_error(message.c_str()); } glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); return shader; } std::map<unsigned long, Renderer::Glyph> Renderer::load_font(FT_Library ft, const std::string& fontfile, unsigned int font_size, const std::string& text) { std::cout << "Loading font at '" << fontfile << "'" << std::endl; FT_Face face; if(FT_New_Face(ft, fontfile.c_str(), 0, &face)) { std::cerr << "Could not initialize font from file at " << fontfile << std::endl; FT_Done_Face(face); return {}; } // set size to load glyphs as FT_Set_Pixel_Sizes(face, 0, font_size); // disable byte-alignment restriction glPixelStorei(GL_UNPACK_ALIGNMENT, 1); std::map<unsigned long, Glyph> glyphs; for (unsigned char c: text) { if(glyphs.contains(c)) continue; if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "ERROR::FREETYTPE: Failed to load Glyph '" << c << "'" << std::endl; continue; } // generate texture unsigned int texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); Glyph glyph = { texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), static_cast<unsigned int>(face->glyph->advance.x) }; glyphs.insert({c, glyph}); } glBindTexture(GL_TEXTURE_2D, 0); // destroy FreeType once we're finished FT_Done_Face(face); return glyphs; } } // namespace engine
42.863568
123
0.619203
547358039612061aa8526099823f2a38d461fac8
11,458
cpp
C++
src/common/backend/utils/adt/oid.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/common/backend/utils/adt/oid.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/common/backend/utils/adt/oid.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* ------------------------------------------------------------------------- * * oid.c * Functions for the built-in type Oid ... also oidvector. * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/utils/adt/oid.c * * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include <limits.h> #include "catalog/pg_type.h" #include "libpq/pqformat.h" #include "utils/array.h" #include "utils/builtins.h" #define OidVectorSize(n) (offsetof(oidvector, values) + (n) * sizeof(Oid)) /***************************************************************************** * USER I/O ROUTINES * *****************************************************************************/ static Oid oidin_subr(const char* s, char** endloc) { unsigned long cvt; char* endptr = NULL; Oid result; if (*s == '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s))); errno = 0; cvt = strtoul(s, &endptr, 10); /* * strtoul() normally only sets ERANGE. On some systems it also may set * EINVAL, which simply means it couldn't parse the input string. This is * handled by the second "if" consistent across platforms. */ if (errno && errno != ERANGE && errno != EINVAL) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s))); if (endptr == s && *s != '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s))); if (errno == ERANGE) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("value \"%s\" is out of range for type oid", s))); if (endloc != NULL) { /* caller wants to deal with rest of string */ *endloc = endptr; } else { /* allow only whitespace after number */ while (*endptr && isspace((unsigned char)*endptr)) endptr++; if (*endptr) ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s))); } result = (Oid)cvt; /* * Cope with possibility that unsigned long is wider than Oid, in which * case strtoul will not raise an error for some values that are out of * the range of Oid. * * For backwards compatibility, we want to accept inputs that are given * with a minus sign, so allow the input value if it matches after either * signed or unsigned extension to long. * * To ensure consistent results on 32-bit and 64-bit platforms, make sure * the error message is the same as if strtoul() had returned ERANGE. */ #if OID_MAX != ULONG_MAX if (cvt != (unsigned long)result && cvt != (unsigned long)((int)result)) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("value \"%s\" is out of range for type oid", s))); #endif return result; } Datum oidin(PG_FUNCTION_ARGS) { char* s = PG_GETARG_CSTRING(0); Oid result; result = oidin_subr(s, NULL); PG_RETURN_OID(result); } Datum oidout(PG_FUNCTION_ARGS) { Oid o = PG_GETARG_OID(0); const int data_len = 12; char* result = (char*)palloc(data_len); errno_t ss_rc = snprintf_s(result, data_len, data_len - 1, "%u", o); securec_check_ss(ss_rc, "\0", "\0"); PG_RETURN_CSTRING(result); } /* * oidrecv - converts external binary format to oid */ Datum oidrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo)PG_GETARG_POINTER(0); PG_RETURN_OID((Oid)pq_getmsgint(buf, sizeof(Oid))); } /* * oidsend - converts oid to binary format */ Datum oidsend(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); StringInfoData buf; pq_begintypsend(&buf); pq_sendint32(&buf, arg1); PG_RETURN_BYTEA_P(pq_endtypsend(&buf)); } /* * construct oidvector given a raw array of Oids * * If oids is NULL then caller must fill values[] afterward */ oidvector* buildoidvector(const Oid* oids, int n) { oidvector* result = NULL; result = (oidvector*)palloc0(OidVectorSize(n)); if (n > 0 && oids) { errno_t ss_rc = memcpy_s(result->values, n * sizeof(Oid), oids, n * sizeof(Oid)); securec_check(ss_rc, "\0", "\0"); } /* * Attach standard array header. For historical reasons, we set the index * lower bound to 0 not 1. */ SET_VARSIZE(result, OidVectorSize(n)); result->ndim = 1; result->dataoffset = 0; /* never any nulls */ result->elemtype = OIDOID; result->dim1 = n; result->lbound1 = 0; return result; } #define OID_MAX_NUM 8192 /* * oidvectorin - converts "num num ..." to internal form */ Datum oidvectorin(PG_FUNCTION_ARGS) { char* oidString = PG_GETARG_CSTRING(0); oidvector* result = NULL; int n; result = (oidvector*)palloc0(OidVectorSize(OID_MAX_NUM)); for (n = 0; n < OID_MAX_NUM; n++) { while (*oidString && isspace((unsigned char)*oidString)) oidString++; if (*oidString == '\0') break; result->values[n] = oidin_subr(oidString, &oidString); } while (*oidString && isspace((unsigned char)*oidString)) oidString++; if (*oidString) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("oidvector has too many elements"))); SET_VARSIZE(result, OidVectorSize(n)); result->ndim = 1; result->dataoffset = 0; /* never any nulls */ result->elemtype = OIDOID; result->dim1 = n; result->lbound1 = 0; PG_RETURN_POINTER(result); } /* * oidvectorout - converts internal form to "num num ..." */ Datum oidvectorout(PG_FUNCTION_ARGS) { Datum oid_array_datum = PG_GETARG_DATUM(0); oidvector* oidArray = (oidvector*)PG_DETOAST_DATUM(oid_array_datum); int num, nnums = oidArray->dim1; char* rp = NULL; char* result = NULL; /* assumes sign, 10 digits, ' ' */ rp = result = (char*)palloc(nnums * 12 + 1); int postition = 0; for (num = 0; num < nnums; num++) { if (num != 0) { *rp++ = ' '; postition++; } errno_t ss_rc = sprintf_s(rp, nnums * 12 + 1 - postition, "%u", oidArray->values[num]); securec_check_ss(ss_rc, "\0", "\0"); while (*++rp != '\0') postition++; } *rp = '\0'; if (oidArray != (oidvector*)DatumGetPointer(oid_array_datum)) pfree_ext(oidArray); PG_RETURN_CSTRING(result); } /* * oidvectorrecv - converts external binary format to oidvector */ Datum oidvectorrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo)PG_GETARG_POINTER(0); FunctionCallInfoData locfcinfo; oidvector* result = NULL; /* * Normally one would call array_recv() using DirectFunctionCall3, but * that does not work since array_recv wants to cache some data using * fcinfo->flinfo->fn_extra. So we need to pass it our own flinfo * parameter. */ InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 3, InvalidOid, NULL, NULL); locfcinfo.arg[0] = PointerGetDatum(buf); locfcinfo.arg[1] = ObjectIdGetDatum(OIDOID); locfcinfo.arg[2] = Int32GetDatum(-1); locfcinfo.argnull[0] = false; locfcinfo.argnull[1] = false; locfcinfo.argnull[2] = false; result = (oidvector*)DatumGetPointer(array_recv(&locfcinfo)); Assert(!locfcinfo.isnull); /* sanity checks: oidvector must be 1-D, 0-based, no nulls */ if (ARR_NDIM(result) != 1 || ARR_HASNULL(result) || ARR_ELEMTYPE(result) != OIDOID || ARR_LBOUND(result)[0] != 0) ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("invalid oidvector data"))); /* check length for consistency with oidvectorin() */ if (ARR_DIMS(result)[0] > FUNC_MAX_ARGS) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("oidvector has too many elements"))); PG_RETURN_POINTER(result); } /* * oidvectorsend - converts oidvector to binary format */ Datum oidvectorsend(PG_FUNCTION_ARGS) { return array_send(fcinfo); } Datum oidvectorin_extend(PG_FUNCTION_ARGS) { return oidvectorin(fcinfo); } Datum oidvectorout_extend(PG_FUNCTION_ARGS) { return oidvectorout(fcinfo); } Datum oidvectorsend_extend(PG_FUNCTION_ARGS) { return oidvectorsend(fcinfo); } Datum oidvectorrecv_extend(PG_FUNCTION_ARGS) { return oidvectorrecv(fcinfo); } /* * oidparse - get OID from IConst/FConst node */ Oid oidparse(Node* node) { switch (nodeTag(node)) { case T_Integer: return intVal(node); case T_Float: /* * Values too large for int4 will be represented as Float * constants by the lexer. Accept these if they are valid OID * strings. */ return oidin_subr(strVal(node), NULL); default: ereport(ERROR, (errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE), errmsg("unrecognized node type: %d", (int)nodeTag(node)))); } return InvalidOid; /* keep compiler quiet */ } /***************************************************************************** * PUBLIC ROUTINES * *****************************************************************************/ Datum oideq(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 == arg2); } Datum oidne(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 != arg2); } Datum oidlt(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 < arg2); } Datum oidle(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 <= arg2); } Datum oidge(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 >= arg2); } Datum oidgt(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_BOOL(arg1 > arg2); } Datum oidlarger(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_OID((arg1 > arg2) ? arg1 : arg2); } Datum oidsmaller(PG_FUNCTION_ARGS) { Oid arg1 = PG_GETARG_OID(0); Oid arg2 = PG_GETARG_OID(1); PG_RETURN_OID((arg1 < arg2) ? arg1 : arg2); } Datum oidvectoreq(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp == 0); } Datum oidvectorne(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp != 0); } Datum oidvectorlt(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp < 0); } Datum oidvectorle(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp <= 0); } Datum oidvectorge(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp >= 0); } Datum oidvectorgt(PG_FUNCTION_ARGS) { int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo)); PG_RETURN_BOOL(cmp > 0); }
26.400922
120
0.616774
5473a402d01ac1bead5979450f8b478098257405
1,972
cpp
C++
test2.cpp
jhxqy/WebServerDemo
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
[ "MIT" ]
null
null
null
test2.cpp
jhxqy/WebServerDemo
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
[ "MIT" ]
null
null
null
test2.cpp
jhxqy/WebServerDemo
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
[ "MIT" ]
null
null
null
// // test2.cpp // EZasync // // Created by 贾皓翔 on 2019/6/5. // Copyright © 2019 贾皓翔. All rights reserved. // #include <stdio.h> #include "asynchttp/HTTP.hpp" using namespace std; using namespace HTTP; int main(){ IOContext ctx; Serv s(ctx,"8088"); HttpDispatcher *http=HttpDispatcherImpl::Create(); http->SetDefaultPath("./web"); http->Register("/hello", [](RequestBody &request,ResponseBody &response){ response.status=200; response.otherHeaders_["Content-Type"]="text/html"; response.out("hello Nice my HTTP!"); }); http->Register("/world", [](RequestBody &request,ResponseBody &response){ response.status=200; response.otherHeaders_["Content-Type"]="text/html;charset=utf-8"; for(auto i:request.headers_){ response.out("%s:%s<br>",i.first.c_str(),i.second.c_str()); } for(auto i:request.cookies_){ response.out("%s=%s<br>",i.first.c_str(),i.second.c_str()); } }); http->Register("/jump", [](RequestBody &request,ResponseBody &response){ response.sendRedirect("/world"); }); http->Register("/param", [](RequestBody &request,ResponseBody& response){ response.out("param:%s",request.parameters.c_str()); }); http->Register("/forward", [](RequestBody &req,ResponseBody &res){ res.out("这是跳转前第一个接口<br>"); res.forward(req,"/world"); }); http->RegisterFilter("/hello", [](RequestBody &request,ResponseBody &response){ cout<<"调用第一个过滤器!"<<endl; return FILTER_NEXT; }); http->RegisterFilter("/index.html", [](RequestBody &request,ResponseBody &response){ if (request.parameters.compare("hello")!=0) { cout<<request.parameters<<endl; response.forward(request, "/hello"); return FILTER_END; } cout<<"NICE!"<<endl; return FILTER_NEXT; }); ctx.run(); }
31.301587
88
0.591785
54759639a050f166bc45c0f04691f95a389bba4d
1,915
cpp
C++
src/Neuron.cpp
AmarOk1412/NeuralDriver
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
[ "WTFPL" ]
null
null
null
src/Neuron.cpp
AmarOk1412/NeuralDriver
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
[ "WTFPL" ]
null
null
null
src/Neuron.cpp
AmarOk1412/NeuralDriver
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
[ "WTFPL" ]
null
null
null
#include "Neuron.h" #include <math.h> #include <random> #include <iostream> #include <assert.h> Neuron::Neuron(const int nbInput) { init(nbInput, 3.4); } Neuron::~Neuron() { } double Neuron::calcOutput(std::vector<double> const& input) { return 1/(1+exp(-thetaTX(input))); } double Neuron::thetaTX(const std::vector<double>& input) { assert(_theta.size() == input.size()); assert(input.size() > 0); double res = .0; std::vector<double>::const_iterator itInputb = input.cbegin(); std::vector<double>::const_iterator itThetab = _theta.cbegin(); std::vector<double>::const_iterator itThetae = _theta.cend(); while(itThetab != itThetae) { res += (*itThetab) * (*itInputb); ++itInputb; ++itThetab; } return res+_biase; } void Neuron::adjust(const double error) { //Error is a ratio std::vector<double>::iterator itThetab = _theta.begin(); std::vector<double>::iterator itThetae = _theta.end(); while(itThetab != itThetae) { *itThetab *= error; ++itThetab; ++itThetae; } } void Neuron::init(int length, double epsilon) { std::uniform_real_distribution<double> unif(-epsilon, epsilon); std::random_device rand_dev; std::mt19937 rand_engine(rand_dev()); for(auto i = 0; i < length; ++i) _theta.push_back(unif(rand_engine)); _biase = unif(rand_engine); } Neuron& Neuron::operator=(const Neuron& o) { //Some parameters will change (to pointer). _input = o._input; _theta = o._theta; _biase = o._biase; _learningRate = o._learningRate; _output = o._output; } const double Neuron::getBiase() const { return _biase; } const std::vector<double>& Neuron::getThetas() const { return _theta; } std::ostream& operator<<(std::ostream & out, const Neuron& n) { out << '[' << n.getBiase() << ','; std::vector<double> thetas = n.getThetas(); for(auto t : thetas) out << t << ','; out << ']'; }
19.742268
66
0.643864
547978b2f97378047c7210e419cf5cedb7255741
1,531
cpp
C++
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
//===--- DarwinSDKInfo.cpp - SDK Information parser for darwin - ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/DarwinSDKInfo.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/JSON.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" using namespace clang::driver; using namespace clang; Expected<Optional<DarwinSDKInfo>> driver::parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath) { llvm::SmallString<256> Filepath = SDKRootPath; llvm::sys::path::append(Filepath, "SDKSettings.json"); llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File = VFS.getBufferForFile(Filepath); if (!File) { // If the file couldn't be read, assume it just doesn't exist. return None; } Expected<llvm::json::Value> Result = llvm::json::parse(File.get()->getBuffer()); if (!Result) return Result.takeError(); if (const auto *Obj = Result->getAsObject()) { auto VersionString = Obj->getString("Version"); if (VersionString) { VersionTuple Version; if (!Version.tryParse(*VersionString)) return DarwinSDKInfo(Version); } } return llvm::make_error<llvm::StringError>("invalid SDKSettings.json", llvm::inconvertibleErrorCode()); }
34.022222
80
0.63292
54802c98caf4d2337d84f7b53369a0cc6d201cb7
334
cpp
C++
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
5
2022-02-01T22:49:51.000Z
2022-03-03T10:18:36.000Z
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
1
2022-01-31T23:09:04.000Z
2022-01-31T23:09:04.000Z
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
null
null
null
// Copyright 2022 Mickael Daniel. All Rights Reserved. #include "XeluIconsDeveloperSettings.h" UXeluIconsDeveloperSettings::UXeluIconsDeveloperSettings() { IconsDataTable = FSoftObjectPath(TEXT("/XeluIcons/DT_Xelu_Icons.DT_Xelu_Icons")); } FName UXeluIconsDeveloperSettings::GetCategoryName() const { return FName("Plugins"); }
22.266667
82
0.805389
54873d2ce7769081b8be72c41d3903efc133f45d
155
cpp
C++
src/Zadanie20.cpp
radzbydzi/Podstawy-Programowania
c97e72fd2fc0ecf3a88b0095cc409802be009013
[ "Unlicense" ]
null
null
null
src/Zadanie20.cpp
radzbydzi/Podstawy-Programowania
c97e72fd2fc0ecf3a88b0095cc409802be009013
[ "Unlicense" ]
null
null
null
src/Zadanie20.cpp
radzbydzi/Podstawy-Programowania
c97e72fd2fc0ecf3a88b0095cc409802be009013
[ "Unlicense" ]
null
null
null
#include "Zadanie20.h" Zadanie20::Zadanie20() { } Zadanie20::~Zadanie20() { } void Zadanie20::run() { cout<<"Zadanie20"<<endl<<endl; pokazTresc(); }
9.117647
31
0.645161
54888c9318b3b338b8652db0a9750d917d1eef3b
297
hpp
C++
include/RegularExpressionMatching.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/RegularExpressionMatching.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/RegularExpressionMatching.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef REGULAR_EXPRESSION_MATCHING_HPP_ #define REGULAR_EXPRESSION_MATCHING_HPP_ #include <string> using namespace std; class RegularExpressionMatching { public: bool isMatch(string s, string p); private: bool isMatch(char _s, char _p); }; #endif // REGULAR_EXPRESSION_MATCHING_HPP_
17.470588
42
0.787879
5489c5139f0a48c5e723f63b2936a0cfd0342dfb
995
cpp
C++
workbench/src/event.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
5
2017-12-27T12:57:36.000Z
2021-10-02T03:21:40.000Z
workbench/src/event.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
9
2020-09-29T22:40:49.000Z
2020-10-17T20:05:05.000Z
workbench/src/event.cpp
MasterQ32/cg-workbench
3d6229b961192689e6dbd0a09ec4b61041ecb155
[ "MIT" ]
null
null
null
#include "event.hpp" #include <SDL.h> #include "sink.hpp" timestamp_t Event::system_time; Event::Event() : current(system_time - 10000), // 10 seconds ago... counter(0) { } void Event::Trigger() { this->triggered = true; this->current = system_time; this->counter += 1; } void Event::Reset() { this->counter = 0; } float Event::GetTimeSinceLastTrigger() const { return (system_time - this->current) / 1000.0; } void Event::NewFrame() { system_time = SDL_GetTicks(); } bool Event::Any(Sink * sink) { if(sink == nullptr) return false; assert(sink->GetType() == CgDataType::Event); for(int i = 0; i < sink->GetSourceCount(); i++) { if(sink->GetObject<CgDataType::Event>(i)) return true; } return false; } int Event::Count(Sink * sink) { if(sink == nullptr) return false; assert(sink->GetType() == CgDataType::Event); int cnt = 0; for(int i = 0; i < sink->GetSourceCount(); i++) { if(sink->GetObject<CgDataType::Event>(i)) ++cnt; } return cnt; }
15.307692
54
0.638191
548bc5e3181dfac55df4e56c841997aa1b26ed76
8,428
hpp
C++
source/list.hpp
saJonMR/programmiersprachen_aufgabenblatt_3
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
[ "MIT" ]
null
null
null
source/list.hpp
saJonMR/programmiersprachen_aufgabenblatt_3
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
[ "MIT" ]
null
null
null
source/list.hpp
saJonMR/programmiersprachen_aufgabenblatt_3
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
[ "MIT" ]
null
null
null
#ifndef BUW_LIST_HPP #define BUW_LIST_HPP #include <cassert> #include <cstddef> //ptrdiff_t #include <iterator> //std::bidirectional_iterator_tag #include <iostream> #include <initializer_list> template <typename T> class List; template <typename T> struct ListNode { T value = T{}; ListNode* prev = nullptr; ListNode* next = nullptr; }; //TODO: Implementierung der Methoden des Iterators // (nach Vorlesung STL-1 am 09. Juni) (Aufgabe 3.11) template <typename T> struct ListIterator { using Self = ListIterator<T>; using value_type = T; using pointer = T*; using reference = T&; using difference_type = ptrdiff_t; using iterator_category = std::bidirectional_iterator_tag; /* Returns Reference to Value of current Node */ T& operator*() const { if(nullptr == node) { throw "Iterator does not point to valid node"; } return node->value; } //call *it /* Returns pointer to Reference of current node */ T* operator->() const { if(nullptr == node) { throw "Iterator does not point to valid node"; } return &node->value; } //call it->method() or it->member /* PREINCREMENT, call: ++it, advances one element forward */ ListIterator<T>& operator++() { if(nullptr == node) { throw "Iterator does not point to valid node"; } node = node->next; return *this; } /* POSTINCREMENT (signature distinguishes the iterators), call: it++, advances one element forward*/ ListIterator<T> operator++(int) { if(nullptr == node) { throw "Iterator does not point to valid node"; } auto newit = *this; ++*this; return newit; } /* Compares Values of Both Nodes */ bool operator==(ListIterator<T> const& x) const { if(x.node == node) { return true; } return false; } // call it: == it /* Compares Values of Both Nodes */ bool operator!=(ListIterator<T> const& x) const { if(x.node != node) { return true; } return false; } // call it: != it /* Advances Iterator */ ListIterator<T> next() const { if (nullptr != node) { return ListIterator{node->next}; } else { return ListIterator{nullptr}; } } ListNode <T>* node = nullptr; }; template <typename T> class List { public: //friend declarations for testing the members template <typename TEST_TYPE> friend size_t get_size(List<TEST_TYPE> const& list_to_test); template <typename TEST_TYPE> friend ListNode<TEST_TYPE>* get_first_pointer(List<TEST_TYPE> const& list_to_test); template <typename TEST_TYPE> friend ListNode<TEST_TYPE>* get_last_pointer(List<TEST_TYPE> const& list_to_test); using value_type = T; using pointer = T*; using const_pointer = T const*; using reference = T&; using const_reference = T const&; using iterator = ListIterator<T>; /* Initializes the List with size_ = 0 and both the first and the last node pointing to null */ List()=default; //Copy Constructor (Deep Copy) /* Initializes a new empty List and copies (deep) the elements of the input List until it reaches the last node */ List(List<T> const& l) : size_{0}, first_{nullptr}, last_{nullptr } { ListNode<T> *node = l.first_; while(node != nullptr) { push_back(node->value); node = node->next; } } //TODO: Initializer-List Konstruktor (3.14 - Teil 1) /* ... */ // test and implement: List(std::initializer_list<T> ini_list) { //not implemented yet } /* Unifying Assignment Operator */ /* Makes Use of Swap function to Assign Pointers and Size */ List& operator=(List rhs) { swap(rhs); return *this; } //swap function that swaps the first_ and last_ pointers as well as size_ void swap(List& rhs) { std::swap(first_, rhs.first_); std::swap(last_, rhs.last_); std::swap(size_, rhs.size_); } /* ... */ // test and implement: bool operator==(List const& rhs) { bool status = false; if(size_ == rhs.size_) { status = true; ListNode<T> *nodelhs = first_; ListNode<T> *noderhs = rhs.first_; while(nodelhs != nullptr && status) { if(nodelhs->value == noderhs->value) { nodelhs = nodelhs->next; noderhs = noderhs->next; } else { status = false; } } } return status; } bool operator!=(List const& rhs) { if(*this == rhs) { return false; } else { return true; } } /* calls clear function */ ~List() { clear(); } //can not really be tested /* Returns iterator that points to first node */ ListIterator<T> begin() { auto begin = first_; return {begin}; } /* Returns iterator that points behind last node (nullptr) */ ListIterator<T> end() { auto end = nullptr; return {end}; } /* Calls pop_front until first_ = last_ and then pops the last element indivdually */ void clear() { while(size_ > 0) { pop_back(); } } /* ... */ //TODO: member function insert (Aufgabe 3.12) /* ... */ //TODO: member function insert (Aufgabe 3.13) /* Reverses List by changing the direction of the pointers, from front to back*/ //TODO: member function reverse (Aufgabe 3.7 - Teil 1) void reverse() { ListNode<T> *node = last_; last_ = first_; first_ = node; while(node != nullptr) { std::swap(node->next, node->prev); node = node->next; } } /* Insert Element at the front of the List */ void push_front(T const& element) { ListNode<T> *node = new ListNode<T>{element}; if (first_ == nullptr) { first_ = node; last_ = node; node->next = nullptr; node->prev = nullptr; } else { node->next = first_; first_->prev = node; first_ = node; } size_++; } /* Insert Element at the back of the List */ void push_back(T const& element) { ListNode<T> *node = new ListNode<T>{element}; if (first_ == nullptr) { first_ = node; last_ = node; node->next = nullptr; node->prev = nullptr; } else { last_->next = node; node->prev = last_; last_ = node; } size_++; } /* Checks if list has one or more than one item and adjusts pointers */ void pop_front() { if(empty()) { throw "List is empty"; } if(first_ == last_) { first_ = nullptr; last_ = nullptr; } else { ListNode<T> *newFirst = first_->next; first_->next = nullptr; delete first_; first_ = newFirst; first_->prev = nullptr; } size_--; } /* Checks if list has one or more than one item and adjusts pointers */ void pop_back() { if(empty()) { throw "List is empty"; } if(first_ == last_) { first_ = nullptr; last_ = nullptr; } else { ListNode<T> *newLast = last_->prev; last_->prev = nullptr; delete last_; last_ = newLast; last_->next = nullptr; } size_--; } /* returns value of first node */ T& front() { if(empty()) { throw "List is empty"; } return first_->value; } /* returns value of last node */ T& back() { if(empty()) { throw "List is empty"; } return last_->value; } /* Returns wether List is empty or not*/ bool empty() const { return size_ == 0; }; /* Size */ std::size_t size() const{ return size_; }; // list members private: std::size_t size_ = 0; ListNode<T>* first_ = nullptr; ListNode<T>* last_ = nullptr; }; /* Makes use of member function reverse - takes a List as input and returns a new one */ //TODO: Freie Funktion reverse //(Aufgabe 3.7 - Teil 2, benutzt Member-Funktion reverse) template<typename T> List<T> reverse(List<T> const& list) { List<T> newL = list; newL.reverse(); return newL; } /* ... */ //TODO: Freie Funktion operator+ (3.14 - Teil 2) #endif // # define BUW_LIST_HPP
24.218391
118
0.568818
548d738958b13f8c71e2e4d7c9fec12a2f52df80
316
cpp
C++
Source/HippoQOR/do_wrapper.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/HippoQOR/do_wrapper.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/HippoQOR/do_wrapper.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//do_wrapper.cpp #include "HippoQOR/do_wrapper.h" //-------------------------------------------------------------------------------- namespace nsUnitTesting { //-------------------------------------------------------------------------------- VirtualDestructable::~VirtualDestructable() { } }//nsUnitTesting
22.571429
83
0.35443
548e9d8103cba0d2c43a2530193557f5d737f284
8,134
cpp
C++
src/main/cpp/rocketmq/CredentialsProvider.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
null
null
null
src/main/cpp/rocketmq/CredentialsProvider.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
null
null
null
src/main/cpp/rocketmq/CredentialsProvider.cpp
lizhanhui/rocketmq-client-cpp
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
[ "Apache-2.0" ]
1
2021-09-16T06:31:07.000Z
2021-09-16T06:31:07.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "fmt/format.h" #include "ghc/filesystem.hpp" #include "google/protobuf/struct.pb.h" #include "google/protobuf/util/json_util.h" #include "spdlog/spdlog.h" #include "MixAll.h" #include "StsCredentialsProviderImpl.h" #include "rocketmq/Logger.h" ROCKETMQ_NAMESPACE_BEGIN StaticCredentialsProvider::StaticCredentialsProvider(std::string access_key, std::string access_secret) : access_key_(std::move(access_key)), access_secret_(std::move(access_secret)) { } Credentials StaticCredentialsProvider::getCredentials() { return Credentials(access_key_, access_secret_); } const char* EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_KEY = "ROCKETMQ_ACCESS_KEY"; const char* EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_SECRET = "ROCKETMQ_ACCESS_SECRET"; EnvironmentVariablesCredentialsProvider::EnvironmentVariablesCredentialsProvider() { char* key = getenv(ENVIRONMENT_ACCESS_KEY); if (key) { access_key_ = std::string(key); } char* secret = getenv(ENVIRONMENT_ACCESS_SECRET); if (secret) { access_secret_ = std::string(secret); } } Credentials EnvironmentVariablesCredentialsProvider::getCredentials() { return Credentials(access_key_, access_secret_); } const char* ConfigFileCredentialsProvider::CREDENTIAL_FILE_ = "rocketmq/credentials"; const char* ConfigFileCredentialsProvider::ACCESS_KEY_FIELD_NAME = "AccessKey"; const char* ConfigFileCredentialsProvider::ACCESS_SECRET_FIELD_NAME = "AccessSecret"; ConfigFileCredentialsProvider::ConfigFileCredentialsProvider() { std::string config_file; if (MixAll::homeDirectory(config_file)) { std::string path_separator(1, ghc::filesystem::path::preferred_separator); if (!absl::EndsWith(config_file, path_separator)) { config_file.append(1, ghc::filesystem::path::preferred_separator); } config_file.append(CREDENTIAL_FILE_); ghc::filesystem::path config_file_path(config_file); std::error_code ec; if (!ghc::filesystem::exists(config_file_path, ec) || ec) { SPDLOG_WARN("Config file[{}] does not exist.", config_file); return; } std::ifstream config_file_stream; config_file_stream.open(config_file.c_str(), std::ios::in | std::ios::ate | std::ios::binary); if (config_file_stream.good()) { auto size = config_file_stream.tellg(); std::string content(size, '\0'); config_file_stream.seekg(0); config_file_stream.read(&content[0], size); config_file_stream.close(); google::protobuf::Struct root; google::protobuf::util::Status status = google::protobuf::util::JsonStringToMessage(content, &root); if (status.ok()) { auto&& fields = root.fields(); if (fields.contains(ACCESS_KEY_FIELD_NAME)) { access_key_ = fields.at(ACCESS_KEY_FIELD_NAME).string_value(); } if (fields.contains(ACCESS_SECRET_FIELD_NAME)) { access_secret_ = fields.at(ACCESS_SECRET_FIELD_NAME).string_value(); } SPDLOG_DEBUG("Credentials for access_key={} loaded", access_key_); } else { SPDLOG_WARN("Failed to parse credential JSON config file. Message: {}", status.message().data()); } } else { SPDLOG_WARN("Failed to open file: {}", config_file); return; } } } ConfigFileCredentialsProvider::ConfigFileCredentialsProvider(std::string config_file, std::chrono::milliseconds refresh_interval) { } Credentials ConfigFileCredentialsProvider::getCredentials() { return Credentials(access_key_, access_secret_); } StsCredentialsProvider::StsCredentialsProvider(std::string ram_role_name) : impl_(absl::make_unique<StsCredentialsProviderImpl>(std::move(ram_role_name))) { } Credentials StsCredentialsProvider::getCredentials() { return impl_->getCredentials(); } StsCredentialsProviderImpl::StsCredentialsProviderImpl(std::string ram_role_name) : ram_role_name_(std::move(ram_role_name)) { } StsCredentialsProviderImpl::~StsCredentialsProviderImpl() { http_client_->shutdown(); } Credentials StsCredentialsProviderImpl::getCredentials() { if (std::chrono::system_clock::now() >= expiration_) { refresh(); } { absl::MutexLock lk(&mtx_); return Credentials(access_key_, access_secret_, session_token_, expiration_); } } void StsCredentialsProviderImpl::refresh() { std::string path = fmt::format("{}{}", RAM_ROLE_URL_PREFIX, ram_role_name_); absl::Mutex sync_mtx; absl::CondVar sync_cv; bool completed = false; auto callback = [&, this](int code, const std::multimap<std::string, std::string>& headers, const std::string& body) { SPDLOG_DEBUG("Received STS response. Code: {}", code); if (static_cast<int>(HttpStatus::OK) == code) { google::protobuf::Struct doc; google::protobuf::util::Status status = google::protobuf::util::JsonStringToMessage(body, &doc); if (status.ok()) { const auto& fields = doc.fields(); assert(fields.contains(FIELD_ACCESS_KEY)); std::string access_key = fields.at(FIELD_ACCESS_KEY).string_value(); assert(fields.contains(FIELD_ACCESS_SECRET)); std::string access_secret = fields.at(FIELD_ACCESS_SECRET).string_value(); assert(fields.contains(FIELD_SESSION_TOKEN)); std::string session_token = fields.at(FIELD_SESSION_TOKEN).string_value(); assert(fields.contains(FIELD_EXPIRATION)); std::string expiration_string = fields.at(FIELD_EXPIRATION).string_value(); absl::Time expiration_instant; std::string parse_error; if (absl::ParseTime(EXPIRATION_DATE_TIME_FORMAT, expiration_string, absl::UTCTimeZone(), &expiration_instant, &parse_error)) { absl::MutexLock lk(&mtx_); access_key_ = std::move(access_key); access_secret_ = std::move(access_secret); session_token_ = std::move(session_token); expiration_ = absl::ToChronoTime(expiration_instant); } else { SPDLOG_WARN("Failed to parse expiration time. Message: {}", parse_error); } } else { SPDLOG_WARN("Failed to parse STS response. Message: {}", status.message().as_string()); } } else { SPDLOG_WARN("STS response code is not OK. Code: {}", code); } { absl::MutexLock lk(&sync_mtx); completed = true; sync_cv.Signal(); } }; http_client_->get(HttpProtocol::HTTP, RAM_ROLE_HOST, 80, path, callback); while (!completed) { absl::MutexLock lk(&sync_mtx); sync_cv.Wait(&sync_mtx); } } const char* StsCredentialsProviderImpl::RAM_ROLE_HOST = "100.100.100.200"; const char* StsCredentialsProviderImpl::RAM_ROLE_URL_PREFIX = "/latest/meta-data/Ram/security-credentials/"; const char* StsCredentialsProviderImpl::FIELD_ACCESS_KEY = "AccessKeyId"; const char* StsCredentialsProviderImpl::FIELD_ACCESS_SECRET = "AccessKeySecret"; const char* StsCredentialsProviderImpl::FIELD_SESSION_TOKEN = "SecurityToken"; const char* StsCredentialsProviderImpl::FIELD_EXPIRATION = "Expiration"; const char* StsCredentialsProviderImpl::EXPIRATION_DATE_TIME_FORMAT = "%Y-%m-%d%ET%H:%H:%S%Ez"; ROCKETMQ_NAMESPACE_END
38.733333
120
0.717482
54908d60e1fa2dd3d5ae4d32336bf6d1e354b105
2,911
cpp
C++
samples/client/enumeration/Client.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
1
2021-11-10T19:36:30.000Z
2021-11-10T19:36:30.000Z
samples/client/enumeration/Client.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
null
null
null
samples/client/enumeration/Client.cpp
vlsinitsyn/axis1
65a622201e526dedf7c3aeadce7cac5bd79895bf
[ "Apache-2.0" ]
2
2021-11-02T13:09:57.000Z
2021-11-10T19:36:22.000Z
#include "EnumerationWS.hpp" #include <stdlib.h> // For malloc(), calloc(), strdup() and free() #include <iostream> #define WSDL_DEFAULT_ENDPOINT "http://localhost:80/axis/enumeration" static void usage( char * programName, char * defaultURL) { cout << "Usage:" << endl << programName << " [-? | service_url] " << endl << " -? Show this help." << endl << " service_url URL of the service." << endl << " Default service URL is assumed to be " << defaultURL << endl; } int main( int argc, char * argv[]) { EnumerationWS * ws; char endpoint[256]; int returnValue = 1; // Assume Failure Type1 * input = NULL; Type1 * result = NULL; bool bSuccess = false; int iRetryIterationCount = 3; sprintf( endpoint, "%s", WSDL_DEFAULT_ENDPOINT); if( argc > 1) { // Watch for special case help request // Check for - only so that it works for //-?, -h or --help; -anything if( !strncmp( argv[1], "-", 1)) { usage( argv[0], endpoint); return 2; } sprintf( endpoint, argv[1]); } do { try { ws = new EnumerationWS( endpoint, APTHTTP1_1); input = new Type1(); xsd__int iEnumInt = ENUMTYPEINT_0; input->setatt_enum_string( "one"); input->setenum_string( "one"); input->setenum_int( &iEnumInt); input->setatt_enum_int( ENUMTYPEINT_1); input->setatt_enum_kind( "CHEQUE"); ws->setTransportProperty( "SOAPAction", "enumeration#getInput"); result = ws->getInput( input); cout << "Result" << endl; if( result == NULL) { cout << " result = NULL" << endl; } else { cout << "att_enum_int " << result->getatt_enum_int() << endl; cout << "att_enum_string " << result->getatt_enum_string() << endl; cout << "enum_int " << result->getenum_int() << endl; cout << "enum_string " << result->getenum_string() << endl; cout << "enum_kind " << result->getatt_enum_kind() << endl; returnValue = 0; // Success } bSuccess = true; } catch( AxisException & e) { bool bSilent = false; if( e.getExceptionCode () == CLIENT_TRANSPORT_OPEN_CONNECTION_FAILED) { if( iRetryIterationCount > 1) { bSilent = true; } } else { iRetryIterationCount = 0; } if( !bSilent) { cerr << e.what () << endl; } } catch( ...) { cerr << "Unknown Exception occured." << endl; } try { delete ws; delete input; delete result; } catch( exception & exception) { cout << "Exception when cleaning up: " << exception.what() << endl; } catch( ...) { cout << "Unknown exception when cleaning up: " << endl; } iRetryIterationCount--; } while( iRetryIterationCount > 0 && !bSuccess); cout << "---------------------- TEST COMPLETE -----------------------------" << endl; cout << "successful" << endl; return returnValue; }
21.723881
89
0.571968
5496e5f2c2d9d4d1c0f06af597e04c1a5be7b8db
30,774
hpp
C++
include/misc.hpp
harith-alsafi/statistic-model-cpp
0883f208ff6dcdc6634b95e88b92e9097bd76475
[ "Condor-1.1", "Naumen", "Xnet", "X11", "MS-PL" ]
null
null
null
include/misc.hpp
harith-alsafi/statistic-model-cpp
0883f208ff6dcdc6634b95e88b92e9097bd76475
[ "Condor-1.1", "Naumen", "Xnet", "X11", "MS-PL" ]
null
null
null
include/misc.hpp
harith-alsafi/statistic-model-cpp
0883f208ff6dcdc6634b95e88b92e9097bd76475
[ "Condor-1.1", "Naumen", "Xnet", "X11", "MS-PL" ]
null
null
null
#pragma once #include <vector> #include <string> #include <iostream> #include <fstream> /** * @file misc.hpp * @author Harith Al-Safi * @brief * @version 0.1 * @date 2021-12-10 * * @copyright Copyright (c) 2021 * */ #include <algorithm> #include <numeric> #include "graphs.hpp" /** * @brief Operator to multiply two vectors * * @tparam TYPE * @param first * @param second * @return std::vector<TYPE> */ template<typename TYPE> std::vector<TYPE> operator *(std::vector<TYPE> first, std::vector<TYPE> second){ if(first.size() != second.size()){ throw std::invalid_argument("Invalid size"); } std::vector<TYPE> temp; for(int i = 0; i < first.size(); i++){ temp.push_back(first[i]*second[i]); } return temp; } /** * @brief Overloads the round function * * @tparam TYPE * @param a the value itself * @param dp number of decimal places * @return TYPE */ template<typename TYPE> TYPE round(TYPE a, int dp = 0){ if(a < TYPE(0)){ return TYPE((int)(a*pow(10, dp)-.5)/pow(10, dp)); } return TYPE((int)(a*pow(10, dp)+.5)/pow(10, dp)); } namespace misc { /** * @brief Genarate vector from min, max andn number of points * * @tparam TYPE * @param mn min val * @param mx max val * @param n number of points * @return std::vector<TYPE> */ template<typename TYPE> std::vector<TYPE> generate_vector(TYPE mn, TYPE mx, int n){ std::vector<TYPE> v; for(TYPE i = mn; i <= mx; i+=(TYPE)(mx-mn)/n){ v.push_back(i); } return v; } /** * @brief Table class to contain the dataframe */ class Table: public std::vector<std::vector<long double>> { public: /** * @brief Struct to contain the quartile range * */ struct QR { /** * @brief Lower quartile * */ long double LQ; /** * @brief Q1 (25%) * */ long double Q1; /** * @brief Q2 (50%) * */ long double Q2; /** * @brief Q3 (75%) * */ long double Q3; /** * @brief Upper quartile * */ long double UQ; }; private: /** * @brief Checks the header and returns index * * @param head * @return int */ int check_header(std::string head){ for(int i = 0; i < headers.size(); i++){ if(headers[i] == head){ return i; } } return -1; } /** * @brief Get the col vector based on header name * * @param headname * @return std::vector<long double> */ std::vector<long double> get_col_(std::string headname){ int j = check_header(headname); std::vector<long double> a; if(j >= 0){ for(int i = 0; i < size(); i++){ a.push_back(at(i).at(j)); } } return a; } /** * @brief Get the return average of all colums in vector * * Used in describe_all() * * @return std::vector<long double> */ std::vector<long double> get_avgs(){ std::vector<long double> a; for(int j = 0; j < headers.size(); j++){ a.push_back(get_avg(get_col_(headers[j]))); } return a; } /** * @brief Get the return std of all colums in vector * * Used in describe_all() * * @return std::vector<long double> */ std::vector<long double> get_stds(){ std::vector<long double> a; for(int j = 0; j < headers.size(); j++){ a.push_back(get_std(get_col_(headers[j]))); } return a; } /** * @brief Get the return variance of all colums in vector * * Used in describe_all() * * @return std::vector<long double> */ std::vector<long double> get_vars(){ std::vector<long double> a; for(int j = 0; j < headers.size(); j++){ a.push_back(get_var(get_col_(headers[j]))); } return a; } /** * @brief Get the return quartile range of all colums in vector * * Used in describe_all() * * @return std::vector<long double> */ std::vector<QR> get_qrs(){ std::vector<QR> a; for(int j = 0; j < headers.size(); j++){ a.push_back(get_qr(get_col_(headers[j]))); } return a; } /** * @brief Get the return sums of all colums in vector * * Used in describe_all() * * @return std::vector<long double> */ std::vector<long double> get_sums(){ std::vector<long double> a; for(int j = 0; j < headers.size(); j++){ a.push_back(get_sum(get_col_(headers[j]))); } return a; } /** * @brief Re-centers a string based on given width * * @param s * @param w * @return std::string */ static std::string center(const string s, const int w) { std::stringstream ss, spaces; int padding = w - s.size(); // count excess room to pad for(int i=0; i<padding/2; ++i) spaces << " "; ss << spaces.str() << s << spaces.str(); // format with padding if(padding>0 && padding%2!=0) // if odd #, add 1 space ss << " "; return ss.str(); } /** * @brief converts double to a string with white space * * @param x * @param width * @return std::string */ static std::string prd(long double x, int width) { std::stringstream ss; ss << std::fixed << std::left; ss.fill(' '); // fill space around displayed # ss.width(width); // set width around displayed # ss.precision(2); // set # places after decimal ss << x; return center(ss.str(), width); } /** * @brief Gives spacing to a string * * @param x * @param width * @return std::string */ static std::string prd(std::string x, int width) { std::stringstream ss; ss << std::left; ss.fill(' '); // fill space around displayed # ss.width(width); // set width around displayed # ss << x; return center(ss.str(), width); } /** * @brief Generates row names * */ void generate_rows(){ rows.clear(); for(int i = 0; i < size(); i++){ rows.push_back("Row-"+std::to_string(i)); } } /** * @brief Checks size of current class * */ void check_size(){ if(empty()){ row = 0; col = 0; return; } col = at(0).size(); row = size(); } /** * @brief Generates line to seperate rows * * @param l * @return std::string */ std::string generate_line(int l){ std::string line; for(int i = 0; i < l; i++){ line+="―"; } return line; } /** * @brief Stores the headers * */ std::vector<std::string> headers; /** * @brief Stores the row names * */ std::vector<std::string> rows; /** * @brief Row size * */ int row; /** * @brief Colum size * */ int col; /** * @brief Spacing size for print * */ int sz = 10; public: /** * @brief Construct a new Table object * */ Table(){} /** * @brief Destroy the Table object * */ ~Table(){} /** * @brief Reads from csv file * * @param file * @return true: if read is success * @return false: if read did not complete */ bool read_csv(std::string filename){ ifstream file(filename); if(file.is_open()){ clear(); headers.clear(); // col name string line, colname; getline(file, line); stringstream ss(line); while(getline(ss, colname, ',')){ headers.push_back(colname); } // data long double val; while(std::getline(file, line)) { // Create a stringstream of the current line std::stringstream ss(line); std::vector<long double> r; while(ss >> val){ r.push_back(val); // If the next token is a comma, ignore it and move on if(ss.peek() == ',') ss.ignore(); } push_back(r); } check_size(); file.close(); return true; } file.close(); return false; } /** * @brief Reads from csv file * * @param file * @return true: if read is success * @return false: if read did not complete */ bool save_csv(std::string filename) { ofstream file(filename); if(file.is_open()){ for(int i = 0; i < headers.size(); i++){ if(i != headers.size()-1){ file << headers[i] << ","; } else{ file << headers[i] << "\n"; } } check_size(); for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(j != col-1){ file << at(i).at(j) << ","; } else if (j == col-1){ file << at(i).at(j) << "\n"; } } } file.close(); return true; } file.close(); return false; } /** * @brief Get the row size object * * @return int */ int get_row_size(){ return size(); } /** * @brief Get the col size object * * @return int */ int get_col_size(){ return at(0).size(); } /** * @brief Returns colum of certain header * * @param headname * @return std::vector<TYPE>& */ std::vector<long double> operator[](std::string headname){ return get_col_(headname); } /** * @brief Sorts data ascending * * @param a * @return std::vector<long double> */ static std::vector<long double> sort_asc(std::vector<long double> & a){ std::vector<long double> v_sorted(a.size()); std::partial_sort_copy(a.begin(), a.end(), v_sorted.begin(), v_sorted.end()); return v_sorted; } /** * @brief Get the min value of vector * * @param a * @return long double */ static long double get_min(std::vector<long double> a){ return *std::min_element(a.begin(), a.end()); } /** * @brief Get the max value of vector * * @param a * @return long double */ static long double get_max(std::vector<long double> a){ return *std::max_element(a.begin(), a.end()); } /** * @brief Get the sum of vector * * @param a * @return long double */ static long double get_sum(std::vector<long double> a){ return std::accumulate(a.begin(), a.end(), 0); } /** * @brief Get the avg of vector * * @param a * @return long double */ static long double get_avg(std::vector<long double> a){ return get_sum(a)/a.size(); } /** * @brief Get the variance of vector * * @param a * @return long double */ static long double get_var(std::vector<long double> a){ long double mean = get_avg(a); int N = a.size(); long double sum = 0; for(int i = 0; i < N; i++){ sum+=pow((a[i]-mean), 2); } return (long double) sum/N; } /** * @brief Get the standard diviation of vector * * @param a * @return long double */ static long double get_std(std::vector<long double> a){ return sqrt(get_var(a)); } /** * @brief Get the quartile range of a vector * * @param a * @return QR */ static QR get_qr(std::vector<long double> a){ QR qr; qr.LQ = get_min(a); qr.UQ = get_max(a); auto a_sorted = sort_asc(a); qr.Q1 = a_sorted.at((int) (a_sorted.size())/4); qr.Q2 = a_sorted.at((int) (a_sorted.size())/2); qr.Q3 = a_sorted.at((int) (3*(a_sorted.size()))/4); return qr; } /** * @brief Get the relation coefficient of two vectors * * @param _x * @param _y * @return long double */ static long double get_r( std::vector<long double> _x, std::vector<long double> _y){ if(_x.size() != _y.size()){ throw std::invalid_argument("misc::Table::get_r -> Size mismatch"); } long double sumx = misc::Table::get_sum(_x); long double sumy = misc::Table::get_sum(_y); long double sumxx = misc::Table::get_sum(_x*_x); long double sumxy = misc::Table::get_sum(_x*_y); long double sumyy = misc::Table::get_sum(_y*_y); return (_x.size()*sumxy-(sumx*sumy))/ (sqrt((_x.size()*sumxx-pow(sumx, 2))*(_x.size()*sumyy-pow(sumy, 2)))); } /** * @brief Shows a certain number of rows in table * * @param r */ void show(int r){ if(rows.empty()){ generate_rows(); } check_size(); std::string line; if(col == 1){ line = generate_line((std::pow(2, 1/col)+0.2)*sz*col); } else{ line = generate_line((std::pow(1.05, 1/col)+1.9/col)*sz*col); } for(int i = -1; i < r; i++){ for(int j = 0; j < col; j++){ // to print header if(i == -1){ if (j == 0 && col > 1){ std::cout << prd(" ", sz) << "│" << prd(headers[j], sz) << "│"; } else if(j == 0 && col == 1){ std::cout << prd(" ", sz) << "│" << prd(headers[j], sz) << "\n"; std::cout << line << "\n"; } else if(j != col-1){ std::cout << prd(headers[j], sz) << "│"; } else{ std::cout << prd(headers[j], sz) << "\n"; std::cout << line << "\n"; } } // printing values else{ // row name + val if(j == 0 && col > 1){ std::cout << prd(rows[i], sz) << "│" << prd(get_col_(headers[j]).at(i), sz) << "│"; } else if(j == 0 && col == 1){ std::cout << prd(rows[i], sz) << "│" << prd(get_col_(headers[j]).at(i), sz) << "│" << "\n"; std::cout << line << "\n"; } else if(j != col-1){ std::cout << prd(get_col_(headers[j]).at(i), sz) << "│"; } else{ std::cout << prd(get_col_(headers[j]).at(i), sz) << "\n"; std::cout << line << "\n"; } } } } } /** * @brief shows all of the table * */ void show(){ check_size(); show(row); } /** * @brief Statistical summary of all colums in table * * @return Table */ Table describe_all(){ Table t; auto avg = get_avgs(); auto std = get_stds(); auto var = get_vars(); auto qrs = get_qrs(); auto sms = get_sums(); check_size(); // loading row names for(int i = 0; i < col; i++){ t.rows.push_back(headers[i]); } // loading col names t.headers.push_back("Mean"); t.headers.push_back("STD"); t.headers.push_back("VAR"); t.headers.push_back("Min"); t.headers.push_back("Q1"); t.headers.push_back("Q2"); t.headers.push_back("Q3"); t.headers.push_back("Max"); t.headers.push_back("IQR"); t.headers.push_back("Sum"); // loading values t.row = t.rows.size(); t.col = t.headers.size(); for(int i = 0; i < t.row; i++){ std::vector<long double> rr; rr.push_back(avg[i]); rr.push_back(std[i]); rr.push_back(var[i]); rr.push_back(qrs[i].LQ); rr.push_back(qrs[i].Q1); rr.push_back(qrs[i].Q2); rr.push_back(qrs[i].Q3); rr.push_back(qrs[i].UQ); rr.push_back(qrs[i].Q3-qrs[i].Q1); rr.push_back(sms[i]); t.push_back(rr); } t.check_size(); t.sz = 11; return t; } /** * @brief Get the row as table * * @param r * @return Table */ Table get_row(int r){ Table t; t.push_back(at(r)); t.headers = headers; if(rows.empty()){ generate_rows(); } t.rows.push_back(rows[r]); return t; } /** * @brief Get the col as table * * @param name * @return Table */ Table get_col(std::string name){ Table t; auto a = get_col_(name); for(int i = 0; i < a.size(); i++){ t.push_back({a[i]}); } if(rows.empty()){ generate_rows(); } t.headers.push_back(headers[check_header(name)]); return t; } /** * @brief Adds new colum * * @param col_name * @param col_data * @return true * @return false */ bool add_col(std::string col_name, std::vector<long double> col_data){ check_size(); if((col_data.size() != row && row != 0) || col_data.empty()){ return false; } headers.push_back(col_name); for(int i = 0; i < col_data.size(); i++){ if(row == 0){ push_back({col_data[i]}); } else{ at(i).push_back(col_data[i]); } } return true; } /** * @brief Shows headers only * */ void show_header(){ show(0); } }; /** * @brief Encapsulates graph.hpp (https://github.com/tdulcet/Tables-and-Graphs) * */ class Plot { public: /** * @brief Colors for plots * */ enum Color { red = 10, green = 11, yellow = 12, purple = 14, blue = 15, white = 16 }; private: /** * @brief Height of terminal plot * */ size_t height; /** * @brief Width of terminal plot * */ size_t width; /** * @brief Minimum x-value * */ long double xmin; /** * @brief Maxmimum x-value * */ long double xmax; /** * @brief Minimum y-value * */ long double ymin; /** * @brief Maximum y-value * */ long double ymax; /** * @brief Size for cols which is 2 * */ const size_t cols = 2; /** * @brief Used to store domain vector * */ std::vector<long double> domain; /** * @brief Stores graphing options * */ graphoptions aoptions; /** * @brief Stores color * */ Color c; /** * @brief Stores title * */ std::string title; public: /** * @brief Construct a new Plot object * * @param h height * @param w width * @param xmn min x * @param xmx max x * @param ymn min y * @param ymx max y */ Plot(int h = 145, int w = 145, long double xmn = -10, long double xmx = 10, long double ymn = -10, long double ymx = 10): height(h), width(w), xmin(xmn), xmax(xmx), ymin(ymn), ymax(ymx){} /** * @brief Set the Domain * * @param xmn * @param xmx */ void set_domain(long double xmn = -10, long double xmx = 10){ xmin = xmn; xmax = xmx; } /** * @brief Set the Range * * @param ymn * @param ymx */ void set_range(long double ymn = -10, long double ymx = 10){ ymin = ymn; ymax = ymx; } /** * @brief Set the Size of figure * * @param h * @param w */ void set_size(int h = 140, int w = 140){ height = h; width = w; } /** * @brief Set the color * * @param cc */ void set_color(Color cc = Color::blue){ c = cc; } /** * @brief Set the title * * @param tt */ void set_title(std::string tt){ title = tt; } /** * @brief Generates domain * * @param n */ void generate_domain(int n = 50){ generate_domain(xmin, xmax, n); } /** * @brief Generates domain to plot function * * @param xmn * @param xmx * @param n number of points */ void generate_domain(long double xmn, long double xmx, int n){ domain = generate_vector(xmn, xmx, n); } /** * @brief Plots vectors * * @param x vector for x * @param y vector for y */ void plot_vect(std::vector<long double> &x, std::vector<long double> &y) { if(x.size() != y.size()){ std::cerr << x.size() << "\t" << y.size() << "\n"; std::cerr << "misc::Plot::plot_vect-> Size mismatch \n"; return; } long double **array; array = new long double *[x.size()]; for (unsigned int i = 0; i < x.size(); ++i){ array[i] = new long double[cols]; } for (unsigned int i = 0; i < x.size(); ++i){ for (unsigned int j = 0; j < cols; ++j){ // x if (j == 0){ array[i][j] = x[i]; } // y else{ array[i][j] = y[i]; } } } aoptions.color = c; std::cout << colors[c] << title << "\n" << colors[Color::white]; graph(height, width, xmin, xmax, ymin, ymax, x.size(), array, aoptions); if(array != NULL){ for (unsigned int i = 0; i < x.size(); ++i){ delete[] array[i]; } delete[] array; } } /** * @brief Plots function * * @tparam LAMBDA * @param fun lambda function */ template<typename LAMBDA> void plot_fun(LAMBDA fun) { std::vector<long double> y; for(int i = 0; i < domain.size(); i++){ y.push_back(fun(domain[i])); } plot_vect(domain, y); } }; }
30.052734
96
0.34136
549a4413d99a4670838f6d27035dc1c820d069e9
3,305
cpp
C++
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
null
null
null
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
null
null
null
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
GBCNewGamePlus/Physics
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
[ "MIT" ]
null
null
null
#include "SphereContactGeneratorSystem.h" #include "ParticleContactComponent.h" namespace Reality { SphereContactGeneratorSystem::SphereContactGeneratorSystem() { requireComponent<SphereComponent>(); requireComponent<ParticleComponent>(); requireComponent<TransformComponent>(); } void SphereContactGeneratorSystem::Update(float deltaTime) { if (!dummyCreated) { dummy = getWorld().createEntity(); dummyCreated = true; } auto entities = getEntities(); for (int i = 0; i < entities.size(); i++) { auto& transform1 = entities[i].getComponent<TransformComponent>(); auto& sphere1 = entities[i].getComponent<SphereComponent>(); auto& particle1 = entities[i].getComponent<ParticleComponent>(); bool collided = false; // Check collisions with other spheres if (entities.size() > 1) { if (i < entities.size() - 1) { for (int j = i + 1; j < entities.size(); j++) { auto& transform2 = entities[j].getComponent<TransformComponent>(); auto& sphere2 = entities[j].getComponent<SphereComponent>(); auto& particle2 = entities[j].getComponent<ParticleComponent>(); if (glm::length(transform1.position - transform2.position) < sphere1.radius + sphere2.radius) { float penetration = sphere1.radius + sphere2.radius - glm::length(transform1.position - transform2.position); ECSEntity e = getWorld().createEntity(); Vector3 normal = glm::normalize(transform1.position - transform2.position); //getWorld().data.renderUtil->DrawLine(transform1.position - sphere1.radius * normal, // transform1.position - sphere1.radius * normal + penetration * normal, Color(0, 0, 1)); e.addComponent<ParticleContactComponent>(entities[i], entities[j], 1.0f, normal, penetration); collided = true; } } } } // Check collision with Hardcoded walls if (abs(transform1.position.x) >= 14) { float penetration = abs(transform1.position.x) - 14; ECSEntity e = getWorld().createEntity(); Vector3 normal = (transform1.position.x > 0 ? -1.0f : 1.0f) * Vector3(1, 0, 0); e.addComponent<ParticleContactComponent>(entities[i], dummy, 1.0f, normal, penetration); collided = true; } if (abs(transform1.position.y - 20) >= 14) { float penetration = abs(transform1.position.y - 20) - 14; ECSEntity e = getWorld().createEntity(); Vector3 normal = ((transform1.position.y - 20) > 0 ? -1.0f : 1.0f) * Vector3(0, 1, 0); e.addComponent<ParticleContactComponent>(entities[i], dummy, 1.0f, normal, penetration); collided = true; } if (abs(transform1.position.z) >= 14) { float penetration = abs(transform1.position.z) - 14; ECSEntity e = getWorld().createEntity(); Vector3 normal = (transform1.position.z > 0 ? -1.0f : 1.0f) * Vector3(0, 0, 1); e.addComponent<ParticleContactComponent>(entities[i], dummy, 1.0f, normal, penetration); collided = true; } Color col = collided ? Color(1, 0, 0, 1) : Color(0, 1, 0, 1); //getWorld().data.renderUtil->DrawSphere(transform1.position, sphere1.radius, col); } //getWorld().data.renderUtil->DrawCube(Vector3(0, 20, 0), Vector3(30, 30, 30)); } }
31.778846
96
0.646596
549e0a60308d6fc7cd2622cc282f2236689aee00
2,950
cc
C++
DAPPLES.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
DAPPLES.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
DAPPLES.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++14 (gcc 8.3) #include <cmath> #include <iostream> #include <limits> #include <vector> constexpr int kG{1'000}; long long CalculateTreeHeight(long long height, int max_velocity) { return static_cast<long long>(std::pow(max_velocity, 2)) / (2 * kG) + height; } class Resident { public: Resident(int height, int age, int growth_quotient) : height_{height}, age_{age}, growth_quotient_{growth_quotient} {} long long GetTreeHeight(int year, int max_velocity) const { return CalculateTreeHeight(GetHeight(year), max_velocity); } private: int height_; int age_; int growth_quotient_; long long GetHeight(int year) const { if (age_ < 20) { const int growth_years{std::min(year, 20 - age_)}; return static_cast<long long>(height_) + growth_years * static_cast<long long>(growth_quotient_); } else { return height_; } } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; while (--t >= 0) { int max_velocity, n; std::cin >> max_velocity >> n; max_velocity *= 100; std::vector<Resident> residents; residents.reserve(n); long long const_min_tree_height{std::numeric_limits<long long>::max()}; long long min_tree_height{std::numeric_limits<long long>::max()}; while (--n >= 0) { int height, age, growth_quotient; std::cin >> height >> age >> growth_quotient; if (age >= 20) { const long long tree_height{CalculateTreeHeight(height, max_velocity)}; if (tree_height < const_min_tree_height) { const_min_tree_height = tree_height; if (const_min_tree_height < min_tree_height) { min_tree_height = const_min_tree_height; } } } else { const Resident new_resident(height, age, growth_quotient); residents.push_back(new_resident); const long long tree_height{ new_resident.GetTreeHeight(0, max_velocity)}; if (tree_height < min_tree_height) { min_tree_height = tree_height; } } } std::cout << "0: " << min_tree_height << "\n"; bool const_heights{false}; for (int year{1}; year <= 20; ++year) { if (!const_heights) { min_tree_height = const_min_tree_height; for (const Resident& resident : residents) { const long long tree_height{ resident.GetTreeHeight(year, max_velocity)}; if (tree_height < min_tree_height) { min_tree_height = tree_height; } } if (min_tree_height == const_min_tree_height) { const_heights = true; } std::cout << year << ": " << min_tree_height << "\n"; } else { std::cout << year << ": " << const_min_tree_height << "\n"; } } } return 0; }
28.365385
80
0.591525
54a0b6e2a9f9e376b72d0ade5bee4b71640c8e76
3,711
cpp
C++
Src/Eni/Gpio/STM32/Gpio.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
Src/Eni/Gpio/STM32/Gpio.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
Src/Eni/Gpio/STM32/Gpio.cpp
vlad230596/Eni
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
[ "MIT" ]
null
null
null
#include "EniConfig.h" #if defined(ENI_GPIO) && defined(ENI_STM) #include "../Gpio.h" #include "GpioPin.h" #if !IS_ENI_GPIO_SUPPORTED #if defined(ENI_HAL_INCLUDE_FILE) #include ENI_HAL_INCLUDE_FILE #else #error "HAL include file missing declaration" #endif #endif namespace Eni { void Gpio::applyConfig(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED *(pin.getConfigRegister()) = static_cast<uint32_t>(pin.init.value) << ((pin.pin % (GpioPin::countPinInConfigRegister)) << 2); #else HAL_GPIO_Init(pin.port, &pin.init); #endif } void Gpio::initInput(const GpioPin& pin, InputMode inputMode) { #if IS_ENI_GPIO_SUPPORTED pin.init.mode.mode = 0; switch(inputMode) { case InputMode::Analog: pin.init.mode.cnf1 = 0; pin.init.mode.cnf0 = 0; break; case InputMode::Floating: pin.init.mode.cnf1 = 0; pin.init.mode.cnf0 = 1; break; case InputMode::PullDown: pin.init.mode.cnf1 = 1; pin.init.mode.cnf0 = 0; pin.port->ODR &= ~pin.mask; break; case InputMode::PullUp: pin.init.mode.cnf1 = 1; pin.init.mode.cnf0 = 0; pin.port->ODR |= pin.mask; break; } #else pin.init.Mode = GPIO_MODE_INPUT; switch(inputMode) { case InputMode::Analog: pin.init.Mode = GPIO_MODE_ANALOG; pin.init.Pull = GPIO_NOPULL; break; case InputMode::Floating: pin.init.Pull = GPIO_NOPULL; break; case InputMode::PullUp: pin.init.Pull = GPIO_PULLUP; break; case InputMode::PullDown: pin.init.Pull = GPIO_PULLDOWN; break; } #endif applyConfig(pin); } void Gpio::initOutput(const GpioPin& pin, OutputMode mode, bool isAlternateFunction, PinSpeed speed) { #if IS_ENI_GPIO_SUPPORTED pin.init.mode.mode = static_cast<uint8_t>(speed); pin.init.mode.cnf1 = isAlternateFunction; switch(mode) { case OutputMode::PushPull: pin.init.mode.cnf0 = 0; break; case OutputMode::OpenDrain: pin.init.mode.cnf0 = 1; break; } #else switch(mode) { case OutputMode::OpenDrain: if(isAlternateFunction) { pin.init.Mode = GPIO_MODE_AF_OD; } else { pin.init.Mode = GPIO_MODE_OUTPUT_OD; } break; case OutputMode::PushPull: if(isAlternateFunction) { pin.init.Mode = GPIO_MODE_AF_PP; } else { pin.init.Mode = GPIO_MODE_OUTPUT_PP; } break; } #endif applyConfig(pin); } void Gpio::disconnect(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED initInput(pin, InputMode::Floating); #else HAL_GPIO_DeInit(pin.port, pin.pin); #endif } void Gpio::set(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED pin.port->BSRR = pin.mask; #else HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_SET); #endif } void Gpio::reset(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED pin.port->BSRR = static_cast<uint32_t>(pin.mask) << 16U; #else HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_RESET); #endif } void Gpio::toggle(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED pin.port->ODR ^= pin.mask; #else HAL_GPIO_TogglePin(pin.port, pin.mask); #endif } bool Gpio::read(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED return (pin.port->IDR & pin.mask) != 0; #else return HAL_GPIO_ReadPin(pin.port, pin.mask) == GPIO_PIN_SET; #endif } bool Gpio::lock(const GpioPin& pin) { #if IS_ENI_GPIO_SUPPORTED /*LOCK key writing sequence: Write 1 Write 0 Write 1 Read 0 Read 1 (this read is optional but confirms that the lock is active) Note: During the LOCK Key Writing sequence, the value of LCK[15:0] must not change */ pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask; pin.port->LCKR = pin.mask; pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask; auto dummy = pin.port->LCKR; static_cast<void>(dummy); return (pin.port->LCKR & GPIO_LCKR_LCKK) != 0; #else return HAL_GPIO_LockPin(pin.port, pin.pin) == HAL_OK; #endif } } #endif
21.327586
126
0.70574
54a1285f6999c571c5406de8597e25057d1389cb
2,537
hpp
C++
cpp/archive/archive-good-stuff/db.hpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
2
2020-03-11T03:53:19.000Z
2020-10-06T03:18:32.000Z
cpp/archive/archive-good-stuff/db.hpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
null
null
null
cpp/archive/archive-good-stuff/db.hpp
MomsFriendlyRobotCompany/gecko
f340381113bdb423a39d47aaee61e013bb9e002a
[ "MIT" ]
null
null
null
/**************************************************\ * The MIT License (MIT) * Copyright (c) 2014 Kevin Walchko * see LICENSE for full details \**************************************************/ #pragma once #include <string> #include <map> #include <tuple> #include <exception> #include <gecko/exceptions.hpp> struct InvalidKey : public std::exception { InvalidKey(const std::string &s): msg("Invalid Key: " + s) {} InvalidKey(): msg("Invalid Key") {} const char * what () const throw () {return msg.c_str();} protected: std::string msg; }; using record_t = std::tuple<std::string, std::string>; // pid endpt /* This is the data base for keeping track of things ... it is simple. Data is tracked 2 ways: - binders (topic, (pid, endpt)) are unique and tracked by topic. Only one process can bind to a topic name - connectors (pid, (topic, endpt)) are tracked by pid because there can be a many to one relationship between processes and topics. */ class DBv { public: DBv(){} std::string get(const std::string& topic); void pushbind(const std::string& topic, const std::string& pid, const std::string& endpt); void pushconn(const std::string& topic, const std::string& pid, const std::string& endpt); // int size(){ return db.size(); } void print(); void saveJson(const std::string& filename){throw NotImplemented("DBv::save()");} // value? protected: void pop(std::map<std::string, record_t>& db, const std::string& key); void printDB(int type, std::map<std::string, record_t>& db); std::map<std::string, record_t> bind, conn; }; // class DB { // public: // DB(){} // std::tuple<std::string, std::string> get(const std::string& topic); // void push(const std::string& topic, const std::string& addr, const std::string& pid); // void pop(const std::string& topic); // int size(){ return db.size(); } // void print(); // // // protected: // // [topic, (addr, pid)] // std::map<std::string, std::tuple<std::string, std::string>> db; // }; // class DBs { // public: // DBs(){} // std::string get(const std::string& key); // void push(const std::string& key, const std::string& val); // void pop(const std::string& key); // int size(){ return db.size(); } // void print(); // void printPs(); // // // protected: // // [topic, (addr, pid)] // std::map<std::string, std::string> db; // }; // struct record { // record() {} // std::string pid, topic, endpt; // int type; // };
29.5
94
0.590067