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
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
75badf88c78b05b59ba0ffb444e53832a715d815
3,171
cc
C++
shill/dbus/chromeos_modem_simple_proxy.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
shill/dbus/chromeos_modem_simple_proxy.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
shill/dbus/chromeos_modem_simple_proxy.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 The Chromium OS 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 "shill/dbus/chromeos_modem_simple_proxy.h" #include <base/bind.h> #include "shill/cellular/cellular_error.h" #include "shill/error.h" #include "shill/logging.h" using std::string; namespace shill { namespace Logging { static auto kModuleLogScope = ScopeLogger::kDBus; static string ObjectID(const dbus::ObjectPath* p) { return p->value(); } } ChromeosModemSimpleProxy::ChromeosModemSimpleProxy( const scoped_refptr<dbus::Bus>& bus, const string& path, const string& service) : proxy_( new org::freedesktop::ModemManager::Modem::SimpleProxy( bus, service, dbus::ObjectPath(path))) {} ChromeosModemSimpleProxy::~ChromeosModemSimpleProxy() {} void ChromeosModemSimpleProxy::GetModemStatus( Error* error, const KeyValueStoreCallback& callback, int timeout) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; proxy_->GetStatusAsync( base::Bind(&ChromeosModemSimpleProxy::OnGetStatusSuccess, weak_factory_.GetWeakPtr(), callback), base::Bind(&ChromeosModemSimpleProxy::OnGetStatusFailure, weak_factory_.GetWeakPtr(), callback), timeout); } void ChromeosModemSimpleProxy::Connect(const KeyValueStore& properties, Error* error, const ResultCallback& callback, int timeout) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; brillo::VariantDictionary properties_dict; KeyValueStore::ConvertToVariantDictionary(properties, &properties_dict); proxy_->ConnectAsync( properties_dict, base::Bind(&ChromeosModemSimpleProxy::OnConnectSuccess, weak_factory_.GetWeakPtr(), callback), base::Bind(&ChromeosModemSimpleProxy::OnConnectFailure, weak_factory_.GetWeakPtr(), callback), timeout); } void ChromeosModemSimpleProxy::OnGetStatusSuccess( const KeyValueStoreCallback& callback, const brillo::VariantDictionary& props) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; KeyValueStore props_store; KeyValueStore::ConvertFromVariantDictionary(props, &props_store); callback.Run(props_store, Error()); } void ChromeosModemSimpleProxy::OnGetStatusFailure( const KeyValueStoreCallback& callback, brillo::Error* dbus_error) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; Error error; CellularError::FromChromeosDBusError(dbus_error, &error); callback.Run(KeyValueStore(), error); } void ChromeosModemSimpleProxy::OnConnectSuccess( const ResultCallback& callback) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; callback.Run(Error()); } void ChromeosModemSimpleProxy::OnConnectFailure( const ResultCallback& callback, brillo::Error* dbus_error) { SLOG(&proxy_->GetObjectPath(), 2) << __func__; Error error; CellularError::FromChromeosDBusError(dbus_error, &error); callback.Run(error); } } // namespace shill
33.378947
74
0.693157
emersion
75bb4de059be545230b138fcde43f895938c4a1e
409
cpp
C++
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void draw_characters(int count, char c) { for (int i = 0; i < count; ++i) { cout << c; } } void christmas_tree(char main_character, int times) { for (int row = 1; row <= times; ++row) { draw_characters(times - row, ' '); draw_characters(row * 2 - 1, main_character); cout << endl; } } int main() { christmas_tree('#', 8); return 0; }
16.36
53
0.594132
greenfox-zerda-sparta
75bcef18d36e759fd1c49f900c6874c2ad77d7d0
55
cpp
C++
src-ui/tablemodel.cpp
ZhaohengLi/library-management
ffdd50e367f50354e07f5cd7aff9c826aac837b0
[ "Apache-2.0" ]
2
2021-09-06T17:13:19.000Z
2022-03-02T06:47:31.000Z
tablemodel.cpp
borneq/userQtExamples
2493a96e26293b3a842a998a09228de9834c1776
[ "MIT" ]
null
null
null
tablemodel.cpp
borneq/userQtExamples
2493a96e26293b3a842a998a09228de9834c1776
[ "MIT" ]
null
null
null
#include "tablemodel.h" TableModel::TableModel() { }
7.857143
24
0.690909
ZhaohengLi
75bdac2cb35e35698d57780b633d79365809eb2e
1,640
cpp
C++
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
1
2021-06-30T06:29:54.000Z
2021-06-30T06:29:54.000Z
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "AnimationFactoryReader.h" #include "FileLogger.h" #include "LoadContentException.h" #include "ContentManager.h" #include "pugixml/pugixml.hpp" std::shared_ptr<AnimationFactory> AnimationFactoryReader::Read(std::string filePath, ContentManager& contentManager) { auto xmlDocument = pugi::xml_document{}; auto result = xmlDocument.load_file(filePath.c_str()); if (!result) { FileLogger::GetInstance().Error("{}() failed: {}. Path: {}", __FUNCTION__, result.description(), filePath); throw LoadContentException(result.description()); } auto rootNode = xmlDocument.child("GameContent"); auto atlasPath = rootNode.child("Animations").attribute("AtlasPath").as_string(); auto resolvedAtlasPath = contentManager.ResolvePath(Path{ filePath }.parent_path(), atlasPath); auto spritesheet = contentManager.Load<Spritesheet>(resolvedAtlasPath); auto animations = AnimationDict{}; for (auto animationNode : rootNode.child("Animations").children("Animation")) { auto name = animationNode.attribute("Name").as_string(); auto defaultAnimateTime = animationNode.attribute("DefaultTime").as_int(); auto isLooping = animationNode.attribute("IsLooping").as_bool(); auto animation = Animation{ name, defaultAnimateTime, isLooping }; for (auto frameNode : animationNode.children("Frame")) { auto name = frameNode.attribute("SpriteID").as_string(); auto time = frameNode.attribute("Time").as_int(); // equals to 0 if Time attribute not found animation.Add(spritesheet->at(name), time); } animations.emplace(name, animation); } return std::make_shared<AnimationFactory>(animations); }
38.139535
116
0.75061
warzes
75c093ce0b68e30ec4281f3659b798d89fc0be6e
929
cpp
C++
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
110
2016-01-14T14:46:16.000Z
2022-03-27T19:00:48.000Z
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
471
2016-08-21T14:48:15.000Z
2022-03-31T20:22:50.000Z
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
33
2016-01-25T23:30:03.000Z
2022-02-18T07:24:45.000Z
#include <windows.h> #include "dynamic_funcs.h" // Since this code requires Win2000 or later, we'll load it dynamically static HMODULE dll_gdi32 = 0; GetGlyphIndicesA_t fGetGlyphIndicesA = 0; GetGlyphIndicesW_t fGetGlyphIndicesW = 0; GetFontUnicodeRanges_t fGetFontUnicodeRanges = 0; void Init() { #ifdef LOAD_GDI32 dll_gdi32 = LoadLibrary("gdi32.dll"); if( dll_gdi32 != 0 ) { fGetGlyphIndicesA = (GetGlyphIndicesA_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesA"); fGetGlyphIndicesW = (GetGlyphIndicesW_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesW"); fGetFontUnicodeRanges = (GetFontUnicodeRanges_t)GetProcAddress(dll_gdi32, "GetFontUnicodeRanges"); } #else fGetGlyphIndicesA = GetGlyphIndicesA; fGetGlyphIndicesW = GetGlyphIndicesW; fGetFontUnicodeRanges = GetFontUnicodeRanges; #endif } void Uninit() { #ifdef LOAD_GDI32 if( dll_gdi32 != 0 ) FreeLibrary(dll_gdi32); #endif }
27.323529
100
0.759957
patridge
75c42169434068f566303a77e8c7e062f4d5bf0d
201
hpp
C++
src/ColorSYMGS.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
5
2015-07-10T16:35:08.000Z
2021-09-13T03:29:37.000Z
src/ColorSYMGS.hpp
zabookey/Kokkos-HPCG
7ca081e51a275c4fb6b21e8871788e88e8715dbc
[ "BSD-3-Clause" ]
null
null
null
src/ColorSYMGS.hpp
zabookey/Kokkos-HPCG
7ca081e51a275c4fb6b21e8871788e88e8715dbc
[ "BSD-3-Clause" ]
3
2019-03-05T16:46:25.000Z
2021-12-22T03:49:00.000Z
#ifndef COLORSYMGS_HPP #define COLORSYMGS_HPP #include "SparseMatrix.hpp" #include "Vector.hpp" #include "KokkosSetup.hpp" int ColorSYMGS(const SparseMatrix & A, const Vector & x, Vector & y); #endif
22.333333
69
0.766169
hpcg-benchmark
75c76b1272dc16e0e71395a36d1be066d448e549
26,695
cpp
C++
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
r2d2rigo/Win2D
3f06d4f19b7d16b67859a1b30ac770215ef3e52d
[ "MIT" ]
1,002
2015-01-09T19:40:01.000Z
2019-05-04T12:05:09.000Z
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
r2d2rigo/Win2D
3f06d4f19b7d16b67859a1b30ac770215ef3e52d
[ "MIT" ]
667
2015-01-02T19:04:11.000Z
2019-05-03T14:43:51.000Z
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
SunburstApps/Win2D.WinUI
75a33f8f4c0c785c2d1b478589fd4d3a9c5b53df
[ "MIT" ]
258
2015-01-06T07:44:49.000Z
2019-05-01T15:50:59.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. #include "pch.h" TEST_CLASS(CanvasImageSourceUnitTests) { public: TEST_METHOD_EX(CanvasImageSourceConstruction) { // // On construction the CanvasImageSource is expected to: // // - create a SurfaceImageSource with the specified width/height and background mode // // - set this as the composable base (queryable by GetComposableBase()) // // - call SetDevice on the SurfaceImageSourceNativeWith2D, passing it // the d2d device associated with the CanvasDevice that was passed in // int expectedHeight = 123; int expectedWidth = 456; CanvasAlphaMode expectedAlphaMode = CanvasAlphaMode::Ignore; auto mockD2DDevice = Make<MockD2DDevice>(); auto mockCanvasDevice = Make<MockCanvasDevice>(); auto mockSurfaceImageSourceFactory = Make<MockSurfaceImageSourceFactory>(); auto mockSurfaceImageSource = Make<MockSurfaceImageSource>(); // // Verify that the SurfaceImageSourceFactory is asked to create a // SurfaceImageSource with correct parameters. // // Note that actualOuter is a raw pointer - we don't want actualOuter to // ever become the last thing referencing the CanvasImageSource (this // could happen since the mock below is called during CanvasImageSource // construction; if that fails then things can blow up since actualOuter // exists outside normal exception cleanup) // bool mockCreateInstanceCalled = false; IInspectable* actualOuter; mockSurfaceImageSourceFactory->MockCreateInstanceWithDimensionsAndOpacity = [&](int32_t actualWidth, int32_t actualHeight, bool isOpaque, IInspectable* outer) { Assert::IsFalse(mockCreateInstanceCalled); Assert::AreEqual(expectedWidth, actualWidth); Assert::AreEqual(expectedHeight, actualHeight); auto actualAlphaMode = isOpaque ? CanvasAlphaMode::Ignore : CanvasAlphaMode::Premultiplied; Assert::AreEqual(expectedAlphaMode, actualAlphaMode); actualOuter = outer; mockCreateInstanceCalled = true; return mockSurfaceImageSource; }; // // Verify that SetDevice is called on the SurfaceImageSource with the // correct D2D device // mockCanvasDevice->MockGetD2DDevice = [&] { return mockD2DDevice; }; mockCanvasDevice->Mockget_Device = [&](ICanvasDevice** value) { ComPtr<ICanvasDevice> device(mockCanvasDevice.Get()); *value = device.Detach(); }; mockSurfaceImageSource->SetDeviceMethod.SetExpectedCalls(1, [&](IUnknown* actualDevice) { ComPtr<IUnknown> expectedDevice; ThrowIfFailed(mockD2DDevice.As(&expectedDevice)); Assert::AreEqual(expectedDevice.Get(), actualDevice); return S_OK; }); // // Actually create the CanvasImageSource // auto canvasImageSource = Make<CanvasImageSource>( mockCanvasDevice.Get(), (float)expectedWidth, (float)expectedHeight, DEFAULT_DPI, expectedAlphaMode, mockSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); Assert::IsTrue(mockCreateInstanceCalled); // // Verify the composition relationship between the CanvasImageSource and // the base class, SurfaceImageSource. // ComPtr<IInspectable> expectedOuter; ThrowIfFailed(canvasImageSource.As(&expectedOuter)); Assert::AreEqual(expectedOuter.Get(), actualOuter); ComPtr<IInspectable> expectedComposableBase; ThrowIfFailed(mockSurfaceImageSource.As(&expectedComposableBase)); Assert::AreEqual(canvasImageSource->GetComposableBase().Get(), expectedComposableBase.Get()); CanvasAlphaMode actualAlphaMode; ThrowIfFailed(canvasImageSource->get_AlphaMode(&actualAlphaMode)); Assert::AreEqual(CanvasAlphaMode::Ignore, actualAlphaMode); } struct AlphaModeFixture { bool ExpectedIsOpaque; AlphaModeFixture() : ExpectedIsOpaque(false) {} void CreateImageSource(CanvasAlphaMode alphaMode) { auto factory = Make<MockSurfaceImageSourceFactory>(); bool createWasCalled = false; factory->MockCreateInstanceWithDimensionsAndOpacity = [&] (int32_t,int32_t,bool opaque,IInspectable*) { createWasCalled = true; Assert::AreEqual(ExpectedIsOpaque, opaque); return Make<StubSurfaceImageSource>(); }; Make<CanvasImageSource>( As<ICanvasResourceCreator>(Make<StubCanvasDevice>()).Get(), 1.0f, 1.0f, DEFAULT_DPI, alphaMode, factory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); Assert::IsTrue(createWasCalled, L"SurfaceImageSourceFactory::Create was called"); } }; TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeIgnore_ThenUnderlyingImageSourceIsOpaque) { AlphaModeFixture f; f.ExpectedIsOpaque = true; f.CreateImageSource(CanvasAlphaMode::Ignore); } TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModePremultiplied_ThenUnderlyingImageSourceIsTransparent) { AlphaModeFixture f; f.ExpectedIsOpaque = false; f.CreateImageSource(CanvasAlphaMode::Premultiplied); } TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeStraight_ThenFailsWithInvalidArg) { AlphaModeFixture f; ExpectHResultException(E_INVALIDARG, [&] { f.CreateImageSource(CanvasAlphaMode::Straight); }); ValidateStoredErrorState(E_INVALIDARG, Strings::InvalidAlphaModeForImageSource); } TEST_METHOD_EX(CanvasImageSourceGetDevice) { ComPtr<ICanvasDevice> expectedCanvasDevice = Make<StubCanvasDevice>(); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( static_cast<ICanvasResourceCreator*>(static_cast<StubCanvasDevice*>(expectedCanvasDevice.Get())), 1.0f, 1.0f, DEFAULT_DPI, CanvasAlphaMode::Premultiplied, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); ComPtr<ICanvasDevice> actualCanvasDevice; ThrowIfFailed(canvasImageSource->get_Device(&actualCanvasDevice)); Assert::AreEqual(expectedCanvasDevice.Get(), actualCanvasDevice.Get()); // Calling get_Device with a nullptr should fail appropriately Assert::AreEqual(E_INVALIDARG, canvasImageSource->get_Device(nullptr)); } struct RecreateFixture { ComPtr<StubCanvasDevice> FirstDevice; ComPtr<MockSurfaceImageSource> SurfaceImageSource; ComPtr<CanvasImageSource> ImageSource; RecreateFixture() : FirstDevice(Make<StubCanvasDevice>()) , SurfaceImageSource(Make<MockSurfaceImageSource>()) { auto surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(SurfaceImageSource.Get()); // On the initial make we know that this succeeds SurfaceImageSource->SetDeviceMethod.AllowAnyCall(); ImageSource = Make<CanvasImageSource>( FirstDevice.Get(), 1.0f, 1.0f, DEFAULT_DPI, CanvasAlphaMode::Premultiplied, surfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); } void ExpectSetDeviceWithNullAndThen(ComPtr<IUnknown> expected) { SurfaceImageSource->SetDeviceMethod.SetExpectedCalls(2, [=] (IUnknown* actualDevice) { if (this->SurfaceImageSource->SetDeviceMethod.GetCurrentCallCount() == 1) { Assert::IsNull(actualDevice); } else { Assert::IsTrue(IsSameInstance(actualDevice, expected.Get())); } return S_OK; }); } }; TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNull_ReturnsInvalidArg) { RecreateFixture f; Assert::AreEqual(E_INVALIDARG, f.ImageSource->Recreate(nullptr)); } TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNewDevice_SetsDevice) { RecreateFixture f; auto secondDevice = Make<StubCanvasDevice>(); f.ExpectSetDeviceWithNullAndThen(secondDevice->GetD2DDevice()); ThrowIfFailed(f.ImageSource->Recreate(secondDevice.Get())); ComPtr<ICanvasDevice> retrievedDevice; ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice)); Assert::IsTrue(IsSameInstance(secondDevice.Get(), retrievedDevice.Get())); } TEST_METHOD_EX(CanvasImageSource_Recreated_WhenPassedOriginalDevice_SetsDevice) { RecreateFixture f; f.ExpectSetDeviceWithNullAndThen(f.FirstDevice->GetD2DDevice()); ThrowIfFailed(f.ImageSource->Recreate(f.FirstDevice.Get())); ComPtr<ICanvasDevice> retrievedDevice; ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice)); Assert::IsTrue(IsSameInstance(f.FirstDevice.Get(), retrievedDevice.Get())); } TEST_METHOD_EX(CanvasImageSource_CreateFromCanvasControl) { auto canvasControlAdapter = std::make_shared<CanvasControlTestAdapter>(); auto canvasControl = Make<CanvasControl>(canvasControlAdapter); // Get the control to a point where it has created the device. canvasControlAdapter->CreateCanvasImageSourceMethod.AllowAnyCall(); auto userControl = static_cast<StubUserControl*>(As<IUserControl>(canvasControl).Get()); ThrowIfFailed(userControl->LoadedEventSource->InvokeAll(nullptr, nullptr)); canvasControlAdapter->RaiseCompositionRenderingEvent(); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( canvasControl.Get(), 123.0f, 456.0f, DEFAULT_DPI, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); // // Verify that the image source and the control are compatible. // ComPtr<ICanvasDevice> controlDevice; ThrowIfFailed(canvasControl->get_Device(&controlDevice)); ComPtr<ICanvasDevice> sisDevice; ThrowIfFailed(canvasImageSource->get_Device(&sisDevice)); Assert::AreEqual(controlDevice.Get(), sisDevice.Get()); } TEST_METHOD_EX(CanvasImageSource_CreateFromDrawingSession) { ComPtr<StubCanvasDevice> canvasDevice = Make<StubCanvasDevice>(); ComPtr<StubD2DDeviceContextWithGetFactory> d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); d2dDeviceContext->SetTextAntialiasModeMethod.SetExpectedCalls(1, [](D2D1_TEXT_ANTIALIAS_MODE mode) { Assert::AreEqual(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE, mode); }); ComPtr<CanvasDrawingSession> drawingSession = CanvasDrawingSession::CreateNew( d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( drawingSession.Get(), 5.0f, 10.0f, DEFAULT_DPI, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); // // Verify that the image source and the drawing session are compatible. // ComPtr<ICanvasDevice> sisDevice; ThrowIfFailed(canvasImageSource->get_Device(&sisDevice)); Assert::AreEqual(static_cast<ICanvasDevice*>(canvasDevice.Get()), sisDevice.Get()); } TEST_METHOD_EX(CanvasImageSource_DpiProperties) { const float dpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); float actualDpi = 0; ThrowIfFailed(canvasImageSource->get_Dpi(&actualDpi)); Assert::AreEqual(dpi, actualDpi); VerifyConvertDipsToPixels(dpi, canvasImageSource); const float testValue = 100; float dips = 0; ThrowIfFailed(canvasImageSource->ConvertPixelsToDips((int)testValue, &dips)); Assert::AreEqual(testValue * DEFAULT_DPI / dpi, dips); } TEST_METHOD_EX(CanvasImageSource_PropagatesDpiToDrawingSession) { const float expectedDpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, expectedDpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); mockDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const&, float dpi) { Assert::AreEqual(expectedDpi, dpi); return nullptr; }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(canvasImageSource->CreateDrawingSession(Color{}, &drawingSession)); } TEST_METHOD_EX(CanvasImageSource_SizeProperties) { const float width = 123; const float height = 456; const float dpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), width, height, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); Size size = { 0, 0 }; ThrowIfFailed(canvasImageSource->get_Size(&size)); Assert::AreEqual(width, size.Width); Assert::AreEqual(height, size.Height); BitmapSize bitmapSize = { 0, 0 }; ThrowIfFailed(canvasImageSource->get_SizeInPixels(&bitmapSize)); Assert::AreEqual(static_cast<uint32_t>(round(width * dpi / DEFAULT_DPI)), bitmapSize.Width); Assert::AreEqual(static_cast<uint32_t>(round(height * dpi / DEFAULT_DPI)), bitmapSize.Height); } }; TEST_CLASS(CanvasImageSourceCreateDrawingSessionTests) { struct Fixture { ComPtr<StubCanvasDevice> m_canvasDevice; ComPtr<MockSurfaceImageSource> m_surfaceImageSource; ComPtr<StubSurfaceImageSourceFactory> m_surfaceImageSourceFactory; std::shared_ptr<MockCanvasImageSourceDrawingSessionFactory> m_canvasImageSourceDrawingSessionFactory; ComPtr<CanvasImageSource> m_canvasImageSource; int m_imageWidth; int m_imageHeight; Color m_anyColor; Fixture(float dpi = DEFAULT_DPI) { m_canvasDevice = Make<StubCanvasDevice>(); m_surfaceImageSource = Make<MockSurfaceImageSource>(); m_surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(m_surfaceImageSource.Get()); m_canvasImageSourceDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); m_surfaceImageSource->SetDeviceMethod.AllowAnyCall(); m_imageWidth = 123; m_imageHeight = 456; m_canvasImageSource = Make<CanvasImageSource>( m_canvasDevice.Get(), (float)m_imageWidth, (float)m_imageHeight, dpi, CanvasAlphaMode::Premultiplied, m_surfaceImageSourceFactory.Get(), m_canvasImageSourceDrawingSessionFactory); m_surfaceImageSource->SetDeviceMethod.SetExpectedCalls(0); m_anyColor = Color{ 1, 2, 3, 4 }; } }; TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesEntireImage) { Fixture f; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float) { Rect expectedRect{ 0, 0, static_cast<float>(f.m_imageWidth), static_cast<float>(f.m_imageHeight) }; Assert::AreEqual(expectedRect, updateRect); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(f.m_anyColor, &drawingSession)); Assert::IsTrue(drawingSession); } TEST_METHOD_EX(CanvasImageSource_CreateDrawingSessionWithUpdateRegion_PassesSpecifiedUpdateRegion) { Fixture f; Rect expectedRect{ 1, 2, 3, 4 }; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float) { Assert::AreEqual(expectedRect, updateRect); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(f.m_anyColor, expectedRect, &drawingSession)); Assert::IsTrue(drawingSession); } TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesClearColor) { Fixture f; int32_t anyLeft = 1; int32_t anyTop = 2; int32_t anyWidth = 3; int32_t anyHeight = 4; Color expectedColor{ 1, 2, 3, 4 }; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(2, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const& clearColor, Rect const&, float) { Assert::AreEqual(expectedColor, clearColor); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> ignoredDrawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(expectedColor, &ignoredDrawingSession)); ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(expectedColor, Rect{ (float)anyLeft, (float)anyTop, (float)anyWidth, (float)anyHeight }, &ignoredDrawingSession)); } }; TEST_CLASS(CanvasImageSourceDrawingSessionFactoryTests) { public: TEST_METHOD_EX(CanvasImageSourceDrawingSessionFactory_CallsBeginDrawWithCorrectUpdateRectangle) { auto drawingSessionFactory = std::make_shared<CanvasImageSourceDrawingSessionFactory>(); auto surfaceImageSource = Make<MockSurfaceImageSource>(); float dpi = 123.0f; Rect updateRectangleInDips{ 10, 20, 30, 40 }; RECT expectedUpdateRectangle = ToRECT(updateRectangleInDips, dpi); surfaceImageSource->BeginDrawMethod.SetExpectedCalls(1, [&] (RECT const& updateRectangle, IID const& iid, void** updateObject, POINT*) { Assert::AreEqual(expectedUpdateRectangle, updateRectangle); auto dc = Make<StubD2DDeviceContext>(nullptr); dc->SetTransformMethod.AllowAnyCall(); return dc.CopyTo(iid, updateObject); }); surfaceImageSource->EndDrawMethod.SetExpectedCalls(1); Color anyClearColor{ 1,2,3,4 }; drawingSessionFactory->Create( Make<MockCanvasDevice>().Get(), As<ISurfaceImageSourceNativeWithD2D>(surfaceImageSource).Get(), std::make_shared<bool>(), anyClearColor, updateRectangleInDips, dpi); } }; TEST_CLASS(CanvasImageSourceDrawingSessionAdapterTests) { public: TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_BeginEndDraw) { auto mockDeviceContext = Make<MockD2DDeviceContext>(); auto mockSurfaceImageSource = Make<MockSurfaceImageSource>(); RECT expectedUpdateRect{ 1, 2, 3, 4 }; POINT beginDrawOffset{ 5, 6 }; D2D1_COLOR_F expectedClearColor{ 7, 8, 9, 10 }; D2D1_POINT_2F expectedOffset{ static_cast<float>(beginDrawOffset.x - expectedUpdateRect.left), static_cast<float>(beginDrawOffset.y - expectedUpdateRect.top) }; mockSurfaceImageSource->BeginDrawMethod.SetExpectedCalls(1, [&](RECT const& updateRect, IID const& iid, void** updateObject, POINT* offset) { Assert::AreEqual(expectedUpdateRect, updateRect); Assert::AreEqual(_uuidof(ID2D1DeviceContext), iid); HRESULT hr = mockDeviceContext.CopyTo(iid, updateObject); *offset = beginDrawOffset; return hr; }); mockDeviceContext->ClearMethod.SetExpectedCalls(1, [&](D2D1_COLOR_F const* color) { Assert::AreEqual(expectedClearColor, *color); }); mockDeviceContext->SetTransformMethod.SetExpectedCalls(1, [&](const D2D1_MATRIX_3X2_F* m) { Assert::AreEqual(1.0f, m->_11); Assert::AreEqual(0.0f, m->_12); Assert::AreEqual(0.0f, m->_21); Assert::AreEqual(1.0f, m->_22); Assert::AreEqual(expectedOffset.x, m->_31); Assert::AreEqual(expectedOffset.y, m->_32); }); mockDeviceContext->SetDpiMethod.SetExpectedCalls(1, [&](float dpiX, float dpiY) { Assert::AreEqual(DEFAULT_DPI, dpiX); Assert::AreEqual(DEFAULT_DPI, dpiY); }); ComPtr<ID2D1DeviceContext1> actualDeviceContext; D2D1_POINT_2F actualOffset; auto adapter = CanvasImageSourceDrawingSessionAdapter::Create( mockSurfaceImageSource.Get(), expectedClearColor, expectedUpdateRect, DEFAULT_DPI, &actualDeviceContext, &actualOffset); Assert::AreEqual<ID2D1DeviceContext1*>(mockDeviceContext.Get(), actualDeviceContext.Get()); Assert::AreEqual(expectedOffset, actualOffset); mockSurfaceImageSource->EndDrawMethod.SetExpectedCalls(1); adapter->EndDraw(actualDeviceContext.Get()); } struct DeviceContextWithRestrictedQI : public MockD2DDeviceContext { // // Restrict this device context implementation so that it can only be // QI'd for ID2D1DeviceContext. // STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppvObject) { if (riid == __uuidof(ID2D1DeviceContext)) return RuntimeClass::QueryInterface(riid, ppvObject); return E_NOINTERFACE; } }; TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_When_SisNative_Gives_Unusuable_DeviceContext_Then_EndDraw_Called) { auto sis = Make<MockSurfaceImageSource>(); sis->BeginDrawMethod.SetExpectedCalls(1, [&](RECT const&, IID const& iid, void** obj, POINT*) { auto deviceContext = Make<DeviceContextWithRestrictedQI>(); return deviceContext.CopyTo(iid, obj); }); sis->EndDrawMethod.SetExpectedCalls(1); // // We expect creating the adapter to fail since our SurfaceImageSource // implementation returns a device context that only implements // ID2D1DeviceContext. // // If this happens we expect BeginDraw to have been called. Then, after // the failure, we expect EndDraw to have been called in order to clean // up properly. // ComPtr<ID2D1DeviceContext1> actualDeviceContext; D2D1_POINT_2F actualOffset; ExpectHResultException(E_NOINTERFACE, [&] { CanvasImageSourceDrawingSessionAdapter::Create( sis.Get(), D2D1_COLOR_F{ 1, 2, 3, 4 }, RECT{ 1, 2, 3, 4 }, DEFAULT_DPI, &actualDeviceContext, &actualOffset); }); } };
39.548148
199
0.65132
r2d2rigo
75ca9fb4e04ff2b0e4d7b0b143bed3015cae2e6c
595
cc
C++
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
#include "Candle.hh" Candle::Candle(const char* textureUrl, sf::Vector2f position, float scale, float width, float height, int col, int row, sf::RenderWindow*& window, b2World*& world) : GameObject(textureUrl, position, scale, width, height, col, row, b2BodyType::b2_staticBody, window, world) { animationsManager = new AnimationsManager(); animationsManager->AddAnimation("idle", new Animation("assets/animations/candle/idle2.anim", drawable)); } Candle::~Candle() { } void Candle::Update(float& deltaTime) { animationsManager->Update(deltaTime); animationsManager->Play("idle"); }
27.045455
106
0.744538
carolinavillam
75cbdb9e5c961527d2241b0d02724dd87a66ba54
127
cpp
C++
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2018-11-21T21:35:21.000Z
2018-11-21T21:35:21.000Z
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2017-05-13T12:21:22.000Z
2017-05-13T12:24:39.000Z
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2017-03-29T17:05:50.000Z
2017-03-29T17:05:50.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "NativeEnemyPlayerStart.h"
15.875
79
0.732283
dakitten2358
75cec848908939229603502e222c52e38afa93d2
475
cpp
C++
lectures/containers/code/list_example2.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
1
2021-09-01T19:09:54.000Z
2021-09-01T19:09:54.000Z
lectures/containers/code/list_example2.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
null
null
null
lectures/containers/code/list_example2.cpp
ahurta92/ams562-notes
e66baa1e50654e125902651f388d45cb32c81f00
[ "MIT" ]
1
2021-11-30T19:26:02.000Z
2021-11-30T19:26:02.000Z
// // Created by adrian on 11/6/21. // #include <list> #include "examples.h" int get_number(const string& s, const list<Entry>& phone_book) { for(auto p=phone_book.begin();p!=phone_book.end();++p) if(p->name == s) return p->number; return 0; // number not found } int main() { list<Entry> contacts = { {"Adrian Hurtado", 1234567}, {"Stella Salina", 1223442}, {"Johnny Z", 2323232}}; int num = get_number("Adrian Hurtado", contacts); cout<<"my number: "<<num; }
21.590909
82
0.646316
ahurta92
75d056890b4cd47c1a4666a5a68f2035ec6f7d31
2,757
cpp
C++
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
#include "argparse.hpp" #include <iostream> #include "cxxopts.hpp" namespace cli { RaytracerOptions parseArguments(int argc, char *argv[]) { RaytracerOptions raytracerOptions; cxxopts::Options options(argv[0], "A toy raytracer by Nicolas Hollmann."); options.add_options("General") ("help", "Print help"); options.add_options("IO") ("o,output", "Output filename", cxxopts::value<std::string>()->default_value("out.ppm"), "file") ("f,format", "Output format", cxxopts::value<std::string>()->default_value("ppm"), "format"); options.add_options("Raytracer") ("w,width", "Width of the target image", cxxopts::value<int>()->default_value("200"), "width") ("h,height", "Height of the target image", cxxopts::value<int>()->default_value("100"), "height") ("s,samples", "Samples per pixel", cxxopts::value<int>()->default_value("100"), "samples") ("d,depth", "Max ray depth", cxxopts::value<int>()->default_value("50"), "depth"); options.add_options("Multithreading") ("p,parallel", "Enables multithreading") ("t,threads", "Sets the thread count, 0 for auto", cxxopts::value<unsigned int>()->default_value("0"), "threads") ("blocksize", "Sets the size of a thread block", cxxopts::value<unsigned int>()->default_value("16"), "size"); options.add_options("Scene") ("world", "The world to render", cxxopts::value<std::string>()->default_value("random"), "world"); try { auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help() << std::endl; exit(0); } raytracerOptions.width = result["width"].as<int>(); raytracerOptions.height = result["height"].as<int>(); raytracerOptions.samples = result["samples"].as<int>(); raytracerOptions.depth = result["depth"].as<int>(); raytracerOptions.filename = result["output"].as<std::string>(); raytracerOptions.format = result["format"].as<std::string>(); raytracerOptions.multithreading = result.count("parallel") != 0; raytracerOptions.threadCount = result["threads"].as<unsigned int>(); raytracerOptions.blockSize = result["blocksize"].as<unsigned int>(); raytracerOptions.world = result["world"].as<std::string>(); } catch (const cxxopts::OptionException& e) { std::cerr << "Error parsing options: " << e.what() << std::endl; exit(1); } return raytracerOptions; } }
41.149254
125
0.571999
NHollmann
75d319b0e4c0901e9010627776cd4a3d52708e83
1,638
cpp
C++
components/physics/scene_physics/tests/fall.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/physics/scene_physics/tests/fall.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/physics/scene_physics/tests/fall.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" using namespace scene_graph::controllers; int main () { printf ("Results of fall_test:\n"); try { PhysicsManager manager (DRIVER_NAME); physics::Scene* scene (new physics::Scene (manager.CreateScene ())); Shape sphere_shape (manager.CreateSphereShape (1.f)); RigidBody body (scene->CreateRigidBody (sphere_shape, 1)); Node::Pointer node (Node::Create ()); printf ("Initial state:\n"); dump_body_position (body); dump_node_position (*node); printf ("Simulating one second, attach controller\n"); scene->PerformSimulation (1.f); SyncPhysicsToNode::Pointer controller (SyncPhysicsToNode::Create (*node, body)); dump_body_position (body); dump_node_position (*node); node->Update (TimeValue (0, 10)); printf ("Update node\n"); node->Update (TimeValue (1, 10)); dump_node_position (*node); printf ("Simulating one second\n"); scene->PerformSimulation (1.f); dump_body_position (body); dump_node_position (*node); printf ("Update node\n"); node->Update (TimeValue (2, 10)); dump_node_position (*node); printf ("Update node\n"); node->Update (TimeValue (3, 10)); dump_node_position (*node); printf ("Simulating one second, detach controller\n"); scene->PerformSimulation (1.f); controller->Detach (); dump_body_position (body); dump_node_position (*node); } catch (std::exception& exception) { printf ("exception: %s\n", exception.what ()); } return 0; }
21.552632
85
0.614774
untgames
75d5469ea85f516ebf9dfddb8943c424e37f1606
351
cc
C++
src/kernel/core/class.cc
cmejj/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
16,500
2015-01-01T00:47:42.000Z
2022-03-31T17:12:02.000Z
src/kernel/core/class.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
66
2015-01-08T15:22:11.000Z
2021-12-16T09:04:37.000Z
src/kernel/core/class.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
3,814
2015-01-01T12:42:31.000Z
2022-03-31T14:26:50.000Z
#include <os.h> /* Static objects */ Io io; /* Input/Output interface */ Architecture arch; /* Cpu and architecture interface */ Vmm vmm; /* Virtual memory manager interface */ Filesystem fsm; /* Filesystem interface */ Module modm; /* Module manager */ Syscalls syscall; /* Syscalls manager */ System sys; /* System manager */
25.071429
57
0.660969
cmejj
75d71582fb69f38016470062819df7410ac3b096
4,166
cpp
C++
test/Test1.cpp
LukasBanana/MercuriusLib
0b80c49b52a166a4a5490f3044c64f4a8895d9ae
[ "BSD-3-Clause" ]
1
2017-04-23T04:04:25.000Z
2017-04-23T04:04:25.000Z
test/Test1.cpp
LukasBanana/MercuriusLib
0b80c49b52a166a4a5490f3044c64f4a8895d9ae
[ "BSD-3-Clause" ]
null
null
null
test/Test1.cpp
LukasBanana/MercuriusLib
0b80c49b52a166a4a5490f3044c64f4a8895d9ae
[ "BSD-3-Clause" ]
null
null
null
/* * Test1.cpp * * This file is part of the "MercuriusLib" project (Copyright (c) 2017 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include <Merc/Merc.h> #include <iostream> #include <cstdlib> static void PrintHostAddresses(const std::string& hostName) { try { auto addresses = Mc::IPAddress::QueryAddressesFromHost(hostName); std::cout << "addresses of host \"" << hostName << "\":" << std::endl; if (!addresses.empty()) { for (const auto& addr : addresses) std::cout << " " << addr->ToString() << std::endl; } else std::cout << " <none>" << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } } static void PrintNetworkAdapter(const Mc::NetworkAdapter& adapter, std::size_t idx) { std::cout << "network adapter " << (idx++) << ':' << std::endl; std::cout << " type = " << Mc::ToString(adapter.type) << std::endl; std::cout << " description = " << adapter.description << std::endl; std::cout << " addressName = " << adapter.addressName << std::endl; std::cout << " subnetMask = " << adapter.subnetMask << std::endl; std::cout << " active = " << std::boolalpha << adapter.active << std::endl; std::cout << " broadcast = " << adapter.BroadcastAddress()->ToString() << std::endl; } int main() { try { Mc::NetworkSystem net; // Print network adapters auto adapters = net.QueryAdapters(); std::size_t adaptersIdx = 0; for (const auto& adapter : adapters) PrintNetworkAdapter(adapter, adaptersIdx); // Sort addresses std::vector<std::unique_ptr<Mc::IPAddress>> address; for (const auto& adapter : adapters) address.emplace_back(Mc::IPAddress::MakeIPv4(0, adapter.addressName)); std::cout << "unsorted addresses:" << std::endl; for (const auto& addr : address) std::cout << " " << addr->ToString() << std::endl; std::sort( address.begin(), address.end(), [](const std::unique_ptr<Mc::IPAddress>& lhs, const std::unique_ptr<Mc::IPAddress>& rhs) { return (*lhs > *rhs); } ); std::cout << "sorted addresses:" << std::endl; for (const auto& addr : address) std::cout << " " << addr->ToString() << std::endl; // Print some IP addresses auto addrLocalhost = Mc::IPAddress::MakeIPv4Localhost(); std::cout << "localhost = " << addrLocalhost->ToString() << std::endl; //PrintHostAddresses("www.google.com"); PrintHostAddresses("www.google.de"); PrintHostAddresses("www.google.ch"); PrintHostAddresses("localhost"); PrintHostAddresses("www.facebook.com"); PrintHostAddresses("www.facebook.de"); // Send HTTP GET request to server auto addrGoogle = Mc::IPAddress::QueryAddressesFromHost("www.google.com"); if (!addrGoogle.empty()) { auto& addr = addrGoogle.front(); addr->Port(80); auto sock = Mc::TCPSocket::Make(Mc::AddressFamily::IPv4); sock->Connect(*addr); std::string getRequest = "GET /index.html HTTP/1.1\r\nHost: www.google.com\r\n\r\n"; sock->Send(getRequest.c_str(), static_cast<int>(getRequest.size() + 1)); char getResponse[513]; while (true) { auto len = sock->Recv(getResponse, 512); if (len > 0) { getResponse[len] = 0; std::cout << getResponse; } else { std::cout << "\n\n"; break; } } } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } #ifdef _WIN32 system("pause"); #endif return 0; } // ================================================================================
29.971223
100
0.512242
LukasBanana
75d82e7e884119071ba9f0788cfc53d8daeb94c3
272
cpp
C++
deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
1
2019-01-31T13:13:03.000Z
2019-01-31T13:13:03.000Z
deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
null
null
null
deprecated_old_files/deprecated_workspace_pkgs/my_stage/src/run_stopper.cpp
Torreshan/TurtleBot
c6ae948364f82f505581dad2ee2dceb95fdcfba8
[ "MIT" ]
1
2019-01-14T16:24:05.000Z
2019-01-14T16:24:05.000Z
#include <ros/ros.h> #include "stopper.h" int main(int argc, char **argv) { // Initiate new ROS node named "stopper" ros::init(argc, argv, "stopper"); // Create new stopper object Stopper stopper; // Start the movement stopper.startMoving(); return 0; }
17
42
0.661765
Torreshan
75da9c1ef3d420e1a32e810b0fe0b90c6f564e25
2,588
hh
C++
sdd/mem/cache_entry.hh
tic-toc/libsdd
5c3deb43523d062929f169c3d7a301240f0fb811
[ "BSD-2-Clause" ]
6
2015-03-21T19:21:29.000Z
2022-01-29T01:20:28.000Z
sdd/mem/cache_entry.hh
tic-toc/libsdd
5c3deb43523d062929f169c3d7a301240f0fb811
[ "BSD-2-Clause" ]
1
2017-02-05T23:39:44.000Z
2017-02-05T23:40:04.000Z
libsdd/sdd/mem/cache_entry.hh
kyouko-taiga/SwiftSDD
9312160e0fac5fef6e605c9e74c543ded9708e54
[ "MIT" ]
3
2016-05-13T14:39:06.000Z
2019-08-09T20:13:39.000Z
/// @file /// @copyright The code is licensed under the BSD License /// <http://opensource.org/licenses/BSD-2-Clause>, /// Copyright (c) 2012-2015 Alexandre Hamez. /// @author Alexandre Hamez #pragma once #include <functional> // hash #include <list> #include <utility> // forward #include "sdd/mem/hash_table.hh" #include "sdd/mem/lru_list.hh" #include "sdd/util/hash.hh" namespace sdd { namespace mem { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Associate an operation to its result into the cache. /// /// The operation acts as a key and the associated result is the value counterpart. template <typename Operation, typename Result> struct cache_entry { // Can't copy a cache_entry. cache_entry(const cache_entry&) = delete; cache_entry& operator=(const cache_entry&) = delete; /// @brief mem::intrusive_member_hook<cache_entry> hook; /// @brief The cached operation. const Operation operation; /// @brief The result of the evaluation of operation. const Result result; /// @brief Where this cache entry is stored in the LRU list. typename lru_list<cache_entry>::const_iterator lru_cit_; /// @brief Constructor. template <typename... Args> cache_entry(Operation&& op, Args&&... args) : hook() , operation(std::move(op)) , result(std::forward<Args>(args)...) , lru_cit_() {} /// @brief Cache entries are only compared using their operations. friend bool operator==(const cache_entry& lhs, const cache_entry& rhs) noexcept { return lhs.operation == rhs.operation; } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::mem namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename Operation, typename Result> struct hash<sdd::mem::cache_entry<Operation, Result>> { std::size_t operator()(const sdd::mem::cache_entry<Operation, Result>& x) { using namespace sdd::hash; // A cache entry must have the same hash as its contained operation. Otherwise, cache::erase() // and cache::insert_check()/cache::insert_commit() won't use the same position in buckets. return seed(x.operation); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std /*------------------------------------------------------------------------------------------------*/
28.755556
100
0.553323
tic-toc
75de7ce582992113a81de3160bf4152d196ac7d8
71,675
cpp
C++
tcs/sam_mw_gen_Type260.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
61
2017-08-09T15:10:59.000Z
2022-02-15T21:45:31.000Z
tcs/sam_mw_gen_Type260.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
462
2017-07-31T21:26:46.000Z
2022-03-30T22:53:50.000Z
tcs/sam_mw_gen_Type260.cpp
gjsoto/ssc
70ef4fdafb9afe0418a9c552485a7116a1b3a743
[ "BSD-3-Clause" ]
73
2017-08-24T17:39:31.000Z
2022-03-28T08:37:47.000Z
#define _TCSTYPEINTERFACE_ #include "tcstype.h" //#include "htf_props.h" #include "sam_csp_util.h" #include <cmath> using namespace std; /* ************************************************************************ Object: Generic solar model Simulation Studio Model: Type260 Author: Michael J. Wagner Date: May 29, 2013 COPYRIGHT 2013 NATIONAL RENEWABLE ENERGY LABORATORY */ enum{ //parameters and inputs P_LATITUDE, P_LONGITUDE, P_TIMEZONE, P_THETA_STOW, P_THETA_DEP, P_INTERP_ARR, P_RAD_TYPE, P_SOLARM, P_T_SFDES, P_IRR_DES, P_ETA_OPT_SOIL, P_ETA_OPT_GEN, P_F_SFHL_REF, P_SFHLQ_COEFS, P_SFHLT_COEFS, P_SFHLV_COEFS, P_QSF_DES, P_W_DES, P_ETA_DES, P_F_WMAX, P_F_WMIN, P_F_STARTUP, P_ETA_LHV, P_ETAQ_COEFS, P_ETAT_COEFS, P_T_PCDES, P_PC_T_CORR, P_F_WPAR_FIXED, P_F_WPAR_PROD, P_WPAR_PRODQ_COEFS, P_WPAR_PRODT_COEFS, P_HRS_TES, P_F_CHARGE, P_F_DISCH, P_F_ETES_0, P_F_TESHL_REF, P_TESHLX_COEFS, P_TESHLT_COEFS, P_NTOD, //P_TOD_SCHED, P_DISWS, P_DISWOS, P_QDISP, P_FDISP, P_ISTABLEUNSORTED, P_OPTICALTABLE, //P_OPTICALTABLEUNS, I_IBN, I_IBH, I_ITOTH, I_TDB, I_TWB, I_VWIND, I_TOUPeriod, O_IRR_USED, O_HOUR_OF_DAY, O_DAY_OF_YEAR, O_DECLINATION, O_SOLTIME, O_HRANGLE, O_SOLALT, O_SOLAZ, O_ETA_OPT_SF, O_F_SFHL_QDNI, O_F_SFHL_TAMB, O_F_SFHL_VWIND, O_Q_HL_SF, O_Q_SF, O_Q_INC, O_PBMODE, O_PBSTARTF, O_Q_TO_PB, O_Q_STARTUP, O_Q_TO_TES, O_Q_FROM_TES, O_E_IN_TES, O_Q_HL_TES, O_Q_DUMP_TESFULL, O_Q_DUMP_TESCHG, O_Q_DUMP_UMIN, O_Q_DUMP_TOT, O_Q_FOSSIL, O_Q_GAS, O_F_EFFPC_QTPB, O_F_EFFPC_TAMB, O_ETA_CYCLE, O_W_GR_SOLAR, O_W_GR_FOSSIL, O_W_GR, O_W_PAR_FIXED, O_W_PAR_PROD, O_W_PAR_TOT, O_W_PAR_ONLINE, O_W_PAR_OFFLINE, O_ENET, //Include N_max N_MAX }; tcsvarinfo sam_mw_gen_type260_variables[] = { { TCS_PARAM, TCS_NUMBER, P_LATITUDE, "latitude", "Site latitude", "deg", "", "", "35" }, { TCS_PARAM, TCS_NUMBER, P_LONGITUDE, "longitude", "Site longitude", "deg", "", "", "-117" }, { TCS_PARAM, TCS_NUMBER, P_TIMEZONE, "timezone", "Site timezone", "hr", "", "", "-8" }, { TCS_PARAM, TCS_NUMBER, P_THETA_STOW, "theta_stow", "Solar elevation angle at which the solar field stops operating", "deg", "", "", "170" }, { TCS_PARAM, TCS_NUMBER, P_THETA_DEP, "theta_dep", "Solar elevation angle at which the solar field begins operating", "deg", "", "", "10" }, { TCS_PARAM, TCS_NUMBER, P_INTERP_ARR, "interp_arr", "Interpolate the array or find nearest neighbor? (1=interp,2=no)", "none", "", "", "1" }, { TCS_PARAM, TCS_NUMBER, P_RAD_TYPE, "rad_type", "Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz)", "none", "", "", "1" }, { TCS_PARAM, TCS_NUMBER, P_SOLARM, "solarm", "Solar multiple", "none", "", "", "2" }, { TCS_PARAM, TCS_NUMBER, P_T_SFDES, "T_sfdes", "Solar field design point temperature (dry bulb)", "C", "", "", "25" }, { TCS_PARAM, TCS_NUMBER, P_IRR_DES, "irr_des", "Irradiation design point", "W/m2", "", "", "950" }, { TCS_PARAM, TCS_NUMBER, P_ETA_OPT_SOIL, "eta_opt_soil", "Soiling optical derate factor", "none", "", "", "0.95" }, { TCS_PARAM, TCS_NUMBER, P_ETA_OPT_GEN, "eta_opt_gen", "General/other optical derate", "none", "", "", "0.99" }, { TCS_PARAM, TCS_NUMBER, P_F_SFHL_REF, "f_sfhl_ref", "Reference solar field thermal loss fraction", "MW/MWcap", "", "", "0.071591" }, { TCS_PARAM, TCS_ARRAY, P_SFHLQ_COEFS, "sfhlQ_coefs", "Irr-based solar field thermal loss adjustment coefficients", "1/MWt", "", "", "1,-0.1,0,0" }, { TCS_PARAM, TCS_ARRAY, P_SFHLT_COEFS, "sfhlT_coefs", "Temp.-based solar field thermal loss adjustment coefficients", "1/C", "", "", "1,0.005,0,0" }, { TCS_PARAM, TCS_ARRAY, P_SFHLV_COEFS, "sfhlV_coefs", "Wind-based solar field thermal loss adjustment coefficients", "1/(m/s)", "", "", "1,0.01,0,0" }, { TCS_PARAM, TCS_NUMBER, P_QSF_DES, "qsf_des", "Solar field thermal production at design", "MWt", "", "", "628" }, { TCS_PARAM, TCS_NUMBER, P_W_DES, "w_des", "Design power cycle gross output", "MWe", "", "", "110" }, { TCS_PARAM, TCS_NUMBER, P_ETA_DES, "eta_des", "Design power cycle gross efficiency", "none", "", "", "0.35" }, { TCS_PARAM, TCS_NUMBER, P_F_WMAX, "f_wmax", "Maximum over-design power cycle operation fraction", "none", "", "", "1.05" }, { TCS_PARAM, TCS_NUMBER, P_F_WMIN, "f_wmin", "Minimum part-load power cycle operation fraction", "none", "", "", "0.25" }, { TCS_PARAM, TCS_NUMBER, P_F_STARTUP, "f_startup", "Equivalent full-load hours required for power system startup", "hours", "", "", "0.2" }, { TCS_PARAM, TCS_NUMBER, P_ETA_LHV, "eta_lhv", "Fossil backup lower heating value efficiency", "none", "", "", "0.9" }, { TCS_PARAM, TCS_ARRAY, P_ETAQ_COEFS, "etaQ_coefs", "Part-load power conversion efficiency adjustment coefficients", "1/MWt", "", "","0.9,0.1,0,0,0" }, { TCS_PARAM, TCS_ARRAY, P_ETAT_COEFS, "etaT_coefs", "Temp.-based power conversion efficiency adjustment coefs.", "1/C", "", "","1,-0.002,0,0,0" }, { TCS_PARAM, TCS_NUMBER, P_T_PCDES, "T_pcdes", "Power conversion reference temperature", "C", "", "", "21" }, { TCS_PARAM, TCS_NUMBER, P_PC_T_CORR, "PC_T_corr", "Power conversion temperature correction mode (1=wetb, 2=dryb)", "none", "", "", "1" }, { TCS_PARAM, TCS_NUMBER, P_F_WPAR_FIXED, "f_Wpar_fixed", "Fixed capacity-based parasitic loss fraction", "MWe/MWcap", "", "", "0.0055" }, { TCS_PARAM, TCS_NUMBER, P_F_WPAR_PROD, "f_Wpar_prod", "Production-based parasitic loss fraction", "MWe/MWe", "", "", "0.08" }, { TCS_PARAM, TCS_ARRAY, P_WPAR_PRODQ_COEFS, "Wpar_prodQ_coefs", "Part-load production parasitic adjustment coefs.", "1/MWe", "", "", "1,0,0,0" }, { TCS_PARAM, TCS_ARRAY, P_WPAR_PRODT_COEFS, "Wpar_prodT_coefs", "Temp.-based production parasitic adjustment coefs.", "1/C", "", "", "1,0,0,0" }, { TCS_PARAM, TCS_NUMBER, P_HRS_TES, "hrs_tes", "Equivalent full-load hours of storage", "hours", "", "", "6" }, { TCS_PARAM, TCS_NUMBER, P_F_CHARGE, "f_charge", "Storage charging energy derate", "none", "", "", "0.98" }, { TCS_PARAM, TCS_NUMBER, P_F_DISCH, "f_disch", "Storage discharging energy derate", "none", "", "", "0.98" }, { TCS_PARAM, TCS_NUMBER, P_F_ETES_0, "f_etes_0", "Initial fractional charge level of thermal storage (0..1)", "none", "", "", "0.1" }, { TCS_PARAM, TCS_NUMBER, P_F_TESHL_REF, "f_teshl_ref", "Reference heat loss from storage per max stored capacity","kWt/MWhr-stored", "", "", "0.35" }, { TCS_PARAM, TCS_ARRAY, P_TESHLX_COEFS, "teshlX_coefs", "Charge-based thermal loss adjustment - constant coef.","1/MWhr-stored", "", "", "1,0,0,0" }, { TCS_PARAM, TCS_ARRAY, P_TESHLT_COEFS, "teshlT_coefs", "Temp.-based thermal loss adjustment - constant coef.", "1/C", "", "", "1,0,0,0" }, { TCS_PARAM, TCS_NUMBER, P_NTOD, "ntod", "Number of time-of-dispatch periods in the dispatch schedule", "none", "", "", "9" }, { TCS_PARAM, TCS_ARRAY, P_DISWS, "disws", "Time-of-dispatch control for with-solar conditions", "none", "", "","0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1" }, { TCS_PARAM, TCS_ARRAY, P_DISWOS, "diswos", "Time-of-dispatch control for without-solar conditions", "none", "", "","0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1" }, { TCS_PARAM, TCS_ARRAY, P_QDISP, "qdisp", "TOD power output control factors", "none", "", "","1,1,1,1,1,1,1,1,1" }, { TCS_PARAM, TCS_ARRAY, P_FDISP, "fdisp", "Fossil backup output control factors", "none", "", "","0,0,0,0,0,0,0,0,0" }, { TCS_PARAM, TCS_NUMBER, P_ISTABLEUNSORTED, "istableunsorted", "Is optical table unsorted? (1=yes, 0=no)", "none", "", "", "0" }, { TCS_PARAM, TCS_MATRIX, P_OPTICALTABLE, "OpticalTable", "Optical table", "none", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_IBN, "ibn", "Beam-normal (DNI) irradiation", "W/m2", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_IBH, "ibh", "Beam-horizontal irradiation", "W/m2", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_ITOTH, "itoth", "Total horizontal irradiation", "W/m2", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_TDB, "tdb", "Ambient dry-bulb temperature", "C", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_TWB, "twb", "Ambient wet-bulb temperature", "C", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_VWIND, "vwind", "Wind velocity", "m/s", "", "", "" }, { TCS_INPUT, TCS_NUMBER, I_TOUPeriod, "TOUPeriod", "The time-of-use period", "", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_IRR_USED, "irr_used", "Irradiation value used in simulation", "W/m2", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_HOUR_OF_DAY, "hour_of_day", "Hour of the day", "hour", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_DAY_OF_YEAR, "day_of_year", "Day of the year", "day", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_DECLINATION, "declination", "Declination angle", "deg", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_SOLTIME, "soltime", "[hour] Solar time of the day", "hour", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_HRANGLE, "hrangle", "Hour angle", "deg", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_SOLALT, "solalt", "Solar elevation angle", "deg", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_SOLAZ, "solaz", "Solar azimuth angle (-180..180, 0deg=South)", "deg", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_ETA_OPT_SF, "eta_opt_sf", "Solar field optical efficiency", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_QDNI, "f_sfhl_qdni", "Solar field load-based thermal loss correction", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_TAMB, "f_sfhl_tamb", "Solar field temp.-based thermal loss correction", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_F_SFHL_VWIND, "f_sfhl_vwind", "Solar field wind-based thermal loss correction", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_HL_SF, "q_hl_sf", "Solar field thermal losses", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_SF, "q_sf", "Solar field delivered thermal power", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_INC, "q_inc", "Qdni - Solar incident energy, before all losses", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_PBMODE, "pbmode", "Power conversion mode", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_PBSTARTF, "pbstartf", "Flag indicating power system startup", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_TO_PB, "q_to_pb", "Thermal energy to the power conversion system", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_STARTUP, "q_startup", "Power conversion startup energy", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_TO_TES, "q_to_tes", "Thermal energy into storage", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_FROM_TES, "q_from_tes", "Thermal energy from storage", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_E_IN_TES, "e_in_tes", "Energy in storage", "MWt-hr", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_HL_TES, "q_hl_tes", "Thermal losses from storage", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TESFULL, "q_dump_tesfull", "Dumped energy exceeding storage charge level max", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TESCHG, "q_dump_teschg", "Dumped energy exceeding exceeding storage charge rate", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_UMIN, "q_dump_umin", "Dumped energy from falling below min. operation fraction", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_DUMP_TOT, "q_dump_tot", "Total dumped energy", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_FOSSIL, "q_fossil", "thermal energy supplied from aux firing", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_Q_GAS, "q_gas", "Energy content of fuel required to supply Qfos", "MWt", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_F_EFFPC_QTPB, "f_effpc_qtpb", "Load-based conversion efficiency correction", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_F_EFFPC_TAMB, "f_effpc_tamb", "Temp-based conversion efficiency correction", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_ETA_CYCLE, "eta_cycle", "Adjusted power conversion efficiency", "none", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_GR_SOLAR, "w_gr_solar", "Power produced from the solar component", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_GR_FOSSIL, "w_gr_fossil", "Power produced from the fossil component", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_GR, "w_gr", "Total gross power production", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_PAR_FIXED, "w_par_fixed", "Fixed parasitic losses", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_PAR_PROD, "w_par_prod", "Production-based parasitic losses", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_PAR_TOT, "w_par_tot", "Total parasitic losses", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_PAR_ONLINE, "w_par_online", "Online parasitics", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_W_PAR_OFFLINE, "w_par_offline", "Offline parasitics", "MWe", "", "", "" }, { TCS_OUTPUT, TCS_NUMBER, O_ENET, "enet", "Net electric output", "MWe", "", "", "" }, { TCS_INVALID, TCS_INVALID, N_MAX, 0, 0, 0, 0, 0, 0 } }; static const double zen_scale = 1.570781477; static const double az_scale = 6.283125908; class sam_mw_gen_type260 : public tcstypeinterface { private: OpticalDataTable optical_table; GaussMarkov *optical_table_uns; //Constants for scaling GM table double eff_scale; //defined later based on max value double pi,Pi,d2r,r2d, g, mtoinch; double latitude; //Site latitude double longitude; //Site longitude double timezone; //Site timezone double theta_stow; //Solar elevation angle at which the solar field stops operating double theta_dep; //Solar elevation angle at which the solar field begins operating int interp_arr; //Interpolate the array or find nearest neighbor? (1=interp,2=no) int rad_type; //Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz) double solarm; //Solar multiple double T_sfdes; //Solar field design point temperature (dry bulb) double irr_des; //Irradiation design point double eta_opt_soil; //Soiling optical derate factor double eta_opt_gen; //General/other optical derate double f_sfhl_ref; //Reference solar field thermal loss fraction double* sfhlQ_coefs; //Irr-based solar field thermal loss adjustment coefficients int nval_sfhlQ_coefs; double* sfhlT_coefs; //Temp.-based solar field thermal loss adjustment coefficients int nval_sfhlT_coefs; double* sfhlV_coefs; //Wind-based solar field thermal loss adjustment coefficients int nval_sfhlV_coefs; double qsf_des; //Solar field thermal production at design double w_des; //Design power cycle gross output double eta_des; //Design power cycle gross efficiency double f_wmax; //Maximum over-design power cycle operation fraction double f_wmin; //Minimum part-load power cycle operation fraction double f_startup; //Equivalent full-load hours required for power system startup double eta_lhv; //Fossil backup lower heating value efficiency double* etaQ_coefs; //Part-load power conversion efficiency adjustment coefficients int nval_etaQ_coefs; double* etaT_coefs; //Temp.-based power conversion efficiency adjustment coefs. int nval_etaT_coefs; double T_pcdes; //Power conversion reference temperature double PC_T_corr; //Power conversion temperature correction mode (1=wetb, 2=dryb) double f_Wpar_fixed; //Fixed capacity-based parasitic loss fraction double f_Wpar_prod; //Production-based parasitic loss fraction double* Wpar_prodQ_coefs; //Part-load production parasitic adjustment coefs. int nval_Wpar_prodQ_coefs; double* Wpar_prodT_coefs; //Temp.-based production parasitic adjustment coefs. int nval_Wpar_prodT_coefs; double hrs_tes; //Equivalent full-load hours of storage double f_charge; //Storage charging energy derate double f_disch; //Storage discharging energy derate double f_etes_0; //Initial fractional charge level of thermal storage (0..1) double f_teshl_ref; //Reference heat loss from storage per max stored capacity double* teshlX_coefs; //Charge-based thermal loss adjustment - constant coef. int nval_teshlX_coefs; double* teshlT_coefs; //Temp.-based thermal loss adjustment - constant coef. int nval_teshlT_coefs; int ntod; //Number of time-of-dispatch periods in the dispatch schedule //double* tod_sched; //Array of touperiod indices int nval_tod_sched; double* disws; //Time-of-dispatch control for with-solar conditions int nval_disws; double* diswos; //Time-of-dispatch control for without-solar conditions int nval_diswos; double* qdisp; //touperiod power output control factors int nval_qdisp; double* fdisp; //Fossil backup output control factors int nval_fdisp; bool istableunsorted; double* OpticalTable_in; //Optical table int nrow_OpticalTable, ncol_OpticalTable; /*double* OpticalTableUns_in; int nrow_OpticalTableUns, ncol_OpticalTableUns;*/ double ibn; //Beam-normal (DNI) irradiation double ibh; //Beam-horizontal irradiation double itoth; //Total horizontal irradiation double tdb; //Ambient dry-bulb temperature double twb; //Ambient wet-bulb temperature double vwind; //Wind velocity double irr_used; //Irradiation value used in simulation double hour_of_day; //Hour of the day double day_of_year; //Day of the year double declination; //Declination angle double soltime; //[hour] Solar time of the day double hrangle; //Hour angle double solalt; //Solar elevation angle double solaz; //Solar azimuth angle (-180..180, 0deg=South) double eta_opt_sf; //Solar field optical efficiency double f_sfhl_qdni; //Solar field load-based thermal loss correction double f_sfhl_tamb; //Solar field temp.-based thermal loss correction double f_sfhl_vwind; //Solar field wind-based thermal loss correction double q_hl_sf; //Solar field thermal losses double q_sf; //Solar field delivered thermal power double q_inc; //Qdni - Solar incident energy, before all losses int pbmode; //Power conversion mode int pbstartf; //Flag indicating power system startup double q_to_pb; //Thermal energy to the power conversion system double q_startup; //Power conversion startup energy double q_to_tes; //Thermal energy into storage double q_from_tes; //Thermal energy from storage double e_in_tes; //Energy in storage double q_hl_tes; //Thermal losses from storage double q_dump_tesfull; //Dumped energy exceeding storage charge level max double q_dump_teschg; //Dumped energy exceeding exceeding storage charge rate double q_dump_umin; //Dumped energy from falling below min. operation fraction double q_dump_tot; //Total dumped energy double q_fossil; //thermal energy supplied from aux firing double q_gas; //Energy content of fuel required to supply Qfos double f_effpc_qtpb; //Load-based conversion efficiency correction double f_effpc_tamb; //Temp-based conversion efficiency correction double eta_cycle; //Adjusted power conversion efficiency double w_gr_solar; //Power produced from the solar component double w_gr_fossil; //Power produced from the fossil component double w_gr; //Total gross power production double w_par_fixed; //Fixed parasitic losses double w_par_prod; //Production-based parasitic losses double w_par_tot; //Total parasitic losses double w_par_online; //Online parasitics double w_par_offline; //Offline parasitics double enet; //Net electric output util::matrix_t<double> OpticalTable; //util::matrix_t<double> OpticalTableUns; //Declare variables that require storage from step to step double dt, start_time, q_des, etesmax, omega, dec, eta_opt_ref, f_qsf, qttmin, qttmax, ptsmax, pfsmax; double etes0, q_startup_remain, q_startup_used; int pbmode0; bool is_sf_init; public: sam_mw_gen_type260( tcscontext *cxt, tcstypeinfo *ti ) : tcstypeinterface(cxt, ti) { //Commonly used values, conversions, etc... Pi = acos(-1.); pi = Pi; r2d = 180./pi; d2r = pi/180.; g = 9.81; //gravitation constant mtoinch = 39.3700787; //[m] -> [in] is_sf_init = false; //Set all values to NaN or nonsense value to prevent misuse latitude = std::numeric_limits<double>::quiet_NaN(); longitude = std::numeric_limits<double>::quiet_NaN(); timezone = std::numeric_limits<double>::quiet_NaN(); theta_stow = std::numeric_limits<double>::quiet_NaN(); theta_dep = std::numeric_limits<double>::quiet_NaN(); interp_arr = -1; rad_type = -1; solarm = std::numeric_limits<double>::quiet_NaN(); T_sfdes = std::numeric_limits<double>::quiet_NaN(); irr_des = std::numeric_limits<double>::quiet_NaN(); eta_opt_soil = std::numeric_limits<double>::quiet_NaN(); eta_opt_gen = std::numeric_limits<double>::quiet_NaN(); f_sfhl_ref = std::numeric_limits<double>::quiet_NaN(); sfhlQ_coefs = NULL; nval_sfhlQ_coefs = -1; sfhlT_coefs = NULL; nval_sfhlT_coefs = -1; sfhlV_coefs = NULL; nval_sfhlV_coefs = -1; qsf_des = std::numeric_limits<double>::quiet_NaN(); w_des = std::numeric_limits<double>::quiet_NaN(); eta_des = std::numeric_limits<double>::quiet_NaN(); f_wmax = std::numeric_limits<double>::quiet_NaN(); f_wmin = std::numeric_limits<double>::quiet_NaN(); f_startup = std::numeric_limits<double>::quiet_NaN(); eta_lhv = std::numeric_limits<double>::quiet_NaN(); etaQ_coefs = NULL; nval_etaQ_coefs = -1; etaT_coefs = NULL; nval_etaT_coefs = -1; T_pcdes = std::numeric_limits<double>::quiet_NaN(); PC_T_corr = std::numeric_limits<double>::quiet_NaN(); f_Wpar_fixed = std::numeric_limits<double>::quiet_NaN(); f_Wpar_prod = std::numeric_limits<double>::quiet_NaN(); Wpar_prodQ_coefs = NULL; nval_Wpar_prodQ_coefs = -1; Wpar_prodT_coefs = NULL; nval_Wpar_prodT_coefs = -1; hrs_tes = std::numeric_limits<double>::quiet_NaN(); f_charge = std::numeric_limits<double>::quiet_NaN(); f_disch = std::numeric_limits<double>::quiet_NaN(); f_etes_0 = std::numeric_limits<double>::quiet_NaN(); f_teshl_ref = std::numeric_limits<double>::quiet_NaN(); teshlX_coefs = NULL; nval_teshlX_coefs = -1; teshlT_coefs = NULL; nval_teshlT_coefs = -1; ntod = -1; //tod_sched = NULL; nval_tod_sched = -1; disws = NULL; nval_disws = -1; diswos = NULL; nval_diswos = -1; qdisp = NULL; nval_qdisp = -1; fdisp = NULL; nval_fdisp = -1; OpticalTable_in = NULL; nrow_OpticalTable = -1, ncol_OpticalTable = -1; istableunsorted = false; optical_table_uns = 0; //NULL eff_scale = 1.; //Set here just in case /*OpticalTableUns_in = NULL; nrow_OpticalTableUns = -1, ncol_OpticalTableUns = -1;*/ ibn = std::numeric_limits<double>::quiet_NaN(); ibh = std::numeric_limits<double>::quiet_NaN(); itoth = std::numeric_limits<double>::quiet_NaN(); tdb = std::numeric_limits<double>::quiet_NaN(); twb = std::numeric_limits<double>::quiet_NaN(); vwind = std::numeric_limits<double>::quiet_NaN(); irr_used = std::numeric_limits<double>::quiet_NaN(); hour_of_day = std::numeric_limits<double>::quiet_NaN(); day_of_year = std::numeric_limits<double>::quiet_NaN(); declination = std::numeric_limits<double>::quiet_NaN(); soltime = std::numeric_limits<double>::quiet_NaN(); hrangle = std::numeric_limits<double>::quiet_NaN(); solalt = std::numeric_limits<double>::quiet_NaN(); solaz = std::numeric_limits<double>::quiet_NaN(); eta_opt_sf = std::numeric_limits<double>::quiet_NaN(); f_sfhl_qdni = std::numeric_limits<double>::quiet_NaN(); f_sfhl_tamb = std::numeric_limits<double>::quiet_NaN(); f_sfhl_vwind = std::numeric_limits<double>::quiet_NaN(); q_hl_sf = std::numeric_limits<double>::quiet_NaN(); q_sf = std::numeric_limits<double>::quiet_NaN(); q_inc = std::numeric_limits<double>::quiet_NaN(); pbmode = -1; pbstartf = -1; q_to_pb = std::numeric_limits<double>::quiet_NaN(); q_startup = std::numeric_limits<double>::quiet_NaN(); q_to_tes = std::numeric_limits<double>::quiet_NaN(); q_from_tes = std::numeric_limits<double>::quiet_NaN(); e_in_tes = std::numeric_limits<double>::quiet_NaN(); q_hl_tes = std::numeric_limits<double>::quiet_NaN(); q_dump_tesfull = std::numeric_limits<double>::quiet_NaN(); q_dump_teschg = std::numeric_limits<double>::quiet_NaN(); q_dump_umin = std::numeric_limits<double>::quiet_NaN(); q_dump_tot = std::numeric_limits<double>::quiet_NaN(); q_fossil = std::numeric_limits<double>::quiet_NaN(); q_gas = std::numeric_limits<double>::quiet_NaN(); f_effpc_qtpb = std::numeric_limits<double>::quiet_NaN(); f_effpc_tamb = std::numeric_limits<double>::quiet_NaN(); eta_cycle = std::numeric_limits<double>::quiet_NaN(); w_gr_solar = std::numeric_limits<double>::quiet_NaN(); w_gr_fossil = std::numeric_limits<double>::quiet_NaN(); w_gr = std::numeric_limits<double>::quiet_NaN(); w_par_fixed = std::numeric_limits<double>::quiet_NaN(); w_par_prod = std::numeric_limits<double>::quiet_NaN(); w_par_tot = std::numeric_limits<double>::quiet_NaN(); w_par_online = std::numeric_limits<double>::quiet_NaN(); w_par_offline = std::numeric_limits<double>::quiet_NaN(); enet = std::numeric_limits<double>::quiet_NaN(); } virtual ~sam_mw_gen_type260(){ /* Clean up on simulation terminate */ if(optical_table_uns != 0) delete optical_table_uns; } virtual int init(){ /* --Initialization call-- Do any setup required here. Get the values of the inputs and parameters */ dt = time_step()/3600.; start_time = -1; latitude = value(P_LATITUDE); //Site latitude [deg] longitude = value(P_LONGITUDE); //Site longitude [deg] timezone = value(P_TIMEZONE); //Site timezone [hr] theta_stow = value(P_THETA_STOW); //Solar elevation angle at which the solar field stops operating [deg] theta_dep = value(P_THETA_DEP); //Solar elevation angle at which the solar field begins operating [deg] interp_arr = (int)value(P_INTERP_ARR); //Interpolate the array or find nearest neighbor? (1=interp,2=no) [none] rad_type = (int)value(P_RAD_TYPE); //Solar resource radiation type (1=DNI,2=horiz.beam,3=tot.horiz) [none] solarm = value(P_SOLARM); //Solar multiple [none] T_sfdes = value(P_T_SFDES); //Solar field design point temperature (dry bulb) [C] irr_des = value(P_IRR_DES); //Irradiation design point [W/m2] eta_opt_soil = value(P_ETA_OPT_SOIL); //Soiling optical derate factor [none] eta_opt_gen = value(P_ETA_OPT_GEN); //General/other optical derate [none] f_sfhl_ref = value(P_F_SFHL_REF); //Reference solar field thermal loss fraction [MW/MWcap] sfhlQ_coefs = value(P_SFHLQ_COEFS, &nval_sfhlQ_coefs); //Irr-based solar field thermal loss adjustment coefficients [1/MWt] sfhlT_coefs = value(P_SFHLT_COEFS, &nval_sfhlT_coefs); //Temp.-based solar field thermal loss adjustment coefficients [1/C] sfhlV_coefs = value(P_SFHLV_COEFS, &nval_sfhlV_coefs); //Wind-based solar field thermal loss adjustment coefficients [1/(m/s)] qsf_des = value(P_QSF_DES); //Solar field thermal production at design [MWt] w_des = value(P_W_DES); //Design power cycle gross output [MWe] eta_des = value(P_ETA_DES); //Design power cycle gross efficiency [none] f_wmax = value(P_F_WMAX); //Maximum over-design power cycle operation fraction [none] f_wmin = value(P_F_WMIN); //Minimum part-load power cycle operation fraction [none] f_startup = value(P_F_STARTUP); //Equivalent full-load hours required for power system startup [hours] eta_lhv = value(P_ETA_LHV); //Fossil backup lower heating value efficiency [none] etaQ_coefs = value(P_ETAQ_COEFS, &nval_etaQ_coefs); //Part-load power conversion efficiency adjustment coefficients [1/MWt] etaT_coefs = value(P_ETAT_COEFS, &nval_etaT_coefs); //Temp.-based power conversion efficiency adjustment coefs. [1/C] T_pcdes = value(P_T_PCDES); //Power conversion reference temperature [C] PC_T_corr = value(P_PC_T_CORR); //Power conversion temperature correction mode (1=wetb, 2=dryb) [none] f_Wpar_fixed = value(P_F_WPAR_FIXED); //Fixed capacity-based parasitic loss fraction [MWe/MWcap] f_Wpar_prod = value(P_F_WPAR_PROD); //Production-based parasitic loss fraction [MWe/MWe] Wpar_prodQ_coefs = value(P_WPAR_PRODQ_COEFS, &nval_Wpar_prodQ_coefs); //Part-load production parasitic adjustment coefs. [1/MWe] Wpar_prodT_coefs = value(P_WPAR_PRODT_COEFS, &nval_Wpar_prodT_coefs); //Temp.-based production parasitic adjustment coefs. [1/C] hrs_tes = value(P_HRS_TES); //Equivalent full-load hours of storage [hours] f_charge = value(P_F_CHARGE); //Storage charging energy derate [none] f_disch = value(P_F_DISCH); //Storage discharging energy derate [none] f_etes_0 = value(P_F_ETES_0); //Initial fractional charge level of thermal storage (0..1) [none] f_teshl_ref = value(P_F_TESHL_REF); //Reference heat loss from storage per max stored capacity [kWt/MWhr-stored] teshlX_coefs = value(P_TESHLX_COEFS, &nval_teshlX_coefs); //Charge-based thermal loss adjustment - constant coef. [1/MWhr-stored] teshlT_coefs = value(P_TESHLT_COEFS, &nval_teshlT_coefs); //Temp.-based thermal loss adjustment - constant coef. [1/C] ntod = (int)value(P_NTOD); //Number of time-of-dispatch periods in the dispatch schedule [none] //tod_sched = value(P_TOD_SCHED, &nval_tod_sched); //Array of touperiod indices [none] disws = value(P_DISWS, &nval_disws); //Time-of-dispatch control for with-solar conditions [none] diswos = value(P_DISWOS, &nval_diswos); //Time-of-dispatch control for without-solar conditions [none] qdisp = value(P_QDISP, &nval_qdisp); //touperiod power output control factors [none] fdisp = value(P_FDISP, &nval_fdisp); //Fossil backup output control factors [none] OpticalTable_in = value(P_OPTICALTABLE, &nrow_OpticalTable, &ncol_OpticalTable); //Optical table [none] istableunsorted = value(P_ISTABLEUNSORTED) == 1.; //Rearrange the optical table into a more useful format OpticalTable.assign(OpticalTable_in, nrow_OpticalTable, ncol_OpticalTable); //Unit conversions latitude *= d2r; longitude *= d2r; theta_stow *= d2r; theta_dep *= d2r; T_sfdes += 273.15; T_pcdes += 273.15; f_teshl_ref *= .001; //Initial calculations //Power block design power q_des = w_des/eta_des; //[MWt] //Maximum energy in storage etesmax = hrs_tes*q_des; //[MW-hr] //Express the dispatch values in dimensional terms for(int i=0; i<ntod; i++){ disws[i] *= etesmax; diswos[i] *= etesmax; qdisp[i] *= q_des; fdisp[i] *= q_des; } /* Set up the optical table object.. The input should be defined as follows: - Data of size nx, ny - OpticalTable of size (nx+1)*(ny+1) - First nx+1 values (row 1) are x-axis values, not data, starting at index 1 - First value of remaining ny rows are y-axis values, not data - Data is contained in cells i,j : where i>1, j>1 A second option using an unstructured array is also possible. The data should be defined as: - N rows - 3 values per row - Azimuth, Zenith, Efficiency point If the OpticalTableUns is given data, it will be used by default. */ if( ! istableunsorted ) { /* Standard azimuth-elevation table */ //does the table look right? if( (nrow_OpticalTable < 5 && ncol_OpticalTable > 3 ) || (ncol_OpticalTable == 3 && nrow_OpticalTable > 4) ) message(TCS_WARNING, "The optical efficiency table option flag may not match the specified table format. If running SSC, ensure \"IsTableUnsorted\"" " =0 if regularly-spaced azimuth-zenith matrix is used and =1 if azimuth,zenith,efficiency points are specified."); if ( nrow_OpticalTable<=0 || ncol_OpticalTable<=0 ) // If these were not set correctly, it will create memory allocation crash not caught by error handling. return -1; double *xax = new double[ncol_OpticalTable-1]; double *yax = new double[nrow_OpticalTable-1]; double *data = new double[(ncol_OpticalTable -1) * (nrow_OpticalTable -1)]; //get the xaxis data values for(int i=1; i<ncol_OpticalTable; i++){ xax[i-1] = OpticalTable.at(0, i)*d2r; } //get the yaxis data values for(int j=1; j<nrow_OpticalTable; j++){ yax[j-1] = OpticalTable.at(j, 0)*d2r; } //Get the data values for(int j=1; j<nrow_OpticalTable; j++){ for(int i=1; i<ncol_OpticalTable; i++){ data[ i-1 + (ncol_OpticalTable-1)*(j-1) ] = OpticalTable.at(j, i); } } optical_table.AddXAxis(xax, ncol_OpticalTable-1); optical_table.AddYAxis(yax, nrow_OpticalTable-1); optical_table.AddData(data); delete [] xax; delete [] yax; delete [] data; } else { /* Use the unstructured data table */ /* ------------------------------------------------------------------------------ Create the regression fit on the efficiency map ------------------------------------------------------------------------------ */ if(ncol_OpticalTable != 3){ message(TCS_ERROR, "The heliostat field efficiency file is not formatted correctly. Type expects 3 columns" " (zenith angle, azimuth angle, efficiency value) and instead has %d cols.", ncol_OpticalTable); return -1; } MatDoub sunpos; vector<double> effs; //read the data from the array into the local storage arrays sunpos.resize(nrow_OpticalTable, VectDoub(2)); effs.resize(nrow_OpticalTable); double eff_maxval = -9.e9; for(int i=0; i<nrow_OpticalTable; i++){ sunpos.at(i).at(0) = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 0 ) / az_scale * pi/180.; sunpos.at(i).at(1) = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 1 ) / zen_scale * pi/180.; double eff = TCS_MATRIX_INDEX( var( P_OPTICALTABLE ), i, 2 ); effs.at(i) = eff; if(eff > eff_maxval) eff_maxval = eff; } //scale values based on maximum. This helps the GM interpolation routine eff_scale = eff_maxval; for( int i=0; i<nrow_OpticalTable; i++) effs.at(i) /= eff_scale; //Create the field efficiency table Powvargram vgram(sunpos, effs, 1.99, 0.); optical_table_uns = new GaussMarkov(sunpos, effs, vgram); //test how well the fit matches the data double err_fit = 0.; int npoints = (int)sunpos.size(); for(int i=0; i<npoints; i++){ double zref = effs.at(i); double zfit = optical_table_uns->interp( sunpos.at(i) ); double dz = zref - zfit; err_fit += dz * dz; } err_fit = sqrt(err_fit); if( err_fit > 0.01 ) message(TCS_WARNING, "The heliostat field interpolation function fit is poor! (err_fit=%f RMS)", err_fit); } //Calculate min/max turbine operation rates qttmin = q_des*f_wmin; qttmax = q_des*f_wmax; //Calculate max TES charging/discharging rates based on solar multiple ptsmax = q_des * solarm; pfsmax = ptsmax / f_disch*f_wmax; //Set initial storage values etes0 = f_etes_0*etesmax; //[MW-hr] Initial value in thermal storage. This keeps track of energy in thermal storage, or e_in_tes pbmode0 = 0; //[-] initial value of power block operation mode pbmode q_startup_remain = f_startup*q_des; //[MW-hr] Initial value of turbine startup energy q_startup_used return true; } void init_sf() { //---- Calculate the "normalized" design-point thermal power. //---Design point values--- //Calculate the design point efficiency based on the solar position at solstice noon, rather than maxval of the table omega = 0.0; //solar noon dec = 23.45*d2r; //declination at summer solstice //Solar altitude at noon on the summer solstice solalt = asin(sin(dec)*sin(latitude)+cos(latitude)*cos(dec)*cos(omega)); double opt_des; if(istableunsorted) { // Use current solar position to interpolate field efficiency table and find solar field efficiency vector<double> sunpos; sunpos.push_back(0.); sunpos.push_back((pi/2. - solalt)/zen_scale); opt_des = optical_table_uns->interp( sunpos ) * eff_scale; } else { opt_des = interp_arr == 1 ? optical_table.interpolate(0.0, max(pi/2.-solalt, 0.0)) : optical_table.nearest(0.0, max(pi/2.-solalt, 0.0)) ; } eta_opt_ref = eta_opt_soil*eta_opt_gen*opt_des; f_qsf = qsf_des/(irr_des*eta_opt_ref*(1.-f_sfhl_ref)); //[MWt/([W/m2] * [-] * [-])] return; } virtual int call(double time, double step, int ncall){ /* -- Standard timestep call -- *get inputs *do calculations *set outputs */ //record the start time if(start_time < 0){ start_time = current_time(); } //If the solar field design point hasn't yet been initialized, do so here. if(! is_sf_init){ //Re-read the location info from the weather reader latitude = value(P_LATITUDE)*d2r; longitude = value(P_LONGITUDE)*d2r; timezone = value(P_TIMEZONE); init_sf(); is_sf_init = true; } //****************************************************************************************************************************** // Time-dependent conditions //****************************************************************************************************************************** ibn = value(I_IBN); //Beam-normal (DNI) irradiation [W/m^2] ibh = value(I_IBH); //Beam-horizontal irradiation [W/m^2] itoth = value(I_ITOTH); //Total horizontal irradiation [W/m^2] tdb = value(I_TDB); //Ambient dry-bulb temperature [C] twb = value(I_TWB); //Ambient wet-bulb temperature [C] vwind = value(I_VWIND); //Wind velocity [m/s] double shift = longitude - timezone*15.*d2r; //int touperiod = CSP::TOU_Reader(tod_sched, time, nval_tod_sched); int touperiod = (int)value(I_TOUPeriod) - 1; // control value between 1 & 9, have to change to 0-8 for array index //Unit conversions tdb += 273.15; twb += 273.15; //Choose which irradiation source will be used switch(rad_type) { case 1: irr_used = ibn; //[W/m2] break; case 2: irr_used = ibh; //[W/m2] break; case 3: irr_used = itoth; //[W/m2] break; } //Choose which dispatch set will be used util::matrix_t<double> dispatch(ntod); if(irr_used>0.){ for(int i=0; i<ntod; i++) dispatch.at(i) = disws[i]; } else{ for(int i=0; i<ntod; i++) dispatch.at(i) = diswos[i]; } //*********** End of input section ********************************************************************************************* //------------------------------------------------------------------------------------------------------------ // Solar field calculations //------------------------------------------------------------------------------------------------------------ hour_of_day = fmod(time/3600., 24.); //hour_of_day of the day (1..24) day_of_year = ceil(time/3600./24.); //Day of the year // Duffie & Beckman 1.5.3b double B = (day_of_year-1)*360.0/365.0*pi/180.0; // Eqn of time in minutes double EOT = 229.2 * (0.000075 + 0.001868 * cos(B) - 0.032077 * sin(B) - 0.014615 * cos(B*2.0) - 0.04089 * sin(B*2.0)); // Declination in radians (Duffie & Beckman 1.6.1) dec = 23.45 * sin(360.0*(284.0+day_of_year)/365.0*pi/180.0) * pi/180.0; // Solar Noon and time in hours double SolarNoon = 12. - ((shift)*180.0/pi) / 15.0 - EOT / 60.0; // 3.13.16 twn: 'TSnow' doesn't seem to be used anywhere, so commenting this out /*double TSnow; if ((hour_of_day - int(hour_of_day)) == 0.00){ TSnow = 1.0; } else{ TSnow = (hour_of_day - floor(hour_of_day))/dt + 1.; }*/ // Deploy & stow times in hours // Calculations modified by MJW 11/13/2009 to correct bug theta_dep = max(theta_dep,1.e-6); double DepHr1 = cos(latitude) / tan(theta_dep); double DepHr2 = -tan(dec) * sin(latitude) / tan(theta_dep); double DepHr3 = (tan(pi-theta_dep) < 0. ? -1. : 1.)*acos((DepHr1*DepHr2 + sqrt(DepHr1*DepHr1-DepHr2*DepHr2+1.0)) / (DepHr1 * DepHr1 + 1.0)) * 180.0 / pi / 15.0; double DepTime = SolarNoon + DepHr3; theta_stow = max(theta_stow,1.e-6); double StwHr1 = cos(latitude) / tan(theta_stow); double StwHr2 = -tan(dec) * sin(latitude) / tan(theta_stow); double StwHr3 = (tan(pi-theta_stow) < 0. ? -1. : 1.)*acos((StwHr1*StwHr2 + sqrt(StwHr1*StwHr1-StwHr2*StwHr2+1.0)) / (StwHr1 * StwHr1 + 1.0)) * 180.0 / pi / 15.0; double StwTime = SolarNoon + StwHr3; // Ftrack is the fraction of the time period that the field is tracking. MidTrack is time at midpoint of operation double HrA = hour_of_day-dt; double HrB = hour_of_day; // Solar field operates double Ftrack, MidTrack; if ((HrB > DepTime) && (HrA < StwTime)){ // solar field deploys during time period if (HrA < DepTime){ Ftrack = (HrB - DepTime) *dt; MidTrack = HrB - Ftrack * 0.5 *dt; // Solar field stows during time period } else if (HrB > StwTime){ Ftrack = (StwTime - HrA) *dt; MidTrack = HrA + Ftrack * 0.5 *dt; } // solar field operates during entire period else{ Ftrack = 1.0; MidTrack = HrA + 0.5 *dt; } } // solar field doesn't operate else{ Ftrack = 0.0; MidTrack = HrA + 0.5 *dt; } double StdTime = MidTrack; soltime = StdTime+((shift)*180.0/pi)/15.0+ EOT/60.0; // hour_of_day angle (arc of sun) in radians omega = (soltime - 12.0)*15.0*pi/180.0; // B. Stine equation for Solar Altitude angle in radians solalt = asin(sin(dec)*sin(latitude)+cos(latitude)*cos(dec)*cos(omega)); solaz = (omega < 0. ? -1. : 1.)*fabs(acos(min(1.0,(cos(pi/2.-solalt)*sin(latitude)-sin(dec))/(sin(pi/2.-solalt)*cos(latitude))))); //Get the current optical efficiency double opt_val; if(istableunsorted) { // Use current solar position to interpolate field efficiency table and find solar field efficiency vector<double> sunpos; sunpos.push_back(solaz/az_scale); sunpos.push_back((pi/2. - solalt)/zen_scale); opt_val = optical_table_uns->interp( sunpos ) * eff_scale; } else { opt_val = interp_arr == 1 ? optical_table.interpolate(solaz, max(pi/2.-solalt, 0.0)) : optical_table.nearest(solaz, max(pi/2.-solalt, 0.0) ); } double eta_arr = max(opt_val*Ftrack, 0.0); //mjw 7.25.11 limit zenith to <90, otherwise the interpolation error message gets called during night hours. eta_opt_sf = eta_arr*eta_opt_soil*eta_opt_gen; //Evaluate solar feild thermal efficiency derate f_sfhl_qdni = 0.; f_sfhl_tamb = 0.; f_sfhl_vwind = 0.; for(int i=0; i<nval_sfhlQ_coefs; i++) f_sfhl_qdni += sfhlQ_coefs[i]*pow(irr_used/irr_des, i); for(int i=0; i<nval_sfhlT_coefs; i++) f_sfhl_tamb += sfhlT_coefs[i]*pow(tdb - T_sfdes, i); for(int i=0; i<nval_sfhlV_coefs; i++) f_sfhl_vwind += sfhlV_coefs[i]*pow(vwind, i); double f_sfhl = 1.0 - f_sfhl_ref * f_sfhl_qdni * f_sfhl_tamb * f_sfhl_vwind; //This ratio indicates the sf thermal efficiency q_hl_sf = f_qsf*irr_used*(1.-f_sfhl)*eta_opt_sf; //[MWt] //Calculate the total solar field thermal output q_sf = f_qsf * f_sfhl * eta_opt_sf * irr_used; //[MWt] //------------------------------------------------------------------------------------------------------------ // Dispatch calculations //------------------------------------------------------------------------------------------------------------ // initialize outputs to 0 q_to_tes = 0.; //| Energy to Thermal Storage q_from_tes = 0.; //| Energy from Thermal Storage e_in_tes = 0.; //| Energy in Thermal Storage q_hl_tes = 0.; //| Energy losses from Thermal Storage q_to_pb = 0.; //| Energy to the Power Block q_dump_tesfull = 0.; //| Energy dumped because the thermal storage is full q_dump_umin = 0.; //| Indicator of being below minimum operation level q_dump_teschg = 0.; //| The amount of energy dumped (more than turbine and storage) q_startup = 0.; //| The energy needed to startup the turbine pbstartf = 0; //| is 1 during the period when powerblock starts up otherwise 0 q_startup_used = q_startup_remain; //| Turbine startup energy for this timestep is equal to the remaining previous energy //--------Plant dispatch strategy-------------------- if (hrs_tes <= 0.){ // No Storage if ((pbmode0==0)||(pbmode0==1)){ // if plant is not already operating in last timestep if (q_sf>0){ if (q_sf>(q_startup_used/dt)){ // Starts plant as exceeds startup energy needed q_to_pb = q_sf - q_startup_used/dt; q_startup = q_startup_used/dt; pbmode = 2; //Power block mode.. 2=starting up pbstartf = 1; //Flag indicating whether the power block starts up in this time period q_startup_used = 0.; //mjw 5-31-13 Reset to zero to handle cases where Qsf-TurSue leads to Qttb < Qttmin } else{ // Plant starting up but not enough energy to make it run - will probably finish in the next timestep q_to_pb = 0.; q_startup_used = q_startup_remain - q_sf*dt; q_startup = q_sf; pbmode = 1; pbstartf = 0; } } else{ // No solar field output so still need same amount of energy as before and nothing changes q_startup_used = f_startup * q_des; pbmode = 0; pbstartf = 0; } } else{ // if the powerblock mode is already 2 (running previous timestep) if (q_sf>0){ // Plant operated last hour_of_day and this one q_to_pb = q_sf; // all power goes from solar field to the powerblock pbmode = 2; // powerblock continuing to operate pbstartf = 0; // powerblock did not start during this timestep } else{ // Plant operated last hour_of_day but not this one q_to_pb = 0.; // No energy to the powerblock pbmode = 0; // turned off powrblock pbstartf = 0; // it didn't start this timeperiod q_startup_used = q_startup_remain; } } // following happens no matter what state the powerblock was in previously if (q_to_pb < qttmin){ // Energy to powerblock less than the minimum that the turbine can run at q_dump_umin = q_to_pb; // The minimum energy (less than the minimum) q_to_pb = 0; // Energy to PB is now 0 pbmode = 0; // PB turned off } if (q_to_pb > qttmax){ // Energy to powerblock greater than what the PB can handle (max) q_dump_teschg = q_to_pb - qttmax; // The energy dumped q_to_pb = qttmax; // the energy to the PB is exactly the maximum } } else{ //With thermal storage //--initialize values q_startup = 0.0; pbstartf = 0; q_dump_teschg = 0.0; q_from_tes = 0.0; if (pbmode0 == 0){ //********************************************************** //****** plant is not already operating ***** //********************************************************** //---Start plant if any of the following conditions are met--- // 1.) Solar field output > 0 // a.) AND energy in TES exceeds w/ solar touperiod fraction // b.) AND energy in TES plus solar field output exceeds turbine fraction // OR // 2.) Solar field is off // a.) AND energy in TES exceeds w/o solar touperiod // b.) AND energy in TES exceeds turbine fraction // OR // 3.) Solar field energy exceeds maximum TES charging rate //------------------------------------------------------------ double EtesA = max(0.0, etes0 - dispatch.at(touperiod)); if ((q_sf + EtesA >= qdisp[touperiod]) || (q_sf > ptsmax)){ // Assumes Operator started plant during previous time period // But TRNSYS cannot do this, so start-up energy is deducted during current timestep. pbmode = 1; q_startup = f_startup * q_des /dt; q_to_pb = qdisp[touperiod]; // set the energy to powerblock equal to the load for this TOU period if (q_sf>q_to_pb){ // if solar field output is greater than what the necessary load ? q_to_tes = q_sf - q_to_pb; // the extra goes to thermal storage q_from_tes = q_startup; // Use the energy from thermal storage to startup the power cycle if (q_to_tes>ptsmax){ // if q to thermal storage exceeds thermal storage max rate Added 9-10-02 q_dump_teschg = q_to_tes - ptsmax; // then dump the excess for this period Added 9-10-02 q_to_tes = ptsmax; } } else{ // q_sf less than the powerblock requirement q_to_tes = 0.0; q_from_tes = q_startup + (1 - q_sf / q_to_pb) * min(pfsmax, q_des); if (q_from_tes>pfsmax) q_from_tes = pfsmax; q_to_pb = q_sf + (1 - q_sf / q_to_pb) * min(pfsmax, q_des); } e_in_tes = etes0 - q_startup + (q_sf - q_to_pb) * dt; // thermal storage energy is initial + what was left pbmode = 2; // powerblock is now running pbstartf = 1; // the powerblock turns on during this timeperiod. } else{ //Store energy not enough stored to start plant q_to_tes = q_sf; // everything goes to thermal storage q_from_tes = 0; // nothing from thermal storage e_in_tes = etes0 + q_to_tes * dt ; q_to_pb = 0; } } else{ //********************************************************** //****** plant is already operating ***** //********************************************************** if ((q_sf + max(0.0,etes0-dispatch.at(touperiod)) /dt) > qdisp[touperiod]){ // if there is sufficient energy to operate at dispatch target output q_to_pb = qdisp[touperiod]; if (q_sf>q_to_pb){ q_to_tes = q_sf - q_to_pb; //extra from what is needed put in thermal storage q_from_tes = 0.; if (q_to_tes>ptsmax){ //check if max power rate to storage exceeded q_dump_teschg = q_to_tes - ptsmax; // if so, dump extra q_to_tes = ptsmax; } } else{ // solar field outptu less than what powerblock needs q_to_tes = 0.; q_from_tes = (1. - q_sf / q_to_pb) * min(pfsmax, q_des); if (q_from_tes>pfsmax) q_from_tes = min(pfsmax, q_des); q_to_pb = q_from_tes + q_sf; } e_in_tes = etes0 + (q_sf - q_to_pb - q_dump_teschg) *dt; // energy of thermal storage is the extra // Check to see if throwing away energy if ( (e_in_tes>etesmax) && (q_to_pb<qttmax) ){ // qttmax (MWt) - power to turbine max if ((e_in_tes - etesmax)/dt < (qttmax - q_to_pb) ){ q_to_pb = q_to_pb + (e_in_tes - etesmax) /dt; e_in_tes = etesmax; } else{ e_in_tes = e_in_tes - (qttmax - q_to_pb) * dt; // should this be etes0 instead of e_in_tes on RHS ?? q_to_pb = qttmax; } q_to_tes = q_sf - q_to_pb; } } else{ //Empties tes to dispatch level if above min load level if ((q_sf + max(0.,etes0-dispatch.at(touperiod)) * dt) > qttmin){ q_from_tes = max(0.,etes0-dispatch.at(touperiod)) * dt; q_to_pb = q_sf + q_from_tes; q_to_tes = 0.; e_in_tes = etes0 - q_from_tes; } else{ q_to_pb = 0.; q_from_tes = 0.; q_to_tes = q_sf; e_in_tes = etes0 + q_to_tes * dt; } } } if (q_to_pb>0) pbmode = 2; else pbmode = 0; //---Calculate TES thermal losses --- // First do the charge-based losses. Use the average charge over the timestep double f_EtesAve = max((e_in_tes + etes0)/2./etesmax, 0.0); double f_teshlX = 0., f_teshlT = 0.; for(int i=0; i<nval_teshlX_coefs; i++) f_teshlX += teshlX_coefs[i]*pow(f_EtesAve, i); //Charge adjustment factor for(int i=0; i<nval_teshlT_coefs; i++) f_teshlT += teshlT_coefs[i]*pow(T_sfdes - tdb, i); //thermal storage heat losses adjusted by charge level and ambient temp. q_hl_tes = f_teshl_ref*etesmax*f_teshlX*f_teshlT; e_in_tes = max(e_in_tes - q_hl_tes*dt, 0.0); // Adjust the energy in thermal storage according to TES thermal losses if (e_in_tes>etesmax){ // trying to put in more than storage can handle q_dump_tesfull = (e_in_tes - etesmax)/dt; //this is the amount dumped when storage is completely full e_in_tes = etesmax; q_to_tes = q_to_tes - q_dump_tesfull; } else{ q_dump_tesfull = 0.; // nothing is dumped if not overfilled } // Check min and max on turbine if (q_to_pb<qttmin){ q_dump_umin = q_to_pb; q_to_pb = 0.; pbmode = 0; } else{ q_dump_umin = 0; } pbmode0 = pbmode; } //------------------------------------------------------------------------------------------------------------ // Fossil backup //------------------------------------------------------------------------------------------------------------ // 5.23.16 twn bug fix (see svn) if( q_to_pb < fdisp[touperiod] ) { // If the thermal power dispatched to the power cycle is less than the level in the fossil control q_fossil = fdisp[touperiod] - q_to_pb; // then the fossil used is the fossil control value minus what's provided by the solar field q_gas = q_fossil / eta_lhv; // Calculate the required fossil heat content based on the LHV efficiency } else { q_fossil = 0.0; q_gas = 0.0; } //if (q_sf < fdisp[touperiod]){ // if the solar provided is less than the level stipulated in the fossil control // q_fossil = fdisp[touperiod] - q_sf; // then the fossil used is the fossil control value minus what's provided by the solar field // q_gas = q_fossil / eta_lhv; // Calculate the required fossil heat content based on the LHV efficiency //} //else{ // q_fossil = 0.; // q_gas = 0.; //} //Adjust the power block energy based on additional fossil backup q_to_pb = q_to_pb + q_fossil; //------------------------------------------------------------------------------------------------------------ // Power block calculations //------------------------------------------------------------------------------------------------------------ double qnorm = q_to_pb/q_des; //The normalized thermal energy flow double tnorm; if(PC_T_corr==1.) //Select the dry or wet bulb temperature as the driving difference tnorm = twb - T_pcdes; else tnorm = tdb - T_pcdes; //Calculate the load-based and temperature-based efficiency correction factors f_effpc_qtpb = 0.; f_effpc_tamb = 0.; for(int i=0; i<nval_etaQ_coefs; i++) f_effpc_qtpb += etaQ_coefs[i]*pow(qnorm, i); for(int i=0; i<nval_etaT_coefs; i++) f_effpc_tamb += etaT_coefs[i]*pow(tnorm, i); eta_cycle = eta_des * f_effpc_qtpb * f_effpc_tamb; //Adjusted power conversion efficiency if(q_to_pb <= 0.) eta_cycle = 0.0; //Set conversion efficiency to zero when the power block isn't operating //Calculate the gross power w_gr = q_to_pb * eta_cycle; //Keep track of what portion is from solar w_gr_solar = (q_to_pb - q_fossil)*eta_cycle; //------------------------------------------------------------------------------------------------------------ // Parasitics //------------------------------------------------------------------------------------------------------------ w_par_fixed = f_Wpar_fixed * w_des; //Fixed parasitic loss based on plant capacity //Production-based parasitic loss double wpar_prodq = 0., wpar_prodt = 0.; for(int i=0; i<nval_Wpar_prodQ_coefs; i++) wpar_prodq += Wpar_prodQ_coefs[i]*pow(qnorm, i); //Power block part-load correction factor for(int i=0; i<nval_Wpar_prodT_coefs; i++) wpar_prodt += Wpar_prodT_coefs[i]*pow(tnorm, i); //Temperature correction factor w_par_prod = f_Wpar_prod * w_gr * wpar_prodq * wpar_prodt; w_par_tot = w_par_fixed + w_par_prod; //Total parasitic loss //Keep track of online/offline parasitics if(w_gr > 0.){ w_par_online = w_par_tot; w_par_offline = 0.; } else{ w_par_online = 0.; w_par_offline = w_par_tot; } //---Calculate net energy output (enet<-->Wnet) --- enet = w_gr - w_par_tot; //Calculate final values declination = dec*r2d; //[deg] Declination angle hrangle = omega*r2d; //[deg] hour_of_day angle solalt = max(solalt*r2d, 0.0); //[deg] Solar elevation angle solaz = solaz*r2d; //[deg] Solar azimuth angle (-180..180, 0deg=South) q_inc = f_qsf*irr_used; //[MWt] Qdni - Solar incident energy, before all losses q_dump_tot = q_dump_tesfull + q_dump_teschg + q_dump_umin; //[MWt] Total dumped energy w_gr_fossil = w_gr - w_gr_solar; //[MWe] Power produced from the fossil component //Set outputs and return value(O_IRR_USED, irr_used); //[W/m2] Irradiation value used in simulation value(O_HOUR_OF_DAY, hour_of_day); //[hour_of_day] hour_of_day of the day value(O_DAY_OF_YEAR, day_of_year); //[day] Day of the year value(O_DECLINATION, declination); //[deg] Declination angle value(O_SOLTIME, soltime); //[hour_of_day] [hour_of_day] Solar time of the day value(O_HRANGLE, hrangle); //[deg] hour_of_day angle value(O_SOLALT, solalt); //[deg] Solar elevation angle value(O_SOLAZ, solaz); //[deg] Solar azimuth angle (-180..180, 0deg=South) value(O_ETA_OPT_SF, eta_opt_sf); //[none] Solar field optical efficiency value(O_F_SFHL_QDNI, f_sfhl_qdni); //[none] Solar field load-based thermal loss correction value(O_F_SFHL_TAMB, f_sfhl_tamb); //[none] Solar field temp.-based thermal loss correction value(O_F_SFHL_VWIND, f_sfhl_vwind); //[none] Solar field wind-based thermal loss correction value(O_Q_HL_SF, q_hl_sf); //[MWt] Solar field thermal losses value(O_Q_SF, q_sf); //[MWt] Solar field delivered thermal power value(O_Q_INC, q_inc); //[MWt] Qdni - Solar incident energy, before all losses value(O_PBMODE, pbmode); //[none] Power conversion mode value(O_PBSTARTF, pbstartf); //[none] Flag indicating power system startup value(O_Q_TO_PB, q_to_pb); //[MWt] Thermal energy to the power conversion system value(O_Q_STARTUP, q_startup); //[MWt] Power conversion startup energy value(O_Q_TO_TES, q_to_tes); //[MWt] Thermal energy into storage value(O_Q_FROM_TES, q_from_tes); //[MWt] Thermal energy from storage value(O_E_IN_TES, e_in_tes); //[MWt-hr] Energy in storage value(O_Q_HL_TES, q_hl_tes); //[MWt] Thermal losses from storage value(O_Q_DUMP_TESFULL, q_dump_tesfull); //[MWt] Dumped energy exceeding storage charge level max value(O_Q_DUMP_TESCHG, q_dump_teschg); //[MWt] Dumped energy exceeding exceeding storage charge rate value(O_Q_DUMP_UMIN, q_dump_umin); //[MWt] Dumped energy from falling below min. operation fraction value(O_Q_DUMP_TOT, q_dump_tot); //[MWt] Total dumped energy value(O_Q_FOSSIL, q_fossil); //[MWt] thermal energy supplied from aux firing value(O_Q_GAS, q_gas); //[MWt] Energy content of fuel required to supply Qfos value(O_F_EFFPC_QTPB, f_effpc_qtpb); //[none] Load-based conversion efficiency correction value(O_F_EFFPC_TAMB, f_effpc_tamb); //[none] Temp-based conversion efficiency correction value(O_ETA_CYCLE, eta_cycle); //[none] Adjusted power conversion efficiency value(O_W_GR_SOLAR, w_gr_solar); //[MWe] Power produced from the solar component value(O_W_GR_FOSSIL, w_gr_fossil); //[MWe] Power produced from the fossil component value(O_W_GR, w_gr); //[MWe] Total gross power production value(O_W_PAR_FIXED, w_par_fixed); //[MWe] Fixed parasitic losses value(O_W_PAR_PROD, w_par_prod); //[MWe] Production-based parasitic losses value(O_W_PAR_TOT, w_par_tot); //[MWe] Total parasitic losses value(O_W_PAR_ONLINE, w_par_online); //[MWe] Online parasitics value(O_W_PAR_OFFLINE, w_par_offline); //[MWe] Offline parasitics value(O_ENET, enet); //[MWe] Net electric output return 0; } virtual int converged(double time){ /* -- Post-convergence call -- Update values that should be transferred to the next time step */ etes0 = e_in_tes; pbmode0 = pbmode; q_startup_remain = q_startup_used; return 0; } }; TCS_IMPLEMENT_TYPE( sam_mw_gen_type260, "Generic Solar Model", "Mike Wagner", 1, sam_mw_gen_type260_variables, NULL, 1 );
53.729385
260
0.549997
gjsoto
75e5596aee746778f78381cffe406ad07ffb5f1a
5,682
cpp
C++
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ cam.setDistance(2500); gui.setup(); gui.add( toggle_0.setup("inside box",false)); gui.add( toggle_1.setup("outside box1",false)); gui.add( toggle_4.setup("outside box2",false)); gui.add( toggle_2.setup("Rotate Auto",false)); gui.add( toggle_3.setup("Rotate Mouse",false)); gui.add( xslider.setup("inside box x",180.0,0.0,360.0)); gui.add( yslider.setup("inside box y",180.0,0.0,360.0)); gui.add( zslider.setup("inside box z",180.0,0.0,360.0)); gui.add( xslider_1.setup("outside box1 x",180.0,0.0,360.0)); gui.add( yslider_1.setup("outside box1 y",180.0,0.0,360.0)); gui.add( zslider_1.setup("outside box1 z",180.0,0.0,360.0)); gui.add( xslider_2.setup("outside box2 x",180.0,0.0,360.0)); gui.add( yslider_2.setup("outside box2 y",180.0,0.0,360.0)); gui.add( zslider_2.setup("outside box2 z",180.0,0.0,360.0)); gui.add(color.setup("back ground color", ofColor(0, 0, 0), ofColor(0, 0), ofColor(255, 255))); gui.add( int_slider_0.setup("number of inside box ",100.0,1.0,1500.0)); gui.add( int_slider_1.setup("number of outside box ",100.0,1.0,1500.0)); gui.add( int_slider_2.setup("number of outside box ",100.0,1.0,1500.0)); bHide = false; open = true; open1 = true; open2 =true; open3=true; open4=true; on = false; for(int i=0;i<int_slider_0;i++){ Box tmp= Box(); boxes.push_back(tmp); } for(int i=0;i<int_slider_1;i++){ Box2 tmp= Box2(); boxes2.push_back(tmp); } for(int i=0;i<int_slider_2;i++){ Box3 tmp= Box3(); boxes3.push_back(tmp); } rotate_x=0; rotate_y=0; rotate_z=0; ofSetFrameRate(60); ofGetFrameNum(); } //-------------------------------------------------------------- void ofApp::update(){ for(int i=0;i< int_slider_0;i++){ boxes[i].update(); } for(int i=0;i< int_slider_1;i++){ boxes2[i].update(); } for(int i=0;i< int_slider_2;i++){ boxes3[i].update(); } rotate_x += 0.3; rotate_y += 0.3; rotate_z += 0.3; ofBackground(color); } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); ofEnableDepthTest(); //rotate------------------------------ if(open2){ if(toggle_2 == true){ ofRotateX(rotate_x); ofRotateY(rotate_y); ofRotateZ(rotate_z); } } //Rotate auto-------------------------- if(open3){ if(toggle_3 == true){ ofRotateX(ofGetMouseX()); ofRotateY(ofGetMouseY()); } } //inside box--------------------------- ofPushMatrix(); if(open){ ofRotate(100, xslider, yslider, zslider); if( toggle_0 == true ){ for(int i=0; i < int_slider_0 ; i++){ boxes[i].draw(); Box tmp =Box(); boxes.push_back(tmp); } } } ofPopMatrix(); //outside box-------------------------- ofPushMatrix(); if(open1){ ofRotate(100, xslider_1, yslider_1, zslider_1); if( toggle_1 == true ){ for(int i=0; i < int_slider_1 ; i++){ boxes2[i].draw(); Box2 tmp =Box2(); boxes2.push_back(tmp); } } } ofPopMatrix(); //outside box-------------------------- ofPushMatrix(); if(open4){ ofRotate(100, xslider_2, yslider_2, zslider_2); if( toggle_4 == true ){ for(int i=0; i < int_slider_2 ; i++){ boxes3[i].draw(); Box3 tmp =Box3(); boxes3.push_back(tmp); } } } ofPopMatrix(); ofDisableDepthTest(); cam.end(); ofPopMatrix(); if(!bHide){ gui.draw(); } ofPushMatrix(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == 'h'){ bHide = !bHide; } if(key == 'f'){ ofToggleFullscreen(); } if(key == '1'){ color = ofColor(255); } if(key == '2'){ color = ofColor(0); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
23.774059
76
0.416579
ryo-simon-mf
75e84d7d6d90fe98b2bfa0f7278e9fe2c28f7805
7,971
cpp
C++
oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp
xriss/gamecake
015e6d324761f46235ee61a61a71dbd9a49f6192
[ "MIT" ]
28
2017-04-20T06:21:26.000Z
2021-12-10T15:22:51.000Z
oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp
sahwar/gamecake
9abcb937c0edc22dee2940cb06ec9a84597e989c
[ "MIT" ]
3
2017-04-05T00:41:45.000Z
2020-04-04T00:44:24.000Z
oldcode/lib_angle/tests/perf_tests/angle_perf_test_main.cpp
sahwar/gamecake
9abcb937c0edc22dee2940cb06ec9a84597e989c
[ "MIT" ]
5
2016-11-26T14:44:55.000Z
2021-07-29T04:25:53.000Z
// // Copyright (c) 2014 The ANGLE Project 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 "SimpleBenchmark.h" #include "BufferSubData.h" #include "TexSubImage.h" #include "PointSprites.h" #include <iostream> #include <rapidjson/document.h> #include <rapidjson/filestream.h> namespace { template <class T> struct Optional { Optional() : valid(false), value(T()) {} explicit Optional(T valueIn) : valid(true), value(valueIn) {} Optional(const Optional &other) : valid(other.valid), value(other.value) {} Optional &operator=(const Optional &other) { this.valid = other.valid; this.value = otehr.value; return *this; } static Optional None() { return Optional(); } bool valid; T value; }; Optional<std::string> GetStringMember(const rapidjson::Document &document, const char *name) { auto typeIt = document.FindMember(name); if (typeIt == document.MemberEnd() || !typeIt->value.IsString()) { std::cerr << "JSON has missing or bad string member '" << name << "'" << std::endl; return Optional<std::string>::None(); } return Optional<std::string>(typeIt->value.GetString()); } Optional<bool> GetBoolMember(const rapidjson::Document &document, const char *name) { auto typeIt = document.FindMember(name); if (typeIt == document.MemberEnd() || !typeIt->value.IsBool()) { std::cerr << "JSON has missing or bad bool member '" << name << "'" << std::endl; return Optional<bool>::None(); } return Optional<bool>(typeIt->value.GetBool()); } Optional<int> GetIntMember(const rapidjson::Document &document, const char *name) { auto typeIt = document.FindMember(name); if (typeIt == document.MemberEnd() || !typeIt->value.IsInt()) { std::cerr << "JSON has missing or bad int member '" << name << "'" << std::endl; return Optional<int>::None(); } return Optional<int>(typeIt->value.GetInt()); } Optional<unsigned int> GetUintMember(const rapidjson::Document &document, const char *name) { auto typeIt = document.FindMember(name); if (typeIt == document.MemberEnd() || !typeIt->value.IsUint()) { std::cerr << "JSON has missing or bad uint member '" << name << "'" << std::endl; return Optional<unsigned int>::None(); } return Optional<unsigned int>(typeIt->value.GetUint()); } EGLint ParseRendererType(const std::string &value) { if (value == "d3d11") { return EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE; } else if (value == "d3d9") { return EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE; } else if (value == "warp") { // TODO(jmadill): other attributes for warp return EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE; } else if (value == "default") { return EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE; } else { return EGL_NONE; } } GLenum ParseAttribType(const std::string &value) { if (value == "float") { return GL_FLOAT; } else if (value == "int") { return GL_INT; } else if (value == "uint") { return GL_UNSIGNED_INT; } else if (value == "short") { return GL_SHORT; } else if (value == "ushort") { return GL_UNSIGNED_SHORT; } else if (value == "byte") { return GL_BYTE; } else if (value == "ubyte") { return GL_UNSIGNED_BYTE; } else { return GL_NONE; } } bool ParseBenchmarkParams(const rapidjson::Document &document, BufferSubDataParams *params) { // Validate params auto type = GetStringMember(document, "type"); auto components = GetUintMember(document, "components"); auto normalized = GetBoolMember(document, "normalized"); auto updateSize = GetUintMember(document, "update_size"); auto bufferSize = GetUintMember(document, "buffer_size"); auto iterations = GetUintMember(document, "iterations"); auto updateRate = GetUintMember(document, "update_rate"); if (!type.valid || !components.valid || !normalized.valid || !updateSize.valid || !bufferSize.valid || !iterations.valid || !updateRate.valid) { return false; } GLenum vertexType = ParseAttribType(type.value); if (vertexType == GL_NONE) { std::cerr << "Invalid attribute type: " << type.value << std::endl; return false; } if (components.value < 1 || components.value > 4) { std::cerr << "Invalid component count: " << components.value << std::endl; return false; } if (normalized.value && vertexType == GL_FLOAT) { std::cerr << "Normalized float is not a valid vertex type." << std::endl; return false; } if (bufferSize.value == 0) { std::cerr << "Zero buffer size is not valid." << std::endl; return false; } if (iterations.value == 0) { std::cerr << "Zero iterations not valid." << std::endl; return false; } params->vertexType = vertexType; params->vertexComponentCount = components.value; params->vertexNormalized = normalized.value; params->updateSize = updateSize.value; params->bufferSize = bufferSize.value; params->iterations = iterations.value; params->updateRate = updateRate.value; return true; } bool ParseBenchmarkParams(const rapidjson::Document &document, TexSubImageParams *params) { // TODO(jmadill): Parse and validate parameters params->imageWidth = 1024; params->imageHeight = 1024; params->subImageHeight = 64; params->subImageWidth = 64; params->iterations = 10; return true; } bool ParseBenchmarkParams(const rapidjson::Document &document, PointSpritesParams *params) { // TODO(jmadill): Parse and validate parameters params->iterations = 10; params->count = 10; params->size = 3.0f; params->numVaryings = 3; return true; } template <class BenchT> int ParseAndRunBenchmark(EGLint rendererType, const rapidjson::Document &document) { BenchT::Params params; if (!ParseBenchmarkParams(document, &params)) { // Parse or validation error return 1; } params.requestedRenderer = rendererType; BenchT benchmark(params); // Run the benchmark return benchmark.run(); } } int main(int argc, char **argv) { if (argc < 3) { std::cerr << "Must specify a renderer and source json file." << std::endl; return 1; } EGLint rendererType = ParseRendererType(std::string(argv[1])); if (rendererType == EGL_NONE) { std::cerr << "Invalid renderer type: " << argv[1] << std::endl; return 1; } FILE *fp = fopen(argv[2], "rt"); if (fp == NULL) { std::cerr << "Cannot open " << argv[2] << std::endl; return 1; } rapidjson::FileStream fileStream(fp); rapidjson::Document document; if (document.ParseStream(fileStream).HasParseError()) { std::cerr << "JSON Parse error code " << document.GetParseError() << "." << std::endl; return 1; } fclose(fp); auto testName = GetStringMember(document, "test"); if (!testName.valid) { return 1; } if (testName.value == "BufferSubData") { return ParseAndRunBenchmark<BufferSubDataBenchmark>(rendererType, document); } else if (testName.value == "TexSubImage") { return ParseAndRunBenchmark<TexSubImageBenchmark>(rendererType, document); } else if (testName.value == "PointSprites") { return ParseAndRunBenchmark<PointSpritesBenchmark>(rendererType, document); } else { std::cerr << "Unknown test: " << testName.value << std::endl; return 1; } }
24.601852
94
0.613474
xriss
75ec66a2cf5a8b24571f5449a2d43f2dc1b23e8f
1,054
cpp
C++
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-01-02T10:29:32.000Z
2022-01-02T10:29:32.000Z
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
null
null
null
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-03-04T12:44:14.000Z
2022-03-04T12:44:14.000Z
class Solution { public: int minimumDeviation(vector<int>& nums) { set <int> s; // Storing all elements in sorted order //insert even directly and odd with one time multiplication //and it will become even for(int i = 0; i<nums.size() ; ++i) { if(nums[i] % 2 == 0) s.insert(nums[i]); else // Odd number are transformed // using 2nd operation s.insert(nums[i] * 2); } // maximum - minimun int diff = *s.rbegin() - *s.begin(); //run the loop untill difference is minimized while(*s.rbegin() % 2 == 0) { // Maximum element of the set int x = *s.rbegin(); s.erase(x); // remove begin element and inserted half of it for minimizing s.insert(x/2); diff = min(diff, *s.rbegin() - *s.begin()); } return diff; } };
28.486486
74
0.446869
Jatin-Shihora
75ec9806e7f829e74e31082fb3e7c290a58961f6
4,810
cpp
C++
SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp
Samsung/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
27
2015-04-24T07:14:55.000Z
2020-01-24T16:16:37.000Z
SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp
Lousnote5/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
null
null
null
SVIEngine/jni/SVI/Render/Geometry/SVIPathPoly.cpp
Lousnote5/SVIEngine
36964f5b296317a3b7b2825137fef921a8c94973
[ "Apache-2.0" ]
15
2015-12-08T14:46:19.000Z
2020-01-21T19:26:41.000Z
#include "../../SVICores.h" #include "../../Slide/SVIBaseSlide.h" #include "../../Slide/SVIProjectionSlide.h" #include "../../Slide/SVIRenderPartManager.h" #include "../SVITexture.h" #include "../SVITextureManager.h" #include "../SVIProgramManager.h" #include "../SVIDebugRenderer.h" #include "../SVIViewport.h" #include "../SVIRenderer.h" #include "../SVIRenderPatch.h" #include "SVIPoly.h" #include "SVIPathPoly.h" namespace SVI { const float cfTestDepth = 1.0f; static const SVIBool DEBUG = SVIFALSE; #define MAX_PATH_POINT 300 /****************************************************************************/ // real time path polygon /****************************************************************************/ SVIPathPoly::SVIPathPoly(SVIGLSurface* surface):SVIPoly(surface){ mHasAdditionalRender = SVIFALSE; mNeedTexcoords = SVITRUE; mNeedIndices = SVITRUE; mNeedNormals = SVIFALSE; mIsAA = SVIFALSE; mAACoord = NULL; mWidth = 200.0f; for (int n = 0; n < 1000; n++){ mWidthFactor.push_back( (float)(rand()%100 - 50) * 0.01f); } } void SVIPathPoly::setup() { //vertices for triangle strip setPrimitiveType(SVI_POLY_TRI_STRIP); } SVIPathPoly::~SVIPathPoly() { } void SVIPathPoly::buildVertices() { SVIFloat widthHalf = mWidth * 0.5f; size_t pathCount = mPath.size(); float distancePath = 0.0f; if (pathCount <= 1) { return; } std::vector<SVIVector3> swapVertices; swapVertices.reserve(0); mPathVertices.swap(swapVertices); mPathVertices.clear(); std::vector<SVIVector2> swapTexCoord; swapTexCoord.reserve(0); mPathTexCoord.swap(swapTexCoord); mPathTexCoord.clear(); std::vector<SVIUShort> swapIndices; swapIndices.reserve(0); mPathIndices.swap(swapIndices); mPathIndices.clear(); std::vector<SVIVector3> swapShadowVertices; swapShadowVertices.reserve(0); mShadowVertices.swap(swapShadowVertices); mShadowVertices.clear(); SVISize size = mSVIGLSurface->getRenderPartManager()->getSize(); SVIUShort index = 0; int width_index = 0; for (size_t n = 0; n < pathCount-1; n++){ SVIVector3 direction = mPath[n+1] - mPath[n]; SVIVector3 up = SVIVector3(0,0,1.0f); SVIVector3 side = up.Cross(direction); side.normalize(); widthHalf = mPath[n].z * 0.5f; SVIVector3 vertexA = mPath[n] - side * widthHalf; SVIVector3 vertexB = mPath[n] + side * widthHalf; mPathVertices.push_back(vertexA); mPathVertices.push_back(vertexB); float shadowWidth = mWidthFactor[width_index++]; width_index = width_index % 1000; vertexA = mPath[n] - side * widthHalf * 1.1f; vertexB = mPath[n] + side * widthHalf * 1.1f; vertexA -= side * shadowWidth * mPath[n].z * 0.08f; vertexB += side * shadowWidth * mPath[n].z * 0.08f; mShadowVertices.push_back(vertexA); mShadowVertices.push_back(vertexB); mPathIndices.push_back(index); mPathIndices.push_back(index+1); index += 2; //SVIDebugRenderer::drawPoint(vertexA, SVIVector4(1,1,1,1)); //SVIDebugRenderer::drawPoint(vertexB, SVIVector4(1,1,1,1)); } mVerticeCount = mPathVertices.size(); mIndicesCount = mPathIndices.size(); for (int n = 0; n < mPathVertices.size(); n++) { float u = (mPathVertices[n].x / (float)mOutpit->mSize.x); float v = (mPathVertices[n].y / (float)mOutpit->mSize.y); mPathTexCoord.push_back(SVIVector2(u, v)); } mVertices = &mPathVertices[0]; mIndices = &mPathIndices[0]; mTextureCoords = &mPathTexCoord[0]; //2011-05-26 ignore z centering //mVertices[SVI_QUAD_LEFT_TOP].x = fInverseXValue * fXDistance - width; //mVertices[SVI_QUAD_LEFT_TOP].y = fInverseYValue * fYDistance - width; } void SVIPathPoly::addPath(float x, float y){ mPath.push_back(SVIVector3(x,y,0.0f)); mNeedToUpdate = SVITRUE; } void SVIPathPoly::clearPath(){ std::vector<SVIVector3> swapVertices; swapVertices.reserve(0); mPath.swap(swapVertices); mPath.clear(); mNeedToUpdate = SVITRUE; } void SVIPathPoly::setWidth(SVIFloat width) { mWidth = width; mNeedToUpdate = SVITRUE; } void SVIPathPoly::setOutfit(SVISlideOutfit * pOutpit){ mOutpit = pOutpit; clearPath(); if (!mOutpit->mPathPoints.empty()){ mPath.assign(mOutpit->mPathPoints.begin(),mOutpit->mPathPoints.end()); } mNeedToUpdate = SVITRUE; } void SVIPathPoly::additionalRender(SVISlideTextureContainer * pContainer) { } SVIInt SVIPathPoly::generatePath() { return 0; } void SVIPathPoly::buildTextureCoordinates() { } }
24.05
106
0.624116
Samsung
75f00f39fe0f4a39addc90305154e7c6205e9604
1,415
cpp
C++
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
3
2019-04-15T14:16:53.000Z
2019-04-26T09:37:19.000Z
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
1
2019-03-11T19:10:33.000Z
2019-03-11T19:10:33.000Z
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
1
2019-04-26T09:38:04.000Z
2019-04-26T09:38:04.000Z
#include <iostream> #include <cstdlib> #include <fstream> #include <string> #include <vector> using namespace std; string zad4_3() { string line; vector<string> content; fstream file("../dane/sygnaly.txt"); // wczytywanie danych z pliku do vectora if (file.is_open()) { while (getline(file, line)) content.push_back(line); } file.close(); // przypisanie zmiennym numerów odpowiadających za pierwszą literę alfabetu w tablicy ASCII (65) // oraz za ostatnią (90) int minAscii = 90; int maxAscii = 65; vector<char> word; vector<string> answerVector; for (int i = 0; i < content.size(); i++) { for (int j = 0; j < content[i].size(); j++) { word.push_back(content[i][j]); } for (int j = 0; j < word.size(); j++) { if (char(word[j]) < minAscii) minAscii = char(word[j]); if (char(word[j]) > maxAscii) maxAscii = char(word[j]); } if (maxAscii - minAscii <= 10) answerVector.push_back(content[i]); word.clear(); minAscii = 90; maxAscii = 65; } string answer = "\n"; for (int i = 0; i < answerVector.size(); i++) answer += answerVector[i] + "\n"; return "4.3. Slowa, w ktorych litery sa maksymalnie oddalone od siebie o 10 znakow: " + answer; }
23.583333
100
0.543463
shilangyu
75f54a8a5cd7b7687c44b8069274ff56398e4f0e
1,587
cpp
C++
src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp
ogycode/CPPFromZero
9df9a9a19850642941ef92bdef9e59477baca202
[ "Apache-2.0" ]
null
null
null
src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp
ogycode/CPPFromZero
9df9a9a19850642941ef92bdef9e59477baca202
[ "Apache-2.0" ]
null
null
null
src/034.STL_UniqueUnique_Copy/034.STL_UniqueUnique_Copy.cpp
ogycode/CPPFromZero
9df9a9a19850642941ef92bdef9e59477baca202
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" using namespace std; bool Pred(const int &i, const int &g) { return i == g; } int main() { system("color 70"); setlocale(0, "Russina"); SetConsoleTitle("034.STL_Unique Unique_Copy"); vector<int> vec{ 1,3,4,4,4,4,67,4,55,2,2,2,2,4,1,5 }; //отсортируем вектор дл¤ стабильной работы алгоритма unique sort(vec.begin(), vec.end()); cout << "Vector befor unique:" << endl; for (auto i : vec) cout << i << " "; cout << endl; //коди ниже удал¤ет элементы в диапазоне которые повтор¤ютс¤ остав뤤 только первое вхождение //этого элемента в коллекции, т.е. коллекци¤ не будет иметь одинаковых элементов //так как алгоритм перезаписует некторые элементы и не измен¤ет размера коллекции //то необходимо удалить неопределенные элементы методом erase auto iter = unique(vec.begin(), vec.end(), Pred); vec.erase(iter, vec.end()); cout << "Vector after unique:" << endl; for (auto i : vec) cout << i << " "; cout << endl; vector<int> vec2{ 4,55,11,11,11,34,5,6,6,3,32,2,22,4,66,66,6,5,5,3,3,5 }; //отсортируем вектор дл¤ стабильной работы алгоритма unique sort(vec2.begin(), vec2.end()); vector<int> vec3; cout << "Vector 2 befor unique_copy:" << endl; for (auto i : vec2) cout << i << " "; cout << endl; //unique_copy делает тоже самое, что и unique но при этом копирует //элементы в новое расположение Ѕ≈« похожих элементов unique_copy(vec2.begin(), vec2.end(), back_inserter(vec3), Pred); cout << "New vector after unique_copy:" << endl; for (auto i : vec3) cout << i << " "; cout << endl; system("pause"); return 0; }
25.190476
94
0.661626
ogycode
75f97aab1684f5ca3f646c331526fdf3ac9a8bfb
4,639
cpp
C++
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
#include "windows.h" #include "../minizip-ng/mz.h" #include "../minizip-ng/mz_strm.h" #include "../minizip-ng/mz_zip.h" #include "../minizip-ng/mz_zip_rw.h" typedef struct mz_zip_reader_s { void *zip_handle; void *file_stream; void *buffered_stream; void *split_stream; void *mem_stream; void *hash; uint16_t hash_algorithm; uint16_t hash_digest_size; mz_zip_file *file_info; const char *pattern; uint8_t pattern_ignore_case; const char *password; void *overwrite_userdata; mz_zip_reader_overwrite_cb overwrite_cb; void *password_userdata; mz_zip_reader_password_cb password_cb; void *progress_userdata; mz_zip_reader_progress_cb progress_cb; uint32_t progress_cb_interval_ms; void *entry_userdata; mz_zip_reader_entry_cb entry_cb; uint8_t raw; uint8_t buffer[UINT16_MAX]; int32_t encoding; uint8_t sign_required; uint8_t cd_verified; uint8_t cd_zipped; uint8_t entry_verified; uint8_t recover; } mz_zip_reader; /***************************************************************************/ typedef struct mz_stream_IStream_s { mz_stream stream; IStream *ps; } mz_stream_IStream; /***************************************************************************/ int32_t mz_stream_IStream_open(void *stream, const char *path, int32_t mode) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; int32_t err = MZ_OK; mem->ps = (IStream *)path; return err; } int32_t mz_stream_IStream_is_open(void *stream) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; if(mem->ps == NULL) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_IStream_read(void *stream, void *buf, int32_t size) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; ULONG ret; mem->ps->Read(buf,size,&ret); return ret; } int32_t mz_stream_IStream_write(void *stream, const void *buf, int32_t size) { return 0; } int64_t mz_stream_IStream_tell(void *stream) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; ULARGE_INTEGER ret; mem->ps->Seek({0}, STREAM_SEEK_CUR,&ret ); return ret.QuadPart; } int32_t mz_stream_IStream_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; int64_t new_pos = 0; int32_t err = MZ_OK; LARGE_INTEGER offL = {}; offL.QuadPart = offset; switch(origin) { case MZ_SEEK_CUR: mem->ps->Seek(offL, STREAM_SEEK_CUR, NULL); break; case MZ_SEEK_END: mem->ps->Seek(offL, STREAM_SEEK_END, NULL); break; case MZ_SEEK_SET: mem->ps->Seek(offL, STREAM_SEEK_SET, NULL); break; default: return MZ_SEEK_ERROR; } return MZ_OK; } int32_t mz_stream_IStream_close(void *stream) { /* We never return errors */ return MZ_OK; } int32_t mz_stream_IStream_error(void *stream) { /* We never return errors */ return MZ_OK; } extern mz_stream_vtbl mz_stream_IStream_vtbl; void *mz_stream_IStream_create(void **stream) { mz_stream_IStream *mem = NULL; mem = (mz_stream_IStream *)MZ_ALLOC(sizeof(mz_stream_IStream)); if(mem != NULL) { memset(mem, 0, sizeof(mz_stream_IStream)); mem->stream.vtbl = &mz_stream_IStream_vtbl; } if(stream != NULL) *stream = mem; return mem; } void mz_stream_IStream_delete(void **stream) { mz_stream_IStream *mem = NULL; if(stream == NULL) return; mem = (mz_stream_IStream *)*stream; if(mem != NULL) { MZ_FREE(mem); } *stream = NULL; } /***************************************************************************/ static mz_stream_vtbl mz_stream_IStream_vtbl = { mz_stream_IStream_open, mz_stream_IStream_is_open, mz_stream_IStream_read, mz_stream_IStream_write, mz_stream_IStream_tell, mz_stream_IStream_seek, mz_stream_IStream_close, mz_stream_IStream_error, mz_stream_IStream_create, mz_stream_IStream_delete, NULL, NULL }; // int32_t mz_zip_reader_open_IStream(void *handle, IStream *ps) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; mz_zip_reader_close(handle); mz_stream_IStream_create(&reader->mem_stream); mz_stream_IStream_open(reader->mem_stream, (char*)ps, MZ_OPEN_MODE_READ); if(err == MZ_OK) err = mz_zip_reader_open(handle, reader->mem_stream); return err; }
25.349727
79
0.632033
Taromati2
75fa3f0e258c665df7572f01b6807b4b5a79f358
1,549
hpp
C++
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
null
null
null
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
1
2021-02-26T11:11:03.000Z
2021-02-26T19:16:10.000Z
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
1
2021-05-17T13:02:49.000Z
2021-05-17T13:02:49.000Z
#ifndef ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP #define ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP #include <stdint.h> #include <base/Time.hpp> #include <moreorg/organization_model/InterfaceConnection.hpp> #include <moreorg/organization_model/ActorModelLink.hpp> namespace owl = owlapi::model; namespace moreorg { namespace moreorg { /** * Statistic of the organization model engine */ struct Statistics { Statistics(); uint32_t upperCombinationBound; uint32_t numberOfInferenceEpochs; base::Time timeCompositeSystemGeneration; base::Time timeRegisterCompositeSystems; base::Time timeInference; base::Time timeElapsed; owl::IRIList interfaces; uint32_t maxAllowedLinks; InterfaceConnectionList links; InterfaceCombinationList linkCombinations; uint32_t constraintsChecked; owl::IRIList actorsAtomic; owl::IRIList actorsKnown; owl::IRIList actorsInferred; owl::IRIList actorsCompositePrevious; //owl::IRIList actorsCompositePost; uint32_t actorsCompositePost; owl::IRIList actorsCompositeModelPrevious; std::vector< std::vector<ActorModelLink> > actorsCompositeModelPost; //uint32_t actorsCompositeModelPost; std::string toString() const; }; std::ostream& operator<<(std::ostream& os, const Statistics& statistics); std::ostream& operator<<(std::ostream& os, const std::vector<Statistics>& statisticsList); } // end namespace moreorg } // end namespace moreorg #endif // ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP
27.660714
90
0.775339
tomcreutz
2f050085d7b99d79442a0c3e6e986aaace885244
365
hpp
C++
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
9
2017-03-30T15:37:09.000Z
2022-02-06T22:44:17.000Z
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
1
2017-04-10T14:59:31.000Z
2017-04-11T14:42:13.000Z
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
6
2017-02-25T00:19:40.000Z
2022-02-16T19:54:45.000Z
class CfgRemoteExec { class Functions { mode = 2; jip = 0; class fnc_AdminReq { allowedTargets=2; }; class ExileServer_system_network_dispatchIncomingMessage { allowedTargets=2; }; class ExileExpansionServer_system_scavenge_spawnLoot { allowedTargets=0; }; }; class Commands { mode=0; jip=0; }; };
22.8125
83
0.632877
x-cessive
2f06c9830e77a368f7eb4bb675e6ad52232b7bcb
1,535
cpp
C++
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#include "game_ui_teleporter.hpp" #include "../ui_text_element.hpp" #include "../ui_button.hpp" #include "../game_ui_manager.hpp" #include "../../game/items/teleporter.hpp" #include "../../engine.hpp" #include "../../game_session.hpp" #include "../../game/character.hpp" namespace space { void GameUITeleporter::init(GameUIManager &uiManager) { _text = uiManager.createElement<UITextElement>(); _uiManager = &uiManager; _text->widthPercent(100); _text->flexShrink(1.0f); addChild(_text); _actionButton = uiManager.createElement<UIButton>(); _actionButton->width(50); _actionButton->text("Go"); addChild(_actionButton); flexDirection(YGFlexDirectionRow); _actionButton->onClick([this, &uiManager] (const sf::Event &e) { if (this->_teleporter.item == nullptr) { return UIEventResult::Triggered; } auto session = uiManager.engine().currentSession(); auto character = session->playerController().controllingCharacter(); auto placed = this->_teleporter.placed; session->moveSpaceObject(static_cast<SpaceObject *>(character), placed->transform().position, placed->insideArea(), true); return UIEventResult::Triggered; }); } void GameUITeleporter::teleporter(PlacedItemPair<Teleporter> teleporter) { _teleporter = teleporter; _text->text(teleporter.item->name()); } } // space
30.098039
134
0.626059
astrellon
2f08e1a5348a24f7626ef50ef47b2c68e4f380e0
5,059
cc
C++
L1Trigger/TrackFindingTracklet/src/Projection.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/TrackFindingTracklet/src/Projection.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/TrackFindingTracklet/src/Projection.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "L1Trigger/TrackFindingTracklet/interface/Projection.h" #include "L1Trigger/TrackFindingTracklet/interface/Settings.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <algorithm> using namespace std; using namespace trklet; void Projection::init(Settings const& settings, unsigned int layerdisk, int iphiproj, int irzproj, int iphider, int irzder, double phiproj, double rzproj, double phiprojder, double rzprojder, double phiprojapprox, double rzprojapprox, double phiprojderapprox, double rzprojderapprox, bool isPSseed) { assert(layerdisk < N_LAYER + N_DISK); valid_ = true; fpgaphiproj_.set(iphiproj, settings.nphibitsstub(layerdisk), true, __LINE__, __FILE__); if (layerdisk < N_LAYER) { fpgarzproj_.set(irzproj, settings.nzbitsstub(layerdisk), false, __LINE__, __FILE__); } else { fpgarzproj_.set(irzproj, settings.nrbitsstub(layerdisk), false, __LINE__, __FILE__); } if (layerdisk < N_LAYER) { if (layerdisk < N_PSLAYER) { fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL123(), false, __LINE__, __FILE__); fpgarzprojder_.set(irzder, settings.nbitszprojderL123(), false, __LINE__, __FILE__); } else { fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL456(), false, __LINE__, __FILE__); fpgarzprojder_.set(irzder, settings.nbitszprojderL456(), false, __LINE__, __FILE__); } } else { fpgaphiprojder_.set(iphider, settings.nbitsphiprojderL123(), false, __LINE__, __FILE__); fpgarzprojder_.set(irzder, settings.nrbitsprojderdisk(), false, __LINE__, __FILE__); } if (layerdisk < N_LAYER) { ////Separate the vm projections into zbins ////This determines the central bin: ////int zbin=4+(zproj.value()>>(zproj.nbits()-3)); ////But we need some range (particularly for L5L6 seed projecting to L1-L3): int offset = isPSseed ? 1 : 4; int ztemp = fpgarzproj_.value() >> (fpgarzproj_.nbits() - settings.MEBinsBits() - NFINERZBITS); unsigned int zbin1 = (1 << (settings.MEBinsBits() - 1)) + ((ztemp - offset) >> NFINERZBITS); unsigned int zbin2 = (1 << (settings.MEBinsBits() - 1)) + ((ztemp + offset) >> NFINERZBITS); if (zbin1 >= settings.MEBins()) { zbin1 = 0; //note that zbin1 is unsigned } if (zbin2 >= settings.MEBins()) { zbin2 = settings.MEBins() - 1; } assert(zbin1 <= zbin2); assert(zbin2 - zbin1 <= 1); fpgarzbin1projvm_.set(zbin1, settings.MEBinsBits(), true, __LINE__, __FILE__); // first z bin int nextbin = zbin1 != zbin2; fpgarzbin2projvm_.set(nextbin, 1, true, __LINE__, __FILE__); // need to check adjacent z bin? //fine vm z bits. Use 4 bits for fine position. starting at zbin 1 int finez = ((1 << (settings.MEBinsBits() + NFINERZBITS - 1)) + ztemp) - (zbin1 << NFINERZBITS); fpgafinerzvm_.set(finez, NFINERZBITS + 1, true, __LINE__, __FILE__); // fine z postions starting at zbin1 } else { //TODO the -3 and +3 should be evaluated and efficiency for matching hits checked. //This code should be migrated in the ProjectionRouter double roffset = 3.0; int rbin1 = 8.0 * (irzproj * settings.krprojshiftdisk() - roffset - settings.rmindiskvm()) / (settings.rmaxdisk() - settings.rmindiskvm()); int rbin2 = 8.0 * (irzproj * settings.krprojshiftdisk() + roffset - settings.rmindiskvm()) / (settings.rmaxdisk() - settings.rmindiskvm()); if (rbin1 < 0) { rbin1 = 0; } rbin2 = clamp(rbin2, 0, 7); assert(rbin1 <= rbin2); assert(rbin2 - rbin1 <= 1); int finer = 64 * ((irzproj * settings.krprojshiftdisk() - settings.rmindiskvm()) - rbin1 * (settings.rmaxdisk() - settings.rmindiskvm()) / 8.0) / (settings.rmaxdisk() - settings.rmindiskvm()); finer = clamp(finer, 0, 15); int diff = rbin1 != rbin2; if (irzder < 0) rbin1 += 8; fpgarzbin1projvm_.set(rbin1, 4, true, __LINE__, __FILE__); // first r bin fpgarzbin2projvm_.set(diff, 1, true, __LINE__, __FILE__); // need to check adjacent r bin fpgafinerzvm_.set(finer, 4, true, __LINE__, __FILE__); // fine r postions starting at rbin1 } //fine phi bits int projfinephi = (fpgaphiproj_.value() >> (fpgaphiproj_.nbits() - (settings.nbitsallstubs(layerdisk) + settings.nbitsvmme(layerdisk) + NFINEPHIBITS))) & ((1 << NFINEPHIBITS) - 1); fpgafinephivm_.set(projfinephi, NFINEPHIBITS, true, __LINE__, __FILE__); // fine phi postions phiproj_ = phiproj; rzproj_ = rzproj; phiprojder_ = phiprojder; rzprojder_ = rzprojder; phiprojapprox_ = phiprojapprox; rzprojapprox_ = rzprojapprox; phiprojderapprox_ = phiprojderapprox; rzprojderapprox_ = rzprojderapprox; }
38.037594
117
0.634908
Purva-Chaudhari
2f0e58369426a872d6e60a0940741337c827f251
1,191
cpp
C++
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
4
2018-07-03T14:21:39.000Z
2021-06-01T06:12:14.000Z
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "icommon.h" #include "net_loop.h" net_driver_t net_drivers[MAX_NET_DRIVERS] = { { "Loopback", false, Loop_Init, Loop_Listen, Loop_SearchForHosts, Loop_Connect, Loop_CheckNewConnections, Loop_GetMessage, Loop_SendMessage, Loop_SendUnreliableMessage, Loop_CanSendMessage, Loop_CanSendUnreliableMessage, Loop_Close, Loop_Shutdown } }; int net_numdrivers = 1; net_landriver_t net_landrivers[MAX_NET_DRIVERS]; int net_numlandrivers = 0;
24.8125
75
0.786734
WarlockD
2f0fadc9f354656100b238a5d7fb9ab957259ea1
3,514
cpp
C++
source/code/utilities/program/wrappers/git/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/utilities/program/wrappers/git/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/utilities/program/wrappers/git/lib.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include <iostream> #include "code/utilities/program/wrappers/git/lib.hpp" #include "code/utilities/program/call/lib.hpp" #include "code/utilities/filesystem/paths/lib.hpp" #include "code/utilities/program/call/lib.hpp" #include "code/utilities/random/lib.hpp" #include "code/utilities/random/files/random_files.hpp" #include "code/utilities/types/strings/observers/converting/lib.hpp" #include "code/utilities/program/call/process_spawn/timed/timed_process_spawner.hpp" std::string Download_Repo_To_Random_Name_In_Temp_Folder(std::string ssh_url) { auto dir = Random_Files::Random_Tmp_Directory(); std::string command = "git clone "; command += ssh_url; command += " "; command += dir; std::cout << command << std::endl; auto spawn = Timed_Process_Spawner::Execute_And_Get_Back_Results(command); if (spawn.results.return_code != 0){ std::cerr << spawn.results.stderr << std::endl; exit(-1); } return dir; } std::string Download_Repo_To_Random_Name_In_Temp_Folder(std::string ssh_url, std::string branch) { auto dir = Random_Files::Random_Tmp_Directory(); std::string command = "git clone "; command += "--branch "; command += branch; command += " "; command += ssh_url; command += " "; command += dir; auto spawn = Timed_Process_Spawner::Execute_And_Get_Back_Results(command); if (spawn.results.return_code != 0){ std::cerr << spawn.results.stderr << std::endl; exit(-1); } return dir; } bool Inside_Git_Repository(){ return Directory_Exists_In_Current_Directory_Or_Any_Parents(".git"); } bool Git_Repo_Dirty(){ return Get_Return_Value_Of_Running("git diff-index --quiet HEAD --;"); } bool Repo_Exists_On_Github(std::string const& user_name, std::string const& repo_name){ //return Successful_Run_Of_Command("wget -q --spider address https://github.com/" + user_name + "/" + repo_name); return Successful_Run_Of_Command("curl -s --head https://github.com/" + user_name + "/" + repo_name + " | head -n 1 | grep \"HTTP/1.[01] [23]..\""); } void Create_Repo_On_Github(std::string const& user_name, std::string const& autorization, std::string const& project_name, std::string const& description){ exec_quietly("curl -u \"" + user_name + ":" + autorization + "\" https://api.github.com/user/repos -d '{\"name\": \"" + project_name + "\", " + "\"description\": \"" + description + "\"}'"); } std::string Get_Path_Of_Directory_Starting_At_Git_Repo_Root(){ return Get_Path_Of_Directory_Starting_From_Root_Directory_Name(".git"); } void Go_To_Git_Repo_Root(){ return Move_Back_Directories_Until_Directory_Exists(".git"); } unsigned int Number_Of_Directories_Deep_In_Git_Repo(){ return Number_Of_Directories_Deep_In_Root_Directory_Name(".git"); } std::string Get_Project_Name(){ return execute("basename `git rev-parse --show-toplevel`"); } std::string Get_Project_URL(){ return execute("git ls-remote --get-url"); } std::string Current_Git_Branch_Name(){ return execute("git rev-parse --abbrev-ref HEAD"); } std::string Git_Username(){ return execute("git config --global user.name"); } std::string Git_Hosted_User(){ auto str = exec("git config --get remote.origin.url"); std::string author; //parse that url to get the author/organization name and repo name seperate bool add_to_first = true; if (!str.empty()) { str.erase(0, 15); for (auto const& it: str) { if (it == '/') {add_to_first = false;} else{ if (add_to_first) {author += it;} } } } return author; } int Number_Of_Commits() { return as_signed(execute("git rev-list --count HEAD")); }
34.116505
190
0.72453
luxe
2f128127c60db93ca245e59efd2846ef5b44d83b
3,553
cpp
C++
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
19
2015-04-25T15:19:59.000Z
2022-02-28T03:00:42.000Z
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
1
2016-01-28T08:50:02.000Z
2021-08-24T02:34:48.000Z
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
7
2015-04-17T16:38:45.000Z
2021-06-25T03:39:39.000Z
#include <save/save.hpp> #include <server.hpp> #include <singleton.hpp> #include <thread_pool.hpp> #include <exception> #include <utility> using namespace MCPP; namespace MCPP { static const Word priority=1; static const String name("Save Manager"); static const String debug_key("save"); static const String save_complete("Save complete - took {0}ns"); static const String save_paused("Save loop paused, skipping"); static const String setting_key("save_frequency"); static const Word frequency_default=5*60*1000; // Every 5 minutes bool SaveManager::is_verbose () { return Server::Get().IsVerbose(debug_key); } void SaveManager::save () { auto & server=Server::Get(); try { Timer timer(Timer::CreateAndStart()); for (auto & callback : callbacks) callback(); auto elapsed=timer.ElapsedNanoseconds(); this->elapsed+=elapsed; ++count; if (is_verbose()) server.WriteLog( String::Format( save_complete, elapsed, frequency ), Service::LogType::Debug ); } catch (...) { try { server.Panic(std::current_exception()); } catch (...) { } throw; } } void SaveManager::save_loop () { auto & server=Server::Get(); if ( lock.Execute([&] () mutable { if (paused) return true; save(); return false; }) && is_verbose() ) server.WriteLog( save_paused, Service::LogType::Debug ); try { server.Pool().Enqueue( frequency, [this] () mutable { save_loop(); } ); } catch (...) { try { server.Panic(std::current_exception()); } catch (...) { } throw; } } static Singleton<SaveManager> singleton; SaveManager & SaveManager::Get () noexcept { return singleton.Get(); } SaveManager::SaveManager () noexcept { paused=false; count=0; elapsed=0; } Word SaveManager::Priority () const noexcept { return priority; } const String & SaveManager::Name () const noexcept { return name; } void SaveManager::Install () { auto & server=Server::Get(); // On shutdown we must save everything // one last time server.OnShutdown.Add([this] () mutable { save(); // Purge all callbacks held which // may have originated from other // modules callbacks.Clear(); }); // Once the install phase is done, and // all modules that wish to save have // added their handlers, start the // save loop server.OnInstall.Add([this] (bool) mutable { Server::Get().Pool().Enqueue( frequency, [this] () mutable { save_loop(); } ); }); // Get the frequency with which saves // should be performed from the backing store frequency=server.Data().GetSetting( setting_key, frequency_default ); } void SaveManager::Add (std::function<void ()> callback) { if (callback) callbacks.Add(std::move(callback)); } void SaveManager::operator () () { lock.Execute([&] () mutable { save(); }); } void SaveManager::Pause () noexcept { lock.Execute([&] () mutable { paused=true; }); } void SaveManager::Resume () noexcept { lock.Execute([&] () mutable { paused=false; }); } SaveManagerInfo SaveManager::GetInfo () const noexcept { return SaveManagerInfo{ frequency, paused, count, elapsed }; } } extern "C" { Module * Load () { return &(SaveManager::Get()); } void Unload () { singleton.Destroy(); } }
14.384615
66
0.599775
RobertLeahy
2f14ea844e12e79dd8fd0b279551e50734feca17
4,250
cpp
C++
src/log.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/log.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/log.cpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: log.cpp 48725 2011-03-02 21:40:59Z mordante $ */ /* Copyright (C) 2003 by David White <dave@whitevine.net> 2004 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Standard logging facilities (implementation). * See also the command line switches --logdomains and --log-@<level@>="domain". */ #include "global.hpp" #include "SDL.h" #include "log.hpp" #include "foreach.hpp" #include <map> #include <sstream> #include <ctime> namespace { class null_streambuf : public std::streambuf { virtual int overflow(int c) { return std::char_traits< char >::not_eof(c); } public: null_streambuf() {} }; } // end anonymous namespace static std::ostream null_ostream(new null_streambuf); static int indent = 0; static bool timestamp = true; static std::ostream *output_stream = NULL; static std::ostream& output() { if(output_stream) { return *output_stream; } return std::cerr; } namespace lg { tredirect_output_setter::tredirect_output_setter(std::ostream& stream) : old_stream_(output_stream) { output_stream = &stream; } tredirect_output_setter::~tredirect_output_setter() { output_stream = old_stream_; } typedef std::map<std::string, int> domain_map; static domain_map *domains; void timestamps(bool t) { timestamp = t; } logger err("error", 0), warn("warning", 1), info("info", 2), debug("debug", 3); log_domain general("general"); log_domain::log_domain(char const *name) : domain_(NULL) { // Indirection to prevent initialization depending on link order. if (!domains) domains = new domain_map; domain_ = &*domains->insert(logd(name, 1)).first; } bool set_log_domain_severity(std::string const &name, int severity) { std::string::size_type s = name.size(); if (name == "all") { foreach (logd &l, *domains) { l.second = severity; } } else if (s > 2 && name.compare(s - 2, 2, "/*") == 0) { foreach (logd &l, *domains) { if (l.first.compare(0, s - 1, name, 0, s - 1) == 0) l.second = severity; } } else { domain_map::iterator it = domains->find(name); if (it == domains->end()) return false; it->second = severity; } return true; } std::string list_logdomains(const std::string& filter) { std::ostringstream res; foreach (logd &l, *domains) { if(l.first.find(filter) != std::string::npos) res << l.first << "\n"; } return res.str(); } std::string get_timestamp(const std::time_t& t, const std::string& format) { char buf[100] = {0}; tm* lt = localtime(&t); if (lt) { strftime(buf, 100, format.c_str(), lt); } return buf; } std::ostream &logger::operator()(log_domain const &domain, bool show_names, bool do_indent) const { if (severity_ > domain.domain_->second) return null_ostream; else { std::ostream& stream = output(); if(do_indent) { for(int i = 0; i != indent; ++i) stream << " "; } if (timestamp) { stream << get_timestamp(time(NULL)); } if (show_names) { stream << name_ << ' ' << domain.domain_->first << ": "; } return stream; } } void scope_logger::do_log_entry(log_domain const &domain, const std::string& str) { output_ = &debug(domain, false, true); str_ = str; ticks_ = SDL_GetTicks(); (*output_) << "{ BEGIN: " << str_ << "\n"; ++indent; } void scope_logger::do_log_exit() { const int ticks = SDL_GetTicks() - ticks_; --indent; do_indent(); if (timestamp) (*output_) << get_timestamp(time(NULL)); (*output_) << "} END: " << str_ << " (took " << ticks << "ms)\n"; } void scope_logger::do_indent() const { for(int i = 0; i != indent; ++i) (*output_) << " "; } std::stringstream wml_error; } // end namespace lg
24.285714
98
0.635529
blackberry
2f1f2df1db8730ae3605308972354cd45da6ec14
2,679
cc
C++
leetcode/Trie/remove_sub_folders_from_the_filesystem.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Trie/remove_sub_folders_from_the_filesystem.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Trie/remove_sub_folders_from_the_filesystem.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
#include <map> #include <string> #include <vector> #include "third_party/gflags/include/gflags.h" #include "third_party/glog/include/logging.h" // Problem: // https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem/ // Solutions: // https://leetcode-cn.com/problems/remove-sub-folders-from-the-filesystem/solution/shi-yong-trie-dui-qian-zhui-bian-li-cha-1nb79/ using namespace std; class Solution { private: class Trie { struct TrieNode { map<char, int> next; bool isEnd; }; vector<TrieNode> trie; public: Trie() { trie.push_back(TrieNode()); } void Insert(int tree_id, string& word, int pos) { if (pos == word.size()) { trie[tree_id].isEnd = true; return; } if (trie[tree_id].next.count(word[pos]) == 0) { trie[tree_id].next[word[pos]] = trie.size(); trie.push_back(TrieNode()); } Insert(trie[tree_id].next[word[pos]], word, pos + 1); } bool Search(int tree_id, string& word, int pos) { if (pos == word.size()) { return trie[tree_id].isEnd; } if (trie[tree_id].next.count(word[pos]) == 0) { return false; } return Search(trie[tree_id].next[word[pos]], word, pos + 1); } bool StartWith(int tree_id, string& word, int pos) { if (pos == word.size()) return true; if (trie[tree_id].next.count(word[pos]) == 0) { return false; } return StartWith(trie[tree_id].next[word[pos]], word, pos + 1); } }; public: vector<string> removeSubfolders(vector<string>& folder) { // 例如:["/c/d","/c/d/e","/c/f"],依次插入folder 建立trie. Trie t; for (auto& path : folder) { t.Insert(0, path, 0); } vector<string> ret; // 对所有路径进行遍历。 for (auto& path : folder) { // 取每个路径的子路径查询,例如 ["/c/d","/c/d/e","/c/f"] // 对 path="/c/d/e" 进行依次查询:"/c/d", // "/c",如果存在("/c/d"),那么path是子路径 // 否则 它不是子路径。 int start = 0; int last_pos = path.size(); bool found = false; while (last_pos > 0) { last_pos = path.substr(start, last_pos).find_last_of('/'); // 找不到就跳出 if (last_pos == std::string::npos) break; string sub_str = path.substr(0, last_pos); if (t.Search(0, sub_str, 0)) { found = true; break; } } if (!found) ret.push_back(path); } return ret; } }; int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, false); vector<string> wordDict({"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"}); Solution solu; auto ret = solu.removeSubfolders(wordDict); return 0; }
26.524752
130
0.571855
LIZHICHAOUNICORN
2f20ddb15c95e2defff68f8191a81f454eb9e14e
4,154
cpp
C++
unit-test/common/test_lag.cpp
google/detectorgraph
d6c923f8e495a21137312b236e35c36a55d3a755
[ "Apache-2.0" ]
43
2018-05-17T07:13:18.000Z
2022-02-02T01:54:06.000Z
unit-test/common/test_lag.cpp
google/detectorgraph
d6c923f8e495a21137312b236e35c36a55d3a755
[ "Apache-2.0" ]
4
2018-09-20T04:14:11.000Z
2018-09-21T08:05:33.000Z
unit-test/common/test_lag.cpp
google/detectorgraph
d6c923f8e495a21137312b236e35c36a55d3a755
[ "Apache-2.0" ]
12
2018-05-17T09:03:31.000Z
2020-10-13T16:38:15.000Z
// Copyright 2017 Nest Labs, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "nltest.h" #include "errortype.hpp" #include "test_lag.h" #include "graph.hpp" #include "lag.hpp" #define SUITE_DECLARATION(name, test_ptr) { #name, test_ptr, setup_##name, teardown_##name } using namespace DetectorGraph; static int setup_lag(void *inContext) { return 0; } static int teardown_lag(void *inContext) { return 0; } namespace { struct StartTopicState : public TopicState { StartTopicState(int aV = 0) : mV(aV) {}; int mV; }; struct LoopTopicState : public TopicState { LoopTopicState(int aV = 0) : mV(aV) {}; int mV; }; struct LoopTestDetector : public Detector , public SubscriberInterface<StartTopicState> , public SubscriberInterface< Lagged<LoopTopicState> > , public Publisher<LoopTopicState> { LoopTestDetector(Graph* graph) : Detector(graph), mState(0) { Subscribe<StartTopicState>(this); Subscribe< Lagged<LoopTopicState> >(this); SetupPublishing<LoopTopicState>(this); } virtual void Evaluate(const StartTopicState& aInData) { mState = LoopTopicState(1); Publish(mState); } virtual void Evaluate(const Lagged<LoopTopicState>& aLoopData) { mState = aLoopData.data; mState.mV++; if (mState.mV < 5) { Publish(mState); } } LoopTopicState mState; }; } static void Test_LaggedDataConstructor(nlTestSuite *inSuite, void *inContext) { Lagged<LoopTopicState> dummy; NL_TEST_ASSERT(inSuite, dummy.data.mV == 0); } static void Test_FeedbackLoop(nlTestSuite *inSuite, void *inContext) { Graph graph; graph.ResolveTopic<StartTopicState>(); Topic< Lagged<LoopTopicState> >* outputTopic = graph.ResolveTopic< Lagged<LoopTopicState> >(); LoopTestDetector detector(&graph); graph.ResolveTopic<LoopTopicState>(); Lag<LoopTopicState> delayDetector(&graph); graph.PushData<StartTopicState>(0); NL_TEST_ASSERT(inSuite, detector.mState.mV == 0); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 1); NL_TEST_ASSERT(inSuite, !outputTopic->HasNewValue()); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 2); NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue()); NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 1); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 3); NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue()); NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 2); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 4); NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue()); NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 3); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 5); NL_TEST_ASSERT(inSuite, outputTopic->HasNewValue()); NL_TEST_ASSERT(inSuite, outputTopic->GetNewValue().data.mV == 4); graph.EvaluateGraph(); NL_TEST_ASSERT(inSuite, detector.mState.mV == 5); NL_TEST_ASSERT(inSuite, !outputTopic->HasNewValue()); } static const nlTest sTests[] = { NL_TEST_DEF("Test_LaggedDataConstructor", Test_LaggedDataConstructor), NL_TEST_DEF("Test_FeedbackLoop", Test_FeedbackLoop), NL_TEST_SENTINEL() }; extern "C" int lag_testsuite(void) { nlTestSuite theSuite = SUITE_DECLARATION(lag, &sTests[0]); nlTestRunner(&theSuite, NULL); return nlTestRunnerStats(&theSuite); }
30.544118
100
0.687771
google
2f2bdcf7447fd4ad54fdfd70d829770df30d3c37
980
cpp
C++
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
1
2021-09-17T13:10:04.000Z
2021-09-17T13:10:04.000Z
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define FAST1 ios_base::sync_with_stdio(false); #define FAST2 cin.tie(NULL); #define allsort(a) sort(a.begin(),a.end()) ll n,k; void solve(){ cin>>n>>k; if(k==0){ cout<<"Yes"<<endl; cout<<0<<endl; return; } if(k%2==0){ cout<<"No"<<endl;; return; } ll sz=0; for(ll i=31;i>=0;i--){ if(((1<<i)&k)!=0){ sz=i+1; break; } } k=(k+(1<<sz)-1)/2; cout<<"Yes"<<endl; cout<<sz<<endl; int ans=1; vector<int> a; for(int i=sz-2;i>=0;i--){ if(((1<<i)&k)!=0){ a.push_back(ans); ans+=(1<<i); } else{ ans-=(1<<i); a.push_back(ans); } } for(int i=sz-2;i>=0;i--) cout<<a[i]<<endl; cout<<ans<<endl; } int main(){ FAST1; FAST2; ll t; cin>>t; while(t--){ solve(); } }
17.5
47
0.418367
Jks08
2f315b9281397276f2339416be7e8d28f31ac034
887
cc
C++
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { private: const int invalid = -1; int getAnswer(vector<int>& answer, vector<int> &nums, int idx) { int max = 0; if (answer[idx] != invalid) { return answer[idx]; } for (int i = idx + 1; i < answer.size(); ++i) { if (nums[idx] >= nums[i]) { continue; } int ret = getAnswer(answer, nums, i); if (max < ret) { max = ret; } } answer[idx] = max + 1; return answer[idx]; } public: int lengthOfLIS(vector<int>& nums) { vector<int> answer(nums.size(), invalid); int ans = 0; for (int i = 0; i < answer.size(); ++i) { int ret = getAnswer(answer, nums, i); if (ans < ret) { ans = ret; } } return ans; } };
23.972973
68
0.421646
ldy121
2f33385320806e4d297750693b873ce73938820c
837
cpp
C++
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> using namespace std; #include "ProblemList.h" /* ********************* *MADE BY MICHAEL LApAN ********************* *this program is a help desk mock up *it proccesses helkp desk tickets, *sorts and stores them. then shows top *25 then bottem 25 */ int main() { ProblemList problems("problems.txt"); ProblemList newProblems("newproblems.txt"); ProblemList solvedProblems("resolvedproblems.txt"); problems += newProblems; problems -= solvedProblems; //couldnt easily incorporate this into class cout << "Priority Submitted By Description" << endl; problems.writeTop(25); system("pause"); //couldnt easily incorporate this into class cout << "Priority Submitted By Description" << endl; problems.writeBottom(25); system("pause"); }
23.25
65
0.67503
hurnhu
2f40127686b3e138bd6d4c51ffba3159a2b80c29
562
cpp
C++
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; #pragma comment(linker,"/stack:1024000000,1024000000") #define db(x) cout<<(x)<<endl #define pf(x) push_front(x) #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define ms(x,y) memset(x,y,sizeof x) typedef long long LL; const double pi=acos(-1),eps=1e-9; const LL inf=0x3f3f3f3f,mod=1e9+7,maxn=1123456; int n,a,x,vis[128],ans; int main(){ ios::sync_with_stdio(0); cin>>n>>x; for(int i=0;i<n;i++){ cin>>a; vis[a]=1; } for(int i=0;i<x;i++) if(!vis[i]) ans++; db(vis[x]?ans+1:ans); return 0; }
22.48
54
0.649466
QAQrz
2f40bd39f42d58fecaad97ea17318d2cace2933c
9,089
cpp
C++
src/Editor/TristeonEditor.cpp
HyperionDH/Tristeon
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
38
2017-12-04T10:48:28.000Z
2018-05-11T09:59:41.000Z
src/Editor/TristeonEditor.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
9
2017-12-04T09:58:55.000Z
2018-02-05T00:06:41.000Z
src/Editor/TristeonEditor.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
3
2018-01-10T13:39:12.000Z
2018-03-17T20:53:22.000Z
#include "Core/MessageBus.h" #ifdef TRISTEON_EDITOR #include "TristeonEditor.h" #include <ImGUI/imgui_impl_glfw_vulkan.h> #include "Core/Engine.h" #include "Core/Rendering/Vulkan/HelperClasses/CommandBuffer.h" #include "Core/Rendering/Vulkan/RenderManagerVulkan.h" #include "Asset Browser/AssetBrowser.h" #include "Scene editor/GameObjectHierarchy.h" #include "Inspector/InspectorWindow.h" #include "Scene editor/SceneWindow.h" #include "Misc/Console.h" #include "Misc/Hardware/Keyboard.h" #include "EditorDragging.h" namespace Tristeon { using namespace Editor; TristeonEditor::TristeonEditor(Core::Engine* engine) { editorCamera = nullptr; Core::VulkanBindingData *vkBinding = Core::VulkanBindingData::getInstance(); this->vkDevice = vkBinding->device; this->engine = engine; bindImGui(vkBinding); initFontsImGui(vkBinding); setupCallbacks(); createCommandBuffers(); //Set style setStyle(); //Create editor windows EditorWindow::editor = this; windows.push_back(std::move(std::make_unique<AssetBrowser>())); windows.push_back(std::move(std::make_unique<GameObjectHierarchy>())); windows.push_back(std::move(std::make_unique<InspectorWindow>())); windows.push_back(std::move(std::make_unique<SceneWindow>(this))); } TristeonEditor::~TristeonEditor() { Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_DEREGISTER, renderable)); delete renderable; vkDevice.waitIdle(); ImGui_ImplGlfwVulkan_Shutdown(); } void TristeonEditor::setStyle() { ImGuiStyle * style = &ImGui::GetStyle(); style->WindowPadding = ImVec2(15, 15); style->WindowRounding = 5.0f; style->FramePadding = ImVec2(5, 5); style->FrameRounding = 4.0f; style->ItemSpacing = ImVec2(12, 8); style->ItemInnerSpacing = ImVec2(8, 6); style->IndentSpacing = 25.0f; style->ScrollbarSize = 15.0f; style->ScrollbarRounding = 9.0f; style->GrabMinSize = 5.0f; style->GrabRounding = 3.0f; style->Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.83f, 1.00f); style->Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_PopupBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.83f, 0.88f); style->Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f); style->Colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_FrameBgActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_TitleBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f); style->Colors[ImGuiCol_TitleBgActive] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_ComboBg] = ImVec4(0.19f, 0.18f, 0.21f, 1.00f); style->Colors[ImGuiCol_CheckMark] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_SliderGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_Button] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ButtonHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_ButtonActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_Header] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_HeaderActive] = ImVec4(0, 0, 0, 0); style->Colors[ImGuiCol_HeaderHovered] = ImVec4(0.301f, 0.537f, .788f, 1); style->Colors[ImGuiCol_Column] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ColumnHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_ColumnActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ResizeGrip] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style->Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_CloseButton] = ImVec4(0.40f, 0.39f, 0.38f, 0.16f); style->Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.40f, 0.39f, 0.38f, 0.39f); style->Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.40f, 0.39f, 0.38f, 1.00f); style->Colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style->Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style->Colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style->Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style->Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f); style->Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(1.00f, 0.98f, 0.95f, 0.73f); style->Colors[ImGuiCol_TSelectableActive] = ImVec4(1,1,1,1); } void TristeonEditor::onGui() { if (Misc::Keyboard::getKeyDown(Misc::KeyCode::SPACE)) { inPlayMode = !inPlayMode; Core::MessageBus::sendMessage(inPlayMode ? Core::MT_GAME_LOGIC_START : Core::MT_GAME_LOGIC_STOP); } //If playing the game it will go in fullscreen, thus the editor no longer needs to be rendered, will be subject to change if (inPlayMode) return; ImGui_ImplGlfwVulkan_NewFrame(); //ImGuizmo::BeginFrame(); //Calling ongui functions of editorwindows for (int i = 0; i < windows.size(); ++i) { windows[i]->onGui(); } //Update dragging if (ImGui::IsMouseReleased(0)) { EditorDragging::reset(); } } void TristeonEditor::render() { if (inPlayMode) return; Core::Rendering::Vulkan::RenderData* d = dynamic_cast<Core::Rendering::Vulkan::RenderData*>(renderable->data); vk::CommandBufferBeginInfo const begin = vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eRenderPassContinue, &d->inheritance); cmd.begin(begin); ImGui_ImplGlfwVulkan_Render(static_cast<VkCommandBuffer>(cmd)); cmd.end(); d->lastUsedSecondaryBuffer = cmd; } void TristeonEditor::bindImGui(Core::VulkanBindingData* vkBinding) { ImGui_ImplGlfwVulkan_Init_Data init_data; init_data.allocator = nullptr; init_data.gpu = static_cast<VkPhysicalDevice>(vkBinding->physicalDevice); init_data.device = static_cast<VkDevice>(vkBinding->device); init_data.render_pass = static_cast<VkRenderPass>(vkBinding->renderPass); init_data.pipeline_cache = NULL; init_data.descriptor_pool = static_cast<VkDescriptorPool>(vkBinding->descriptorPool); init_data.check_vk_result = [](VkResult err) { Misc::Console::t_assert(err == VK_SUCCESS, "Editor vulkan error: " + err); }; ImGui_ImplGlfwVulkan_Init(vkBinding->window, true, &init_data); } void TristeonEditor::initFontsImGui(Core::VulkanBindingData* vkBinding) { VkResult err = vkResetCommandPool( static_cast<VkDevice>(vkBinding->device), static_cast<VkCommandPool>(vkBinding->commandPool), 0); Misc::Console::t_assert(err == VK_SUCCESS, "Failed to reset command pool: " + to_string(static_cast<vk::Result>(err))); VkCommandBuffer const cmd = static_cast<VkCommandBuffer>(Core::Rendering::Vulkan::CommandBuffer::begin(vkBinding->commandPool, vkBinding->device)); ImGui_ImplGlfwVulkan_CreateFontsTexture(cmd); Core::Rendering::Vulkan::CommandBuffer::end(static_cast<vk::CommandBuffer>(cmd), vkBinding->graphicsQueue, vkBinding->device, vkBinding->commandPool); vkBinding->device.waitIdle(); ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects(); } void TristeonEditor::setupCallbacks() { //Subscribe to render callback Core::MessageBus::subscribeToMessage(Core::MT_PRERENDER, std::bind(&TristeonEditor::onGui, this)); Core::MessageBus::subscribeToMessage(Core::MT_SHARE_DATA, [&](Core::Message msg) { Core::Rendering::Vulkan::EditorData* data = dynamic_cast<Core::Rendering::Vulkan::EditorData*>(msg.userData); if (data != nullptr) this->editorCamera = data; }); renderable = new Core::Rendering::UIRenderable(); renderable->onRender += [&]() { render(); }; Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_REGISTER, renderable)); } void TristeonEditor::createCommandBuffers() { Core::VulkanBindingData* binding = Core::VulkanBindingData::getInstance(); Misc::Console::t_assert(binding != nullptr, "Tristeon editor currently only supports vulkan!"); vk::CommandBufferAllocateInfo alloc = vk::CommandBufferAllocateInfo(binding->commandPool, vk::CommandBufferLevel::eSecondary, 1); vk::Result const r = binding->device.allocateCommandBuffers(&alloc, &cmd); Misc::Console::t_assert(r == vk::Result::eSuccess, "Failed to allocate command buffers: " + to_string(r)); } } #endif
42.078704
152
0.728793
HyperionDH
2f41e4c1d1f0071946aea4c61dff3941058b388f
567
cpp
C++
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
#include <iostream> #include "Exer13_28_BinStrTree_point.h" using std::cout; using std::endl; int main() { TreeNode t1("t1"); TreeNode t2 = t1; t1.read(cout) << endl; t2.write("t2"); t2.read(cout) << endl; { TreeNode t3(t2); t3.read(cout) << endl; t3.write("t3"); t3.read(cout) << endl;; } TreeNode t4("t4"); TreeNode t5("t5"); t4.read(cout) << endl;; t5.read(cout) << endl; t4 = t4; BinStrTree r1; BinStrTree r2(r1); BinStrTree r3; r3 = r1; r3 = r3; return 0; }
18.9
39
0.527337
sjbarigye
2f46731513ee8207fa214c84ef6cf66b94654967
10,622
cpp
C++
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
//================================================================================ // Copyright (c) 2013 ~ 2020. HyungKi Jeong(clonextop@gmail.com) // All rights reserved. // // The 3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause) // // Redistribution and use in source and binary forms, // with or without modification, are permitted provided // that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. // // Title : Scenario test // Rev. : 8/13/2020 Thu (clonextop@gmail.com) //================================================================================ #include "ScenarioTest.h" static CString __sScenarioPath; static CString __sProgramPath; REGISTER_LOCALED_DOCUMENT_EX(ScenarioTest) { CString sName(pDoc->DocumentTitle()); if(!sName.Compare(_T("Scenario Test"))) { // default scenario path pDoc->DocumentTitle(_L(DOCUMENT_TITLE)); __sScenarioPath = _T("%PROJECT%Program\\ScenarioTest"); __sProgramPath = _T("%PROJECT%Program"); return TRUE; } else { // user defined scenario path int iPos = 0; LPCTSTR sDelim = _T(":"); CString sTitle = sName.Tokenize(sDelim, iPos); __sScenarioPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program\\ScenarioTest"); __sProgramPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program"); sName.Format(_T("%s(%s)"), _L(DOCUMENT_TITLE), (LPCTSTR)sTitle); pDoc->DocumentTitle(sName); return TRUE; } return TRUE; } LPCTSTR g_sTestStatus[TEST_STATUS_SIZE]; ScenarioTest::ScenarioTest(ITDDocument* pDoc) { m_bInitialized = FALSE; m_pDoc = pDoc; m_HtmlTable.Create(pDoc, _T("../media/tables.html"), 0, 0, 100, 100); m_HtmlTable.SetManager(this); m_pHtmlTable = &m_HtmlTable; { // initialize test status string g_sTestStatus[TEST_STATUS_NOT_TESTED] = _L(TEST_STATUS_NOT_TESTED); g_sTestStatus[TEST_STATUS_RUN_PASSED] = _L(TEST_STATUS_RUN_PASSED); g_sTestStatus[TEST_STATUS_RUN_FAILED] = _L(TEST_STATUS_RUN_FAILED); g_sTestStatus[TEST_STATUS_RUN_CRACHED] = _L(TEST_STATUS_RUN_CRACHED); g_sTestStatus[TEST_STATUS_COMPILE_FAILED] = _L(TEST_STATUS_COMPILE_FAILED); g_sTestStatus[TEST_STATUS_LINK_FAILED] = _L(TEST_STATUS_LINK_FAILED); g_sTestStatus[TEST_STATUS_FILE_NOT_FOUND] = _L(TEST_STATUS_FILE_NOT_FOUND); g_sTestStatus[TEST_STATUS_SYSTEM_IS_REQUIRED] = _L(TEST_STATUS_SYSTEM_IS_REQUIRED); g_sTestStatus[TEST_STATUS_SCORE] = _L(TEST_STATUS_SCORE); } { ITDPropertyData* pProperty; pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_NAME_FILTER, _L(NAME_FILTER), (DWORD_PTR)((LPCTSTR)m_TestList.TestFilter()), _L(DESC_NAME_FILTER)); pProperty->UpdateConfigFile(); } { m_TimeToday = GetCurrentDayTime(); m_pDoc->SetTimer(COMMAND_ID_REFRESH_TABLE, 1000 * 60 * 60); // every 1 hour, refresh table when day changed } } ScenarioTest::~ScenarioTest(void) { m_pDoc->KillTimer(COMMAND_ID_REFRESH_TABLE); } BOOL ScenarioTest::OnPropertyUpdate(ITDPropertyData* pProperty) { pProperty->UpdateData(); pProperty->UpdateConfigFile(FALSE); switch(pProperty->GetID()) { case PROPERTY_ID_NAME_FILTER: if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else { m_TestList.Clear(); m_TestList.Refresh(); g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE)); } break; default: break; } return TRUE; } void ScenarioTest::OnSize(int width, int height) { if(m_HtmlTable.Control()) { ITDLayout* pLayout; pLayout = m_HtmlTable.Control()->GetObject()->GetLayout(); pLayout->SetSize(width, height); } } BOOL ScenarioTest::OnCommand(DWORD command, WPARAM wParam, LPARAM lParam) { switch(command) { case COMMAND_ID_DO_TEST: m_pDoc->KillTimer(command); if(OnTest()) m_pDoc->SetTimer(command, 0); break; case COMMAND_ID_REFRESH_TABLE: if(!m_pDoc->IsLocked() && (m_TimeToday != GetCurrentDayTime())) { m_TestList.Refresh(); m_TimeToday = GetCurrentDayTime(); } break; default: break; } return FALSE; } LPCTSTR ScenarioTest::OnHtmlBeforeNavigate(DWORD dwID, LPCTSTR lpszURL) { if(m_bInitialized) { if(_tcsstr(lpszURL, _T("group:")) == lpszURL) { int iGroupID; _stscanf(&lpszURL[6], _T("%d"), &iGroupID); StartTest(&lpszURL[6]); } else if(_tcsstr(lpszURL, _T("test:")) == lpszURL) { StartTest(&lpszURL[5], FALSE); } else if(_tcsstr(lpszURL, _T("folder:")) == lpszURL) { TestGroup* pGroup = m_TestList.FindGroup(&lpszURL[7]); if(pGroup) pGroup->OpenFolder(); } else if(_tcsstr(lpszURL, _T("open:")) == lpszURL) { Execute(&lpszURL[5], TRUE); } else if(_tcsstr(lpszURL, _T("execute:")) == lpszURL) { Execute(&lpszURL[8]); } else if(_tcsstr(lpszURL, _T("quit:")) == lpszURL) { g_pSystem->LogWarning(_L(FORCE_TO_QUIT_PROGRAM)); TestVector* pTestVector = TestVector::CurrentTestVecotr(); if(pTestVector) ForceToQuit(pTestVector->Group()->GetConfig(TG_DESC_PROGRAM)); } else if(_tcsstr(lpszURL, _T("refresh:")) == lpszURL) { if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else { m_TestList.Refresh(); g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE)); } } else if(_tcsstr(lpszURL, _T("testall:")) == lpszURL) { if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else StartTest(); } return NULL; } return lpszURL; } void ScenarioTest::SetLock(BOOL bLock) { if(bLock) { m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><button class='ShadowButton'>%s</button></td><td style='text-align:right'></td></tbody></table>\");"), _L(TEST_IN_PROGRESS)); } else { m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><a href='testall:'><button class='ShadowButton'>%s</button></a></td><td style='text-align:right'><a href='refresh:'><img class='MiniButton' src='refresh.png' title='%s'></a></td></tbody></table>\");"), _L(TEST_ALL), _L(RESCAN_ALL)); } if(m_bInitialized) { if(bLock) { m_pDoc->Lock(); } else { m_pDoc->UnLock(); } } } void ScenarioTest::OnHtmlDocumentComplete(DWORD dwID, LPCTSTR lpszURL) { if(!m_bInitialized) { m_TestList.Initialize(__sScenarioPath, __sProgramPath); SetLock(FALSE); m_bInitialized = TRUE; } } void ScenarioTest::Execute(LPCTSTR sScript, BOOL bShell) { CString Script(sScript); Script.Replace(_T("/"), _T("\\")); Script.Replace(_T("%20"), _T(" ")); { int iPos = 0; LPCTSTR sDelim = _T("?"); CString sExecuteFile, sArg, sRunPath; sExecuteFile = Script.Tokenize(sDelim, iPos); if(iPos > 0) sArg = Script.Tokenize(sDelim, iPos); if(iPos > 0) sRunPath = Script.Tokenize(sDelim, iPos); if(sRunPath.IsEmpty()) sRunPath = _T("%PROJECT%Program"); sRunPath = g_pSystem->RetrieveFullPath(sRunPath); sExecuteFile = g_pSystem->RetrieveFullPath(sExecuteFile); if(bShell) ShellExecute(NULL, NULL, sExecuteFile, sArg, NULL, SW_SHOW); else g_pSystem->ExecuteFile(sExecuteFile, sArg, TRUE, NULL, sRunPath, _T("*E:"), -1, _T("*I:"), 1, NULL); } } void ScenarioTest::StartTest(LPCTSTR sPath, BOOL bGroup) { if(!sPath) { // add all TestGroup* pGroup = m_TestList.GetNextGroup(); while(pGroup) { TestVector* pVector = pGroup->GetNextVector(); while(pVector) { m_Scenario.push_back(pVector); pVector = pGroup->GetNextVector(pVector); } pGroup = m_TestList.GetNextGroup(pGroup); } } else if(bGroup) { // add group TestGroup* pGroup = m_TestList.FindGroup(sPath); TestVector* pVector = NULL; if(pGroup) pVector = pGroup->GetNextVector(); while(pVector) { m_Scenario.push_back(pVector); pVector = pGroup->GetNextVector(pVector); } } else { // add vector TestVector* pVector = m_TestList.FindVector(sPath); if(pVector) m_Scenario.push_back(pVector); } if(m_Scenario.size() > 1) { SetEnvironmentVariable(_T("SIM_WAVE_MODE"), _T("None")); } { CString sSize; sSize.Format(_T("%d"), m_Scenario.size()); SetEnvironmentVariable(_T("GROUP_TEST_SIZE"), (LPCTSTR)sSize); } if(!m_pDoc->IsLocked()) { m_pDoc->SetTimer(COMMAND_ID_DO_TEST, 0); } else { g_pSystem->LogInfo(_L(ADD_TEST_LIST), sPath); } } BOOL ScenarioTest::OnTest(void) { TestVector* pVector = m_Scenario.front(); if(pVector) { SetLock(); m_Scenario.pop_front(); pVector->DoTest(); m_TestList.UpdateTable(); SetLock(FALSE); } if(!m_Scenario.size()) { ITDDocument* pDoc = g_pSystem->GetDocument(_T("System")); if(pDoc) pDoc->GetImplementation()->OnCommand(TD_EXTERNAL_COMMAND - 1); g_pSystem->LogInfo(_L(TEST_IS_OVER)); return FALSE; } return TRUE; } #include <TlHelp32.h> void ScenarioTest::ForceToQuit(LPCTSTR sFileName) { HANDLE hSnapShot; PROCESSENTRY32 pEntry; hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL); if(hSnapShot == INVALID_HANDLE_VALUE) { return; } pEntry.dwSize = sizeof(pEntry); if(Process32First(hSnapShot, &pEntry)) { do { if(!_tcscmp(pEntry.szExeFile, sFileName)) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID); if(hProcess) { if(TerminateProcess(hProcess, 0)) { unsigned long nCode; GetExitCodeProcess(hProcess, &nCode); } CloseHandle(hProcess); } break; } } while(Process32Next(hSnapShot, &pEntry)); } }
28.785908
302
0.695914
testdrive-profiling-master
2f4974d6d95586a9cbf61a1a1bf9c636ea7023a5
11,536
cpp
C++
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
null
null
null
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
null
null
null
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
1
2021-05-09T12:51:18.000Z
2021-05-09T12:51:18.000Z
#include "bruneton_probe_renderer.h" #include "../renderer.h" #include "../resource_manager.h" #include "../logger.h" #define _USE_MATH_DEFINES #include <math.h> #include <gtc/matrix_transform.hpp> namespace nimble { // ----------------------------------------------------------------------------------------------------------------------------------- BrunetonProbeRenderer::BrunetonProbeRenderer() { } // ----------------------------------------------------------------------------------------------------------------------------------- BrunetonProbeRenderer::~BrunetonProbeRenderer() { } // ----------------------------------------------------------------------------------------------------------------------------------- bool BrunetonProbeRenderer::initialize(Renderer* renderer, ResourceManager* res_mgr) { register_float_parameter("Sun Radius", m_sun_angular_radius); register_float_parameter("Exposure", m_exposure); // Values from "Reference Solar Spectral Irradiance: ASTM G-173", ETR column // (see http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/ASTMG173.html), // summed and averaged in each bin (e.g. the value for 360nm is the average // of the ASTM G-173 values for all wavelengths between 360 and 370nm). // Values in W.m^-2. int lambda_min = 360; int lambda_max = 830; double kSolarIrradiance[] = { 1.11776, 1.14259, 1.01249, 1.14716, 1.72765, 1.73054, 1.6887, 1.61253, 1.91198, 2.03474, 2.02042, 2.02212, 1.93377, 1.95809, 1.91686, 1.8298, 1.8685, 1.8931, 1.85149, 1.8504, 1.8341, 1.8345, 1.8147, 1.78158, 1.7533, 1.6965, 1.68194, 1.64654, 1.6048, 1.52143, 1.55622, 1.5113, 1.474, 1.4482, 1.41018, 1.36775, 1.34188, 1.31429, 1.28303, 1.26758, 1.2367, 1.2082, 1.18737, 1.14683, 1.12362, 1.1058, 1.07124, 1.04992 }; // Values from http://www.iup.uni-bremen.de/gruppen/molspec/databases/ // referencespectra/o3spectra2011/index.html for 233K, summed and averaged in // each bin (e.g. the value for 360nm is the average of the original values // for all wavelengths between 360 and 370nm). Values in m^2. double kOzoneCrossSection[] = { 1.18e-27, 2.182e-28, 2.818e-28, 6.636e-28, 1.527e-27, 2.763e-27, 5.52e-27, 8.451e-27, 1.582e-26, 2.316e-26, 3.669e-26, 4.924e-26, 7.752e-26, 9.016e-26, 1.48e-25, 1.602e-25, 2.139e-25, 2.755e-25, 3.091e-25, 3.5e-25, 4.266e-25, 4.672e-25, 4.398e-25, 4.701e-25, 5.019e-25, 4.305e-25, 3.74e-25, 3.215e-25, 2.662e-25, 2.238e-25, 1.852e-25, 1.473e-25, 1.209e-25, 9.423e-26, 7.455e-26, 6.566e-26, 5.105e-26, 4.15e-26, 4.228e-26, 3.237e-26, 2.451e-26, 2.801e-26, 2.534e-26, 1.624e-26, 1.465e-26, 2.078e-26, 1.383e-26, 7.105e-27 }; // From https://en.wikipedia.org/wiki/Dobson_unit, in molecules.m^-2. double kDobsonUnit = 2.687e20; // Maximum number density of ozone molecules, in m^-3 (computed so at to get // 300 Dobson units of ozone - for this we divide 300 DU by the integral of // the ozone density profile defined below, which is equal to 15km). double kMaxOzoneNumberDensity = 300.0 * kDobsonUnit / 15000.0; // Wavelength independent solar irradiance "spectrum" (not physically // realistic, but was used in the original implementation). double kConstantSolarIrradiance = 1.5; double kTopRadius = 6420000.0; double kRayleigh = 1.24062e-6; double kRayleighScaleHeight = 8000.0; double kMieScaleHeight = 1200.0; double kMieAngstromAlpha = 0.0; double kMieAngstromBeta = 5.328e-3; double kMieSingleScatteringAlbedo = 0.9; double kMiePhaseFunctionG = 0.8; double kGroundAlbedo = 0.1; double max_sun_zenith_angle = (m_use_half_precision ? 102.0 : 120.0) / 180.0 * M_PI; DensityProfileLayer* rayleigh_layer = new DensityProfileLayer("rayleigh", 0.0, 1.0, -1.0 / kRayleighScaleHeight, 0.0, 0.0); DensityProfileLayer* mie_layer = new DensityProfileLayer("mie", 0.0, 1.0, -1.0 / kMieScaleHeight, 0.0, 0.0); // Density profile increasing linearly from 0 to 1 between 10 and 25km, and // decreasing linearly from 1 to 0 between 25 and 40km. This is an approximate // profile from http://www.kln.ac.lk/science/Chemistry/Teaching_Resources/ // Documents/Introduction%20to%20atmospheric%20chemistry.pdf (page 10). std::vector<DensityProfileLayer*> ozone_density; ozone_density.push_back(new DensityProfileLayer("absorption0", 25000.0, 0.0, 0.0, 1.0 / 15000.0, -2.0 / 3.0)); ozone_density.push_back(new DensityProfileLayer("absorption1", 0.0, 0.0, 0.0, -1.0 / 15000.0, 8.0 / 3.0)); std::vector<double> wavelengths; std::vector<double> solar_irradiance; std::vector<double> rayleigh_scattering; std::vector<double> mie_scattering; std::vector<double> mie_extinction; std::vector<double> absorption_extinction; std::vector<double> ground_albedo; for (int l = lambda_min; l <= lambda_max; l += 10) { double lambda = l * 1e-3; // micro-meters double mie = kMieAngstromBeta / kMieScaleHeight * pow(lambda, -kMieAngstromAlpha); wavelengths.push_back(l); if (m_use_constant_solar_spectrum) solar_irradiance.push_back(kConstantSolarIrradiance); else solar_irradiance.push_back(kSolarIrradiance[(l - lambda_min) / 10]); rayleigh_scattering.push_back(kRayleigh * pow(lambda, -4)); mie_scattering.push_back(mie * kMieSingleScatteringAlbedo); mie_extinction.push_back(mie); absorption_extinction.push_back(m_use_ozone ? kMaxOzoneNumberDensity * kOzoneCrossSection[(l - lambda_min) / 10] : 0.0); ground_albedo.push_back(kGroundAlbedo); } m_sky_model.m_half_precision = m_use_half_precision; m_sky_model.m_combine_scattering_textures = m_use_combined_textures; m_sky_model.m_use_luminance = m_use_luminance; m_sky_model.m_wave_lengths = wavelengths; m_sky_model.m_solar_irradiance = solar_irradiance; m_sky_model.m_sun_angular_radius = m_sun_angular_radius; m_sky_model.m_bottom_radius = m_bottom_radius; m_sky_model.m_top_radius = kTopRadius; m_sky_model.m_rayleigh_density = rayleigh_layer; m_sky_model.m_rayleigh_scattering = rayleigh_scattering; m_sky_model.m_mie_density = mie_layer; m_sky_model.m_mie_scattering = mie_scattering; m_sky_model.m_mie_extinction = mie_extinction; m_sky_model.m_mie_phase_function_g = kMiePhaseFunctionG; m_sky_model.m_absorption_density = ozone_density; m_sky_model.m_absorption_extinction = absorption_extinction; m_sky_model.m_ground_albedo = ground_albedo; m_sky_model.m_max_sun_zenith_angle = max_sun_zenith_angle; m_sky_model.m_length_unit_in_meters = m_length_unit_in_meters; int num_scattering_orders = 4; bool status = m_sky_model.initialize(num_scattering_orders, renderer, res_mgr); glm::mat4 capture_projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f); glm::mat4 capture_views[] = { glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)) }; for (int i = 0; i < 6; i++) m_cubemap_views[i] = capture_projection * capture_views[i]; m_sun_dir = glm::vec3(0.0f); std::vector<std::string> defines; if (m_use_luminance == LUMINANCE::NONE) defines.push_back("RADIANCE_API_ENABLED"); if (m_use_combined_textures) defines.push_back("COMBINED_SCATTERING_TEXTURES"); m_env_map_vs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_vs.glsl", GL_VERTEX_SHADER, defines); m_env_map_fs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_fs.glsl", GL_FRAGMENT_SHADER, defines); if (m_env_map_vs && m_env_map_fs) { m_env_map_program = renderer->create_program(m_env_map_vs, m_env_map_fs); if (!m_env_map_program) { NIMBLE_LOG_ERROR("Failed to create program"); return false; } } else { NIMBLE_LOG_ERROR("Failed to load shaders"); return false; } return status; } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::env_map(double delta, Renderer* renderer, Scene* scene) { uint32_t num_lights = scene->directional_light_count(); DirectionalLight* lights = scene->directional_lights(); if (num_lights > 0) { DirectionalLight& light = lights[0]; glm::vec3 sun_dir = light.transform.forward(); if (m_sun_dir != sun_dir) { m_sun_dir = sun_dir; for (int i = 0; i < 6; i++) m_cubemap_rtv[i] = RenderTargetView(i, 0, 0, scene->env_map()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); m_env_map_program->use(); m_sky_model.bind_rendering_uniforms(m_env_map_program.get()); m_env_map_program->set_uniform("sun_size", glm::vec2(tan(m_sun_angular_radius), cos(m_sun_angular_radius))); m_env_map_program->set_uniform("sun_direction", -light.transform.forward()); m_env_map_program->set_uniform("earth_center", glm::vec3(0.0f, -m_bottom_radius / m_length_unit_in_meters, 0.0f)); m_env_map_program->set_uniform("exposure", m_exposure); for (int i = 0; i < 6; i++) { m_env_map_program->set_uniform("view_projection", m_cubemap_views[i]); renderer->bind_render_targets(1, &m_cubemap_rtv[i], nullptr); glViewport(0, 0, ENVIRONMENT_MAP_SIZE, ENVIRONMENT_MAP_SIZE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); renderer->cube_vao()->bind(); glDrawArrays(GL_TRIANGLES, 0, 36); } } } } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::diffuse(double delta, Renderer* renderer, Scene* scene) { } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::specular(double delta, Renderer* renderer, Scene* scene) { } // ----------------------------------------------------------------------------------------------------------------------------------- std::string BrunetonProbeRenderer::probe_contribution_shader_path() { return ""; } // ----------------------------------------------------------------------------------------------------------------------------------- } // namespace nimble
46.704453
527
0.59492
Hanggansta
2f49e24392da7f48d3dc992e0586a7843d6639a6
18,714
cc
C++
Translator_file/examples/step-26/step-26.cc
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
Translator_file/examples/step-26/step-26.cc
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
Translator_file/examples/step-26/step-26.cc
jiaqiwang969/deal.ii-course-practice
0da5ad1537d8152549d8a0e4de5872efe7619c8a
[ "MIT" ]
null
null
null
/* --------------------------------------------------------------------- * * Copyright (C) 2013 - 2021 by the deal.II authors * * This file is part of the deal.II library. * * The deal.II library is free software; you can use it, redistribute * it, and/or modify it under the terms of the GNU Lesser General * Public License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * The full text of the license can be found in the file LICENSE.md at * the top level directory of deal.II. * * --------------------------------------------------------------------- * * Author: Wolfgang Bangerth, Texas A&M University, 2013 */ // 程序以通常的包含文件开始,所有这些文件你现在应该都见过了。 #include <deal.II/base/utilities.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/function.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/full_matrix.h> #include <deal.II/lac/dynamic_sparsity_pattern.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/solver_cg.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/affine_constraints.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_refinement.h> #include <deal.II/grid/grid_out.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/numerics/data_out.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/numerics/error_estimator.h> #include <deal.II/numerics/solution_transfer.h> #include <deal.II/numerics/matrix_tools.h> #include <fstream> #include <iostream> // 然后照例将这个程序的所有内容放入一个命名空间,并将deal.II命名空间导入到我们将要工作的命名空间中。 namespace Step26 { using namespace dealii; // @sect3{The <code>HeatEquation</code> class} // 下一个部分是这个程序的主类的声明。它沿用了以前的例子中公认的路径。如果你看过 step-6 ,例如,这里唯一值得注意的是,我们需要建立两个矩阵(质量和拉普拉斯矩阵),并保存当前和前一个时间步骤的解。然后,我们还需要存储当前时间、时间步长和当前时间步长的编号。最后一个成员变量表示介绍中讨论的theta参数,它允许我们在一个程序中处理显式和隐式欧拉方法,以及Crank-Nicolson方法和其他通用方法。 // 就成员函数而言,唯一可能的惊喜是 <code>refine_mesh</code> 函数需要最小和最大的网格细化级别的参数。这样做的目的在介绍中已经讨论过了。 template <int dim> class HeatEquation { public: HeatEquation(); void run(); private: void setup_system(); void solve_time_step(); void output_results() const; void refine_mesh(const unsigned int min_grid_level, const unsigned int max_grid_level); Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; AffineConstraints<double> constraints; SparsityPattern sparsity_pattern; SparseMatrix<double> mass_matrix; SparseMatrix<double> laplace_matrix; SparseMatrix<double> system_matrix; Vector<double> solution; Vector<double> old_solution; Vector<double> system_rhs; double time; double time_step; unsigned int timestep_number; const double theta; }; // @sect3{Equation data} // 在下面的类和函数中,我们实现了定义这个问题的各种数据(右手边和边界值),这些数据在这个程序中使用,我们需要函数对象。右手边的选择是在介绍的最后讨论的。对于边界值,我们选择零值,但这很容易在下面改变。 template <int dim> class RightHandSide : public Function<dim> { public: RightHandSide() : Function<dim>() , period(0.2) {} virtual double value(const Point<dim> & p, const unsigned int component = 0) const override; private: const double period; }; template <int dim> double RightHandSide<dim>::value(const Point<dim> & p, const unsigned int component) const { (void)component; AssertIndexRange(component, 1); Assert(dim == 2, ExcNotImplemented()); const double time = this->get_time(); const double point_within_period = (time / period - std::floor(time / period)); if ((point_within_period >= 0.0) && (point_within_period <= 0.2)) { if ((p[0] > 0.5) && (p[1] > -0.5)) return 1; else return 0; } else if ((point_within_period >= 0.5) && (point_within_period <= 0.7)) { if ((p[0] > -0.5) && (p[1] > 0.5)) return 1; else return 0; } else return 0; } template <int dim> class BoundaryValues : public Function<dim> { public: virtual double value(const Point<dim> & p, const unsigned int component = 0) const override; }; template <int dim> double BoundaryValues<dim>::value(const Point<dim> & /*p*/, const unsigned int component) const { (void)component; Assert(component == 0, ExcIndexRange(component, 0, 1)); return 0; } // @sect3{The <code>HeatEquation</code> implementation} // 现在是实现主类的时候了。让我们从构造函数开始,它选择了一个线性元素,一个时间步长为1/500的常数(记得上面把右边的源的一个周期设置为0.2,所以我们用100个时间步长来解决每个周期),并通过设置 $\theta=1/2$ 选择了Crank Nicolson方法. template <int dim> HeatEquation<dim>::HeatEquation() : fe(1) , dof_handler(triangulation) , time_step(1. / 500) , theta(0.5) {} // @sect4{<code>HeatEquation::setup_system</code>} // 下一个函数是设置DoFHandler对象,计算约束,并将线性代数对象设置为正确的大小。我们还在这里通过简单地调用库中的两个函数来计算质量和拉普拉斯矩阵。 // 注意我们在组装矩阵时不考虑悬挂节点的约束(两个函数都有一个AffineConstraints参数,默认为一个空对象)。这是因为我们要在结合当前时间步长的矩阵后,在run()中浓缩约束。 template <int dim> void HeatEquation<dim>::setup_system() { dof_handler.distribute_dofs(fe); std::cout << std::endl << "===========================================" << std::endl << "Number of active cells: " << triangulation.n_active_cells() << std::endl << "Number of degrees of freedom: " << dof_handler.n_dofs() << std::endl << std::endl; constraints.clear(); DoFTools::make_hanging_node_constraints(dof_handler, constraints); constraints.close(); DynamicSparsityPattern dsp(dof_handler.n_dofs()); DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, /*keep_constrained_dofs = */ true); sparsity_pattern.copy_from(dsp); mass_matrix.reinit(sparsity_pattern); laplace_matrix.reinit(sparsity_pattern); system_matrix.reinit(sparsity_pattern); MatrixCreator::create_mass_matrix(dof_handler, QGauss<dim>(fe.degree + 1), mass_matrix); MatrixCreator::create_laplace_matrix(dof_handler, QGauss<dim>(fe.degree + 1), laplace_matrix); solution.reinit(dof_handler.n_dofs()); old_solution.reinit(dof_handler.n_dofs()); system_rhs.reinit(dof_handler.n_dofs()); } // @sect4{<code>HeatEquation::solve_time_step</code>} // 下一个函数是解决单个时间步骤的实际线性系统的函数。这里没有什么值得惊讶的。 template <int dim> void HeatEquation<dim>::solve_time_step() { SolverControl solver_control(1000, 1e-8 * system_rhs.l2_norm()); SolverCG<Vector<double>> cg(solver_control); PreconditionSSOR<SparseMatrix<double>> preconditioner; preconditioner.initialize(system_matrix, 1.0); cg.solve(system_matrix, solution, system_rhs, preconditioner); constraints.distribute(solution); std::cout << " " << solver_control.last_step() << " CG iterations." << std::endl; } // @sect4{<code>HeatEquation::output_results</code>} // 在生成图形输出方面也没有什么新东西,只是我们告诉DataOut对象当前的时间和时间步长是多少,以便将其写入输出文件中。 template <int dim> void HeatEquation<dim>::output_results() const { DataOut<dim> data_out; data_out.attach_dof_handler(dof_handler); data_out.add_data_vector(solution, "U"); data_out.build_patches(); data_out.set_flags(DataOutBase::VtkFlags(time, timestep_number)); const std::string filename = "solution-" + Utilities::int_to_string(timestep_number, 3) + ".vtk"; std::ofstream output(filename); data_out.write_vtk(output); } // @sect4{<code>HeatEquation::refine_mesh</code>} // 这个函数是程序中最有趣的部分。它负责自适应网格细化的工作。这个函数执行的三个任务是:首先找出需要细化/粗化的单元,然后实际进行细化,最后在两个不同的网格之间传输解向量。第一个任务是通过使用成熟的凯利误差估计器来实现的。第二项任务是实际进行再细化。这也只涉及到基本的函数,例如 <code>refine_and_coarsen_fixed_fraction</code> ,它可以细化那些具有最大估计误差的单元,这些误差加起来占60%,并粗化那些具有最小误差的单元,这些单元加起来占40%的误差。请注意,对于像当前这样的问题,即有事发生的区域正在四处移动,我们希望积极地进行粗化,以便我们能够将单元格移动到有必要的地方。 // 正如在介绍中已经讨论过的,太小的网格会导致太小的时间步长,而太大的网格会导致太小的分辨率。因此,在前两个步骤之后,我们有两个循环,将细化和粗化限制在一个允许的单元范围内。 template <int dim> void HeatEquation<dim>::refine_mesh(const unsigned int min_grid_level, const unsigned int max_grid_level) { Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); KellyErrorEstimator<dim>::estimate( dof_handler, QGauss<dim - 1>(fe.degree + 1), std::map<types::boundary_id, const Function<dim> *>(), solution, estimated_error_per_cell); GridRefinement::refine_and_coarsen_fixed_fraction(triangulation, estimated_error_per_cell, 0.6, 0.4); if (triangulation.n_levels() > max_grid_level) for (const auto &cell : triangulation.active_cell_iterators_on_level(max_grid_level)) cell->clear_refine_flag(); for (const auto &cell : triangulation.active_cell_iterators_on_level(min_grid_level)) cell->clear_coarsen_flag(); // 上面这两个循环略有不同,但这很容易解释。在第一个循环中,我们没有调用 <code>triangulation.end()</code> ,而是调用 <code>triangulation.end_active(max_grid_level)</code> 。这两个调用应该产生相同的迭代器,因为迭代器是按级别排序的,不应该有任何级别高于 <code>max_grid_level</code> 的单元格。事实上,这段代码确保了这种情况的发生。 // 作为网格细化的一部分,我们需要将旧的网格中的解向量转移到新的网格中。为此,我们使用了SolutionTransfer类,我们必须准备好需要转移到新网格的解向量(一旦完成细化,我们将失去旧的网格,所以转移必须与细化同时发生)。在我们调用这个函数的时候,我们将刚刚计算出解决方案,所以我们不再需要old_solution变量(它将在网格被细化后被解决方案覆盖,也就是在时间步长结束时;见下文)。换句话说,我们只需要一个求解向量,并将其复制到一个临时对象中,当我们进一步向下调用 <code>setup_system()</code> 时,它就不会被重置。 // 因此,我们将一个SolutionTransfer对象附加到旧的DoF处理程序中,以初始化它。然后,我们准备好三角形和数据向量,以便进行细化(按照这个顺序)。 SolutionTransfer<dim> solution_trans(dof_handler); Vector<double> previous_solution; previous_solution = solution; triangulation.prepare_coarsening_and_refinement(); solution_trans.prepare_for_coarsening_and_refinement(previous_solution); // 现在一切都准备好了,所以进行细化并在新网格上重新创建DoF结构,最后在 <code>setup_system</code> 函数中初始化矩阵结构和新的向量。接下来,我们实际执行从旧网格到新网格的插值解。最后一步是对解向量应用悬空节点约束,即确保位于悬空节点上的自由度值,使解是连续的。这是必要的,因为SolutionTransfer只对单元格进行局部操作,不考虑邻域。 triangulation.execute_coarsening_and_refinement(); setup_system(); solution_trans.interpolate(previous_solution, solution); constraints.distribute(solution); } // @sect4{<code>HeatEquation::run</code>} // 这是程序的主要驱动,我们在这里循环所有的时间步骤。在函数的顶部,我们通过重复第一个时间步长,设置初始全局网格细化的数量和自适应网格细化的初始周期数量。然后,我们创建一个网格,初始化我们要处理的各种对象,设置一个标签,说明我们在重新运行第一个时间步长时应该从哪里开始,并将初始解插值到网格上(我们在这里选择了零函数,当然,我们可以用更简单的方法,直接将解向量设置为零)。我们还输出一次初始时间步长。 // @note 如果你是一个有经验的程序员,你可能会对我们在这段代码中使用 <code>goto</code> 语句感到吃惊 <code>goto</code> 语句现在已经不是特别受人欢迎了,因为计算机科学界的大师之一Edsgar Dijkstra在1968年写了一封信,叫做 "Go To Statement considered harmful"(见<a href="http:en.wikipedia.org/wiki/Considered_harmful">here</a>)。这段代码的作者全心全意地赞同这一观念。 <code>goto</code> 是难以理解的。事实上,deal.II几乎不包含任何出现的情况:不包括基本上是从书本上转录的代码,也不计算重复的代码片断,在写这篇笔记时,大约60万行代码中有3个位置;我们还在4个教程程序中使用它,其背景与这里完全相同。与其在这里试图证明这种情况的出现,不如先看看代码,我们在函数的最后再来讨论这个问题。 template <int dim> void HeatEquation<dim>::run() { const unsigned int initial_global_refinement = 2; const unsigned int n_adaptive_pre_refinement_steps = 4; GridGenerator::hyper_L(triangulation); triangulation.refine_global(initial_global_refinement); setup_system(); unsigned int pre_refinement_step = 0; Vector<double> tmp; Vector<double> forcing_terms; start_time_iteration: time = 0.0; timestep_number = 0; tmp.reinit(solution.size()); forcing_terms.reinit(solution.size()); VectorTools::interpolate(dof_handler, Functions::ZeroFunction<dim>(), old_solution); solution = old_solution; output_results(); // 然后我们开始主循环,直到计算的时间超过我们的结束时间0.5。第一个任务是建立我们需要在每个时间步骤中解决的线性系统的右手边。回顾一下,它包含项 $MU^{n-1}-(1-\theta)k_n AU^{n-1}$ 。我们把这些项放到变量system_rhs中,借助于一个临时矢量。 while (time <= 0.5) { time += time_step; ++timestep_number; std::cout << "Time step " << timestep_number << " at t=" << time << std::endl; mass_matrix.vmult(system_rhs, old_solution); laplace_matrix.vmult(tmp, old_solution); system_rhs.add(-(1 - theta) * time_step, tmp); // 第二块是计算源项的贡献。这与术语 $k_n \left[ (1-\theta)F^{n-1} + \theta F^n \right]$ 相对应。下面的代码调用 VectorTools::create_right_hand_side 来计算向量 $F$ ,在这里我们在评估之前设置了右侧(源)函数的时间。这一切的结果最终都在forcing_terms变量中。 RightHandSide<dim> rhs_function; rhs_function.set_time(time); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(fe.degree + 1), rhs_function, tmp); forcing_terms = tmp; forcing_terms *= time_step * theta; rhs_function.set_time(time - time_step); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(fe.degree + 1), rhs_function, tmp); forcing_terms.add(time_step * (1 - theta), tmp); // 接下来,我们将强迫项加入到来自时间步长的强迫项中,同时建立矩阵 $M+k_n\theta A$ ,我们必须在每个时间步长中进行反转。这些操作的最后一块是消除线性系统中悬挂的节点约束自由度。 system_rhs += forcing_terms; system_matrix.copy_from(mass_matrix); system_matrix.add(theta * time_step, laplace_matrix); constraints.condense(system_matrix, system_rhs); // 在解决这个问题之前,我们还需要做一个操作:边界值。为此,我们创建一个边界值对象,将适当的时间设置为当前时间步长的时间,并像以前多次那样对其进行评估。其结果也被用来在线性系统中设置正确的边界值。 { BoundaryValues<dim> boundary_values_function; boundary_values_function.set_time(time); std::map<types::global_dof_index, double> boundary_values; VectorTools::interpolate_boundary_values(dof_handler, 0, boundary_values_function, boundary_values); MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution, system_rhs); } // 有了这些,我们要做的就是解决这个系统,生成图形数据,以及...... solve_time_step(); output_results(); // ...负责网格的细化。在这里,我们要做的是:(i)在求解过程的最开始,细化所要求的次数,之后我们跳到顶部重新开始时间迭代,(ii)之后每隔五步细化一次。 // 时间循环和程序的主要部分以开始进入下一个时间步骤结束,将old_solution设置为我们刚刚计算出的解决方案。 if ((timestep_number == 1) && (pre_refinement_step < n_adaptive_pre_refinement_steps)) { refine_mesh(initial_global_refinement, initial_global_refinement + n_adaptive_pre_refinement_steps); ++pre_refinement_step; tmp.reinit(solution.size()); forcing_terms.reinit(solution.size()); std::cout << std::endl; goto start_time_iteration; } else if ((timestep_number > 0) && (timestep_number % 5 == 0)) { refine_mesh(initial_global_refinement, initial_global_refinement + n_adaptive_pre_refinement_steps); tmp.reinit(solution.size()); forcing_terms.reinit(solution.size()); } old_solution = solution; } } } // namespace Step26 // 现在你已经看到了这个函数的作用,让我们再来看看 <code>goto</code> 的问题。从本质上讲,代码所做的事情是这样的。 // @code // void run () // { // initialize; // start_time_iteration: // for (timestep=1...) // { // solve timestep; // if (timestep==1 && not happy with the result) // { // adjust some data structures; // goto start_time_iteration; simply try again // } // postprocess; // } // } // @endcode // 这里,"对结果满意 "的条件是我们想保留当前的网格,还是宁愿细化网格并在新网格上重新开始。我们当然可以用下面的方法来取代 <code>goto</code> 的使用。 // @code // void run () // { // initialize; // while (true) // { // solve timestep; // if (not happy with the result) // adjust some data structures; // else // break; // } // postprocess; // for (timestep=2...) // { // solve timestep; // postprocess; // } // } // @endcode // 这样做的好处是摆脱了 <code>goto</code> ,但缺点是必须在两个不同的地方重复实现 "解算时间步长 "和 "后处理 "操作的代码。这可以通过将这些部分的代码(在上面的实际实现中是相当大的块)放到自己的函数中来解决,但是一个带有 <code>break</code> 语句的 <code>while(true)</code> 循环并不真的比 <code>goto</code> 容易阅读或理解。 // 最后,人们可能会简单地同意,<i>in general</i> 。 // <code>goto</code> 语句是个坏主意,但要务实地指出,在某些情况下,它们可以帮助避免代码重复和尴尬的控制流。这可能就是其中之一,它与Steve McConnell在他关于良好编程实践的优秀书籍 "Code Complete" @cite CodeComplete 中采取的立场一致(见 step-1 的介绍中提到的这本书),该书花了惊人的10页来讨论一般的 <code>goto</code> 问题。 // @sect3{The <code>main</code> function} // 走到这一步,这个程序的主函数又没有什么好讨论的了:它看起来就像自 step-6 以来的所有此类函数一样。 int main() { try { using namespace Step26; HeatEquation<2> heat_equation_solver; heat_equation_solver.run(); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; }
34.212066
439
0.610185
jiaqiwang969
2f4c96320cf49fba14bc658832b4d561c921f50e
480
cpp
C++
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; //base class class shape{ protected: int width; int height; public: void setwidth(int w) { width=w; } void setheight(int h) { height=h; } }; //drived class class rectangle:public shape { public: int get_area(){ return (width*height); } }; int main() { rectangle rect; rect.setwidth(5); rect.setheight(7); cout<<"total area :"<<rect.get_area()<<endl; }
14.117647
48
0.572917
jattramesh
2f515c43df3d33da482c89eb87ec4ec7fecec030
1,405
cpp
C++
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// // https://open.kattis.com/problems/ummcode #include <vector> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <stack> #include <cmath> #include <map> #include <utility> #include <queue> #include <iomanip> #include <deque> #include <set> #define Forcase int __t;cin>>__t;for(int cases=1;cases<=__t;cases++) #define For(i, n) for(int i=0;i<n;i++) #define Fore(e, arr) for(auto e:arr) #define INF 1e9 #define LINF 1e18 #define EPS 1e-9 using ull = unsigned long long; using ll = long long; using namespace std; bool um(string& s) { Fore (c, s) { if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) { if (c != 'm' && c != 'u') return false; } } return true; } int main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); // cout.tie(NULL); string s, str; getline(cin, s); stringstream ss; ss << s; while (ss >> s) { if (um(s)) { str += s; } } string real; Fore (c, str) { if (c == 'm' || c == 'u') real += c; } for (int i = 0; i < real.size(); i += 7) { char c = 0; for (int j = i; j < i + 7; j++) { c *= 2; if (real[j] == 'u') { c++; } } cout << c; } cout << '\n'; //cout << real << ' ' << str << '\n'; return 0; }
19.246575
68
0.472598
YourName0729
016ab541edfdb0fec8da16e434d4e8cfc51d05ba
3,234
cxx
C++
src/libprocxx/io/file_descriptor.cxx
vencik/libprocxx
9ed1672951c7c4ac452dd3843735fe0fe3ab33d2
[ "BSD-3-Clause" ]
null
null
null
src/libprocxx/io/file_descriptor.cxx
vencik/libprocxx
9ed1672951c7c4ac452dd3843735fe0fe3ab33d2
[ "BSD-3-Clause" ]
null
null
null
src/libprocxx/io/file_descriptor.cxx
vencik/libprocxx
9ed1672951c7c4ac452dd3843735fe0fe3ab33d2
[ "BSD-3-Clause" ]
null
null
null
/** * \file * \brief File descriptor wrapper * * \date 2018/04/01 * \author Vaclav Krpec <vencik@razdva.cz> * * * LEGAL NOTICE * * Copyright (c) 2017, Vaclav Krpec * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "file_descriptor.hxx" #include <stdexcept> extern "C" { #include <unistd.h> #include <fcntl.h> } namespace libprocxx { namespace io { file_descriptor::file_descriptor(const file_descriptor & orig) { close(); m_fd = ::dup(orig.m_fd); } file_descriptor & file_descriptor::operator = (int fd) { close(); m_fd = fd; return *this; } int file_descriptor::status() const { int flags = ::fcntl(m_fd, F_GETFL); if (-1 == flags) throw std::runtime_error( "libprocxx::io::file_descriptor::status: " "failed to get status flags"); return flags; } void file_descriptor::status(int flags) { if (-1 == ::fcntl(m_fd, F_SETFL, flags)) throw std::runtime_error( "libprocxx::io::file_descriptor::status: " "failed to set status flags"); } void file_descriptor::close() { if (closed()) return; ::close(m_fd); m_fd = -1; } std::tuple<size_t, int> file_descriptor::read(void * data, size_t size) { const ssize_t rcnt = ::read(m_fd, data, size); return -1 == rcnt ? std::tuple<size_t, int>(0, errno) : std::tuple<size_t, int>((size_t)rcnt, 0); } std::tuple<size_t, int> file_descriptor::write(const void * data, size_t size) { const ssize_t wcnt = ::write(m_fd, data, size); return -1 == wcnt ? std::tuple<size_t, int>(0, errno) : std::tuple<size_t, int>((size_t)wcnt, 0); } }} // end of namespace libprocxx::io
28.619469
80
0.679344
vencik
016d09b9894428db9518336c24de38bfe10ec957
611
cpp
C++
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
// Soma de Casas // https://neps.academy/lesson/173 #include <iostream> using namespace std; #define MAXN 100000 int N, K, casas[MAXN]; int busca(int x) { int ini=0, fim=N-1, meio; while (ini<=fim) { meio = (ini+fim)/2; if (casas[meio] > x) fim = meio-1; if (casas[meio] < x) ini = meio+1; if (casas[meio] == x) return true; } return false; } int main() { cin >> N; for (int i = 0; i < N; i++) cin >> casas[i]; cin >> K; for (int i = 0; i < N; i++) { if (busca(K-casas[i])) { cout << casas[i] << ' ' << K-casas[i] << endl; break; } } return 0; }
16.078947
52
0.513912
homembaixinho
016ebe407f7707d1008e404dfdf8d8e80e371d03
2,808
cpp
C++
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
karenl7/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
6
2019-01-30T00:11:55.000Z
2022-03-09T02:44:51.000Z
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
null
null
null
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
4
2018-09-08T00:16:55.000Z
2022-03-09T02:44:54.000Z
void add_lane_disturbance_v2( beacls::FloatVec& lane, const std::vector<size_t> shape, beacls::FloatVec range, beacls::FloatVec gmin, beacls::FloatVec gmax, FLOAT_TYPE vehicle_width, FLOAT_TYPE fill_Value, size_t dim){ FLOAT_TYPE x_unit = (static_cast<float>(shape[0])-1)/(gmax[0]-gmin[0]); FLOAT_TYPE y_unit = (static_cast<float>(shape[1])-1)/(gmax[1]-gmin[1]); FLOAT_TYPE b_unit = (static_cast<float>(shape[4])-1)/(gmax[4]-gmin[4]); long unsigned int x1 = (long unsigned int)(x_unit*(range[0]-gmin[0])+0.5); long unsigned int x2 = (long unsigned int)(x_unit*(range[1]-gmin[0])+0.5); beacls::IntegerVec x_index{x1,x2}; long unsigned int y1 = (long unsigned int)(y_unit*(range[2]-gmin[1])+0.5); long unsigned int y2 = (long unsigned int)(y_unit*(range[3]-gmin[1])+0.5); beacls::IntegerVec y_index{y1,y2}; long unsigned int x_size, y_size, z_size, a_size, b_size, y, z, a, b, b2y, yz_unit; FLOAT_TYPE y_add = (y_unit*vehicle_width); FLOAT_TYPE x_add = (x_unit*vehicle_width); beacls::IntegerVec n; x_size = x2-x1+1; y_size = y2-y1+1; z_size = shape[2]; a_size = shape[3]; b_size = shape[4]; // printf("x_size: %lu\n", x_size); // printf("y_size: %lu\n", y_size); beacls::IntegerVec b2y_index; beacls::IntegerVec y_addvec{0,0}; beacls::IntegerVec x_addvec{(long unsigned int)((static_cast<float>(x_size)-1.)/2.-x_add+0.5),(long unsigned int)((static_cast<float>(x_size)-1.)/2.+x_add+0.5)}; beacls::IntegerVec b_addvec{(long unsigned int)((range[2]-gmin[4])*b_unit+0.5),(long unsigned int)((range[3]-gmin[4])*b_unit+0.5)}; // printf("b_addvec: %lu\n", b_addvec[0]); // printf("b_addvec: %lu\n", b_addvec[1]); b_addvec[1] = b_addvec[1]; FLOAT_TYPE by_unit = 1.;//static_cast<float>(b_addvec[1]-b_addvec[0]+1)/y_size; for (b = b_addvec[0]; b < b_addvec[1]+1; ++b) { for (a = 0; a < a_size; ++a) { for (z = 0; z < z_size; ++z) { y_addvec[0] = (long unsigned int)((b-b_addvec[0])/by_unit-y_add+0.5); y_addvec[1] = (long unsigned int)((b-b_addvec[0])/by_unit+y_add+0.5); // printf("y_addvec: %lu\n", y_addvec[0]); // printf("y_addvec: %lu\n", y_addvec[1]); if (y_addvec[0]<0 || y_addvec[0]>1000){ y_addvec[0] = 0; } if (y_addvec[1]>y_size-1){ y_addvec[1] = y_size-1; } for (y = y_addvec[0]; y < y_addvec[1]+1; ++y){ n = {b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[0], b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[1]}; std::fill(lane.begin()+n[0],lane.begin()+n[1]+1,fill_Value); } } } } }
40.114286
215
0.603276
karenl7
0170c9fa6a328def88ae44587ce0c326d53f3be7
1,619
cpp
C++
src/log/log.cpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
null
null
null
src/log/log.cpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
8
2018-05-26T19:27:53.000Z
2018-10-28T19:31:33.000Z
src/log/log.cpp
kodo-pp/IVR
e904341d1850baf81e8aeecbf498691fbe8e50aa
[ "MIT" ]
1
2019-05-07T15:32:38.000Z
2019-05-07T15:32:38.000Z
#include <atomic> #include <chrono> #include <codecvt> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <locale> #include <mutex> #include <modbox/log/log.hpp> static std::recursive_mutex lbfMutex; std::recursive_mutex logMutex; static std::wstring cachedLineBegin; static std::atomic<time_t> prevTime(0); // OK, too lazy to cope with references, so let's pray and hope that compiler // will optimize it to move semantics static LogStream logStream([]() -> std::wstring { auto stl_now = std::chrono::system_clock::now(); time_t c_now = std::chrono::system_clock::to_time_t(stl_now); if (c_now == prevTime) { lbfMutex.lock(); std::wstring copied = cachedLineBegin; lbfMutex.unlock(); return copied; } prevTime = c_now; struct tm* tm_now = new struct tm; localtime_r(&c_now, tm_now); char* lineBegin; // Current time // Example: // [LOG: 23.11.2039 16:44:37] asprintf(&lineBegin, "[LOG: %02d.%02d.%d %02d:%02d:%02d] T~%04u | ", tm_now->tm_mday, tm_now->tm_mon + 1, tm_now->tm_year + 1900, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, (uint)pthread_self() % 10000); std::wstring stlLineBegin(lineBegin, lineBegin + strlen(lineBegin)); free(lineBegin); lbfMutex.lock(); cachedLineBegin = stlLineBegin; lbfMutex.unlock(); delete tm_now; return stlLineBegin; }); static LogStream& logStreamLink = logStream; LogStream& getLogStream() { return logStreamLink; }
24.164179
77
0.632489
kodo-pp
01711e943bc73ff5e41c51c8f7030c4bafda1b67
7,173
cpp
C++
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include "test.h" #include "player/PlayFramesAction.h" TEST(playFramesAction_tests, afterDeclaration){ PlayFramesAction playFramesAction; playFramesAction.printInfo("pre:"); EXPECT_FALSE(playFramesAction.isActive()); } TEST(playFramesAction_tests, afterInit){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 50, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); EXPECT_TRUE(playFramesAction.isActive( )); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); } TEST(playFramesAction_tests, printStateForStaticFrame){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 10, 1, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); playFramesAction.printInfo("pre:"); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_STREQ(playFramesAction.getActionName(), "Play Frame"); } TEST(playFramesAction_tests, wrongAaction){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{ANIMATE, 10, 50, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); } TEST(playFramesAction_tests, testNext){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); EXPECT_FALSE(sframe.isLastFrame); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); playFramesAction.printState(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 1); } TEST(playFramesAction_tests, testNextWithPixelFrame){ // 3 frames: red, blue, green for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(0, p, RED); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(1, p, BLUE); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(2 ,p, GREEN); } PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); // test the first 3 frames EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgbVal rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 254); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 254); playFramesAction.setDimFactor(0.1); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 25); // 254/10 EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_EQ(rgb0.r, 0); } TEST(playFramesAction_tests, testWithDimFactor){ // 3 frames: red, blue, green for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(0, p, RED); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(1, p, BLUE); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(2 ,p, GREEN); } PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; options.dimFactor = 0.1; playFramesAction.init(rawCmd0, &sframe, options); playFramesAction.printInfo(""); // test the first 3 frames EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgbVal rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 25); // 254/10 EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 25); // 254/10 playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 25); // 254/10 EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_EQ(rgb0.r, 0); } TEST(playFramesAction_tests, testFinishedAbstract){ PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); AbstractAction *a = dynamic_cast<AbstractAction*>(&playFramesAction); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_FALSE(sframe.isLastFrame); for (int i=0; i<3*3-2; i++) { a->next(); EXPECT_FALSE(sframe.isLastFrame); } // last iteration a->next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_FALSE(sframe.isLastFrame); // finished a->next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_FALSE(playFramesAction.isActive()); EXPECT_TRUE(sframe.isLastFrame); } TEST(playFramesAction_tests, testBackwardComplete){ PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 12, 10, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; EXPECT_FALSE(playFramesAction.isActive()); playFramesAction.init(rawCmd0, &sframe, options); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_FALSE(sframe.isLastFrame); for (int i=0; i<3*3-3; i++) { playFramesAction.next(); EXPECT_FALSE(sframe.isLastFrame); } // last iteration playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_FALSE(sframe.isLastFrame); // finished playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_FALSE(playFramesAction.isActive()); EXPECT_TRUE(sframe.isLastFrame); }
29.763485
71
0.732748
gmoehler
01715332cdd82763d0e23ef996bb901ffbd4d0c7
16,727
cpp
C++
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Filename: BaseWindow.cpp //////////////////////////////////////////////////////////////////////////////// #include "BaseWindow.h" #include "imgui.h" #include "..\imgui_extension.h" Jani::Inspector::BaseWindow::BaseWindow(InspectorManager& _inspector_manager, const std::string _window_type_name) : m_inspector_manager(_inspector_manager) { static WindowId unique_index_counter = 0; m_unique_id = unique_index_counter++; m_name = _window_type_name; m_unique_name = _window_type_name + "###" + std::to_string(m_unique_id); } Jani::Inspector::BaseWindow::~BaseWindow() { RemoveAllInputWindowConnections(*this); RemoveAllOutputWindowConnections(*this); } void Jani::Inspector::BaseWindow::PreUpdate() { m_updated = false; } void Jani::Inspector::BaseWindow::Update() { m_updated = true; } void Jani::Inspector::BaseWindow::Draw( const CellsInfos& _cell_infos, const WorkersInfos& _workers_infos) { } void Jani::Inspector::BaseWindow::DrawConnections() { auto DrawConnection = [](ImVec2 _from, ImVec2 _to, ImColor _color) -> void { ImVec2 lenght = ImVec2(_to.x - _from.x, _to.y - _from.y); float factor_from_points = std::sqrt(std::pow(lenght.x, 2) + std::pow(lenght.y, 2)) / 2.0f; auto pos0 = _from; auto cp0 = ImVec2(_from.x - factor_from_points, _from.y); auto cp1 = ImVec2(_to.x + factor_from_points, _to.y); auto pos1 = _to; ImGui::GetForegroundDrawList()->AddBezierCurve( pos0, cp0, cp1, pos1, _color, 2); }; auto GetColorForDataType = [](WindowDataType _data_type) -> ImColor { switch (_data_type) { case WindowDataType::EntityData: { return ImColor(ImVec4(0.9f, 0.3f, 0.3f, 1.0f)); } case WindowDataType::EntityId: { return ImColor(ImVec4(0.3f, 0.9f, 0.3f, 1.0f)); } case WindowDataType::Constraint: { return ImColor(ImVec4(0.3f, 0.3f, 0.9f, 1.0f)); } case WindowDataType::Position: { return ImColor(ImVec4(0.7f, 0.9f, 0.3f, 1.0f)); } case WindowDataType::VisualizationSettings: { return ImColor(ImVec4(0.3f, 0.7f, 0.9f, 1.0f)); } default: { return ImColor(ImVec4(0.9f, 0.9f, 0.9f, 1.0f)); } } }; for (int i = 0; i < m_output_connections.size(); i++) { auto& output_connection_info = m_output_connections[i]; for (auto& [window_id, window] : output_connection_info) { DrawConnection(m_outputs_position, window->GetConnectionInputPosition(), GetColorForDataType(magic_enum::enum_value<WindowDataType>(i))); } } if (m_receiving_connection) { DrawConnection(m_receiving_connection->window->GetConnectionOutputPosition(), m_inputs_position, GetColorForDataType(m_receiving_connection->data_type)); } if (m_creating_connection_payload) { DrawConnection(m_outputs_position, ImGui::GetMousePos(), GetColorForDataType(m_creating_connection_payload->data_type)); } } bool Jani::Inspector::BaseWindow::CanAcceptInputConnection(const WindowInputConnection& _connection) { return false; } std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::DrawOutputOptions(ImVec2 _button_size) { return std::nullopt; } Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetInputTypes() const { return WindowDataType::None; } Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetOutputTypes() const { return WindowDataType::None; } std::optional<std::unordered_map<Jani::EntityId, Jani::Inspector::EntityData>> Jani::Inspector::BaseWindow::GetOutputEntityData() const { return std::nullopt; } std::optional<std::vector<Jani::EntityId>> Jani::Inspector::BaseWindow::GetOutputEntityId() const { return std::nullopt; } std::optional<std::vector<std::shared_ptr<Jani::Inspector::Constraint>>> Jani::Inspector::BaseWindow::GetOutputConstraint() const { return std::nullopt; } std::optional<std::vector<Jani::WorldPosition>> Jani::Inspector::BaseWindow::GetOutputPosition() const { return std::nullopt; } std::optional<Jani::Inspector::VisualizationSettings> Jani::Inspector::BaseWindow::GetOutputVisualizationSettings() const { return std::nullopt; } void Jani::Inspector::BaseWindow::OnPositionChange(ImVec2 _current_pos, ImVec2 _new_pos, ImVec2 _delta) { /* stub */ } void Jani::Inspector::BaseWindow::OnSizeChange(ImVec2 _current_size, ImVec2 _new_size, ImVec2 _delta) { /* stub */ } Jani::Inspector::WindowId Jani::Inspector::BaseWindow::GetId() const { return m_unique_id; } bool Jani::Inspector::BaseWindow::WasUpdated() const { return m_updated; } ImVec2 Jani::Inspector::BaseWindow::GetWindowPos() const { return m_window_pos; } ImVec2 Jani::Inspector::BaseWindow::GetWindowSize() const { return m_is_visible ? m_window_size : ImVec2(m_window_size.x, m_header_height); } const std::string Jani::Inspector::BaseWindow::GetUniqueName() const { return m_unique_name; } bool Jani::Inspector::BaseWindow::IsVisible() const { return m_is_visible; } void Jani::Inspector::BaseWindow::DrawTitleBar(bool _edit_mode, std::optional<WindowInputConnection> _connection) { ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.25f, 0.25f, 0.25f, 1.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); if (ImGui::BeginChild("Title Bar", ImVec2(ImGui::GetWindowSize().x, m_header_height), false, ImGuiWindowFlags_NoDecoration)) { if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered()) { m_is_moving = true; } ImGui::AlignTextToFramePadding(); ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPos().x + 5.0f, ImGui::GetCursorPos().y)); if (ImGui::Button("#")) { m_is_visible = !m_is_visible; } ImGui::SameLine(); ImGui::Text(m_name.c_str()); ImGui::SameLine(); ImVec2 current_cursor_pos = ImGui::GetCursorPos(); float remaining_width = ImGui::GetWindowSize().x; float options_button_size = ImGui::CalcTextSize("*").x + 20.0f; float input_button_size = ImGui::CalcTextSize("+ INPUT").x + 5.0f; float output_button_size = ImGui::CalcTextSize("- OUTPUT").x + 10.0f; float input_button_begin = remaining_width - (options_button_size + input_button_size + output_button_size); float output_button_begin = remaining_width - (options_button_size + output_button_size); float options_button_begin = remaining_width - options_button_size; if (_edit_mode) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.3f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.5f, 0.5f, 0.5f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.4f, 0.4f, 0.4f, 1.0f)); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 2.0f); ImGui::SetWindowFontScale(0.7f); ImGui::SetCursorPos(ImVec2(input_button_begin, current_cursor_pos.y + 3.0f)); m_inputs_position = ImGui::GetCursorScreenPos(); if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); } ImGui::Button("+ INPUT"); if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(0) && _connection && _connection->window != this && !ImGui::GetIO().KeyCtrl) { m_receiving_connection = _connection; ImGui::OpenPopup("Input Popup"); } if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) { RemoveAllInputWindowConnections(*this); } m_inputs_position = m_inputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f); ImGui::SameLine(); ImGui::SetCursorPos(ImVec2(output_button_begin, current_cursor_pos.y + 3.0f)); m_outputs_position = ImGui::GetCursorScreenPos(); if (_connection) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); } if (ImGui::Button("- OUTPUT")) { ImGui::OpenPopup("Output Popup"); } if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) { RemoveAllOutputWindowConnections(*this); } if (_connection) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } m_outputs_position = m_outputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f); ImGui::SetWindowFontScale(1.0f); ImGui::PopStyleVar(); ImGui::PopStyleColor(3); ImGui::SameLine(); } ImGui::SetCursorPos(ImVec2(options_button_begin, current_cursor_pos.y)); if (ImGui::Button("*")) { } ImGui::NewLine(); if (ImGui::BeginPopup("Input Popup") && m_receiving_connection) { if (CanAcceptInputConnection(m_receiving_connection.value())) { AddWindowConnection(*m_receiving_connection->window, *this, m_receiving_connection->data_type, m_receiving_connection->connection_type); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } else { m_receiving_connection = std::nullopt; } if (ImGui::BeginPopup("Output Popup")) { auto creating_connection_payload = DrawOutputOptions(ImVec2(200.0f, 30.0f)); if (creating_connection_payload) { m_creating_connection_payload = creating_connection_payload; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); if (!ImGui::IsMouseDown(0)) { m_is_moving = false; } if (m_is_moving) { auto IO = ImGui::GetIO(); OnPositionChange(ImGui::GetWindowPos(), ImGui::GetWindowPos() + IO.MouseDelta, IO.MouseDelta); m_window_pos = ImVec2(ImGui::GetWindowPos().x + IO.MouseDelta.x, ImGui::GetWindowPos().y + IO.MouseDelta.y); } } void Jani::Inspector::BaseWindow::ProcessResize() { if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered()) { float resize_bar_length = 10.0f; auto mouse_position = ImGui::GetMousePos(); auto left_pos_diff = mouse_position.x - m_window_pos.x; auto top_pos_diff = mouse_position.y - m_window_pos.y; auto right_pos_diff = (m_window_pos.x + m_window_size.x) - mouse_position.x; auto bottom_pos_diff = (m_window_pos.y + m_window_size.y) - mouse_position.y; if (left_pos_diff > 0.f && left_pos_diff < resize_bar_length) { m_is_resizing[0] = true; } if (top_pos_diff > 0.f && top_pos_diff < resize_bar_length) { // m_is_resizing[1] = true; } if (right_pos_diff > 0.f && right_pos_diff < resize_bar_length) { m_is_resizing[2] = true; } if (bottom_pos_diff > 0.f && bottom_pos_diff < resize_bar_length) { m_is_resizing[3] = true; } } if (!ImGui::IsMouseDown(0)) { m_is_resizing[0] = false; m_is_resizing[1] = false; m_is_resizing[2] = false; m_is_resizing[3] = false; } /* if (m_is_resizing[0]) { OnSizeChange(m_window_size, m_window_size - ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(-ImGui::GetIO().MouseDelta.x, 0.0f)); m_window_pos.x += ImGui::GetIO().MouseDelta.x; m_window_size.x -= ImGui::GetIO().MouseDelta.x; } */ /* if (m_is_resizing[1]) { m_window_pos.y -= ImGui::GetIO().MouseDelta.y; m_window_size.y += ImGui::GetIO().MouseDelta.y; } */ if (m_is_resizing[2]) { OnSizeChange(m_window_size, m_window_size + ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f)); m_window_size.x += ImGui::GetIO().MouseDelta.x; } if (m_is_resizing[3]) { OnSizeChange(m_window_size, m_window_size + ImVec2(0.0f, ImGui::GetIO().MouseDelta.y), ImVec2(0.0f, ImGui::GetIO().MouseDelta.y)); m_window_size.y += ImGui::GetIO().MouseDelta.y; } } ImVec2 Jani::Inspector::BaseWindow::GetConnectionInputPosition() const { return m_inputs_position; } ImVec2 Jani::Inspector::BaseWindow::GetConnectionOutputPosition() const { return m_outputs_position; } std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::GetCreatingConnectionPayload() const { return m_creating_connection_payload; } void Jani::Inspector::BaseWindow::ResetIsCreatingConnection() { m_creating_connection_payload = std::nullopt; } bool Jani::Inspector::BaseWindow::AddWindowConnection(BaseWindow& _from, BaseWindow& _to, WindowDataType _data_type, WindowConnectionType _connection_type) { auto data_enum_index = magic_enum::enum_index(_data_type); if (!data_enum_index) { return false; } if (IsConnectedRecursively(_to, _from)) { return false; } if (_to.m_input_connections[data_enum_index.value()] != std::nullopt || _from.m_output_connections[data_enum_index.value()].find(_to.GetId()) != _from.m_output_connections[data_enum_index.value()].end()) { return false; } _to.m_input_connections[data_enum_index.value()] = { &_from, _data_type, _connection_type }; _from.m_output_connections[data_enum_index.value()].insert({ _to.GetId(),&_to }); return true; } bool Jani::Inspector::BaseWindow::IsConnectedRecursively(BaseWindow& _current_window, BaseWindow& _target) { for (auto& output_connections : _current_window.m_output_connections) { for (auto& [window_id, window] : output_connections) { if (window_id == _target.GetId()) { return true; } if (IsConnectedRecursively(*window, _target)) { return true; } } } return false; } bool Jani::Inspector::BaseWindow::RemoveWindowConnection(BaseWindow& _window, WindowDataType _data_type) { auto data_enum_index = magic_enum::enum_index(_data_type); if (!data_enum_index) { return false; } if (_window.m_input_connections[data_enum_index.value()] == std::nullopt) { return false; } _window.m_input_connections[data_enum_index.value()].value().window->m_output_connections[data_enum_index.value()].erase(_window.GetId()); _window.m_input_connections[data_enum_index.value()] = std::nullopt; return true; } void Jani::Inspector::BaseWindow::RemoveAllInputWindowConnections(BaseWindow& _window) { for (int i = 0; i < magic_enum::enum_count<WindowDataType>(); i++) { if (_window.m_input_connections[i].has_value()) { RemoveWindowConnection(_window, magic_enum::enum_value<WindowDataType>(i)); } } } void Jani::Inspector::BaseWindow::RemoveAllOutputWindowConnections(BaseWindow& _window) { for (auto& output_connection_info : _window.m_output_connections) { for (auto& [window_id, window] : output_connection_info) { for (int i = 0; i < window->m_input_connections.size(); i++) { auto& other_window_input_connection = window->m_input_connections[i]; if (other_window_input_connection && other_window_input_connection->window->GetId() == _window.GetId()) { other_window_input_connection = std::nullopt; } } } output_connection_info.clear(); } }
32.99211
241
0.628505
RodrigoHolztrattner
0171b344cb1d582828969b7e099d9e2168cb09f5
5,000
cpp
C++
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
#include <lbmemcheck.hpp> #include <srs_kernel_log.hpp> #ifndef lbtrace #define lbtrace srs_trace #endif #ifndef lberror #define lberror srs_error #endif lbmemcheck_ctx* g_pmcc = NULL; lbmemcheck_ctx* lbmemcheck_initialize() { lbmemcheck_ctx* pmcc = (lbmemcheck_ctx*)::calloc(1, sizeof(lbmemcheck_ctx)); pmcc->plist = lblist_create_context(__INT32_MAX__); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pmcc->pmutex = (pthread_mutex_t*)::malloc(sizeof(pthread_mutex_t)); memset(pmcc->pmutex, 0, sizeof(pthread_mutex_t)); pthread_mutexattr_t attr; pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(pmcc->plist->pmutex, &attr); #endif lbtrace("pmcc:%p = lbmemcheck_initialize\n", pmcc); return pmcc; } void lbmemcheck_finialize(lbmemcheck_ctx** ppmcc) { lbtrace("lbmemcheck_finialize, ppmcc:%p\n", ppmcc); if(ppmcc && *ppmcc) { lbmemcheck_ctx* pmcc = *ppmcc; lbtrace("lbmemcheck_finialize, pmcc:%p\n", pmcc); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pthread_mutex_lock(pmcc->pmutex); #endif lbmem_blk* pmb = NULL; lblist_node* pnode = NULL; lbtrace("%d block of memory maybe leak\n", lblist_size(pmcc->plist)); while(lblist_size(pmcc->plist) > 0)//(pmb = (lbmem_blk*)lblist_pop(pmcc->plist)) { pmb = (lbmem_blk*)lblist_pop(pmcc->plist); lbtrace("leak memory [%s:%d %s] memory ptr:%p, size:%d\n", pmb->pfile_name, pmb->nfile_line, pmb->pfunc_name, pmb->pblock_ptr, pmb->nblock_size); if(pmb->pfile_name) { ::free(pmb->pfile_name); pmb->pfile_name = NULL; } if(pmb->pfunc_name) { ::free(pmb->pfunc_name); pmb->pfunc_name = NULL; } ::free(pmb); } lblist_close_context(&pmcc->plist); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pthread_mutex_unlock(pmcc->pmutex); pthread_mutex_destroy(pmcc->pmutex); free(pmcc->pmutex); #endif ::free(pmcc); *ppmcc = pmcc = NULL; } } int lbmemcheck_add_block(lbmemcheck_ctx* pmcc, void* ptr, int size, const char* pfile_name, const int nfile_line, const char* pfunc_name) { if(!pmcc || !ptr) { return -1; } //lbtrace("new T(pmcc:%p, ptr:%p, size:%d, pfile_name:%s, nfile_line:%d, pfunc_name:%s)\n", pmcc, ptr, size, pfile_name, nfile_line, pfunc_name); assert(pmcc); assert(ptr); lbmem_blk* pmb = (lbmem_blk*)::calloc(1, sizeof(lbmem_blk)); if(NULL == pmb) { lberror("out of memory calloc lbmem_blk failed!\n"); assert(0); return -1; } pmb->pblock_ptr = ptr; pmb->nblock_size = size; int len = strlen(pfile_name) + 1; pmb->pfile_name = (char*)::calloc(len, sizeof(char)); if(NULL == pmb->pfile_name) { lberror("out of memory calloc pfile_name %s failed!\n", pfile_name); assert(0); return -1; } memcpy(pmb->pfile_name, pfile_name, len); pmb->nfile_line = nfile_line; len = strlen(pfunc_name); pmb->pfunc_name = (char*)::calloc(len, sizeof(char)); if(NULL == pmb->pfunc_name) { lberror("out of memory calloc pfunc_name %s failed!\n", pfunc_name); assert(0); return -1; } memcpy(pmb->pfunc_name, pfunc_name, len); return lblist_push(pmcc->plist, pmb); } int lbmemcheck_remove_block(lbmemcheck_ctx* pmcc, void* ptr) { /*assert(pmcc); assert(ptr);*/ //lbtrace("pmcc:%p, delete ptr:%p", pmcc, ptr); if(!pmcc || !ptr || !pmcc->plist) { return -1; } lbmem_blk* pmb = NULL; for(lblist_node* pnode = pmcc->plist->head; pnode != NULL; pnode = pnode->pnext) { pmb = (lbmem_blk*)pnode->pitem; //LBLIST_ENUM_BEGIN(lbmem_blk, pmcc->plist, pmb); if(pmb && ptr == pmb->pblock_ptr) { if(pmb->pfile_name) { ::free(pmb->pfile_name); pmb->pfile_name = NULL; } if(pmb->pfunc_name) { ::free(pmb->pfunc_name); pmb->pfunc_name = NULL; } ::free(pmb); lblist_remove_node(pmcc->plist, pnode); return 0; } } //LBLIST_ENUM_END() lberror("Invalid ptr:%p, not foud from alloc list!\n", ptr); return -1; } #ifdef __cplusplus template<class T> inline T* lbmem_new(int count, const char* pfile_name, const int nfile_line, const char* pfunc_name) { T* ptr = NULL; if(count > 1) { ptr = new T[count]; } else { ptr = new T(); } lbmemcheck_add_block(g_pmcc, ptr, sizeof(T) * count, pfile_name, nfile_line, pfunc_name); return ptr; } template<class T> inline void lbmem_delete(T* ptr, int isarray) { if(isarray) { delete[] ptr; } else { delete ptr; } lbmemcheck_remove_block(g_pmcc, ptr); } #endif
28.248588
157
0.5894
breezeewu
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
closedsum
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
Sygmei
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
Kauehenrik
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
hiroshin-dev
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
Ujjawalgupta42
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
njlr
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
SCUTSSE
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
Wzzzx
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
rboman
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
venim1103
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
atree-GitHub
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
LioBuitrago
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
Hopobcn
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
amilearning
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
meelgroup
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
partouf
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
jackMilano
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
0yinf
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
stepanp
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
s1eve-mcdichae1
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
llHoYall
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
JohanMabille
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
PowerOfNames
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
sikol
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
leftidev
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
stijnvanhoey
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
jnvshubham7
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
oscillator25
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
lutrarutra
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
izenecloud
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
kengonakajima
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
jingcao80
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
Phygon
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
Mark1626
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
tonyfloatersu
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
sigurdstorve
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
dawmlight
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
rianders
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
raptoravis
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
IanHG
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
homembaixinho
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
a-w
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
sarang-apps
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
drjod
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
GuinsooLab
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
RipcordSoftware
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
decouple
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
dudpray0220