hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
46e31f5ef6009a1e381cb73a26bc2c125f756ba1
2,171
hpp
C++
VMDK.hpp
zigmundmatasko/makevhdx
554123b2c75c0116203457e6f6144d1de22e8269
[ "MIT" ]
1
2020-04-15T16:39:19.000Z
2020-04-15T16:39:19.000Z
VMDK.hpp
zigmundmatasko/makevhdx
554123b2c75c0116203457e6f6144d1de22e8269
[ "MIT" ]
null
null
null
VMDK.hpp
zigmundmatasko/makevhdx
554123b2c75c0116203457e6f6144d1de22e8269
[ "MIT" ]
null
null
null
#pragma once #include "Image.hpp" #include "RAW.hpp" #include <PathCch.h> #include <ctime> struct VMDK : RAW { protected: HANDLE image_file_desc; WCHAR flat_file_name[MAX_PATH]; UINT32 sector_size; public: VMDK() = default; VMDK(_In_z_ PCWSTR file_name) : RAW(file_name) { // create new FLAT file name wcscpy_s(flat_file_name, file_name); PathCchRemoveExtension(flat_file_name, MAX_PATH); wcscat_s(flat_file_name, L"-flat.vmdk"); }; void ReadHeader() { RAW::ReadHeader(); } void ConstructHeader(_In_ UINT64 disk_size, _In_ UINT32 block_size, _In_ UINT32 sector_size_in, _In_ bool is_fixed) { sector_size = sector_size_in; RAW::ConstructHeader(disk_size, block_size, sector_size, is_fixed); } void WriteHeader() const { // Open descriptor file = original_file_name FILE* f; _wfopen_s(&f,original_file_name, L"wt"); // write metadata /* # Disk DescriptorFile version=1 CID=RANDOM UINT32 parentCID=ffffffff createType="VMFS" isNativeSnapshot="no" # Extent description RW COUNT_OF_SECTORS VMFS "FILENAME-flat.vmdk" # The Disk Data Base ddb.virtualHWVersion="7" ddb.adapterType="lsilogic" ddb.geometry.sectors="255" ddb.geometry.heads="16" ddb.geometry.cylinders="COUNT_OF_SECTORS/16/255" */ if (f) { srand((unsigned)time(0)); fwprintf( f, L"# Disk DescriptorFile\n" L"version=1\n" L"CID=%8.8x\n" L"parentCID=ffffffff\n" L"createType=\"VMFS\"\n" L"isNativeSnapshot=\"no\"\n" L"\n" L"RW %llu VMFS \"%s\"\n" L"\n" L"ddb.virtualHWVersion=\"7\"\n" L"ddb.adapterType=\"lsilogic\"\n" L"ddb.geometry.sectors=\"255\"\n" L"ddb.geometry.heads=\"16\"\n" L"ddb.geometry.cylinders=\"%lli\"\n", rand(), raw_disk_size.QuadPart / sector_size, PathFindFileNameW(flat_file_name), raw_disk_size.QuadPart / sector_size / 16 / 255 ); // Close descriptor file fclose(f); } RAW::WriteHeader(); } PCSTR GetImageTypeName() const noexcept { return "VMDK"; } PCWSTR GetFileName() { return flat_file_name; } };
23.095745
117
0.646707
[ "geometry" ]
46e447095f8cf5ee5d5c994776a30e5af182572e
4,869
hpp
C++
hydra/vulkan/buffer.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
2
2016-09-15T22:29:46.000Z
2017-11-30T11:16:12.000Z
hydra/vulkan/buffer.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
hydra/vulkan/buffer.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
// // file : buffer.hpp // in : file:///home/tim/projects/hydra/hydra/vulkan/buffer.hpp // // created by : Timothée Feuillet // date: Fri Aug 26 2016 23:02:00 GMT+0200 (CEST) // // // Copyright (c) 2016 Timothée Feuillet // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef __N_24932140943134326865_101749810_BUFFER_HPP__ #define __N_24932140943134326865_101749810_BUFFER_HPP__ #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "../hydra_exception.hpp" #include "device.hpp" #include "device_memory.hpp" namespace neam { namespace hydra { namespace vk { class buffer { public: // advanced /// \brief Create from the create info vulkan structure buffer(device &_dev, const VkBufferCreateInfo &create_info) : dev(_dev), buffer_size(create_info.size) { check::on_vulkan_error::n_throw_exception(dev._vkCreateBuffer(&create_info, nullptr, &vk_buffer)); } /// \brief Create from an already existing vulkan buffer object buffer(device &_dev, VkBuffer _vk_buffer, size_t _buffer_size) : dev(_dev), vk_buffer(_vk_buffer), buffer_size(_buffer_size) {} public: /// \brief Create a buffer (with sharing mode = exclusive) buffer(device &_dev, size_t size, VkBufferUsageFlags usage, VkBufferCreateFlags flags = 0) : buffer(_dev, VkBufferCreateInfo { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, nullptr, flags, size, usage, VK_SHARING_MODE_EXCLUSIVE, 0, nullptr }) {} /// \brief Create a buffer (with sharing mode = concurrent) buffer(device &_dev, size_t size, VkBufferUsageFlags usage, const std::vector<uint32_t> &queue_family_indices, VkBufferCreateFlags flags = 0) : buffer(_dev, VkBufferCreateInfo { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, nullptr, flags, size, usage, VK_SHARING_MODE_CONCURRENT, (uint32_t)queue_family_indices.size(), queue_family_indices.data() }) {} buffer(buffer &&o) : dev(o.dev), vk_buffer(o.vk_buffer), buffer_size(o.buffer_size) { o.vk_buffer = nullptr; } buffer &operator = (buffer &&o) { if (&o == this) return *this; check::on_vulkan_error::n_assert(&dev != &o.dev, "could not move-assign a buffer from a different vulkan device"); if (vk_buffer) dev._vkDestroyBuffer(vk_buffer, nullptr); vk_buffer = o.vk_buffer; o.vk_buffer = nullptr; buffer_size = o.buffer_size; return *this; } ~buffer() { if (vk_buffer) dev._vkDestroyBuffer(vk_buffer, nullptr); } /// \brief Bind some memory to the buffer void bind_memory(const device_memory &mem, size_t offset) { check::on_vulkan_error::n_throw_exception(dev._vkBindBufferMemory(vk_buffer, mem._get_vk_device_memory(), offset)); } /// \brief Return the buffer size (in byte) size_t size() const { return buffer_size; } /// \brief Return the memory requirements of the buffer VkMemoryRequirements get_memory_requirements() const { VkMemoryRequirements ret; dev._vkGetBufferMemoryRequirements(vk_buffer, &ret); return ret; } public: // advanced /// \brief Return the underlying VkBuffer VkBuffer _get_vk_buffer() const { return vk_buffer; } private: device &dev; VkBuffer vk_buffer; size_t buffer_size; }; } // namespace vk } // namespace hydra } // namespace neam #endif // __N_24932140943134326865_101749810_BUFFER_HPP__
36.886364
151
0.651263
[ "object", "vector" ]
46e7a9d0a09b4da4a2b519918598bc890e350446
1,259
cpp
C++
aws-cpp-sdk-devicefarm/source/model/UpdateUploadRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-devicefarm/source/model/UpdateUploadRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-devicefarm/source/model/UpdateUploadRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/devicefarm/model/UpdateUploadRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::DeviceFarm::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateUploadRequest::UpdateUploadRequest() : m_arnHasBeenSet(false), m_nameHasBeenSet(false), m_contentTypeHasBeenSet(false), m_editContent(false), m_editContentHasBeenSet(false) { } Aws::String UpdateUploadRequest::SerializePayload() const { JsonValue payload; if(m_arnHasBeenSet) { payload.WithString("arn", m_arn); } if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_contentTypeHasBeenSet) { payload.WithString("contentType", m_contentType); } if(m_editContentHasBeenSet) { payload.WithBool("editContent", m_editContent); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateUploadRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DeviceFarm_20150623.UpdateUpload")); return headers; }
19.075758
97
0.73471
[ "model" ]
46f90a9181fc2764d71fdd48fb18edff96a146d7
4,345
cpp
C++
mainapp/Classes/Common/Controls/TraceField/Utils/TraceFieldDepot.cpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
mainapp/Classes/Common/Controls/TraceField/Utils/TraceFieldDepot.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
123
2019-05-28T14:03:04.000Z
2019-07-12T04:23:26.000Z
pehlaschool/Classes/Common/Controls/TraceField/Utils/TraceFieldDepot.cpp
maqsoftware/Pehla-School-Hindi
61aeae0f1d91952b44eaeaff5d2f6ec1d5aa3c43
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // TraceFieldDepot.cpp on Jun 17, 2016 // TodoSchool // // Copyright (c) 2016 Enuma, Inc. All rights reserved. // See LICENSE.md for more details. // #include "TraceFieldDepot.h" #include "Utils/JsonUtils.h" #include "Utils/StringUtils.h" BEGIN_NS_TRACEFIELD string TraceFieldDepot::assetPrefix() const { string It = "Common/Controls/TraceField"; return It; } string TraceFieldDepot::defaultFont() const { // return "fonts/TSAlphabets.ttf"; return "fonts/kitkitalphabet.ttf"; } string TraceFieldDepot::cursorFilename() const { string It = assetPrefix() + "/TraceField_Cursor2.png"; return It; } float TraceFieldDepot::cursorMaxRadius() const { return 118.f * 2.1f / 2.f; // XXX } Sprite* TraceFieldDepot::createBackgroundSprite(const Size& ParentSize) const { // NB(xenosoz, 2016): Default configurations. In Pixels (px). int Width = 1218; int Height = 1616; int MarginTop = 92; int MarginRight = 82; int MarginBottom = 92; Json::Value BackgroundJson; if (jsonFromFile(assetPrefix() + "/TraceField_Background.json", BackgroundJson)) { // NB(xenosoz, 2016): Override default configurations. Json::Value& Json = BackgroundJson; parseIntWithSuffix(Width, Json.get("width", "").asString(), "px"); parseIntWithSuffix(Height, Json.get("height", "").asString(), "px"); parseIntWithSuffix(MarginTop, Json.get("margin-top", "").asString(), "px"); parseIntWithSuffix(MarginRight, Json.get("margin-right", "").asString(), "px"); parseIntWithSuffix(MarginBottom, Json.get("margin-bottom", "").asString(), "px"); } Sprite* It = Sprite::create(assetPrefix() + "/TraceField_Background.png"); if (It) { const Size& Size = It->getContentSize(); if (Size.width != Width || Size.height != Height) { CCLOGWARN("Unexpected sprite size: TraceField_Background.png"); CCLOGWARN("Given: (width: %f, height: %f)", Size.width, Size.height); CCLOGWARN("Expected: (width: %d, height: %d)", Width, Height); } It->setAnchorPoint(Vec2::ANCHOR_BOTTOM_RIGHT); It->setPosition(Point(ParentSize.width - MarginRight, MarginBottom)); } return It; } void TraceFieldDepot::preloadSoundEffects() const { for (auto& Effect : soundEffectsToPreload()) { Effect.preload(); } } SoundEffect TraceFieldDepot::soundForTrace() const { string P = assetPrefix() + "/Sounds"; return SoundEffect(P + "/SFX_PENCILLOOP.m4a"); } Json::Value TraceFieldDepot::jsonForGlyphArchive(string Str) { Json::Value JsonValue; string GlyphName; if (Str == "1" || Str == "2" || Str == "3" || Str == "4" || Str == "5" || Str == "6" || Str == "7" || Str == "8" || Str == "9" || Str == "0") { GlyphName = "TSAlphabets"; } else { GlyphName = "kitkitalphabet"; } // XXX string Filename; if (isDigit(Str)) Filename = (assetPrefix() + "/Glyphs") + ("/" + GlyphName + ".Digit") + ("/" + Str + "/") + (GlyphName + ".Digit." + Str + ".json"); else if (isUpper(Str)) Filename = (assetPrefix() + "/Glyphs") + ("/" + GlyphName + ".Latin_Capital") + ("/" + Str + "/") + (GlyphName + ".Latin_Capital." + Str + ".json"); else if (isLower(Str)) Filename = (assetPrefix() + "/Glyphs") + ("/" + GlyphName + ".Latin_Small") + ("/" + toUpper(Str) + "/") + (GlyphName + ".Latin_Small." + toUpper(Str) + ".json"); else if (isPunct(Str)) Filename = (assetPrefix() + "/Glyphs") + ("/" + GlyphName + ".Special") + ("/" + toURLEncoded(Str) + "/") + (GlyphName + ".Special." + toURLEncoded(Str) + ".json"); if (Filename.empty()) { return JsonValue; } string JsonStr = FileUtils::getInstance()->getStringFromFile(Filename); Json::Reader JsonReader; if (!JsonReader.parse(JsonStr, JsonValue)) { CCLOGERROR("JSON reader parse error: %s", Filename.c_str()); JsonValue.clear(); } return JsonValue; } TraceKnotList TraceFieldDepot::knotListForGlyphArchive(string Str) { Json::Value JsonValue = jsonForGlyphArchive(Str); TraceKnotList KnotList(JsonValue); return KnotList; } vector<SoundEffect> TraceFieldDepot::soundEffectsToPreload() const { return { soundForTrace(), }; } END_NS_TRACEFIELD
32.916667
172
0.618182
[ "vector" ]
46fed304ecba22efa61cb06b35790da8d55f0579
337
cpp
C++
contest/array.cpp
alchemz/hackerrank
6f9b5a67c0d50e9c3b682ba234bea0d3d71b9f38
[ "MIT" ]
3
2016-03-15T20:42:38.000Z
2017-01-30T07:27:33.000Z
contest/array.cpp
alchemz/hackerrank
6f9b5a67c0d50e9c3b682ba234bea0d3d71b9f38
[ "MIT" ]
null
null
null
contest/array.cpp
alchemz/hackerrank
6f9b5a67c0d50e9c3b682ba234bea0d3d71b9f38
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main(){ int size; int num; cin>>size; int arr[size]; for(int i=0; i<size; i++){ cin>>num; arr[i]=num; } for(int j=size-1; j>=0; j--){ cout<<arr[j]<<" "; } return 0; }
12.481481
31
0.534125
[ "vector" ]
20013c35604daa546837b0d2e60d54a213bf8df2
1,931
cpp
C++
aws-cpp-sdk-appstream/source/model/UpdateDirectoryConfigRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-appstream/source/model/UpdateDirectoryConfigRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-appstream/source/model/UpdateDirectoryConfigRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/appstream/model/UpdateDirectoryConfigRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::AppStream::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateDirectoryConfigRequest::UpdateDirectoryConfigRequest() : m_directoryNameHasBeenSet(false), m_organizationalUnitDistinguishedNamesHasBeenSet(false), m_serviceAccountCredentialsHasBeenSet(false) { } Aws::String UpdateDirectoryConfigRequest::SerializePayload() const { JsonValue payload; if(m_directoryNameHasBeenSet) { payload.WithString("DirectoryName", m_directoryName); } if(m_organizationalUnitDistinguishedNamesHasBeenSet) { Array<JsonValue> organizationalUnitDistinguishedNamesJsonList(m_organizationalUnitDistinguishedNames.size()); for(unsigned organizationalUnitDistinguishedNamesIndex = 0; organizationalUnitDistinguishedNamesIndex < organizationalUnitDistinguishedNamesJsonList.GetLength(); ++organizationalUnitDistinguishedNamesIndex) { organizationalUnitDistinguishedNamesJsonList[organizationalUnitDistinguishedNamesIndex].AsString(m_organizationalUnitDistinguishedNames[organizationalUnitDistinguishedNamesIndex]); } payload.WithArray("OrganizationalUnitDistinguishedNames", std::move(organizationalUnitDistinguishedNamesJsonList)); } if(m_serviceAccountCredentialsHasBeenSet) { payload.WithObject("ServiceAccountCredentials", m_serviceAccountCredentials.Jsonize()); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateDirectoryConfigRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "PhotonAdminProxyService.UpdateDirectoryConfig")); return headers; }
30.650794
209
0.815122
[ "model" ]
200bdd0feb95e1ce395489cdea7226ddd56cb994
14,400
cpp
C++
test/crypto/testcrypto.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
133
2015-02-22T23:56:53.000Z
2022-03-13T19:24:21.000Z
test/crypto/testcrypto.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
93
2015-08-31T15:35:07.000Z
2021-04-27T21:41:13.000Z
test/crypto/testcrypto.cpp
resosafe/boxbackup
c56291558de634f3fe6675aeb381ba99f68b78cb
[ "BSD-3-Clause" ]
19
2015-08-31T14:13:34.000Z
2021-12-12T15:20:17.000Z
// -------------------------------------------------------------------------- // // File // Name: testcrypto.cpp // Purpose: test lib/crypto // Created: 1/12/03 // // -------------------------------------------------------------------------- #include "Box.h" #include <string.h> #include <openssl/rand.h> #include "CipherContext.h" #include "CipherBlowfish.h" #include "CipherAES.h" #include "CipherException.h" #include "CollectInBufferStream.h" #include "Guards.h" #include "RollingChecksum.h" #include "Random.h" #include "Test.h" #include "MemLeakFindOn.h" #define STRING1 "Mary had a little lamb" #define STRING2 "Skjdf sdjf sjksd fjkhsdfjk hsdfuiohcverfg sdfnj sdfgkljh sdfjb jlhdfvghsdip vjsdfv bsdfhjvg yuiosdvgpvj kvbn m,sdvb sdfuiovg sdfuivhsdfjkv" #define KEY "0123456701234567012345670123456" #define KEY2 "1234567012345670123456A" #define CHECKSUM_DATA_SIZE (128*1024) #define CHECKSUM_BLOCK_SIZE_BASE (65*1024) #define CHECKSUM_BLOCK_SIZE_LAST (CHECKSUM_BLOCK_SIZE_BASE + 64) #define CHECKSUM_ROLLS 16 // Copied from BackupClientCryptoKeys.h #define BACKUPCRYPTOKEYS_FILENAME_KEY_START 0 #define BACKUPCRYPTOKEYS_FILENAME_KEY_LENGTH 56 #define BACKUPCRYPTOKEYS_FILENAME_IV_START (0 + BACKUPCRYPTOKEYS_FILENAME_KEY_LENGTH) #define BACKUPCRYPTOKEYS_FILENAME_IV_LENGTH 8 void check_random_int(uint32_t max) { for(int c = 0; c < 1024; ++c) { uint32_t v = Random::RandomInt(max); TEST_THAT(v >= 0 && v <= max); } } #define ZERO_BUFFER(x) ::memset(x, 0, sizeof(x)); template<typename CipherType, int BLOCKSIZE> void test_cipher() { { // Make a couple of cipher contexts CipherContext encrypt1; encrypt1.Reset(); encrypt1.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); TEST_CHECK_THROWS(encrypt1.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))), CipherException, AlreadyInitialised); // Encrpt something char buf1[256]; unsigned int buf1_used = encrypt1.TransformBlock(buf1, sizeof(buf1), STRING1, sizeof(STRING1)); TEST_THAT(buf1_used >= sizeof(STRING1)); // Decrypt it CipherContext decrypt1; decrypt1.Init(CipherContext::Decrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); char buf1_de[256]; unsigned int buf1_de_used = decrypt1.TransformBlock(buf1_de, sizeof(buf1_de), buf1, buf1_used); TEST_THAT(buf1_de_used == sizeof(STRING1)); TEST_THAT(memcmp(STRING1, buf1_de, sizeof(STRING1)) == 0); // Use them again... char buf1_de2[256]; unsigned int buf1_de2_used = decrypt1.TransformBlock(buf1_de2, sizeof(buf1_de2), buf1, buf1_used); TEST_THAT(buf1_de2_used == sizeof(STRING1)); TEST_THAT(memcmp(STRING1, buf1_de2, sizeof(STRING1)) == 0); // Test the interface char buf2[256]; TEST_CHECK_THROWS(encrypt1.Transform(buf2, sizeof(buf2), STRING1, sizeof(STRING1)), CipherException, BeginNotCalled); TEST_CHECK_THROWS(encrypt1.Final(buf2, sizeof(buf2)), CipherException, BeginNotCalled); encrypt1.Begin(); int e = 0; e = encrypt1.Transform(buf2, sizeof(buf2), STRING2, sizeof(STRING2) - 16); e += encrypt1.Transform(buf2 + e, sizeof(buf2) - e, STRING2 + sizeof(STRING2) - 16, 16); e += encrypt1.Final(buf2 + e, sizeof(buf2) - e); TEST_THAT(e >= (int)sizeof(STRING2)); // Then decrypt char buf2_de[256]; decrypt1.Begin(); TEST_CHECK_THROWS(decrypt1.Transform(buf2_de, 2, buf2, e), CipherException, OutputBufferTooSmall); TEST_CHECK_THROWS(decrypt1.Final(buf2_de, 2), CipherException, OutputBufferTooSmall); int d = decrypt1.Transform(buf2_de, sizeof(buf2_de), buf2, e - 48); d += decrypt1.Transform(buf2_de + d, sizeof(buf2_de) - d, buf2 + e - 48, 48); d += decrypt1.Final(buf2_de + d, sizeof(buf2_de) - d); TEST_THAT(d == sizeof(STRING2)); TEST_THAT(memcmp(STRING2, buf2_de, sizeof(STRING2)) == 0); // Try a reset and rekey encrypt1.Reset(); encrypt1.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY2, sizeof(KEY2))); buf1_used = encrypt1.TransformBlock(buf1, sizeof(buf1), STRING1, sizeof(STRING1)); } // Test initialisation vectors { // Init with random IV CipherContext encrypt2; encrypt2.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); int ivLen; char iv2[BLOCKSIZE]; const void *ivGen = encrypt2.SetRandomIV(ivLen); TEST_THAT(ivLen == BLOCKSIZE); // block size TEST_THAT(ivGen != 0); memcpy(iv2, ivGen, ivLen); char buf3[256]; unsigned int buf3_used = encrypt2.TransformBlock(buf3, sizeof(buf3), STRING2, sizeof(STRING2)); // Encrypt again with different IV char iv3[BLOCKSIZE]; int ivLen3; const void *ivGen3 = encrypt2.SetRandomIV(ivLen3); TEST_THAT(ivLen3 == BLOCKSIZE); // block size TEST_THAT(ivGen3 != 0); memcpy(iv3, ivGen3, ivLen3); // Check the two generated IVs are different TEST_THAT(memcmp(iv2, iv3, BLOCKSIZE) != 0); char buf4[256]; unsigned int buf4_used = encrypt2.TransformBlock(buf4, sizeof(buf4), STRING2, sizeof(STRING2)); // check encryptions are different TEST_THAT(buf3_used == buf4_used); TEST_THAT(memcmp(buf3, buf4, buf3_used) != 0); // Test that decryption with the right IV works CipherContext decrypt2; decrypt2.Init(CipherContext::Decrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY), iv2)); char buf3_de[256]; unsigned int buf3_de_used = decrypt2.TransformBlock(buf3_de, sizeof(buf3_de), buf3, buf3_used); TEST_THAT(buf3_de_used == sizeof(STRING2)); TEST_THAT(memcmp(STRING2, buf3_de, sizeof(STRING2)) == 0); // And that using the wrong one doesn't decrypt2.SetIV(iv3); buf3_de_used = decrypt2.TransformBlock(buf3_de, sizeof(buf3_de), buf3, buf3_used); TEST_THAT(buf3_de_used == sizeof(STRING2)); TEST_THAT(memcmp(STRING2, buf3_de, sizeof(STRING2)) != 0); } // Test with padding off. { CipherContext encrypt3; encrypt3.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); encrypt3.UsePadding(false); // Should fail because the encrypted size is not a multiple of the block size char buf4[256]; encrypt3.Begin(); ZERO_BUFFER(buf4); int buf4_used = encrypt3.Transform(buf4, sizeof(buf4), STRING2, 6); TEST_CHECK_THROWS(encrypt3.Final(buf4, sizeof(buf4)), CipherException, EVPFinalFailure); // Check a nice encryption with the correct block size CipherContext encrypt4; encrypt4.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); encrypt4.UsePadding(false); encrypt4.Begin(); ZERO_BUFFER(buf4); buf4_used = encrypt4.Transform(buf4, sizeof(buf4), STRING2, 16); buf4_used += encrypt4.Final(buf4+buf4_used, sizeof(buf4)); TEST_THAT(buf4_used == 16); // Check it's encrypted to the same thing as when there's padding on CipherContext encrypt4b; encrypt4b.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); encrypt4b.Begin(); char buf4b[256]; ZERO_BUFFER(buf4b); int buf4b_used = encrypt4b.Transform(buf4b, sizeof(buf4b), STRING2, 16); buf4b_used += encrypt4b.Final(buf4b + buf4b_used, sizeof(buf4b)); TEST_THAT(buf4b_used == 16+BLOCKSIZE); TEST_THAT(::memcmp(buf4, buf4b, 16) == 0); // Decrypt char buf4_de[256]; CipherContext decrypt4; decrypt4.Init(CipherContext::Decrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); decrypt4.UsePadding(false); decrypt4.Begin(); ZERO_BUFFER(buf4_de); int buf4_de_used = decrypt4.Transform(buf4_de, sizeof(buf4_de), buf4, 16); buf4_de_used += decrypt4.Final(buf4_de+buf4_de_used, sizeof(buf4_de)); TEST_THAT(buf4_de_used == 16); TEST_THAT(::memcmp(buf4_de, STRING2, 16) == 0); // Test that the TransformBlock thing works as expected too with blocks the same size as the input TEST_THAT(encrypt4.TransformBlock(buf4, 16, STRING2, 16) == 16); // But that it exceptions if we try the trick with padding on encrypt4.UsePadding(true); TEST_CHECK_THROWS(encrypt4.TransformBlock(buf4, 16, STRING2, 16), CipherException, OutputBufferTooSmall); } // And again, but with different string size { char buf4[256]; int buf4_used; // Check a nice encryption with the correct block size CipherContext encrypt4; encrypt4.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); encrypt4.UsePadding(false); encrypt4.Begin(); ZERO_BUFFER(buf4); buf4_used = encrypt4.Transform(buf4, sizeof(buf4), STRING2, (BLOCKSIZE*3)); // do three blocks worth buf4_used += encrypt4.Final(buf4+buf4_used, sizeof(buf4)); TEST_THAT(buf4_used == (BLOCKSIZE*3)); // Check it's encrypted to the same thing as when there's padding on CipherContext encrypt4b; encrypt4b.Init(CipherContext::Encrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); encrypt4b.Begin(); char buf4b[256]; ZERO_BUFFER(buf4b); int buf4b_used = encrypt4b.Transform(buf4b, sizeof(buf4b), STRING2, (BLOCKSIZE*3)); buf4b_used += encrypt4b.Final(buf4b + buf4b_used, sizeof(buf4b)); TEST_THAT(buf4b_used == (BLOCKSIZE*4)); TEST_THAT(::memcmp(buf4, buf4b, (BLOCKSIZE*3)) == 0); // Decrypt char buf4_de[256]; CipherContext decrypt4; decrypt4.Init(CipherContext::Decrypt, CipherType(CipherDescription::Mode_CBC, KEY, sizeof(KEY))); decrypt4.UsePadding(false); decrypt4.Begin(); ZERO_BUFFER(buf4_de); int buf4_de_used = decrypt4.Transform(buf4_de, sizeof(buf4_de), buf4, (BLOCKSIZE*3)); buf4_de_used += decrypt4.Final(buf4_de+buf4_de_used, sizeof(buf4_de)); TEST_THAT(buf4_de_used == (BLOCKSIZE*3)); TEST_THAT(::memcmp(buf4_de, STRING2, (BLOCKSIZE*3)) == 0); // Test that the TransformBlock thing works as expected too with blocks the same size as the input TEST_THAT(encrypt4.TransformBlock(buf4, (BLOCKSIZE*3), STRING2, (BLOCKSIZE*3)) == (BLOCKSIZE*3)); // But that it exceptions if we try the trick with padding on encrypt4.UsePadding(true); TEST_CHECK_THROWS(encrypt4.TransformBlock(buf4, (BLOCKSIZE*3), STRING2, (BLOCKSIZE*3)), CipherException, OutputBufferTooSmall); } } int test(int argc, const char *argv[]) { Random::Initialise(); // Cipher type ::printf("Blowfish...\n"); test_cipher<CipherBlowfish, 8>(); #ifndef HAVE_OLD_SSL ::printf("AES...\n"); test_cipher<CipherAES, 16>(); #else ::printf("Skipping AES -- not supported by version of OpenSSL in use.\n"); #endif // Test with known plaintext and ciphertext (correct algorithm used, etc) { FileStream keyfile("testfiles/bbackupd.keys"); // Ideally we would use a 448 bit (56 byte) key here, since that's what we do in // real life, but unfortunately the OpenSSL command-line tool only supports 128-bit // Blowfish keys, so it's hard to generate a reference ciphertext unless we restrict // ourselves to what OpenSSL can support too. // https://security.stackexchange.com/questions/25393/openssl-blowfish-key-limited-to-256-bits char key[16], iv[BACKUPCRYPTOKEYS_FILENAME_IV_LENGTH]; if(!keyfile.ReadFullBuffer(key, sizeof(key), 0)) { TEST_FAIL_WITH_MESSAGE("Failed to read full key length from file"); } keyfile.Seek(BACKUPCRYPTOKEYS_FILENAME_KEY_LENGTH, IOStream::SeekType_Absolute); if(!keyfile.ReadFullBuffer(iv, sizeof(iv), 0)) { TEST_FAIL_WITH_MESSAGE("Failed to read full IV length from file"); } CipherContext encryptor; CipherContext decryptor; encryptor.Reset(); encryptor.Init(CipherContext::Encrypt, CipherBlowfish(CipherDescription::Mode_CBC, key, sizeof(key))); ASSERT(encryptor.GetIVLength() == sizeof(iv)); encryptor.SetIV(iv); decryptor.Reset(); decryptor.Init(CipherContext::Decrypt, CipherBlowfish(CipherDescription::Mode_CBC, key, sizeof(key))); ASSERT(decryptor.GetIVLength() == sizeof(iv)); decryptor.SetIV(iv); // The encrypted file bfdlink.h.enc was generated with the following command: // key=`dd if=bbackupd.keys bs=1 count=16 | hexdump -e '/1 "%02x"'` // iv=`dd if=bbackupd.keys bs=1 skip=56 count=8 | hexdump -e '/1 "%02x"'` // openssl enc -bf -in bfdlink.h -K $key -iv $iv // And has MD5 checksum 586b65fdd07474bc139c0795d344d8ad FileStream plaintext_file("testfiles/bfdlink.h", O_RDONLY); FileStream ciphertext_file("testfiles/bfdlink.h.enc", O_RDONLY); CollectInBufferStream plaintext, ciphertext; plaintext_file.CopyStreamTo(plaintext); ciphertext_file.CopyStreamTo(ciphertext); plaintext.SetForReading(); ciphertext.SetForReading(); MemoryBlockGuard<void *> encrypted( encryptor.MaxOutSizeForInBufferSize(ciphertext.GetSize())); int encrypted_size = encryptor.TransformBlock(encrypted.GetPtr(), encrypted.GetSize(), plaintext.GetBuffer(), plaintext.GetSize()); TEST_EQUAL(ciphertext.GetSize(), encrypted_size); TEST_EQUAL(0, memcmp(encrypted.GetPtr(), ciphertext.GetBuffer(), encrypted_size)); MemoryBlockGuard<void *> decrypted(ciphertext.GetSize() + 16); int decrypted_size = decryptor.TransformBlock(decrypted.GetPtr(), decrypted.GetSize(), encrypted.GetPtr(), encrypted_size); TEST_EQUAL(plaintext.GetSize(), decrypted_size); TEST_EQUAL(0, memcmp(decrypted.GetPtr(), plaintext.GetBuffer(), decrypted_size)); } ::printf("Misc...\n"); // Check rolling checksums uint8_t *checkdata_blk = (uint8_t *)malloc(CHECKSUM_DATA_SIZE); uint8_t *checkdata = checkdata_blk; RAND_bytes(checkdata, CHECKSUM_DATA_SIZE); for(int size = CHECKSUM_BLOCK_SIZE_BASE; size <= CHECKSUM_BLOCK_SIZE_LAST; ++size) { // Test skip-roll code RollingChecksum rollFast(checkdata, size); rollFast.RollForwardSeveral(checkdata, checkdata+size, size, CHECKSUM_ROLLS/2); RollingChecksum calc(checkdata + (CHECKSUM_ROLLS/2), size); TEST_THAT(calc.GetChecksum() == rollFast.GetChecksum()); //printf("size = %d\n", size); // Checksum to roll RollingChecksum roll(checkdata, size); // Roll forward for(int l = 0; l < CHECKSUM_ROLLS; ++l) { // Calculate new one RollingChecksum calc(checkdata, size); //printf("%08X %08X %d %d\n", roll.GetChecksum(), calc.GetChecksum(), checkdata[0], checkdata[size]); // Compare them! TEST_THAT(calc.GetChecksum() == roll.GetChecksum()); // Roll it onwards roll.RollForward(checkdata[0], checkdata[size], size); // increment ++checkdata; } } ::free(checkdata_blk); // Random integers check_random_int(0); check_random_int(1); check_random_int(5); check_random_int(15); // all 1's check_random_int(1022); return 0; }
37.305699
156
0.726042
[ "transform" ]
200d2aa3e9c6fea4725083c301f039ecc3d6a4e5
2,310
cpp
C++
BOJ_solve/8161.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
4
2021-01-27T11:51:30.000Z
2021-01-30T17:02:55.000Z
BOJ_solve/8161.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
null
null
null
BOJ_solve/8161.cpp
biyotte/Code_of_gunwookim
b8b679ea56b8684ec44a7911211edee1fb558a96
[ "MIT" ]
5
2021-01-27T11:46:12.000Z
2021-05-06T05:37:47.000Z
#include <bits/stdc++.h> #define x first #define y second #define pb push_back #define all(v) v.begin(),v.end() #pragma gcc optimize("O3") #pragma gcc optimize("Ofast") #pragma gcc optimize("unroll-loops") using namespace std; const int INF = 1e9; const int TMX = 1 << 18; const long long llINF = 3e18+10; const long long mod = 1e9+7; const long long hashmod = 100003; const int MAXN = 100000; const int MAXM = 1000000; typedef long long ll; typedef long double ld; typedef pair <int,int> pi; typedef pair <ll,ll> pl; typedef vector <int> vec; typedef vector <pi> vecpi; typedef long long ll; int n,mn,mx; int p[1000005]; int d[1000005][2]; int dp[1000005][2]; int leaf; bool iscyc[1000005],c[1000005]; vec v[1000005]; int cyc[1000005],sz; void getCycle(int x) { if(c[x]) { cyc[sz++] = x; iscyc[x] = 1; for(int i = p[x];i != x;i = p[i]) iscyc[i] = 1, cyc[sz++] = i; return; } c[x] = 1; getCycle(p[x]); } void dfs(int x) { if(!iscyc[x]||p[x] == x) leaf = 1; c[x] = 1; bool cn = (p[x] == x); d[x][0] = d[x][1] = 0; for(int i : v[x]) { if(iscyc[i]) continue; dfs(i); cn = 1; d[x][0] = min(d[x][0]+d[i][1],INF); d[x][1] = min(d[x][1]+min(d[i][0],d[i][1]),INF); } d[x][1] = min(INF,d[x][1]+1); if(!cn) d[x][0] = 0, d[x][1] = INF; if(!iscyc[x]) mx += cn; } void Comp(int x) { leaf = 0; sz = 0; getCycle(x); int i; for(i = 0;i < sz;i++) { dfs(cyc[i]); if(d[cyc[i]][1] == INF) d[cyc[i]][1] = 1; } dp[0][0] = d[cyc[0]][0], dp[0][1] = INF; for(i = 1;i < sz;i++) { dp[i][0] = min(INF,dp[i-1][1]+d[cyc[i]][0]); dp[i][1] = min(INF,min(dp[i-1][0],dp[i-1][1])+d[cyc[i]][1]); } int ret = dp[sz-1][1]; dp[0][0] = INF, dp[0][1] = d[cyc[0]][1]; for(i = 1;i < sz;i++) { dp[i][0] = min(INF,dp[i-1][1]+d[cyc[i]][0]); dp[i][1] = min(INF,min(dp[i-1][0],dp[i-1][1])+d[cyc[i]][1]); } ret = min({ret,dp[sz-1][0],dp[sz-1][1]}); mn += ret; mx += (leaf ? sz : sz-1); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for(int i = 1;i <= n;i++) cin >> p[i], v[p[i]].pb(i); for(int i = 1;i <= n;i++) { if(!c[i]) Comp(i); } cout << mn << ' ' << mx; }
24.574468
70
0.48658
[ "vector" ]
2017c7ce09be9069e7335e6ab2e22aad70b72958
14,992
hpp
C++
core/src/impl/Morpheus_MatrixMarket_Impl.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
1
2021-12-18T01:18:49.000Z
2021-12-18T01:18:49.000Z
core/src/impl/Morpheus_MatrixMarket_Impl.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
5
2021-10-05T15:12:02.000Z
2022-01-21T23:26:41.000Z
core/src/impl/Morpheus_MatrixMarket_Impl.hpp
morpheus-org/morpheus
8f12b7b75fb7c7c02a4d5d41c64791bacc2f54c6
[ "Apache-2.0" ]
null
null
null
/** * Morpheus_MatrixMarket_Impl.hpp * * EPCC, The University of Edinburgh * * (c) 2021 - 2022 The University of Edinburgh * * Contributing Authors: * Christodoulos Stylianou (c.stylianou@ed.ac.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MORPHEUS_MATRIX_MARKET_IMPL_HPP #define MORPHEUS_MATRIX_MARKET_IMPL_HPP #include <vector> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <Morpheus_Core.hpp> #include <Morpheus_Exceptions.hpp> #include <Morpheus_CooMatrix.hpp> #include <Morpheus_DenseMatrix.hpp> #include <Morpheus_Sort.hpp> #include <Morpheus_Copy.hpp> namespace Morpheus { namespace Io { // forward decl template <typename Matrix, typename Stream> void read_matrix_market_stream(Matrix& mtx, Stream& input); namespace Impl { inline void tokenize(std::vector<std::string>& tokens, const std::string& str, const std::string& delimiters = "\n\r\t ") { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } struct matrix_market_banner { std::string storage; // "array" or "coordinate" std::string symmetry; // "general", "symmetric" // "hermitian", or "skew-symmetric" std::string type; // "complex", "real", "integer", or "pattern" }; template <typename Stream> void read_matrix_market_banner(matrix_market_banner& banner, Stream& input) { std::string line; std::vector<std::string> tokens; // read first line std::getline(input, line); Impl::tokenize(tokens, line); if (tokens.size() != 5 || tokens[0] != "%%MatrixMarket" || tokens[1] != "matrix") throw Morpheus::IOException("invalid MatrixMarket banner"); banner.storage = tokens[2]; banner.type = tokens[3]; banner.symmetry = tokens[4]; if (banner.storage != "array" && banner.storage != "coordinate") throw Morpheus::IOException("invalid MatrixMarket storage format [" + banner.storage + "]"); if (banner.type != "complex" && banner.type != "real" && banner.type != "integer" && banner.type != "pattern") throw Morpheus::IOException("invalid MatrixMarket data type [" + banner.type + "]"); if (banner.symmetry != "general" && banner.symmetry != "symmetric" && banner.symmetry != "hermitian" && banner.symmetry != "skew-symmetric") throw Morpheus::IOException("invalid MatrixMarket symmetry [" + banner.symmetry + "]"); } template <typename ValueType, typename... Properties, typename Stream> void read_coordinate_stream(Morpheus::CooMatrix<ValueType, Properties...>& coo, Stream& input, const matrix_market_banner& banner) { using IndexType = typename Morpheus::CooMatrix<ValueType, Properties...>::index_type; // read file contents line by line std::string line; // skip over banner and comments do { std::getline(input, line); } while (line[0] == '%'); // line contains [num_rows num_columns num_entries] std::vector<std::string> tokens; Impl::tokenize(tokens, line); if (tokens.size() != 3) throw Morpheus::IOException("invalid MatrixMarket coordinate format"); IndexType num_rows, num_cols, num_entries; std::istringstream(tokens[0]) >> num_rows; std::istringstream(tokens[1]) >> num_cols; std::istringstream(tokens[2]) >> num_entries; coo.resize(num_rows, num_cols, num_entries); IndexType num_entries_read = 0; // read file contents if (banner.type == "pattern") { while (num_entries_read < coo.nnnz() && !input.eof()) { input >> coo.row_indices(num_entries_read); input >> coo.column_indices(num_entries_read); num_entries_read++; } auto values_begin = coo.values().data(); auto values_end = coo.values().data() + coo.values().size(); std::fill(values_begin, values_end, ValueType(1)); } else if (banner.type == "real" || banner.type == "integer") { while (num_entries_read < coo.nnnz() && !input.eof()) { ValueType real; input >> coo.row_indices(num_entries_read); input >> coo.column_indices(num_entries_read); input >> real; coo.values(num_entries_read) = real; num_entries_read++; } } else if (banner.type == "complex") { throw Morpheus::NotImplementedException( "Morpheus does not currently support complex " "matrices"); } else { throw Morpheus::IOException("invalid MatrixMarket data type"); } if (num_entries_read != coo.nnnz()) throw Morpheus::IOException( "unexpected EOF while reading MatrixMarket entries"); // check validity of row and column index data if (coo.nnnz() > 0) { auto row_indices_begin = coo.row_indices().data(); auto row_indices_end = coo.row_indices().data() + coo.row_indices().size(); IndexType min_row_index = *std::min_element(row_indices_begin, row_indices_end); IndexType max_row_index = *std::max_element(row_indices_begin, row_indices_end); auto column_indices_begin = coo.column_indices().data(); auto column_indices_end = coo.column_indices().data() + coo.column_indices().size(); IndexType min_col_index = *std::min_element(column_indices_begin, column_indices_end); IndexType max_col_index = *std::max_element(column_indices_begin, column_indices_end); if (min_row_index < 1) throw Morpheus::IOException("found invalid row index (index < 1)"); if (min_col_index < 1) throw Morpheus::IOException("found invalid column index (index < 1)"); if (max_row_index > coo.nrows()) throw Morpheus::IOException("found invalid row index (index > num_rows)"); if (max_col_index > coo.ncols()) throw Morpheus::IOException( "found invalid column index (index > num_columns)"); } // convert base-1 indices to base-0 for (IndexType n = 0; n < coo.nnnz(); n++) { coo.row_indices(n) -= 1; coo.column_indices(n) -= 1; } // expand symmetric formats to "general" format if (banner.symmetry != "general") { IndexType off_diagonals = 0; for (IndexType n = 0; n < coo.nnnz(); n++) if (coo.row_indices(n) != coo.column_indices(n)) off_diagonals++; IndexType general_num_entries = coo.nnnz() + off_diagonals; Morpheus::CooMatrix<ValueType, Properties...> general(num_rows, num_cols, general_num_entries); if (banner.symmetry == "symmetric") { IndexType nnz = 0; for (IndexType n = 0; n < coo.nnnz(); n++) { // copy entry over general.row_indices(nnz) = coo.row_indices(n); general.column_indices(nnz) = coo.column_indices(n); general.values(nnz) = coo.values(n); nnz++; // duplicate off-diagonals if (coo.row_indices(n) != coo.column_indices(n)) { general.row_indices(nnz) = coo.column_indices(n); general.column_indices(nnz) = coo.row_indices(n); general.values(nnz) = coo.values(n); nnz++; } } } else if (banner.symmetry == "hermitian") { throw Morpheus::NotImplementedException( "MatrixMarket I/O does not currently support hermitian matrices"); // TODO } else if (banner.symmetry == "skew-symmetric") { // TODO throw Morpheus::NotImplementedException( "MatrixMarket I/O does not currently support skew-symmetric " "matrices"); } // store full matrix in coo coo = general; } // if (banner.symmetry != "general") // sort indices by (row,column) Morpheus::sort_by_row_and_column(coo); } template <typename ValueType, typename... Properties, typename Stream> void read_array_stream(Morpheus::DenseMatrix<ValueType, Properties...>& mtx, Stream& input, const matrix_market_banner& banner) { using IndexType = typename Morpheus::DenseMatrix<ValueType, Properties...>::index_type; // read file contents line by line std::string line; // skip over banner and comments do { std::getline(input, line); } while (line[0] == '%'); std::vector<std::string> tokens; Impl::tokenize(tokens, line); if (tokens.size() != 2) throw Morpheus::IOException("invalid MatrixMarket array format"); IndexType num_rows, num_cols; std::istringstream(tokens[0]) >> num_rows; std::istringstream(tokens[1]) >> num_cols; Morpheus::DenseMatrix<ValueType, Properties...> dense(num_rows, num_cols); size_t num_entries = num_rows * num_cols; size_t num_entries_read = 0; IndexType nrows = 0, ncols = 0; // read file contents if (banner.type == "pattern") { throw Morpheus::NotImplementedException( "pattern array MatrixMarket format is not supported"); } else if (banner.type == "real" || banner.type == "integer") { while (num_entries_read < num_entries && !input.eof()) { double real; input >> real; dense(nrows, ncols) = ValueType(real); num_entries_read++; ncols++; if (num_entries_read % ncols == 0) { nrows++; ncols = 0; } } } else if (banner.type == "complex") { throw Morpheus::NotImplementedException("complex type is not supported"); } else { throw Morpheus::IOException("invalid MatrixMarket data type"); } if (num_entries_read != num_entries) throw Morpheus::IOException( "unexpected EOF while reading MatrixMarket entries"); if (banner.symmetry != "general") throw Morpheus::NotImplementedException( "only general array symmetric MatrixMarket format is supported"); mtx = dense; // Morpheus::copy(dense, mtx); } template <template <class, class...> class Container, class T, class... P, typename Stream> void read_matrix_market_stream( Container<T, P...>& mtx, Stream& input, Morpheus::Impl::SparseMatTag, typename std::enable_if< is_container<typename Container<T, P...>::tag>::value && is_HostSpace_v<typename Container<T, P...>::memory_space>>::type* = nullptr) { // read banner matrix_market_banner banner; read_matrix_market_banner(banner, input); if (banner.storage == "coordinate") { Morpheus::CooMatrix<T, P...> temp; read_coordinate_stream(temp, input, banner); Morpheus::convert(temp, mtx); } else // banner.storage == "array" { Morpheus::DenseMatrix<T, P...> temp; read_array_stream(temp, input, banner); Morpheus::convert(temp, mtx); } } template <typename Matrix, typename Stream> void read_matrix_market_stream(Matrix& mtx, Stream& input, Morpheus::DenseVectorTag) { // array1d case using ValueType = typename Matrix::value_type; using Space = Kokkos::Serial; Morpheus::DenseMatrix<ValueType, Space> temp; Morpheus::Io::read_matrix_market_stream(temp, input); Morpheus::copy(temp, mtx); } template <typename Stream, typename ScalarType> void write_value(Stream& output, const ScalarType& value) { output << value; } template <typename ValueType, typename... Properties, typename Stream> void write_coordinate_stream( const Morpheus::CooMatrix<ValueType, Properties...>& coo, Stream& output) { if (std::is_floating_point_v<ValueType> || std::is_integral_v<ValueType>) { output << "%%MatrixMarket matrix coordinate real general\n"; } else { // output << "%%MatrixMarket matrix coordinate complex general\n"; throw Morpheus::NotImplementedException("complex type is not supported."); } output << "\t" << coo.nrows() << "\t" << coo.ncols() << "\t" << coo.nnnz() << "\n"; for (size_t i = 0; i < size_t(coo.nnnz()); i++) { output << (coo.row_indices(i) + 1) << " "; output << (coo.column_indices(i) + 1) << " "; Morpheus::Io::Impl::write_value(output, coo.values(i)); output << "\n"; } } template <template <class, class...> class Container, class T, class... P, typename Stream> void write_matrix_market_stream( const Container<T, P...>& mtx, Stream& output, Morpheus::Impl::SparseMatTag, typename std::enable_if< is_container<typename Container<T, P...>::tag>::value && is_Host_Memoryspace_v<typename Container<T, P...>::memory_space>>:: type* = nullptr) { // general sparse case Morpheus::CooMatrix<T, P...> coo; Morpheus::convert(mtx, coo); Morpheus::Io::Impl::write_coordinate_stream(coo, output); } template <typename Matrix, typename Stream> void write_matrix_market_stream(const Matrix& mtx, Stream& output, Morpheus::DenseVectorTag) { using ValueType = typename Matrix::value_type; if (std::is_floating_point_v<ValueType> || std::is_integral_v<ValueType>) { output << "%%MatrixMarket matrix array real general\n"; } else { // output << "%%MatrixMarket matrix array complex general\n"; throw Morpheus::NotImplementedException("complex type is not supported."); } output << "\t" << mtx.size() << "\t1\n"; for (size_t i = 0; i < mtx.size(); i++) { write_value(output, mtx[i]); output << "\n"; } } template <typename Matrix, typename Stream> void write_matrix_market_stream(const Matrix& mtx, Stream& output, Morpheus::DenseMatrixTag) { using ValueType = typename Matrix::value_type; if (std::is_floating_point_v<ValueType> || std::is_integral_v<ValueType>) { output << "%%MatrixMarket matrix array real general\n"; } else { // output << "%%MatrixMarket matrix array complex general\n"; throw Morpheus::NotImplementedException("complex type is not supported."); } output << "\t" << mtx.nrows() << "\t" << mtx.ncols() << "\n"; for (size_t j = 0; j < mtx.nrows(); j++) { for (size_t i = 0; i < mtx.ncols(); i++) { write_value(output, mtx(i, j)); output << "\n"; } } } } // namespace Impl } // namespace Io } // namespace Morpheus #endif // MORPHEUS_MATRIX_MARKET_IMPL_HPP
33.765766
80
0.653282
[ "vector" ]
2022fdc04090da32c29225c92ab2ad7b0694e798
11,435
cpp
C++
vue/monde.cpp
mourad1081/LaRevancheDesIndustriels
e70e4fc961fe9bbc6035d71da996e85952b3edfe
[ "FTL" ]
null
null
null
vue/monde.cpp
mourad1081/LaRevancheDesIndustriels
e70e4fc961fe9bbc6035d71da996e85952b3edfe
[ "FTL" ]
null
null
null
vue/monde.cpp
mourad1081/LaRevancheDesIndustriels
e70e4fc961fe9bbc6035d71da996e85952b3edfe
[ "FTL" ]
null
null
null
#include "monde.h" Monde::Monde(int largeurFenetre, int hauteurFenetre) throw(ExceptionGame) : _niveauActuel(1) { _largeurFenetre = largeurFenetre; _hauteurFenetre = hauteurFenetre; _horiScroll = 0; _vertiScroll = 0; _niveau = new Niveau(_niveauActuel); _nbrTuilesEnColonneMonde = _niveau->getNbrColonne(); _nbrTuilesEnLigneMonde = _niveau->getNbrLigne(); _schema = _niveau->getNiveau(); // ouvre le fichier de configuration en lecture ifstream fichierConfig(NOM_FICHIER_CONFIG.c_str(), ios::in); if ( fichierConfig ) { chargerInfoDepuisFichier(fichierConfig); }else{ throw new ExceptionGame("Erreur d'ouverture du fichier de configuration"); } fichierConfig.close(); _son = new GestionSon(); } int Monde::getNiveauActuel() const { return _niveauActuel; } void Monde::setNiveauActuel(int nouveauNiveau) throw(ExceptionGame) { _niveauActuel = nouveauNiveau; delete _niveau; _niveau = new Niveau(_niveauActuel); _schema = _niveau->getNiveau(); _horiScroll = 0; _vertiScroll = 0; _nbrTuilesEnColonneMonde = _niveau->getNbrColonne(); _nbrTuilesEnLigneMonde = _niveau->getNbrLigne(); } void Monde::setHoriScroll(int horiScroll){ _horiScroll = horiScroll; } void Monde::setVertiScroll(int vertiScroll){ _vertiScroll = vertiScroll; } int Monde::getHoriScroll()const{ return _horiScroll; } int Monde::getVertiScroll()const{ return _vertiScroll; } int Monde::getLargeurTuile() const{ return _largeurTuile; } int Monde::getHauteurTuile() const{ return _hauteurTuile; } int Monde::getNbrTuilesEnColonneMonde() const{ return _nbrTuilesEnColonneMonde; } int Monde::getNbrTuilesEnLigneMonde()const{ return _nbrTuilesEnLigneMonde; } int Monde::getMaxX()const{ return this->getNbrTuilesEnColonneMonde() * this->getLargeurTuile(); } int Monde::getMaxY()const{ return this->getNbrTuilesEnLigneMonde() * this->getHauteurTuile(); } int Monde::getLargeurFenetre() const{ return _largeurFenetre; } int Monde::getHauteurFenetre() const{ return _hauteurFenetre; } vector<SDL_Rect> Monde::getListPosMonstres() { return _niveau->getListPosMonstres(); } void Monde::AfficherMonde(SDL_Surface * fenetre){ SDL_Rect rectDest; int numTuile; int minX,minY,maxX,maxY; minX = _horiScroll / _largeurTuile-1; minY = _vertiScroll / _hauteurTuile-1; maxX = ((_horiScroll + _largeurFenetre) / _largeurTuile); maxY = ((_vertiScroll + _hauteurFenetre) / _hauteurTuile); for ( int i = minX; i <= maxX ; i++){ for ( int j = minY ; j <= maxY ; j++){ rectDest.x = i * _largeurTuile - _horiScroll; rectDest.y = j * _hauteurTuile - _vertiScroll; if ( i < 0 || i >= _nbrTuilesEnColonneMonde || j < 0 || j >= _nbrTuilesEnLigneMonde){ numTuile = 0; }else{ numTuile = _schema[j][i]; } SDL_BlitSurface(_imagesDesTuiles ,&(_tuiles[numTuile].getRectangle()),fenetre,&rectDest); } } } bool Monde::collisionPerso(Hero *h) { SDL_Rect posHero = h->getPosTestHero(); int x1, x2, y1, y2,i,j; Uint16 indicetile; //On teste si la position du joueur n'est pas en dehors de la map, //si c'est le cas, on retourne vrai. if (posHero.x < 0 || posHero.y < 0 || posHero.x + posHero.w >= this->getMaxX() || posHero.y + posHero.h >= this->getMaxY() - 10) { return true; } x1 = posHero.x / _largeurTuile; y1 = posHero.y / _hauteurTuile; x2 = (posHero.x + posHero.w -1) / _largeurTuile; y2 = (posHero.y + posHero.h -1) / _hauteurTuile; for ( i = x1 ; i <= x2 ; i++) { for ( j = y1 ; j <= y2 ; j++){ indicetile = _schema[j][i]; if (_tuiles[indicetile].getType() == TypeTuile::PLEIN){ return true; } //On gère la tuile des pieces. if (_tuiles[indicetile].getType() == TypeTuile::PIECE){ if(posHero.x <= (i * _largeurTuile) + 2*(_largeurTuile/3) && posHero.y <= (j * _hauteurTuile) + 2*(_hauteurTuile / 3) && posHero.x + posHero.w >= (i * _largeurTuile) + (_largeurTuile/3) && posHero.y + posHero.h >= (j * _hauteurTuile) + (_hauteurTuile / 3)){ _schema[j][i] = 6; h->incNbPoints(); //Mourad -- Bruitage _son->demarrerBruitage("son/bruitages/coin.wav", 1); //Fin Mourad if(h->getNbPoints() > 0 && h->getNbPoints()%50 == 0){ h->setNbVies(h->getNbVies()+1); } } } if (_tuiles[indicetile].getType() == TypeTuile::VIDE_AVEC_DEGATS){ if(posHero.y + posHero.h >= (j * _hauteurTuile)+ (_hauteurTuile / 3) && posHero.x <= (i * _largeurTuile) + 2*(_largeurTuile/3) && posHero.x + posHero.w >= (i * _largeurTuile) + (_largeurTuile/3)){ if(_schema[j][i] == 10){ _schema[j][i] = 11; } if(h->getTimerMort() == 0){ h->setTimerMort(30); } } } } } return false; } bool Monde::collisionMonstre(Monstre *m){ SDL_Rect posMonstre = m->getPosTestMonstre(); int x1, x2, y1, y2,i,j; Uint16 indicetile; //On teste si la position du monstre n'est pas en dehors de la map, //si c'est le cas, on retourne vrai. if (posMonstre.x < 0 || posMonstre.y < 0 || posMonstre.x + posMonstre.w >= this->getMaxX() || posMonstre.y + posMonstre.h >= this->getMaxY()) { return true; } x1 = posMonstre.x / _largeurTuile; y1 = posMonstre.y / _hauteurTuile; x2 = (posMonstre.x + posMonstre.w -1) / _largeurTuile; y2 = (posMonstre.y + posMonstre.h -1) / _hauteurTuile; for ( i = x1 ; i <= x2 ; i++) { for ( j = y1 ; j <= y2 ; j++){ indicetile = _schema[j][i]; if (_tuiles[indicetile].getType() == TypeTuile::PLEIN){ return true; } if (_tuiles[indicetile].getType() == TypeTuile::VIDE_AVEC_DEGATS){ return true; } if( i-1 >= 0 && i+1 <=_nbrTuilesEnColonneMonde && j+2 < _nbrTuilesEnLigneMonde){ if (((_tuiles[_schema[j+2][i]].getType() == TypeTuile::VIDE || _tuiles[_schema[j+2][i]].getType() == TypeTuile::VIDE_AVEC_DEGATS) && _tuiles[_schema[j+2][i-1]].getType() == TypeTuile::PLEIN) || ((_tuiles[_schema[j+2][i]].getType() == TypeTuile::VIDE || _tuiles[_schema[j+2][i]].getType() == TypeTuile::VIDE_AVEC_DEGATS) && _tuiles[_schema[j+2][i+1]].getType() == TypeTuile::PLEIN)) { return true; } } } } return false; } void Monde::chargerInfoDepuisFichier(ifstream &fichier) throw(ExceptionGame){ string baliseTitre, nomFichierImage, baliseNbrTuileImg; string baliseTypeTuile, typeTuile; fichier >> baliseTitre; if ( ! baliseTitre.compare(BALISE_FICHIER_IMAGE) ){ fichier >> nomFichierImage; _imagesDesTuiles = chargerImage(nomFichierImage); }else{ throw new ExceptionGame("Votre fichier ne contient pas la balise #nomFichierImage"); } fichier >> baliseNbrTuileImg; if ( ! baliseNbrTuileImg.compare(BALISE_NBR_T_H_FI) ){ fichier >> _nbrTuilesEnColonne; }else{ throw new ExceptionGame("Votre fichier ne contient pas la balise #nbrTuilesColonneFichierImage"); } fichier >> baliseNbrTuileImg; if ( ! baliseNbrTuileImg.compare(BALISE_NBR_T_V_FI) ){ fichier >> _nbrTuilesEnLigne; }else{ throw new ExceptionGame("Votre fichier ne contient pas la balise #nbrTuilesLigneFichierImage"); } _largeurTuile = _imagesDesTuiles->w / _nbrTuilesEnColonne; _hauteurTuile = _imagesDesTuiles->h / _nbrTuilesEnLigne; fichier >> baliseTypeTuile; if ( ! baliseTypeTuile.compare(BALISE_TYPE_TUILE) ){ _tuiles.resize(_nbrTuilesEnLigne*_nbrTuilesEnColonne); for ( int j=0,numTuile=0 ; j < _nbrTuilesEnLigne ; j++){ for ( int i=0 ; i < _nbrTuilesEnColonne ; i++){ _tuiles[numTuile].setRectangle(_largeurTuile ,_hauteurTuile ,i*_largeurTuile ,j*_hauteurTuile); fichier >> typeTuile; fichier >> typeTuile; if ( ! typeTuile.compare("plein") ) { _tuiles[numTuile].setType(TypeTuile::PLEIN); } else if ( ! typeTuile.compare("vide") ) { _tuiles[numTuile].setType(TypeTuile::VIDE); } else if( ! typeTuile.compare("vide_avec_degats") ){ _tuiles[numTuile].setType(TypeTuile::VIDE_AVEC_DEGATS); } else if( ! typeTuile.compare("piece") ){ _tuiles[numTuile].setType(TypeTuile::PIECE); } else if( ! typeTuile.compare("fin_niveau") ){ _tuiles[numTuile].setType(TypeTuile::FIN_NIVEAU); } else { _tuiles[numTuile].setType(TypeTuile::VIDE); } numTuile++; } } }else{ throw new ExceptionGame("Votre fichier ne contient pas la balise #typeTuile"); } } bool Monde::finDuNiveau(Hero *h){ SDL_Rect posHero = h->getPosTestHero(); int x1, x2, y1, y2,i,j; Uint16 indicetile; x1 = posHero.x / _largeurTuile; y1 = posHero.y / _hauteurTuile; x2 = (posHero.x + posHero.w -1) / _largeurTuile; y2 = (posHero.y + posHero.h -1) / _hauteurTuile; for ( i = x1 ; i <= x2 ; i++) { for ( j = y1 ; j <= y2 ; j++){ indicetile = _schema[j][i]; //Si on est sur le bonhomme, on passe au niveau suivant if (_tuiles[indicetile].getType() == TypeTuile::FIN_NIVEAU) { //Mourad -- Bruitage _son->demarrerBruitage("son/bruitages/level_fini.wav", 1); //Fin Mourad if(this->getNiveauActuel() <= 4){ this->setNiveauActuel(this->getNiveauActuel()+1); SDL_Rect posDebutHero = h->getPosTestHero(); posDebutHero.x = 0; posDebutHero.y = 0; h->setPosReelHero(&posDebutHero); return true; } } } } return false; } SDL_Surface* Monde::chargerImage(string nomFichierImage){ //SDL_Surface* image_result; // charge l'image dans image_ram en RAM SDL_Surface* image_ram = SDL_LoadBMP(nomFichierImage.c_str()); if (image_ram == NULL){ throw new ExceptionGame("l'image "+nomFichierImage+" est introuvable "); } //image_result = SDL_DisplayFormat(image_ram); //SDL_FreeSurface(image_ram); return image_ram; }
34.546828
105
0.561871
[ "vector" ]
202726cdd131b29ec4e6417d13671115fe9cfd7d
1,898
cpp
C++
src/TimerThing.cpp
tetious/LarkyPrint
c3165778f244ddf1f58b0401c772ea2d3f8e4631
[ "MIT" ]
null
null
null
src/TimerThing.cpp
tetious/LarkyPrint
c3165778f244ddf1f58b0401c772ea2d3f8e4631
[ "MIT" ]
null
null
null
src/TimerThing.cpp
tetious/LarkyPrint
c3165778f244ddf1f58b0401c772ea2d3f8e4631
[ "MIT" ]
null
null
null
#include <algorithm> #include <functional> #include <utility> #include "Thing.h" #include "TimerThing.h" #include "Arduino.h" using namespace std; unsigned int TimerThing::setTimeout(const unsigned long _millis, function<void()> lambda) { timeouts.push_back({_millis, move(lambda)}); return timeouts.size(); } void TimerThing::clearTimeout(unsigned int id) { timeouts.erase(timeouts.begin() + id); } Thing TimerThing::defer(const unsigned long _millis, function<void()> lambda) { return defer_abs(_millis + millis(), move(lambda)); } Thing TimerThing::defer_abs(const unsigned long _millis, function<void()> lambda) { auto thing = Thing{this, _millis, move(lambda)}; things.push_back(thing); return thing; } void TimerThing::loop(const unsigned long _millis) { vector<Thing> triggeredThings; vector<Thing> new_first; static auto inLoop = false; if (!inLoop) { inLoop = true; auto it = things.begin(); while (it != things.end()) { if(it->when <= _millis) { it->lambda(); it = things.erase(it); } else { it++; } } for (auto timeout: timeouts) { if (_millis % timeout.timeout == 0) { timeout.lambda(); } } inLoop = false; } else { Serial.printf("TimerThing::loop while already looping [%u]!\r\n", _millis); } } TimerThing &TimerThing::Instance() { static TimerThing instance; return instance; } TimerThing::TimerThing() { xTaskCreate([](void *o) { TickType_t lastWakeTime; const auto freq = 1 / portTICK_PERIOD_MS; while (true) { lastWakeTime = xTaskGetTickCount(); static_cast<TimerThing *>(o)->loop(millis()); vTaskDelayUntil(&lastWakeTime, freq); } }, "tt_loop", 2048, this, 2, nullptr); }
26
91
0.60432
[ "vector" ]
202bbd645f7515677fda07f86192e13c90b060c1
16,075
cpp
C++
src/xrEngine/xr_efflensflare.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrEngine/xr_efflensflare.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrEngine/xr_efflensflare.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "stdafx.h" #pragma hdrstop #include "xr_efflensflare.h" #include "IGame_Persistent.h" #include "Environment.h" // Instead of SkeletonCustom: #include "xrCore/Animation/Bone.hpp" #include "Include/xrRender/Kinematics.h" #include "xrCDB/Intersect.hpp" #include "Common/object_broker.h" #ifdef _EDITOR #include "ui_toolscustom.h" #include "ui_main.h" #else #include "xr_object.h" #include "IGame_Level.h" #endif #define FAR_DIST g_pGamePersistent->Environment().CurrentEnv->far_plane //#define MAX_Flares 24 ////////////////////////////////////////////////////////////////////////////// // Globals /////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #define BLEND_INC_SPEED 8.0f #define BLEND_DEC_SPEED 4.0f //------------------------------------------------------------------------------ void CLensFlareDescriptor::SetSource(float fRadius, bool ign_color, pcstr tex_name, pcstr sh_name) { m_Source.fRadius = fRadius; m_Source.shader = sh_name; m_Source.texture = tex_name; m_Source.ignore_color = ign_color; } void CLensFlareDescriptor::SetGradient(float fMaxRadius, float fOpacity, pcstr tex_name, pcstr sh_name) { m_Gradient.fRadius = fMaxRadius; m_Gradient.fOpacity = fOpacity; m_Gradient.shader = sh_name; m_Gradient.texture = tex_name; } void CLensFlareDescriptor::AddFlare(float fRadius, float fOpacity, float fPosition, pcstr tex_name, pcstr sh_name) { SFlare F; F.fRadius = fRadius; F.fOpacity = fOpacity; F.fPosition = fPosition; F.shader = sh_name; F.texture = tex_name; m_Flares.push_back(F); } struct FlareDescriptorFields { pcstr line; pcstr shader; pcstr texture; pcstr radius; pcstr ignore_color; }; FlareDescriptorFields SourceFields = { "source", "source_shader", "source_texture", "source_radius", "source_ignore_color" }; FlareDescriptorFields SunFields = { "sun", "sun_shader", "sun_texture", "sun_radius", "sun_ignore_color" }; void CLensFlareDescriptor::load(CInifile const* pIni, pcstr sect) { section = sect; const auto read = [&](FlareDescriptorFields f) { m_Flags.set(flSource, pIni->r_bool(sect, f.line)); if (m_Flags.is(flSource)) { pcstr s = pIni->r_string(sect, f.shader); pcstr t = pIni->r_string(sect, f.texture); float r = pIni->r_float(sect, f.radius); bool i = pIni->r_bool(sect, f.ignore_color); SetSource(r, i, t, s); } }; if (pIni->line_exist(sect, SourceFields.line)) { read(SourceFields); // What if someone adapted SOC configs and didn't deleted "source" field? // Try to read "sun" optional overriding values. if (pIni->line_exist(sect, SunFields.line)) read(SunFields); } else read(SunFields); m_Flags.set(flFlare, pIni->r_bool(sect, "flares")); if (m_Flags.is(flFlare)) { pcstr S = pIni->r_string(sect, "flare_shader"); pcstr T = pIni->r_string(sect, "flare_textures"); pcstr R = pIni->r_string(sect, "flare_radius"); pcstr O = pIni->r_string(sect, "flare_opacity"); pcstr P = pIni->r_string(sect, "flare_position"); u32 tcnt = _GetItemCount(T); string256 name; for (u32 i = 0; i < tcnt; i++) { _GetItem(R, i, name); float r = (float)atof(name); _GetItem(O, i, name); float o = (float)atof(name); _GetItem(P, i, name); float p = (float)atof(name); _GetItem(T, i, name); AddFlare(r, o, p, name, S); } } m_Flags.set(flGradient, CInifile::isBool(pIni->r_string(sect, "gradient"))); if (m_Flags.is(flGradient)) { pcstr S = pIni->r_string(sect, "gradient_shader"); pcstr T = pIni->r_string(sect, "gradient_texture"); float r = pIni->r_float(sect, "gradient_radius"); float o = pIni->r_float(sect, "gradient_opacity"); SetGradient(r, o, T, S); } m_StateBlendUpSpeed = 1.f / (_max(pIni->r_float(sect, "blend_rise_time"), 0.f) + EPS_S); m_StateBlendDnSpeed = 1.f / (_max(pIni->r_float(sect, "blend_down_time"), 0.f) + EPS_S); OnDeviceCreate(); } void CLensFlareDescriptor::OnDeviceCreate() { // shaders m_Gradient.m_pRender->CreateShader(*m_Gradient.shader, *m_Gradient.texture); m_Source.m_pRender->CreateShader(*m_Source.shader, *m_Source.texture); for (const auto& flare : m_Flares) flare.m_pRender->CreateShader(*flare.shader, *flare.texture); } void CLensFlareDescriptor::OnDeviceDestroy() { // shaders m_Gradient.m_pRender->DestroyShader(); m_Source.m_pRender->DestroyShader(); for (const auto& flare : m_Flares) flare.m_pRender->DestroyShader(); } //------------------------------------------------------------------------------ CLensFlare::CLensFlare() { // Device dwFrame = 0xfffffffe; fBlend = 0.f; LightColor.set(0xFFFFFFFF); fGradientValue = 0.f; m_Current = 0; m_State = lfsNone; m_StateBlend = 0.f; #ifndef _EDITOR for (auto& ray : m_ray_cache) { for (auto& vert : ray.verts) vert.set(0, 0, 0); } #endif OnDeviceCreate(); } CLensFlare::~CLensFlare() { OnDeviceDestroy(); delete_data(m_Palette); } #ifndef _EDITOR struct STranspParam { Fvector P; Fvector D; float f; // CLensFlare* parent; collide::ray_cache* pray_cache; float vis; float vis_threshold; STranspParam(collide::ray_cache* p, const Fvector& _P, const Fvector& _D, float _f, float _vis_threshold) : P(_P), D(_D), f(_f), pray_cache(p), vis(1.f), vis_threshold(_vis_threshold) { } }; IC bool material_callback(collide::rq_result& result, LPVOID params) { STranspParam* fp = (STranspParam*)params; float vis = 1.f; if (result.O) { vis = 0.f; IKinematics* K = PKinematics(result.O->GetRenderData().visual); if (K && (result.element > 0)) vis = g_pGamePersistent->MtlTransparent(K->LL_GetData(u16(result.element)).game_mtl_idx); } else { CDB::TRI* T = g_pGameLevel->ObjectSpace.GetStaticTris() + result.element; vis = g_pGamePersistent->MtlTransparent(T->material); if (fis_zero(vis)) { Fvector* V = g_pGameLevel->ObjectSpace.GetStaticVerts(); fp->pray_cache->set(fp->P, fp->D, fp->f, true); fp->pray_cache->verts[0].set(V[T->verts[0]]); fp->pray_cache->verts[1].set(V[T->verts[1]]); fp->pray_cache->verts[2].set(V[T->verts[2]]); } } fp->vis *= vis; return (fp->vis > fp->vis_threshold); } #endif IC void blend_lerp(float& cur, float tgt, float speed, float dt) { float diff = tgt - cur; float diff_a = _abs(diff); if (diff_a < EPS_S) return; float mot = speed * dt; if (mot > diff_a) mot = diff_a; cur += (diff / diff_a) * mot; } #if 0 static pcstr state_to_string(const CLensFlare::LFState& state) { switch (state) { case CLensFlare::lfsNone: return("none"); case CLensFlare::lfsIdle: return("idle"); case CLensFlare::lfsHide: return("hide"); case CLensFlare::lfsShow: return("show"); default: NODEFAULT; } #ifdef DEBUG return (0); #endif // DEBUG } #endif static Fvector2 RayDeltas[CLensFlare::MAX_RAYS] = { {0, 0}, {1, 0}, {-1, 0}, {0, -1}, {0, 1}, }; void CLensFlare::OnFrame(shared_str id) { if (dwFrame == Device.dwFrame) return; #ifndef _EDITOR if (!g_pGameLevel) return; #endif dwFrame = Device.dwFrame; R_ASSERT(_valid(g_pGamePersistent->Environment().CurrentEnv->sun_dir)); vSunDir.mul(g_pGamePersistent->Environment().CurrentEnv->sun_dir, -1); R_ASSERT(_valid(vSunDir)); // color float tf = g_pGamePersistent->Environment().fTimeFactor; Fvector& c = g_pGamePersistent->Environment().CurrentEnv->sun_color; LightColor.set(c.x, c.y, c.z, 1.f); CInifile const* pIni = g_pGamePersistent->Environment().m_suns_config; if (!pIni) pIni = pSettings; CLensFlareDescriptor* desc = id.size() ? g_pGamePersistent->Environment().add_flare(m_Palette, id, pIni) : nullptr; // LFState previous_state = m_State; switch (m_State) { case lfsNone: m_State = lfsShow; m_Current = desc; break; case lfsIdle: if (desc != m_Current) m_State = lfsHide; break; case lfsShow: m_StateBlend = m_Current ? (m_StateBlend + m_Current->m_StateBlendUpSpeed * Device.fTimeDelta * tf) : 1.f + EPS; if (m_StateBlend >= 1.f) m_State = lfsIdle; break; case lfsHide: m_StateBlend = m_Current ? (m_StateBlend - m_Current->m_StateBlendDnSpeed * Device.fTimeDelta * tf) : 0.f - EPS; if (m_StateBlend <= 0.f) { m_State = lfsShow; m_Current = desc; m_StateBlend = m_Current ? m_Current->m_StateBlendUpSpeed * Device.fTimeDelta * tf : 0; } break; } // Msg ("%6d : [%s] -> [%s]", Device.dwFrame, state_to_string(previous_state), state_to_string(m_State)); clamp(m_StateBlend, 0.f, 1.f); if ((m_Current == 0) || (LightColor.magnitude_rgb() == 0.f)) { bRender = false; return; } // // Compute center and axis of flares // float fDot; Fvector vecPos; Fmatrix matEffCamPos; matEffCamPos.identity(); // Calculate our position and direction matEffCamPos.i.set(Device.vCameraRight); matEffCamPos.j.set(Device.vCameraTop); matEffCamPos.k.set(Device.vCameraDirection); vecPos.set(Device.vCameraPosition); vecDir.set(0.0f, 0.0f, 1.0f); matEffCamPos.transform_dir(vecDir); vecDir.normalize(); // Figure out of light (or flare) might be visible vecLight.set(vSunDir); vecLight.normalize(); fDot = vecLight.dotproduct(vecDir); if (fDot <= 0.01f) { bRender = false; return; } else bRender = true; // Calculate the point directly in front of us, on the far clip plane float fDistance = FAR_DIST * 0.75f; vecCenter.mul(vecDir, fDistance); vecCenter.add(vecPos); // Calculate position of light on the far clip plane vecLight.mul(fDistance / fDot); vecLight.add(vecPos); // Compute axis which goes from light through the center of the screen vecAxis.sub(vecLight, vecCenter); // // Figure out if light is behind something else vecX.set(1.0f, 0.0f, 0.0f); matEffCamPos.transform_dir(vecX); vecX.normalize(); R_ASSERT(_valid(vecX)); vecY.crossproduct(vecX, vecDir); R_ASSERT(_valid(vecY)); #ifdef _EDITOR float dist = UI->ZFar(); if (Tools->RayPick(Device.m_Camera.GetPosition(), vSunDir, dist)) fBlend = fBlend - BLEND_DEC_SPEED * Device.fTimeDelta; else fBlend = fBlend + BLEND_INC_SPEED * Device.fTimeDelta; #else // Side vectors to bend normal. Fvector vecSx; Fvector vecSy; // float fScale = m_Current->m_Source.fRadius * vSunDir.magnitude(); // float fScale = m_Current->m_Source.fRadius; // HACK: it must be read from the weather! float fScale = 0.02f; vecSx.mul(vecX, fScale); vecSy.mul(vecY, fScale); IGameObject* o_main = g_pGameLevel->CurrentViewEntity(); R_ASSERT(_valid(vSunDir)); STranspParam TP(&m_ray_cache[0], Device.vCameraPosition, vSunDir, 1000.f, EPS_L); R_ASSERT(_valid(TP.P)); R_ASSERT(_valid(TP.D)); collide::ray_defs RD(TP.P, TP.D, TP.f, CDB::OPT_CULL, collide::rqtBoth); float fVisResult = 0.0f; for (int i = 0; i < MAX_RAYS; ++i) { TP.D = vSunDir; TP.D.add(Fvector().mul(vecSx, RayDeltas[i].x)); TP.D.add(Fvector().mul(vecSy, RayDeltas[i].y)); R_ASSERT(_valid(TP.D)); TP.pray_cache = &(m_ray_cache[i]); TP.vis = 1.0f; RD.dir = TP.D; if (m_ray_cache[i].result && m_ray_cache[i].similar(TP.P, TP.D, TP.f)) { // similar with previous query == 0 TP.vis = 0.f; } else { float _u, _v, _range; if (CDB::TestRayTri(TP.P, TP.D, m_ray_cache[i].verts, _u, _v, _range, false) && (_range > 0 && _range < TP.f)) { TP.vis = 0.f; } else { // cache outdated. real query. r_dest.r_clear(); if (g_pGameLevel->ObjectSpace.RayQuery(r_dest, RD, material_callback, &TP, NULL, o_main)) m_ray_cache[i].result = false; } } fVisResult += TP.vis; } fVisResult *= (1.0f / MAX_RAYS); // blend_lerp(fBlend,TP.vis,BLEND_DEC_SPEED,Device.fTimeDelta); blend_lerp(fBlend, fVisResult, BLEND_DEC_SPEED, Device.fTimeDelta); /* IGameObject* o_main = g_pGameLevel->CurrentViewEntity(); STranspParam TP (&m_ray_cache,Device.vCameraPosition,vSunDir,1000.f,EPS_L); collide::ray_defs RD (TP.P,TP.D,TP.f,CDB::OPT_CULL,collide::rqtBoth); if (m_ray_cache.result&&m_ray_cache.similar(TP.P,TP.D,TP.f)){ // similar with previous query == 0 TP.vis = 0.f; }else{ float _u,_v,_range; if (CDB::TestRayTri(TP.P,TP.D,m_ray_cache.verts,_u,_v,_range,false)&&(_range>0 && _range<TP.f)){ TP.vis = 0.f; }else{ // cache outdated. real query. r_dest.r_clear (); if (g_pGameLevel->ObjectSpace.RayQuery (r_dest,RD,material_callback,&TP,NULL,o_main)) m_ray_cache.result = false ; } } blend_lerp(fBlend,TP.vis,BLEND_DEC_SPEED,Device.fTimeDelta); */ /* IGameObject* o_main = g_pGameLevel->CurrentViewEntity(); STranspParam TP (this,Device.vCameraPosition,vSunDir,1000.f,EPS_L); collide::ray_defs RD (TP.P,TP.D,TP.f,CDB::OPT_CULL,collide::rqtBoth); if (m_ray_cache.result&&m_ray_cache.similar(TP.P,TP.D,TP.f)){ // similar with previous query == 0 TP.vis = 0.f; }else{ float _u,_v,_range; if (CDB::TestRayTri(TP.P,TP.D,m_ray_cache.verts,_u,_v,_range,false)&&(_range>0 && _range<TP.f)){ TP.vis = 0.f; }else{ // cache outdated. real query. r_dest.r_clear (); if (g_pGameLevel->ObjectSpace.RayQuery (r_dest,RD,material_callback,&TP,NULL,o_main)) m_ray_cache.result = false ; } } blend_lerp(fBlend,TP.vis,BLEND_DEC_SPEED,Device.fTimeDelta); */ #endif clamp(fBlend, 0.0f, 1.0f); // gradient if (m_Current->m_Flags.is(CLensFlareDescriptor::flGradient)) { Fvector scr_pos; Device.mFullTransform.transform(scr_pos, vecLight); float kx = 1, ky = 1; float sun_blend = 0.5f; float sun_max = 2.5f; scr_pos.y *= -1; if (_abs(scr_pos.x) > sun_blend) kx = ((sun_max - (float)_abs(scr_pos.x))) / (sun_max - sun_blend); if (_abs(scr_pos.y) > sun_blend) ky = ((sun_max - (float)_abs(scr_pos.y))) / (sun_max - sun_blend); if (!((_abs(scr_pos.x) > sun_max) || (_abs(scr_pos.y) > sun_max))) { float op = m_StateBlend * m_Current->m_Gradient.fOpacity; fGradientValue = kx * ky * op * fBlend; } else fGradientValue = 0; } } void CLensFlare::Render(bool bSun, bool bFlares, bool bGradient) { if (!bRender) return; if (!m_Current) return; VERIFY(m_Current); m_pRender->Render(*this, bSun, bFlares, bGradient); } shared_str CLensFlare::AppendDef(CEnvironment& environment, CInifile const* pIni, pcstr sect) { if (!sect || (0 == sect[0])) return ""; environment.add_flare(m_Palette, sect, pIni); return sect; } void CLensFlare::OnDeviceCreate() { // VS m_pRender->OnDeviceCreate(); // palette for (const auto& descr : m_Palette) descr->OnDeviceCreate(); } void CLensFlare::OnDeviceDestroy() { // palette for (const auto& descr : m_Palette) descr->OnDeviceDestroy(); // VS m_pRender->OnDeviceDestroy(); }
28.35097
120
0.607527
[ "render", "transform" ]
45ca2d1f635304a923b3a34becffdd7c1eef6e12
61,316
cp
C++
Text/Mod/Rulers.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2018-03-15T00:25:25.000Z
2018-03-15T00:25:25.000Z
Text/Mod/Rulers.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Text/Mod/Rulers.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE TextRulers; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) (* re-check alien attributes: consider projection semantics *) IMPORT Kernel, Strings, Services, Fonts, Ports, Stores, Models, Views, Controllers, Properties, Dialog, TextModels; CONST (** Attributes.valid, Prop.known/valid **) (* Mark.kind *) first* = 0; left* = 1; right* = 2; lead* = 3; asc* = 4; dsc* = 5; grid* = 6; opts* = 7; tabs* = 8; (* additional values for icons held by Mark.kind *) invalid = -1; firstIcon = 10; lastIcon = 25; rightToggle = 10; gridDec = 12; gridVal = 13; gridInc = 14; leftFlush = 16; centered = 17; rightFlush = 18; justified = 19; leadDec = 21; leadVal = 22; leadInc = 23; pageBrk = 25; modeIcons = {leftFlush .. justified}; validIcons = {rightToggle, gridDec .. gridInc, leftFlush .. justified, leadDec .. leadInc, pageBrk}; fieldIcons = {gridVal, leadVal}; (** Attributes.opts **) leftAdjust* = 0; rightAdjust* = 1; (** both: fully justified; none: centered **) noBreakInside* = 2; pageBreak* = 3; parJoin* = 4; (** pageBreak of this ruler overrides parJoin request of previous ruler **) rightFixed* = 5; (** has fixed right border **) options = {leftAdjust .. rightFixed}; (* options mask *) adjMask = {leftAdjust, rightAdjust}; (** Attributes.tabType[i] **) maxTabs* = 32; centerTab* = 0; rightTab* = 1; (** both: (reserved); none: leftTab **) barTab* = 2; tabOptions = {centerTab .. barTab}; (* mask for presently valid options *) mm = Ports.mm; inch16 = Ports.inch DIV 16; point = Ports.point; tabBarHeight = 11 * point; scaleHeight = 10 * point; iconBarHeight = 14 * point; rulerHeight = tabBarHeight + scaleHeight + iconBarHeight; iconHeight = 10 * point; iconWidth = 12 * point; iconGap = 2 * point; iconPin = rulerHeight - (iconBarHeight - iconHeight) DIV 2; rulerChangeKey = "#Text:RulerChange"; minVersion = 0; maxAttrVersion = 2; maxStyleVersion = 0; maxStdStyleVersion = 0; maxRulerVersion = 0; maxStdRulerVersion = 0; TYPE Tab* = RECORD stop*: INTEGER; type*: SET END; TabArray* = RECORD (* should be POINTER TO ARRAY OF Tab -- but cannot protect *) len*: INTEGER; tab*: ARRAY maxTabs OF Tab END; Attributes* = POINTER TO EXTENSIBLE RECORD (Stores.Store) init-: BOOLEAN; (* immutable once init holds *) first-, left-, right-, lead-, asc-, dsc-, grid-: INTEGER; opts-: SET; tabs-: TabArray END; AlienAttributes* = POINTER TO RECORD (Attributes) store-: Stores.Alien END; Style* = POINTER TO ABSTRACT RECORD (Models.Model) attr-: Attributes END; Ruler* = POINTER TO ABSTRACT RECORD (Views.View) style-: Style END; Prop* = POINTER TO RECORD (Properties.Property) first*, left*, right*, lead*, asc*, dsc*, grid*: INTEGER; opts*: RECORD val*, mask*: SET END; tabs*: TabArray END; UpdateMsg* = RECORD (Models.UpdateMsg) (** domaincast upon style update **) style*: Style; oldAttr*: Attributes END; Directory* = POINTER TO ABSTRACT RECORD attr-: Attributes END; StdStyle = POINTER TO RECORD (Style) END; StdRuler = POINTER TO RECORD (Ruler) sel: INTEGER; (* sel # invalid => sel = kind of selected mark *) px, py: INTEGER (* sel # invalid => px, py of selected mark *) END; StdDirectory = POINTER TO RECORD (Directory) END; Mark = RECORD ruler: StdRuler; l, r, t, b: INTEGER; px, py, px0, py0, x, y: INTEGER; kind, index: INTEGER; type: SET; (* valid if kind = tabs *) tabs: TabArray; (* if valid: tabs[index].type = type *) dirty: BOOLEAN END; SetAttrOp = POINTER TO RECORD (Stores.Operation) style: Style; attr: Attributes END; NeutralizeMsg = RECORD (Views.Message) END; VAR dir-, stdDir-: Directory; def: Attributes; prop: Prop; (* recycled *) globRd: TextModels.Reader; (* cache for temp reader; beware of reentrance *) font: Fonts.Font; marginGrid, minTabWidth, tabGrid: INTEGER; PROCEDURE ^ DoSetAttrOp (s: Style; attr: Attributes); PROCEDURE CopyTabs (IN src: TabArray; OUT dst: TabArray); (* a TabArray is a 256 byte structure - copying of used parts is much faster than ":= all" *) VAR i, n: INTEGER; BEGIN n := src.len; dst.len := n; i := 0; WHILE i < n DO dst.tab[i] := src.tab[i]; INC(i) END END CopyTabs; (** Attributes **) PROCEDURE (a: Attributes) CopyFrom- (source: Stores.Store), EXTENSIBLE; BEGIN WITH source: Attributes DO ASSERT(~a.init, 20); ASSERT(source.init, 21); a.init := TRUE; a.first := source.first; a.left := source.left; a.right := source.right; a.lead := source.lead; a.asc := source.asc; a.dsc := source.dsc; a.grid := source.grid; a.opts := source.opts; CopyTabs(source.tabs, a.tabs) END END CopyFrom; PROCEDURE (a: Attributes) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE; (** pre: a.init **) VAR i: INTEGER; typedTabs: BOOLEAN; BEGIN ASSERT(a.init, 20); a.Externalize^(wr); i := 0; WHILE (i < a.tabs.len) & (a.tabs.tab[i].type = {}) DO INC(i) END; typedTabs := i < a.tabs.len; IF typedTabs THEN wr.WriteVersion(maxAttrVersion) ELSE wr.WriteVersion(1) (* versions before 2 had only leftTabs *) END; wr.WriteInt(a.first); wr.WriteInt(a.left); wr.WriteInt(a.right); wr.WriteInt(a.lead); wr.WriteInt(a.asc); wr.WriteInt(a.dsc); wr.WriteInt(a.grid); wr.WriteSet(a.opts); wr.WriteXInt(a.tabs.len); i := 0; WHILE i < a.tabs.len DO wr.WriteInt(a.tabs.tab[i].stop); INC(i) END; IF typedTabs THEN i := 0; WHILE i < a.tabs.len DO wr.WriteSet(a.tabs.tab[i].type); INC(i) END END END Externalize; PROCEDURE (a: Attributes) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE; (** pre: ~a.init **) (** post: a.init **) VAR thisVersion, i, n, trash: INTEGER; trashSet: SET; BEGIN ASSERT(~a.init, 20); a.init := TRUE; a.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxAttrVersion, thisVersion); IF rd.cancelled THEN RETURN END; rd.ReadInt(a.first); rd.ReadInt(a.left); rd.ReadInt(a.right); rd.ReadInt(a.lead); rd.ReadInt(a.asc); rd.ReadInt(a.dsc); rd.ReadInt(a.grid); rd.ReadSet(a.opts); rd.ReadXInt(n); a.tabs.len := MIN(n, maxTabs); i := 0; WHILE i < a.tabs.len DO rd.ReadInt(a.tabs.tab[i].stop); INC(i) END; WHILE i < n DO rd.ReadInt(trash); INC(i) END; IF thisVersion = 0 THEN (* convert from v0 rightFixed to v1 ~rightFixed default *) INCL(a.opts, rightFixed) END; IF thisVersion >= 2 THEN i := 0; WHILE i < a.tabs.len DO rd.ReadSet(a.tabs.tab[i].type); INC(i) END; WHILE i < n DO rd.ReadSet(trashSet); INC(i) END ELSE i := 0; WHILE i < a.tabs.len DO a.tabs.tab[i].type := {}; INC(i) END END END Internalize; PROCEDURE Set (p: Prop; opt: INTEGER; VAR x: INTEGER; min, max, new: INTEGER); BEGIN IF opt IN p.valid THEN x := MAX(min, MIN(max, new)) END END Set; PROCEDURE ModifyFromProp (a: Attributes; p: Properties.Property); CONST maxW = 10000*mm; maxH = 32767 * point; VAR i: INTEGER; type, mask: SET; BEGIN WHILE p # NIL DO WITH p: Prop DO Set(p, first, a.first, 0, maxW, p.first); Set(p, left, a.left, 0, maxW, p.left); Set(p, right, a.right, MAX(a.left, a.first), maxW, p.right); Set(p, lead, a.lead, 0, maxH, p.lead); Set(p, asc, a.asc, 0, maxH, p.asc); Set(p, dsc, a.dsc, 0, maxH - a.asc, p.dsc); Set(p, grid, a.grid, 1, maxH, p.grid); IF opts IN p.valid THEN a.opts := a.opts * (-p.opts.mask) + p.opts.val * p.opts.mask END; IF (tabs IN p.valid) & (p.tabs.len >= 0) THEN IF (p.tabs.len > 0) & (p.tabs.tab[0].stop >= 0) THEN i := 0; a.tabs.len := MIN(p.tabs.len, maxTabs); REPEAT a.tabs.tab[i].stop := p.tabs.tab[i].stop; type := p.tabs.tab[i].type; mask := tabOptions; IF type * {centerTab, rightTab} = {centerTab, rightTab} THEN mask := mask - {centerTab, rightTab} END; a.tabs.tab[i].type := a.tabs.tab[i].type * (-mask) + type * mask; INC(i) UNTIL (i = a.tabs.len) OR (p.tabs.tab[i].stop < p.tabs.tab[i - 1].stop); a.tabs.len := i ELSE a.tabs.len := 0 END END ELSE END; p := p.next END END ModifyFromProp; PROCEDURE (a: Attributes) ModifyFromProp- (p: Properties.Property), NEW, EXTENSIBLE; BEGIN ModifyFromProp(a, p) END ModifyFromProp; PROCEDURE (a: Attributes) InitFromProp* (p: Properties.Property), NEW, EXTENSIBLE; (** pre: ~a.init **) (** post: (a.init, p # NIL & x IN p.valid) => x set in a, else x defaults in a **) BEGIN ASSERT(~a.init, 20); a.init := TRUE; a.first := def.first; a.left := def.left; a.right := def.right; a.lead := def.lead; a.asc := def.asc; a.dsc := def.dsc; a.grid := def.grid; a.opts := def.opts; CopyTabs(def.tabs, a.tabs); ModifyFromProp(a, p) END InitFromProp; PROCEDURE (a: Attributes) Equals* (b: Attributes): BOOLEAN, NEW, EXTENSIBLE; (** pre: a.init, b.init **) VAR i: INTEGER; BEGIN ASSERT(a.init, 20); ASSERT(b.init, 21); IF a # b THEN i := 0; WHILE (i < a.tabs.len) & (a.tabs.tab[i].stop = b.tabs.tab[i].stop) & (a.tabs.tab[i].type = b.tabs.tab[i].type) DO INC(i) END; RETURN (Services.SameType(a, b)) & (a.first = b.first) & (a.left = b.left) & (a.right = b.right) & (a.lead = b.lead) & (a.asc = b.asc) & (a.dsc = b.dsc) & (a.grid = b.grid) & (a.opts = b.opts) & (a.tabs.len = b.tabs.len) & (i = a.tabs.len) ELSE RETURN TRUE END END Equals; PROCEDURE (a: Attributes) Prop* (): Properties.Property, NEW, EXTENSIBLE; (** pre: a.init **) (** post: x attr in a => x IN p.valid, m set to value of attr in a **) VAR p: Prop; BEGIN ASSERT(a.init, 20); NEW(p); p.known := {first .. tabs}; p.valid := p.known; p.first := a.first; p.left := a.left; p.right := a.right; p.lead := a.lead; p.asc := a.asc; p.dsc := a.dsc; p.grid := a.grid; p.opts.val := a.opts; p.opts.mask := options; CopyTabs(a.tabs, p.tabs); RETURN p END Prop; PROCEDURE ReadAttr* (VAR rd: Stores.Reader; OUT a: Attributes); VAR st: Stores.Store; alien: AlienAttributes; BEGIN rd.ReadStore(st); ASSERT(st # NIL, 100); IF st IS Stores.Alien THEN NEW(alien); alien.store := st(Stores.Alien); Stores.Join(alien, alien.store); alien.InitFromProp(NIL); a := alien ELSE a := st(Attributes) END END ReadAttr; PROCEDURE WriteAttr* (VAR wr: Stores.Writer; a: Attributes); BEGIN ASSERT(a # NIL, 20); ASSERT(a.init, 21); WITH a: AlienAttributes DO wr.WriteStore(a.store) ELSE wr.WriteStore(a) END END WriteAttr; PROCEDURE ModifiedAttr* (a: Attributes; p: Properties.Property): Attributes; (** pre: a.init **) (** post: x IN p.valid => x in new attr set to value in p, else set to value in a **) VAR h: Attributes; BEGIN ASSERT(a.init, 20); h := Stores.CopyOf(a)(Attributes); h.ModifyFromProp(p); RETURN h END ModifiedAttr; (** AlienAttributes **) PROCEDURE (a: AlienAttributes) Externalize- (VAR wr: Stores.Writer); BEGIN HALT(100) END Externalize; PROCEDURE (a: AlienAttributes) Internalize- (VAR rd: Stores.Reader); BEGIN HALT(100) END Internalize; PROCEDURE (a: AlienAttributes) InitFromProp* (p: Properties.Property); BEGIN a.InitFromProp^(NIL) END InitFromProp; PROCEDURE (a: AlienAttributes) ModifyFromProp- (p: Properties.Property); BEGIN (* a.InitFromProp^(NIL) *) a.InitFromProp(NIL) END ModifyFromProp; (** Style **) (* PROCEDURE (s: Style) PropagateDomain-, EXTENSIBLE; VAR dom: Stores.Domain; BEGIN ASSERT(s.attr # NIL, 20); dom := s.attr.Domain(); IF (dom # NIL) & (dom # s.Domain()) THEN s.attr := Stores.CopyOf(s.attr)(Attributes) END; Stores.InitDomain(s.attr, s.Domain()) END PropagateDomain; *) PROCEDURE (s: Style) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE; BEGIN s.Externalize^(wr); wr.WriteVersion(maxStyleVersion); WriteAttr(wr, s.attr) END Externalize; PROCEDURE (s: Style) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE; VAR thisVersion: INTEGER; BEGIN s.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxStyleVersion, thisVersion); IF rd.cancelled THEN RETURN END; ReadAttr(rd, s.attr); Stores.Join(s, s.attr) END Internalize; PROCEDURE (s: Style) SetAttr* (attr: Attributes), NEW, EXTENSIBLE; (** pre: attr.init **) (** post: s.attr = attr OR s.attr.Equals(attr) **) BEGIN ASSERT(attr.init, 20); DoSetAttrOp(s, attr) END SetAttr; PROCEDURE (s: Style) CopyFrom- (source: Stores.Store), EXTENSIBLE; BEGIN WITH source: Style DO ASSERT(source.attr # NIL, 21); s.SetAttr(Stores.CopyOf(source.attr)(Attributes)) (* bkwd-comp hack to avoid link *) (* copy would not be necessary if Attributes were immutable (and assigned to an Immutable Domain) *) END END CopyFrom; (* PROCEDURE (s: Style) InitFrom- (source: Models.Model), EXTENSIBLE; BEGIN WITH source: Style DO ASSERT(source.attr # NIL, 21); s.SetAttr(Stores.CopyOf(source.attr)(Attributes)) (* bkwd-comp hack to avoid link *) END END InitFrom; *) (** Directory **) PROCEDURE (d: Directory) SetAttr* (attr: Attributes), NEW, EXTENSIBLE; (** pre: attr.init **) (** post: d.attr = ModifiedAttr(attr, p) [ p.valid = {opts, tabs}, p.tabs.len = 0, p.opts.mask = {noBreakInside.. parJoin}, p.opts.val = {} ] **) VAR p: Prop; BEGIN ASSERT(attr.init, 20); IF attr.tabs.len > 0 THEN NEW(p); p.valid := {opts, tabs}; p.opts.mask := {noBreakInside, pageBreak, parJoin}; p.opts.val := {}; p.tabs.len := 0; attr := ModifiedAttr(attr, p) END; d.attr := attr END SetAttr; PROCEDURE (d: Directory) NewStyle* (attr: Attributes): Style, NEW, ABSTRACT; PROCEDURE (d: Directory) New* (style: Style): Ruler, NEW, ABSTRACT; PROCEDURE (d: Directory) NewFromProp* (p: Prop): Ruler, NEW, EXTENSIBLE; BEGIN RETURN d.New(d.NewStyle(ModifiedAttr(d.attr, p))) END NewFromProp; PROCEDURE Deposit*; BEGIN Views.Deposit(dir.New(NIL)) END Deposit; (** Ruler **) PROCEDURE (r: Ruler) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE; BEGIN ASSERT(r.style # NIL, 20); r.Externalize^(wr); wr.WriteVersion(maxRulerVersion); wr.WriteStore(r.style) END Externalize; PROCEDURE (r: Ruler) InitStyle* (s: Style), NEW; (** pre: r.style = NIL, s # NIL, style.attr # NIL **) (** post: r.style = s **) BEGIN ASSERT((r.style = NIL) OR (r.style = s), 20); ASSERT(s # NIL, 21); ASSERT(s.attr # NIL, 22); r.style := s; Stores.Join(r, s) END InitStyle; PROCEDURE (r: Ruler) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE; VAR st: Stores.Store; thisVersion: INTEGER; BEGIN r.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxRulerVersion, thisVersion); IF rd.cancelled THEN RETURN END; rd.ReadStore(st); IF st IS Stores.Alien THEN rd.TurnIntoAlien(Stores.alienComponent); RETURN END; r.InitStyle(st(Style)) END Internalize; (* PROCEDURE (r: Ruler) InitModel* (m: Models.Model), EXTENSIBLE; (** pre: r.style = NIL, m # NIL, style.attr # NIL, m IS Style **) (** post: r.style = m **) BEGIN WITH m: Style DO ASSERT((r.style = NIL) OR (r.style = m), 20); ASSERT(m # NIL, 21); ASSERT(m.attr # NIL, 22); r.style := m ELSE HALT(23) END END InitModel; *) (* PROCEDURE (r: Ruler) PropagateDomain-, EXTENSIBLE; BEGIN ASSERT(r.style # NIL, 20); Stores.InitDomain(r.style, r.Domain()) END PropagateDomain; *) PROCEDURE CopyOf* (r: Ruler; shallow: BOOLEAN): Ruler; VAR v: Views.View; BEGIN ASSERT(r # NIL, 20); v := Views.CopyOf(r, shallow); RETURN v(Ruler) END CopyOf; (** Prop **) PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN); VAR valid: SET; i: INTEGER; c, m: SET; eq: BOOLEAN; BEGIN WITH q: Prop DO valid := p.valid * q.valid; equal := TRUE; i := 0; WHILE (i < p.tabs.len) & (p.tabs.tab[i].stop = q.tabs.tab[i].stop) & (p.tabs.tab[i].type = q.tabs.tab[i].type) DO INC(i) END; IF p.first # q.first THEN EXCL(valid, first) END; IF p.left # q.left THEN EXCL(valid, left) END; IF p.right # q.right THEN EXCL(valid, right) END; IF p.lead # q.lead THEN EXCL(valid, lead) END; IF p.asc # q.asc THEN EXCL(valid, asc) END; IF p.dsc # q.dsc THEN EXCL(valid, dsc) END; IF p.grid # q.grid THEN EXCL(valid, grid) END; Properties.IntersectSelections(p.opts.val, p.opts.mask, q.opts.val, q.opts.mask, c, m, eq); IF m = {} THEN EXCL(valid, opts) ELSIF (opts IN valid) & ~eq THEN p.opts.mask := m; equal := FALSE END; IF (p.tabs.len # q.tabs.len) OR (q.tabs.len # i) THEN EXCL(valid, tabs) END; IF p.valid # valid THEN p.valid := valid; equal := FALSE END END END IntersectWith; (** ruler construction **) (*property-based facade procedures *) PROCEDURE SetFirst* (r: Ruler; x: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {first}; prop.first := x; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetFirst; PROCEDURE SetLeft* (r: Ruler; x: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {left}; prop.left := x; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetLeft; PROCEDURE SetRight* (r: Ruler; x: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {right}; prop.right := x; prop.opts.mask := {rightFixed}; prop.opts.val := {}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetRight; PROCEDURE SetFixedRight* (r: Ruler; x: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {right, opts}; prop.right := x; prop.opts.mask := {rightFixed}; prop.opts.val := {rightFixed}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetFixedRight; PROCEDURE SetLead* (r: Ruler; h: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {lead}; prop.lead := h; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetLead; PROCEDURE SetAsc* (r: Ruler; h: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {asc}; prop.asc := h; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetAsc; PROCEDURE SetDsc* (r: Ruler; h: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {dsc}; prop.dsc := h; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetDsc; PROCEDURE SetGrid* (r: Ruler; h: INTEGER); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {grid}; prop.grid := h; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetGrid; PROCEDURE SetLeftFlush* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {leftAdjust, rightAdjust}; prop.opts.val := {leftAdjust}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetLeftFlush; PROCEDURE SetRightFlush* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {leftAdjust, rightAdjust}; prop.opts.val := {rightAdjust}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetRightFlush; PROCEDURE SetCentered* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {leftAdjust, rightAdjust}; prop.opts.val := {}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetCentered; PROCEDURE SetJustified* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {leftAdjust, rightAdjust}; prop.opts.val := {leftAdjust, rightAdjust}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetJustified; PROCEDURE SetNoBreakInside* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {noBreakInside}; prop.opts.val := {noBreakInside}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetNoBreakInside; PROCEDURE SetPageBreak* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {pageBreak}; prop.opts.val := {pageBreak}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetPageBreak; PROCEDURE SetParJoin* (r: Ruler); BEGIN ASSERT(r.style # NIL, 20); prop.valid := {opts}; prop.opts.mask := {parJoin}; prop.opts.val := {parJoin}; r.style.SetAttr(ModifiedAttr(r.style.attr, prop)) END SetParJoin; PROCEDURE AddTab* (r: Ruler; x: INTEGER); VAR ra: Attributes; i: INTEGER; BEGIN ASSERT(r.style # NIL, 20); ra := r.style.attr; i := ra.tabs.len; ASSERT(i < maxTabs, 21); ASSERT((i = 0) OR (ra.tabs.tab[i - 1].stop < x), 22); prop.valid := {tabs}; CopyTabs(ra.tabs, prop.tabs); prop.tabs.tab[i].stop := x; prop.tabs.tab[i].type := {}; INC(prop.tabs.len); r.style.SetAttr(ModifiedAttr(ra, prop)) END AddTab; PROCEDURE MakeCenterTab* (r: Ruler); VAR ra: Attributes; i: INTEGER; BEGIN ASSERT(r.style # NIL, 20); ra := r.style.attr; i := ra.tabs.len; ASSERT(i > 0, 21); prop.valid := {tabs}; CopyTabs(ra.tabs, prop.tabs); prop.tabs.tab[i - 1].type := prop.tabs.tab[i - 1].type + {centerTab} - {rightTab}; r.style.SetAttr(ModifiedAttr(ra, prop)) END MakeCenterTab; PROCEDURE MakeRightTab* (r: Ruler); VAR ra: Attributes; i: INTEGER; BEGIN ASSERT(r.style # NIL, 20); ra := r.style.attr; i := ra.tabs.len; ASSERT(i > 0, 21); prop.valid := {tabs}; CopyTabs(ra.tabs, prop.tabs); prop.tabs.tab[i - 1].type := prop.tabs.tab[i - 1].type - {centerTab} + {rightTab}; r.style.SetAttr(ModifiedAttr(ra, prop)) END MakeRightTab; PROCEDURE MakeBarTab* (r: Ruler); VAR ra: Attributes; i: INTEGER; BEGIN ASSERT(r.style # NIL, 20); ra := r.style.attr; i := ra.tabs.len; ASSERT(i > 0, 21); prop.valid := {tabs}; CopyTabs(ra.tabs, prop.tabs); prop.tabs.tab[i - 1].type := prop.tabs.tab[i - 1].type + {barTab}; r.style.SetAttr(ModifiedAttr(ra, prop)) END MakeBarTab; (* SetAttrOp *) PROCEDURE (op: SetAttrOp) Do; VAR s: Style; attr: Attributes; upd: UpdateMsg; BEGIN s := op.style; attr := s.attr; s.attr := op.attr; op.attr := attr; (*Stores.InitDomain(s.attr, s.Domain());*) (* Stores.Join(s, s.attr); *) ASSERT((s.attr=NIL) OR Stores.Joined(s, s.attr), 100); upd.style := s; upd.oldAttr := attr; Models.Domaincast(s.Domain(), upd) END Do; PROCEDURE DoSetAttrOp (s: Style; attr: Attributes); VAR op: SetAttrOp; BEGIN IF (s.attr # attr) OR ~s.attr.Equals(attr) THEN (* IF attr.Domain() # s.Domain() THEN attr := Stores.CopyOf(attr)(Attributes) END; *) IF ~Stores.Joined(s, attr) THEN IF ~Stores.Unattached(attr) THEN attr := Stores.CopyOf(attr)(Attributes) END; Stores.Join(s, attr) END; NEW(op); op.style := s; op.attr := attr; Models.Do(s, rulerChangeKey, op) END END DoSetAttrOp; (* grid definitions *) PROCEDURE MarginGrid (x: INTEGER): INTEGER; BEGIN RETURN (x + marginGrid DIV 2) DIV marginGrid * marginGrid END MarginGrid; PROCEDURE TabGrid (x: INTEGER): INTEGER; BEGIN RETURN (x + tabGrid DIV 2) DIV tabGrid * tabGrid END TabGrid; (* nice graphical primitives *) PROCEDURE DrawCenteredInt (f: Views.Frame; x, y, n: INTEGER); VAR sw: INTEGER; s: ARRAY 32 OF CHAR; BEGIN Strings.IntToString(n, s); sw := font.StringWidth(s); f.DrawString(x - sw DIV 2, y, Ports.defaultColor, s, font) END DrawCenteredInt; PROCEDURE DrawNiceRect (f: Views.Frame; l, t, r, b: INTEGER); VAR u: INTEGER; BEGIN u := f.dot; f.DrawRect(l, t, r - u, b - u, 0, Ports.defaultColor); f.DrawLine(l + u, b - u, r - u, b - u, u, Ports.grey25); f.DrawLine(r - u, t + u, r - u, b - u, u, Ports.grey25) END DrawNiceRect; PROCEDURE DrawScale (f: Views.Frame; l, t, r, b, clipL, clipR: INTEGER); VAR u, h, x, px, sw: INTEGER; i, n, d1, d2: INTEGER; s: ARRAY 32 OF CHAR; BEGIN f.DrawRect(l, t, r, b, Ports.fill, Ports.grey12); u := f.dot; IF Dialog.metricSystem THEN d1 := 2; d2 := 10 ELSE d1 := 2; d2 := 16 END; DEC(b, point); sw := 2*u + font.StringWidth("8888888888"); x := l + tabGrid; i := 0; n := 0; WHILE x <= r DO INC(i); px := TabGrid(x); IF i = d2 THEN h := 6*point; i := 0; INC(n); IF (px >= clipL - sw) & (px < clipR) THEN Strings.IntToString(n, s); f.DrawString(px - 2*u - font.StringWidth(s), b - 3*point, Ports.defaultColor, s, font) END ELSIF i MOD d1 = 0 THEN h := 2*point ELSE h := 0 END; IF (px >= clipL) & (px < clipR) & (h > 0) THEN f.DrawLine(px, b, px, b - h, 0, Ports.defaultColor) END; INC(x, tabGrid) END END DrawScale; PROCEDURE InvertTabMark (f: Views.Frame; l, t, r, b: INTEGER; type: SET; show: BOOLEAN); VAR u, u2, u3, yc, i, ih: INTEGER; BEGIN u := f.dot; u2 := 2*u; u3 := 3*u; IF ~ODD((r - l) DIV u) THEN DEC(r, u) END; yc := l + (r - l) DIV u DIV 2 * u; IF barTab IN type THEN f.MarkRect(yc, b - u3, yc + u, b - u2, Ports.fill, Ports.invert, show); f.MarkRect(yc, b - u, yc + u, b, Ports.fill, Ports.invert, show) END; IF centerTab IN type THEN f.MarkRect(l + u, b - u2, r - u, b - u, Ports.fill, Ports.invert, show) ELSIF rightTab IN type THEN f.MarkRect(l, b - u2, yc + u, b - u, Ports.fill, Ports.invert, show) ELSE f.MarkRect(yc, b - u2, r, b - u, Ports.fill, Ports.invert, show) END; DEC(b, u3); INC(l, u2); DEC(r, u2); ih := (r - l) DIV 2; i := b - t; t := b - u; WHILE (i > 0) & (r > l) DO DEC(i, u); f.MarkRect(l, t, r, b, Ports.fill, Ports.invert, show); IF i <= ih THEN INC(l, u); DEC(r, u) END; DEC(t, u); DEC(b, u) END END InvertTabMark; PROCEDURE InvertFirstMark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN); VAR u, i, ih: INTEGER; BEGIN u := f.dot; i := b - t; t := b - u; ih := r - l; WHILE (i > 0) & (r > l) DO DEC(i, u); f.MarkRect(l, t, r, b, Ports.fill, Ports.invert, show); IF i <= ih THEN DEC(r, u) END; DEC(t, u); DEC(b, u) END END InvertFirstMark; PROCEDURE InvertLeftMark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN); VAR u, i, ih: INTEGER; BEGIN u := f.dot; i := b - t; b := t + u; ih := r - l; WHILE (i > 0) & (r > l) DO DEC(i, u); f.MarkRect(l, t, r, b, Ports.fill, Ports.invert, show); IF i <= ih THEN DEC(r, u) END; INC(t, u); INC(b, u) END END InvertLeftMark; PROCEDURE InvertRightMark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN); VAR u, i, ih: INTEGER; BEGIN u := f.dot; IF ~ODD((b - t) DIV u) THEN INC(t, u) END; ih := r - l; l := r - u; i := b - t; b := t + u; WHILE (i > 0) & (i > ih) DO DEC(i, u); f.MarkRect(l, t, r, b, Ports.fill, Ports.invert, show); DEC(l, u); INC(t, u); INC(b, u) END; WHILE (i > 0) & (r > l) DO DEC(i, u); f.MarkRect(l, t, r, b, Ports.fill, Ports.invert, show); INC(l, u); INC(t, u); INC(b, u) END END InvertRightMark; (* marks *) PROCEDURE SetMark (VAR m: Mark; r: StdRuler; px, py: INTEGER; kind, index: INTEGER); BEGIN m.ruler := r; m.kind := kind; m.px := px; m.py := py; CASE kind OF first: m.l := px; m.r := m.l + 4*point; m.b := py - 7*point; m.t := m.b - 4*point | left: m.l := px; m.r := m.l + 4*point; m.b := py - 2*point; m.t := m.b - 4*point | right: m.r := px; m.l := m.r - 4*point; m.b := py - 3*point; m.t := m.b - 7*point | tabs: m.l := px - 4*point; m.r := m.l + 9*point; m.b := py - 5*point; m.t := m.b - 6*point; m.type := r.style.attr.tabs.tab[index].type | firstIcon .. lastIcon: m.l := px; m.r := px + iconWidth; m.t := py; m.b := py + iconHeight ELSE HALT(100) END END SetMark; PROCEDURE Try (VAR m: Mark; r: StdRuler; px, py, x, y: INTEGER; kind, index: INTEGER); BEGIN IF m.kind = invalid THEN SetMark(m, r, px, py, kind, index); IF (m.l - point <= x) & (x < m.r + point) & (m.t - point <= y) & (y < m.b + point) THEN m.px0 := m.px; m.py0 := m.py; m.x := x; m.y := y; IF kind = tabs THEN m.index := index; CopyTabs(r.style.attr.tabs, m.tabs) END ELSE m.kind := invalid END END END Try; PROCEDURE InvertMark (VAR m: Mark; f: Views.Frame; show: BOOLEAN); (* pre: kind # invalid *) BEGIN CASE m.kind OF first: InvertFirstMark(f, m.l, m.t, m.r, m.b, show) | left: InvertLeftMark(f, m.l, m.t, m.r, m.b, show) | right: InvertRightMark(f, m.l, m.t, m.r, m.b, show) | tabs: InvertTabMark(f, m.l, m.t, m.r, m.b, m.type, show) END END InvertMark; PROCEDURE HiliteMark (VAR m: Mark; f: Views.Frame; show: BOOLEAN); BEGIN f.MarkRect(m.l, m.t, m.r - point, m.b - point, Ports.fill, Ports.hilite, show) END HiliteMark; PROCEDURE HiliteThisMark (r: StdRuler; f: Views.Frame; kind: INTEGER; show: BOOLEAN); VAR m: Mark; px, w, h: INTEGER; BEGIN IF (kind # invalid) & (kind IN validIcons) THEN px := iconGap + (kind - firstIcon) * (iconWidth + iconGap); r.context.GetSize(w, h); SetMark(m, r, px, h - iconPin, kind, -1); HiliteMark(m, f, show) END END HiliteThisMark; PROCEDURE DrawMark (VAR m: Mark; f: Views.Frame); (* pre: kind # invalid *) VAR a: Attributes; l, t, r, b, y, d, e, asc, dsc, fw: INTEGER; i: INTEGER; w: ARRAY 4 OF INTEGER; BEGIN a := m.ruler.style.attr; l := m.l + 2 * point; t := m.t + 2 * point; r := m.r - 4 * point; b := m.b - 3 * point; font.GetBounds(asc, dsc, fw); y := (m.t + m.b + asc) DIV 2; w[0] := (r - l) DIV 2; w[1] := r - l; w[2] := (r - l) DIV 3; w[3] := (r - l) * 2 DIV 3; CASE m.kind OF rightToggle: IF rightFixed IN a.opts THEN d := 0; y := (t + b) DIV 2 - point; e := (l + r) DIV 2 + point; WHILE t < y DO f.DrawLine(e - d, t, e, t, point, Ports.defaultColor); INC(d, point); INC(t, point) END; WHILE t < b DO f.DrawLine(e - d, t, e, t, point, Ports.defaultColor); DEC(d, point); INC(t, point) END ELSE DEC(b, point); f.DrawLine(l, t, r, t, point, Ports.defaultColor); f.DrawLine(l, b, r, b, point, Ports.defaultColor); f.DrawLine(l, t, l, b, point, Ports.defaultColor); f.DrawLine(r, t, r, b, point, Ports.defaultColor) END | gridDec: WHILE t < b DO f.DrawLine(l, t, r, t, point, Ports.defaultColor); INC(t, 2 * point) END | gridVal: DrawCenteredInt(f, (l + r) DIV 2, y, a.grid DIV point) | gridInc: WHILE t < b DO f.DrawLine(l, t, r, t, point, Ports.defaultColor); INC(t, 3 * point) END | leftFlush: i := 0; WHILE t < b DO d := w[i]; i := (i + 1) MOD LEN(w); f.DrawLine(l, t, l + d, t, point, Ports.defaultColor); INC(t, 2 * point) END | centered: i := 0; WHILE t < b DO d := (r - l - w[i]) DIV 2; i := (i + 1) MOD LEN(w); f.DrawLine(l + d, t, r - d, t, point, Ports.defaultColor); INC(t, 2 * point) END | rightFlush: i := 0; WHILE t < b DO d := w[i]; i := (i + 1) MOD LEN(w); f.DrawLine(r - d, t, r, t, point, Ports.defaultColor); INC(t, 2 * point) END | justified: WHILE t < b DO f.DrawLine(l, t, r, t, point, Ports.defaultColor); INC(t, 2 * point) END | leadDec: f.DrawLine(l, t, l, t + point, point, Ports.defaultColor); INC(t, 2 * point); WHILE t < b DO f.DrawLine(l, t, r, t, point, Ports.defaultColor); INC(t, 2 * point) END | leadVal: DrawCenteredInt(f, (l + r) DIV 2, y, m.ruler.style.attr.lead DIV point) | leadInc: f.DrawLine(l, t, l, t + 3 * point, point, Ports.defaultColor); INC(t, 4 * point); WHILE t < b DO f.DrawLine(l, t, r, t, point, Ports.defaultColor); INC(t, 2 * point) END | pageBrk: DEC(b, point); IF pageBreak IN a.opts THEN y := (t + b) DIV 2 - point; f.DrawLine(l, t, l, y, point, Ports.defaultColor); f.DrawLine(r, t, r, y, point, Ports.defaultColor); f.DrawLine(l, y, r, y, point, Ports.defaultColor); INC(y, 2 * point); f.DrawLine(l, y, r, y, point, Ports.defaultColor); f.DrawLine(l, y, l, b, point, Ports.defaultColor); f.DrawLine(r, y, r, b, point, Ports.defaultColor) ELSE f.DrawLine(l, t, l, b, point, Ports.defaultColor); f.DrawLine(r, t, r, b, point, Ports.defaultColor) END ELSE HALT(100) END; IF ~(m.kind IN {gridVal, leadVal}) THEN DrawNiceRect(f, m.l, m.t, m.r, m.b) END END DrawMark; PROCEDURE GetMark (VAR m: Mark; r: StdRuler; f: Views.Frame; x, y: INTEGER; canCreate: BOOLEAN ); (* pre: ~canCreate OR (f # NIL) *) VAR a: Attributes; px, w, h: INTEGER; i: INTEGER; BEGIN m.kind := invalid; m.dirty := FALSE; a := r.style.attr; r.context.GetSize(w, h); (* first try scale *) Try(m, r, a.first, h, x, y, first, 0); Try(m, r, a.left, h, x, y, left, 0); IF rightFixed IN a.opts THEN Try(m, r, a.right, h, x, y, right, 0) END; i := 0; WHILE (m.kind = invalid) & (i < a.tabs.len) DO Try(m, r, a.tabs.tab[i].stop, h, x, y, tabs, i); INC(i) END; IF (m.kind = invalid) & (y >= h - tabBarHeight) & (a.tabs.len < maxTabs) THEN i := 0; px := TabGrid(x); WHILE (i < a.tabs.len) & (a.tabs.tab[i].stop < px) DO INC(i) END; IF (i = 0) OR (px - a.tabs.tab[i - 1].stop >= minTabWidth) THEN IF (i = a.tabs.len) OR (a.tabs.tab[i].stop - px >= minTabWidth) THEN IF canCreate THEN (* set new tab stop, initially at end of list *) m.kind := tabs; m.index := a.tabs.len; m.dirty := TRUE; CopyTabs(a.tabs, m.tabs); m.tabs.len := a.tabs.len + 1; m.tabs.tab[a.tabs.len].stop := px; m.tabs.tab[a.tabs.len].type := {}; a.tabs.tab[a.tabs.len].stop := px; a.tabs.tab[a.tabs.len].type := {}; SetMark(m, r, px, h, tabs, m.index); InvertMark(m, f, Ports.show); m.px0 := m.px; m.py0 := m.py; m.x := x; m.y := y END END END END; (* next try icon bar *) px := iconGap; i := firstIcon; WHILE i <= lastIcon DO IF i IN validIcons THEN Try(m, r, px, h - iconPin, x, y, i, 0) END; INC(px, iconWidth + iconGap); INC(i) END END GetMark; PROCEDURE SelectMark (r: StdRuler; f: Views.Frame; IN m: Mark); BEGIN r.sel := m.kind; r.px := m.px; r.py := m.py END SelectMark; PROCEDURE DeselectMark (r: StdRuler; f: Views.Frame); BEGIN HiliteThisMark(r, f, r.sel, Ports.hide); r.sel := invalid END DeselectMark; (* mark interaction *) PROCEDURE Mode (r: StdRuler): INTEGER; VAR a: Attributes; i: INTEGER; BEGIN a := r.style.attr; IF a.opts * adjMask = {leftAdjust} THEN i := leftFlush ELSIF a.opts * adjMask = {} THEN i := centered ELSIF a.opts * adjMask = {rightAdjust} THEN i := rightFlush ELSE (* a.opts * adjMask = adjMask *) i := justified END; RETURN i END Mode; PROCEDURE GrabMark (VAR m: Mark; r: StdRuler; f: Views.Frame; x, y: INTEGER); BEGIN GetMark(m, r, f, x, y, TRUE); DeselectMark(r, f); IF m.kind = Mode(r) THEN m.kind := invalid END END GrabMark; PROCEDURE TrackMark (VAR m: Mark; f: Views.Frame; x, y: INTEGER; modifiers: SET); VAR px, py, w, h: INTEGER; BEGIN IF m.kind # invalid THEN px := m.px + x - m.x; py := m.py + y - m.y; IF m.kind = tabs THEN px := TabGrid(px) ELSIF m.kind IN validIcons THEN IF (m.l <= x) & (x < m.r) THEN px := 1 ELSE px := 0 END ELSE px := MarginGrid(px) END; IF m.kind IN {right, tabs} THEN m.ruler.context.GetSize(w, h); IF (0 <= y) & (y < h + scaleHeight) OR (Controllers.extend IN modifiers) THEN py := h ELSE py := -1 (* moved mark out of ruler: delete tab stop or fixed right margin *) END ELSIF m.kind IN validIcons THEN IF (m.t <= y) & (y < m.b) THEN py := 1 ELSE py := 0 END ELSE py := MarginGrid(py) END; IF (m.kind IN {right, tabs}) & ((m.px # px) OR (m.py # py)) THEN INC(m.x, px - m.px); INC(m.y, py - m.py); InvertMark(m, f, Ports.hide); SetMark(m, m.ruler, px, py, m.kind, m.index); InvertMark(m, f, Ports.show); m.dirty := TRUE ELSIF (m.kind IN {first, left}) & (m.px # px) THEN INC(m.x, px - m.px); InvertMark(m, f, Ports.hide); SetMark(m, m.ruler, px, m.py, m.kind, m.index); InvertMark(m, f, Ports.show) ELSIF (m.kind IN validIcons) & (m.px * m.py # px * py) THEN HiliteMark(m, f, Ports.show); IF m.kind IN modeIcons THEN HiliteThisMark(m.ruler, f, Mode(m.ruler), Ports.hide) END; m.px := px; m.py := py END END END TrackMark; PROCEDURE ShiftMarks (a: Attributes; p: Prop; mask: SET; x0, dx: INTEGER); VAR new: SET; i, j, t0, t1: INTEGER; tab0, tab1: TabArray; BEGIN new := mask - p.valid; IF first IN new THEN p.first := a.first END; IF tabs IN new THEN CopyTabs(a.tabs, p.tabs) END; p.valid := p.valid + mask; IF first IN mask THEN INC(p.first, dx) END; IF tabs IN mask THEN i := 0; WHILE (i < p.tabs.len) & (p.tabs.tab[i].stop < x0) DO tab0.tab[i] := p.tabs.tab[i]; INC(i) END; t0 := i; t1 := 0; WHILE i < p.tabs.len DO tab1.tab[t1].stop := p.tabs.tab[i].stop + dx; tab1.tab[t1].type := p.tabs.tab[i].type; INC(t1); INC(i) END; i := 0; j := 0; p.tabs.len := 0; WHILE i < t0 DO (* merge sort *) WHILE (j < t1) & (tab1.tab[j].stop < tab0.tab[i].stop) DO p.tabs.tab[p.tabs.len] := tab1.tab[j]; INC(p.tabs.len); INC(j) END; IF (j < t1) & (tab1.tab[j].stop = tab0.tab[i].stop) THEN INC(j) END; p.tabs.tab[p.tabs.len] := tab0.tab[i]; INC(p.tabs.len); INC(i) END; WHILE j < t1 DO p.tabs.tab[p.tabs.len] := tab1.tab[j]; INC(p.tabs.len); INC(j) END END END ShiftMarks; PROCEDURE ShiftDependingMarks (VAR m: Mark; p: Prop); VAR a: Attributes; dx: INTEGER; BEGIN a := m.ruler.style.attr; dx := m.px - m.px0; CASE m.kind OF first: ShiftMarks(a, p, {tabs}, 0, dx) | left: ShiftMarks(a, p, {first, tabs}, 0, dx) | tabs: ShiftMarks(a, p, {tabs}, m.px0, dx) ELSE END END ShiftDependingMarks; PROCEDURE AdjustMarks (VAR m: Mark; f: Views.Frame; modifiers: SET); VAR r: StdRuler; a: Attributes; p: Prop; g: INTEGER; i, j: INTEGER; shift: BOOLEAN; type: SET; BEGIN r := m.ruler; IF (m.kind # invalid) & (m.kind IN validIcons) & (m.px = 1) & (m.py = 1) OR (m.kind # invalid) & ~(m.kind IN validIcons) & ((m.px # m.px0) OR (m.py # m.py0) OR (m.kind = tabs) (*(m.tabs.len # r.style.attr.tabs.len)*) ) THEN a := r.style.attr; NEW(p); p.valid := {}; shift := (Controllers.modify IN modifiers) & (m.tabs.len = r.style.attr.tabs.len); CASE m.kind OF first: p.valid := {first}; p.first := m.px | left: p.valid := {left}; p.left := m.px | right: IF m.py >= 0 THEN p.valid := {right}; p.right := m.px ELSE p.valid := {opts}; p.opts.val := {}; p.opts.mask := {rightFixed} END | tabs: IF ~m.dirty THEN p.valid := {tabs}; CopyTabs(m.tabs, p.tabs); i := m.index; type := m.tabs.tab[i].type; IF shift THEN type := type * {barTab}; IF type = {} THEN type := {barTab} ELSE type := {} END; p.tabs.tab[i].type := p.tabs.tab[i].type - {barTab} + type ELSE type := type * {centerTab, rightTab}; IF type = {} THEN type := {centerTab} ELSIF type = {centerTab} THEN type := {rightTab} ELSE type := {} END; p.tabs.tab[i].type := p.tabs.tab[i].type - {centerTab, rightTab} + type END ELSIF ~shift THEN p.valid := {tabs}; p.tabs.len := m.tabs.len - 1; i := 0; WHILE i < m.index DO p.tabs.tab[i] := m.tabs.tab[i]; INC(i) END; INC(i); WHILE i < m.tabs.len DO p.tabs.tab[i - 1] := m.tabs.tab[i]; INC(i) END; i := 0; WHILE (i < p.tabs.len) & (p.tabs.tab[i].stop < m.px) DO INC(i) END; IF (m.px >= MIN(a.first, a.left)) & (m.px <= f.r) & (m.py >= 0) & ((i = 0) OR (m.px - p.tabs.tab[i - 1].stop >= minTabWidth)) & ((i = p.tabs.len) OR (p.tabs.tab[i].stop - m.px >= minTabWidth)) THEN j := p.tabs.len; WHILE j > i DO p.tabs.tab[j] := p.tabs.tab[j - 1]; DEC(j) END; p.tabs.tab[i].stop := m.px; p.tabs.tab[i].type := m.tabs.tab[m.index].type; INC(p.tabs.len) END; i := 0; WHILE (i < p.tabs.len) & (p.tabs.tab[i].stop = a.tabs.tab[i].stop) & (p.tabs.tab[i].type = a.tabs.tab[i].type) DO INC(i) END; IF (i = p.tabs.len) & (p.tabs.len = a.tabs.len) THEN RETURN END (* did not change *) END | rightToggle: p.valid := {right, opts}; IF ~(rightFixed IN a.opts) THEN p.right := f.r DIV marginGrid * marginGrid END; p.opts.val := a.opts / {rightFixed}; p.opts.mask := {rightFixed} | gridDec: p.valid := {asc, grid}; g := a.grid - point; IF g = 0 THEN p.grid := 1; p.asc := 0 ELSE p.grid := g; p.asc := g - a.dsc END | gridVal: SelectMark(r, f, m); RETURN | gridInc: p.valid := {asc, grid}; g := a.grid + point; DEC(g, g MOD point); p.grid := g; p.asc := g - a.dsc | leftFlush: p.valid := {opts}; p.opts.val := {leftAdjust}; p.opts.mask := adjMask | centered: p.valid := {opts}; p.opts.val := {}; p.opts.mask := adjMask | rightFlush: p.valid := {opts}; p.opts.val := {rightAdjust}; p.opts.mask := adjMask | justified: p.valid := {opts}; p.opts.val := adjMask; p.opts.mask := adjMask | leadDec: p.valid := {lead}; p.lead := a.lead - point | leadVal: SelectMark(r, f, m); RETURN | leadInc: p.valid := {lead}; p.lead := a.lead + point | pageBrk: p.valid := {opts}; p.opts.val := a.opts / {pageBreak}; p.opts.mask := {pageBreak} ELSE HALT(100) END; IF shift THEN ShiftDependingMarks(m, p) END; IF m.kind IN validIcons - modeIcons THEN HiliteMark(m, f, Ports.hide) END; r.style.SetAttr(ModifiedAttr(a, p)) END END AdjustMarks; (* primitivies for standard ruler *) PROCEDURE Track (r: StdRuler; f: Views.Frame; IN msg: Controllers.TrackMsg); VAR m: Mark; x, y, res: INTEGER; modifiers: SET; isDown: BOOLEAN; cmd: ARRAY 128 OF CHAR; BEGIN GrabMark(m, r, f, msg.x, msg.y); REPEAT f.Input(x, y, modifiers, isDown); TrackMark(m, f, x, y, modifiers) UNTIL ~isDown; AdjustMarks(m, f, modifiers); IF Controllers.doubleClick IN msg.modifiers THEN CASE m.kind OF | invalid: Dialog.MapString("#Text:OpenRulerDialog", cmd); Dialog.Call(cmd, "", res) | gridVal, leadVal: Dialog.MapString("#Text:OpenSizeDialog", cmd); Dialog.Call(cmd, "", res) ELSE END END END Track; PROCEDURE Edit (r: StdRuler; f: Views.Frame; VAR msg: Controllers.EditMsg); VAR v: Views.View; BEGIN CASE msg.op OF Controllers.copy: msg.view := Views.CopyOf(r, Views.deep); msg.isSingle := TRUE | Controllers.paste: v := msg.view; WITH v: Ruler DO r.style.SetAttr(v.style.attr) ELSE END ELSE END END Edit; PROCEDURE PollOps (r: StdRuler; f: Views.Frame; VAR msg: Controllers.PollOpsMsg); BEGIN msg.type := "TextRulers.Ruler"; msg.pasteType := "TextRulers.Ruler"; msg.selectable := FALSE; msg.valid := {Controllers.copy, Controllers.paste} END PollOps; PROCEDURE SetProp (r: StdRuler; VAR msg: Properties.SetMsg; VAR requestFocus: BOOLEAN); VAR a1: Attributes; px, py, g: INTEGER; sel: INTEGER; p: Properties.Property; sp: Properties.StdProp; rp: Prop; BEGIN p := msg.prop; sel := r.sel; px := r.px; py := r.py; IF sel # invalid THEN WHILE (p # NIL) & ~(p IS Properties.StdProp) DO p := p.next END; IF p # NIL THEN sp := p(Properties.StdProp); IF (r.sel = leadVal) & (Properties.size IN sp.valid) THEN NEW(rp); rp.valid := {lead}; rp.lead := sp.size ELSIF (r.sel = gridVal) & (Properties.size IN sp.valid) THEN g := sp.size; DEC(g, g MOD point); NEW(rp); rp.valid := {asc, grid}; IF g = 0 THEN rp.asc := 0; rp.grid := 1 ELSE rp.asc := g - r.style.attr.dsc; rp.grid := g END ELSE rp := NIL END END; p := rp END; a1 := ModifiedAttr(r.style.attr, p); IF ~a1.Equals(r.style.attr) THEN r.style.SetAttr(a1); IF requestFocus & (r.sel = invalid) THEN (* restore mark selection *) r.sel := sel; r.px := px; r.py := py END ELSE requestFocus := FALSE END END SetProp; PROCEDURE PollProp (r: StdRuler; VAR msg: Properties.PollMsg); VAR p: Properties.StdProp; BEGIN CASE r.sel OF invalid: msg.prop := r.style.attr.Prop() | leadVal: NEW(p); p.known := {Properties.size}; p.valid := p.known; p.size := r.style.attr.lead; msg.prop := p | gridVal: NEW(p); p.known := {Properties.size}; p.valid := p.known; p.size := r.style.attr.grid; msg.prop := p ELSE HALT(100) END END PollProp; (* StdStyle *) PROCEDURE (r: StdStyle) Internalize (VAR rd: Stores.Reader); VAR thisVersion: INTEGER; BEGIN r.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxStdStyleVersion, thisVersion) END Internalize; PROCEDURE (r: StdStyle) Externalize (VAR wr: Stores.Writer); BEGIN r.Externalize^(wr); wr.WriteVersion(maxStdStyleVersion) END Externalize; (* PROCEDURE (r: StdStyle) CopyFrom (source: Stores.Store); BEGIN r.SetAttr(source(StdStyle).attr) END CopyFrom; *) (* StdRuler *) PROCEDURE (r: StdRuler) Internalize (VAR rd: Stores.Reader); VAR thisVersion: INTEGER; BEGIN r.Internalize^(rd); IF rd.cancelled THEN RETURN END; rd.ReadVersion(minVersion, maxStdRulerVersion, thisVersion); IF rd.cancelled THEN RETURN END; r.sel := invalid END Internalize; PROCEDURE (r: StdRuler) Externalize (VAR wr: Stores.Writer); BEGIN r.Externalize^(wr); wr.WriteVersion(maxStdRulerVersion) END Externalize; PROCEDURE (r: StdRuler) ThisModel (): Models.Model; BEGIN RETURN r.style END ThisModel; PROCEDURE (r: StdRuler) CopyFromModelView (source: Views.View; model: Models.Model); BEGIN r.sel := invalid; r.InitStyle(model(Style)) END CopyFromModelView; PROCEDURE (ruler: StdRuler) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR a: Attributes; m: Mark; u, scale, tabBar, px, w, h: INTEGER; i: INTEGER; BEGIN u := f.dot; a := ruler.style.attr; ruler.context.GetSize(w, h); tabBar := h - tabBarHeight; scale := tabBar - scaleHeight; w := MIN(f.r + 10 * mm, 10000 * mm); (* high-level clipping *) f.DrawLine(0, scale - u, w - u, scale - u, u, Ports.grey25); f.DrawLine(0, tabBar - u, w - u, tabBar - u, u, Ports.grey50); DrawScale(f, 0, scale, w, tabBar, l, r); DrawNiceRect(f, 0, h - rulerHeight, w, h); SetMark(m, ruler, a.first, h, first, -1); InvertMark(m, f, Ports.show); SetMark(m, ruler, a.left, h, left, -1); InvertMark(m, f, Ports.show); IF rightFixed IN a.opts THEN SetMark(m, ruler, a.right, h, right, -1); InvertMark(m, f, Ports.show) END; i := 0; WHILE i < a.tabs.len DO SetMark(m, ruler, a.tabs.tab[i].stop, h, tabs, i); InvertMark(m, f, Ports.show); INC(i) END; px := iconGap; i := firstIcon; WHILE i <= lastIcon DO IF i IN validIcons THEN SetMark(m, ruler, px, h - iconPin, i, -1); DrawMark(m, f) END; INC(px, iconWidth + iconGap); INC(i) END; HiliteThisMark(ruler, f, Mode(ruler), Ports.show) END Restore; PROCEDURE (ruler: StdRuler) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER); BEGIN HiliteThisMark(ruler, f, ruler.sel, Ports.show) END RestoreMarks; PROCEDURE (r: StdRuler) GetBackground (VAR color: Ports.Color); BEGIN color := Ports.background END GetBackground; PROCEDURE (r: StdRuler) Neutralize; VAR msg: NeutralizeMsg; BEGIN Views.Broadcast(r, msg) END Neutralize; PROCEDURE (r: StdRuler) HandleModelMsg (VAR msg: Models.Message); BEGIN WITH msg: UpdateMsg DO Views.Update(r, Views.keepFrames) ELSE END END HandleModelMsg; PROCEDURE (r: StdRuler) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message); BEGIN WITH msg: NeutralizeMsg DO DeselectMark(r, f) ELSE END END HandleViewMsg; PROCEDURE (r: StdRuler) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View ); VAR requestFocus: BOOLEAN; BEGIN WITH msg: Controllers.TrackMsg DO Track(r, f, msg) | msg: Controllers.EditMsg DO Edit(r, f, msg) | msg: Controllers.MarkMsg DO r.RestoreMarks(f, f.l, f.t, f.r, f.b) | msg: Controllers.SelectMsg DO IF ~msg.set THEN DeselectMark(r, f) END | msg: Controllers.PollOpsMsg DO PollOps(r, f, msg) | msg: Properties.CollectMsg DO PollProp(r, msg.poll) | msg: Properties.EmitMsg DO requestFocus := f.front; SetProp(r, msg.set, requestFocus); msg.requestFocus := requestFocus ELSE END END HandleCtrlMsg; PROCEDURE (r: StdRuler) HandlePropMsg (VAR msg: Properties.Message); VAR m: Mark; requestFocus: BOOLEAN; w, h: INTEGER; BEGIN WITH msg: Properties.SizePref DO msg.w := 10000 * Ports.mm; msg.h := rulerHeight | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: Properties.FocusPref DO IF msg.atLocation THEN r.context.GetSize(w, h); GetMark(m, r, NIL, msg.x, msg.y, FALSE); msg.hotFocus := (m.kind # invalid) & ~(m.kind IN fieldIcons) OR (msg.y >= h - tabBarHeight); msg.setFocus := ~msg.hotFocus END | msg: TextModels.Pref DO msg.opts := {TextModels.maskChar, TextModels.hideable}; msg.mask := TextModels.para | msg: Properties.SetMsg DO requestFocus := FALSE; SetProp(r, msg, requestFocus) | msg: Properties.PollMsg DO PollProp(r, msg) ELSE END END HandlePropMsg; (* StdDirectory *) PROCEDURE (d: StdDirectory) NewStyle (attr: Attributes): Style; VAR s: StdStyle; BEGIN IF attr = NIL THEN attr := d.attr END; NEW(s); s.SetAttr(attr); RETURN s END NewStyle; PROCEDURE (d: StdDirectory) New (style: Style): Ruler; VAR r: StdRuler; BEGIN IF style = NIL THEN style := d.NewStyle(NIL) END; NEW(r); r.InitStyle(style); r.sel := invalid; RETURN r END New; (** miscellaneous **) PROCEDURE GetValidRuler* (text: TextModels.Model; pos, hint: INTEGER; VAR ruler: Ruler; VAR rpos: INTEGER ); (** pre: (hint < 0 OR (ruler, rpos) is first ruler before hint & 0 <= pos <= t.Length() **) (** post: hint < rpos <= pos & rpos = Pos(ruler) & (no ruler in (rpos, pos]) OR ((ruler, rpos) unmodified) **) VAR view: Views.View; BEGIN IF pos < text.Length() THEN INC(pos) END; (* let a ruler dominate its own position *) IF pos < hint THEN hint := -1 END; globRd := text.NewReader(globRd); globRd.SetPos(pos); REPEAT globRd.ReadPrevView(view) UNTIL globRd.eot OR (view IS Ruler) OR (globRd.Pos() < hint); IF (view # NIL) & (view IS Ruler) THEN ruler := view(Ruler); rpos := globRd.Pos() END END GetValidRuler; PROCEDURE SetDir* (d: Directory); (** pre: d # NIL, d.attr # NIL **) (** post: dir = d **) BEGIN ASSERT(d # NIL, 20); ASSERT(d.attr.init, 21); dir := d END SetDir; PROCEDURE Init; VAR d: StdDirectory; fnt: Fonts.Font; asc, dsc, w: INTEGER; BEGIN IF Dialog.metricSystem THEN marginGrid := 1*mm; minTabWidth := 1*mm; tabGrid := 1*mm ELSE marginGrid := inch16; minTabWidth := inch16; tabGrid := inch16 END; fnt := Fonts.dir.Default(); font := Fonts.dir.This(fnt.typeface, 7*point, {}, Fonts.normal); (* font for ruler scales *) NEW(prop); prop.valid := {first .. tabs}; prop.first := 0; prop.left := 0; IF Dialog.metricSystem THEN prop.right := 165*mm ELSE prop.right := 104*inch16 END; fnt.GetBounds(asc, dsc, w); prop.lead := 0; prop.asc := asc; prop.dsc := dsc; prop.grid := 1; prop.opts.val := {leftAdjust}; prop.opts.mask := options; prop.tabs.len := 0; NEW(def); def.InitFromProp(prop); NEW(d); d.attr := def; dir := d; stdDir := d END Init; PROCEDURE Cleaner; BEGIN globRd := NIL END Cleaner; BEGIN Init; Kernel.InstallCleaner(Cleaner) CLOSE Kernel.RemoveCleaner(Cleaner) END TextRulers.
36.650329
116
0.515265
[ "model" ]
45cf7ec3eb1c2bc605627639741ddf2ceb17a3df
1,988
cc
C++
code/render/physics/havok/havokutil.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/physics/havok/havokutil.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/physics/havok/havokutil.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // havokutil.cc // (C) 2013-2014 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "havokutil.h" #include "..\physicsobject.h" #include "havokbody.h" #include "havokcharacterrigidbody.h" #include "havokstatic.h" namespace Havok { //------------------------------------------------------------------------------ /** */ void HavokUtil::CheckWorldObjectUserData(hkUlong userData) { n_assert2(0 != userData, "Userdata for havok entity is zero! When creating the entity its userdata must be set to the nebula-physobject that owns it"); Ptr<Physics::PhysicsObject> physObject = (Physics::PhysicsObject*)userData; n_assert(physObject.isvalid()); } //------------------------------------------------------------------------------ /** */ bool HavokUtil::HasHavokRigidBody(const Ptr<Physics::PhysicsObject>& obj) { return obj->IsA(HavokBody::RTTI) || obj->IsA(HavokCharacterRigidBody::RTTI) || obj->IsA(HavokStatic::RTTI); } //------------------------------------------------------------------------------ /** */ hkRefPtr<hkpRigidBody> HavokUtil::GetHavokRigidBody(const Ptr<Physics::PhysicsObject>& obj) { if (obj->IsA(HavokBody::RTTI)) { return ((HavokBody*)obj.get())->GetRigidBody(); } else if (obj->IsA(HavokCharacterRigidBody::RTTI)) { return ((HavokCharacterRigidBody*)obj.get())->GetRigidBody(); } //FIXME: check if works with phantoms - then this needs restructuring since phantoms use no hkpRigidBody //else if (object->IsA(HavokCharacterPhantom::RTTI)) //{ // rigidBody = ((HavokCharacterPhantom*)object.get())->GetRigidBody(); //} else if (obj->IsA(HavokStatic::RTTI)) { return ((HavokStatic*)obj.get())->GetRigidBody(); } else { n_error("HavokUtil::GetHavokRigidBody: The given physicsobject is not recognized to contain a hkpRigidBody!"); } return 0; } }
28.811594
152
0.574447
[ "object" ]
45d374d803ce6b98c64d2fcf4c81bf84f3527eb7
591
cpp
C++
tests/auto_reset_unittest.cpp
tongzhipeng/KBase
c6a4ce7592dfcf8e000045f3ef03a9badf023ccf
[ "MIT" ]
20
2016-05-16T07:02:09.000Z
2021-06-07T10:21:24.000Z
tests/auto_reset_unittest.cpp
tongzhipeng/KBase
c6a4ce7592dfcf8e000045f3ef03a9badf023ccf
[ "MIT" ]
1
2020-07-09T02:00:36.000Z
2020-07-11T03:46:52.000Z
tests/auto_reset_unittest.cpp
tongzhipeng/KBase
c6a4ce7592dfcf8e000045f3ef03a9badf023ccf
[ "MIT" ]
13
2016-03-09T09:52:17.000Z
2021-09-09T14:50:13.000Z
/* @ 0xCCCCCCCC */ #include <vector> #include "catch2/catch.hpp" #include "kbase/auto_reset.h" namespace kbase { TEST_CASE("Restoring variable's original value", "[AutoReset]") { std::vector<std::string> value {"hello", "world", "kc"}; SECTION("reset to original value once going out of scope") { auto vec = value; { AutoReset<decltype(vec)> value_guard(&vec); vec.pop_back(); vec.push_back("this is a test"); REQUIRE(value != vec); } REQUIRE(value == vec); } } } // namespace kbase
17.909091
63
0.566836
[ "vector" ]
45d5436aeb632ad89e22531eaecda84031dc494c
3,064
hpp
C++
include/private/coherence/native/windows/WindowsTime.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/private/coherence/native/windows/WindowsTime.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/private/coherence/native/windows/WindowsTime.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_WINDOWS_TIME_HPP #define COH_WINDOWS_TIME_HPP #include "coherence/lang/compatibility.hpp" #include "private/coherence/native/NativeTime.hpp" #include <time.h> #include <sstream> COH_OPEN_NAMESPACE3(coherence,native,windows) /** * Delta between Windows C++ epoch 1/1/1601 and Unix epoch 1/1/1970 */ #define DELTA_EPOCH_IN_MILLIS 11644473600000LL /** * Windows implementation of NativeTime. * * @author mf 2007.12.19 */ class COH_EXPORT WindowsTime : public coherence::native::NativeTime { // ----- constructor ---------------------------------------------------- public: /** * Construct a new WindowsTime object. */ WindowsTime() { } /** * Destructor. */ virtual ~WindowsTime() { } // ----- NativeTime interface ------------------------------------------- public: /** * @inheritDoc */ virtual int64_t currentTimeMillis() const { SYSTEMTIME systemTime; GetSystemTime(&systemTime); FILETIME fileTime; SystemTimeToFileTime(&systemTime, &fileTime); ULARGE_INTEGER uli; uli.LowPart = fileTime.dwLowDateTime; uli.HighPart = fileTime.dwHighDateTime; ULONGLONG systemTimeIn_ms(uli.QuadPart / 10000); return systemTimeIn_ms - DELTA_EPOCH_IN_MILLIS; } /** * @inheritDoc */ virtual Date::View createDate(int64_t lMillis) const { lMillis += DELTA_EPOCH_IN_MILLIS; // ensure that millis is > 0 and that it isn't too large COH_ENSURE_PARAM_RELATION(lMillis, >, 0); COH_ENSURE_PARAM_RELATION(lMillis, <, int64_t(COH_INT64(0x7FFFFF, 0xFFFFFFFF))); ULARGE_INTEGER uli; uli.QuadPart = lMillis * 10000; FILETIME fileTime; fileTime.dwLowDateTime = uli.LowPart; fileTime.dwHighDateTime = uli.HighPart; SYSTEMTIME systemTime; FileTimeToSystemTime(&fileTime, &systemTime); SystemTimeToTzSpecificLocalTime(NULL, &systemTime, &systemTime); return Date::create(systemTime.wYear, systemTime.wMonth, systemTime.wDay, systemTime.wHour, systemTime.wMinute, systemTime.wSecond, systemTime.wMilliseconds); } }; COH_CLOSE_NAMESPACE3 // ----- NativeTime factory methods ----------------------------------------- COH_OPEN_NAMESPACE2(coherence,native) NativeTime* NativeTime::instance() { static NativeTime* INSTANCE = new coherence::native::windows::WindowsTime(); return INSTANCE; } COH_STATIC_INIT(NativeTime::instance()); COH_CLOSE_NAMESPACE2 #endif // COH_WINDOWS_TIME_HPP
25.747899
77
0.58094
[ "object" ]
45d801e2528b28d1b83942f46e9f0a217c1a718b
12,922
hpp
C++
Common/Interpreter/String.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Common/Interpreter/String.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Common/Interpreter/String.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
#ifndef _STRING_HPP_ #define _STRING_HPP_ #include <boost/shared_ptr.hpp> #include <boost/algorithm/string.hpp> #include <functional> #include <string> #include "config.hpp" #include "Macros.hpp" #include "Base.hpp" #include "Indexable.hpp" using namespace boost; using namespace log4cpp; NAMESPACE_BEGIN(interp) template <class EncodingT> class Bool; template <class EncodingT> class String : public Base<EncodingT>, public Indexable<EncodingT> { private: typename EncodingT::string_t m_value; public: // Constructor String(); String(typename EncodingT::string_t const& value); String(typename EncodingT::char_t const& value); FACTORY_PROTOTYPE1(String, In< boost::shared_ptr< Base<EncodingT> > >) String(boost::shared_ptr< Base<EncodingT> > const& value); // Accessors typename EncodingT::string_t const& value() const; void value(typename EncodingT::string_t const& value); virtual boost::shared_ptr< Base<EncodingT> > valueAt(size_t i) const; virtual size_t length() const; // Virtual methods virtual typename EncodingT::string_t toString() const; virtual boost::shared_ptr< Base<EncodingT> > clone() const; virtual typename EncodingT::string_t getClassName() const; virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params); // Dynamic methods FACTORY_PROTOTYPE1(concat, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > concat(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(equals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > equals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(notEquals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > notEquals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(iequals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > iequals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(notIEquals, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > notIEquals(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(inferior, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > inferior(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(inferiorOrEqual, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > inferiorOrEqual(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(superior, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > superior(boost::shared_ptr< Base<EncodingT> > const& val) const; FACTORY_PROTOTYPE1(superiorOrEqual, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > superiorOrEqual(boost::shared_ptr< Base<EncodingT> > const& val) const; boost::shared_ptr< Base<EncodingT> > size() const; FACTORY_PROTOTYPE1(addValue, In< boost::shared_ptr< Base<EncodingT> > >) void addValue(boost::shared_ptr< Base<EncodingT> > const& val); FACTORY_PROTOTYPE2(insertValue, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void insertValue(boost::shared_ptr< Base<EncodingT> > const& i, boost::shared_ptr< Base<EncodingT> > const& val); FACTORY_PROTOTYPE3(insertList, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void insertList(boost::shared_ptr< Base<EncodingT> > const& i1, boost::shared_ptr< Base<EncodingT> > const& i2, boost::shared_ptr< Base<EncodingT> > const& val); FACTORY_PROTOTYPE1(removeValue, In< boost::shared_ptr< Base<EncodingT> > >) void removeValue(boost::shared_ptr< Base<EncodingT> > const& i); FACTORY_PROTOTYPE2(removeList, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void removeList(boost::shared_ptr< Base<EncodingT> > const& i1, boost::shared_ptr< Base<EncodingT> > const& i2); FACTORY_PROTOTYPE1(getValue, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getValue(boost::shared_ptr< Base<EncodingT> > const& i) const; FACTORY_PROTOTYPE2(getList, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getList(boost::shared_ptr< Base<EncodingT> > const& i1, boost::shared_ptr< Base<EncodingT> > const& i2) const; FACTORY_PROTOTYPE2(match, In< boost::shared_ptr< Base<EncodingT> > >, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > match(boost::shared_ptr< Base<EncodingT> > const& regex, boost::shared_ptr< Base<EncodingT> >& matches) const; FACTORY_PROTOTYPE5(search, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, InOut< boost::shared_ptr< Base<EncodingT> > >, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > search(boost::shared_ptr< Base<EncodingT> > const& start, boost::shared_ptr< Base<EncodingT> > const& end, boost::shared_ptr< Base<EncodingT> > const& regex, boost::shared_ptr< Base<EncodingT> >& matches, boost::shared_ptr< Base<EncodingT> >& next) const; FACTORY_PROTOTYPE1(split, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > split(boost::shared_ptr< Base<EncodingT> > const& regex) const; FACTORY_PROTOTYPE2(replaceAll, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void replaceAll(boost::shared_ptr< Base<EncodingT> > const& search, boost::shared_ptr< Base<EncodingT> > const& replace); FACTORY_PROTOTYPE4(replaceRegex, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void replaceRegex(boost::shared_ptr< Base<EncodingT> > const& start, boost::shared_ptr< Base<EncodingT> > const& end, boost::shared_ptr< Base<EncodingT> > const& regex, boost::shared_ptr< Base<EncodingT> > const& replace); FACTORY_PROTOTYPE1(append, In< boost::shared_ptr< Base<EncodingT> > >) void append(boost::shared_ptr< Base<EncodingT> > const& val); FACTORY_PROTOTYPE2(insert, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void insert(boost::shared_ptr< Base<EncodingT> > const& pos, boost::shared_ptr< Base<EncodingT> > const& val); FACTORY_PROTOTYPE2(remove, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) void remove(boost::shared_ptr< Base<EncodingT> > const& pos, boost::shared_ptr< Base<EncodingT> > const& len); FACTORY_PROTOTYPE2(substring, In< boost::shared_ptr< Base<EncodingT> > >, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > substring(boost::shared_ptr< Base<EncodingT> > const& pos, boost::shared_ptr< Base<EncodingT> > const& len) const; boost::shared_ptr< Base<EncodingT> > hash() const; void trim(); // Methods registration FACTORY_BEGIN_REGISTER CLASS_REGISTER (String) CLASS_REGISTER1 (String) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, concat, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, inferior, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, inferiorOrEqual, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, superior, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, superiorOrEqual, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, equals, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, notEquals, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, iequals, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, notIEquals, const_t) METHOD_REGISTER (String, boost::shared_ptr< Base<EncodingT> >, size, const_t) METHOD_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, getValue, const_t) METHOD_REGISTER2 (String, boost::shared_ptr< Base<EncodingT> >, getList, const_t) METHOD_REGISTER1 (String, void, addValue, no_const_t) METHOD_REGISTER2 (String, void, insertValue, no_const_t) METHOD_REGISTER3 (String, void, insertList, no_const_t) METHOD_REGISTER1 (String, void, removeValue, no_const_t) METHOD_REGISTER2 (String, void, removeList, no_const_t) METHOD_KEY_REGISTER2 (String, boost::shared_ptr< Base<EncodingT> >, match, const_t, UCS("String::Match")) METHOD_KEY_REGISTER5 (String, boost::shared_ptr< Base<EncodingT> >, search, const_t, UCS("String::Search")) METHOD_KEY_REGISTER1 (String, boost::shared_ptr< Base<EncodingT> >, split, const_t, UCS("String::Split")) METHOD_KEY_REGISTER2 (String, void, replaceAll, no_const_t, UCS("String::ReplaceAll")) METHOD_KEY_REGISTER4 (String, void, replaceRegex, no_const_t, UCS("String::ReplaceRegex")) METHOD_KEY_REGISTER1 (String, void, append, no_const_t, UCS("String::Append")) METHOD_KEY_REGISTER2 (String, void, insert, no_const_t, UCS("String::Insert")) METHOD_KEY_REGISTER2 (String, void, remove, no_const_t, UCS("String::Remove")) METHOD_KEY_REGISTER2 (String, boost::shared_ptr< Base<EncodingT> >, substring, const_t, UCS("String::SubString")) METHOD_KEY_REGISTER (String, boost::shared_ptr< Base<EncodingT> >, hash, const_t, UCS("String::Hash")) METHOD_KEY_REGISTER (String, void, trim, no_const_t, UCS("String::Trim")) FACTORY_END_REGISTER // Methods unregistration FACTORY_BEGIN_UNREGISTER CLASS_UNREGISTER (String) CLASS_UNREGISTER1 (String) METHOD_UNREGISTER1(String, concat) METHOD_UNREGISTER1(String, inferior) METHOD_UNREGISTER1(String, inferiorOrEqual) METHOD_UNREGISTER1(String, superior) METHOD_UNREGISTER1(String, superiorOrEqual) METHOD_UNREGISTER1(String, equals) METHOD_UNREGISTER1(String, notEquals) METHOD_UNREGISTER1(String, iequals) METHOD_UNREGISTER1(String, notIEquals) METHOD_UNREGISTER (String, size) METHOD_UNREGISTER1(String, getValue) METHOD_UNREGISTER2(String, getList) METHOD_UNREGISTER1(String, addValue) METHOD_UNREGISTER2(String, insertValue) METHOD_UNREGISTER3(String, insertList) METHOD_UNREGISTER1(String, removeValue) METHOD_UNREGISTER2(String, removeList) METHOD_KEY_UNREGISTER2(UCS("String::Match")) METHOD_KEY_UNREGISTER5(UCS("String::Search")) METHOD_KEY_UNREGISTER1(UCS("String::Split")) METHOD_KEY_UNREGISTER2(UCS("String::ReplaceAll")) METHOD_KEY_UNREGISTER4(UCS("String::ReplaceRegex")) METHOD_KEY_UNREGISTER1(UCS("String::Append")) METHOD_KEY_UNREGISTER2(UCS("String::Insert")) METHOD_KEY_UNREGISTER2(UCS("String::Remove")) METHOD_KEY_UNREGISTER2(UCS("String::SubString")) METHOD_KEY_UNREGISTER (UCS("String::Hash")) METHOD_KEY_UNREGISTER (UCS("String::Trim")) FACTORY_END_UNREGISTER }; template <class EncodingT2, class EncodingT> bool check_string(boost::shared_ptr< Base<EncodingT> > const& val, typename EncodingT2::string_t& n); template <class EncodingT2, class EncodingT> bool check_char(boost::shared_ptr< Base<EncodingT> > const& val, typename EncodingT2::char_t& n); template <class EncodingT2, class EncodingT> bool reset_string(boost::shared_ptr< Base<EncodingT> >& val, typename EncodingT2::string_t const& n); NAMESPACE_END #include "String_impl.hpp" #endif
59.004566
260
0.673735
[ "vector" ]
45d9a5b9f5fa845e4353fb983042ed5ba637e6b1
2,585
hpp
C++
Held-Karp-algorithm/Held-Karp-algorithm/TSP/Base/TSP.hpp
mikymaione/Held-Karp-algorithm
1ae926dfa5aaee72652875d7bd5bc6fdce19f64b
[ "MIT" ]
1
2020-03-20T09:49:33.000Z
2020-03-20T09:49:33.000Z
Held-Karp-algorithm/Held-Karp-algorithm/TSP/Base/TSP.hpp
mikymaione/Held-Karp-algorithm
1ae926dfa5aaee72652875d7bd5bc6fdce19f64b
[ "MIT" ]
null
null
null
Held-Karp-algorithm/Held-Karp-algorithm/TSP/Base/TSP.hpp
mikymaione/Held-Karp-algorithm
1ae926dfa5aaee72652875d7bd5bc6fdce19f64b
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020: Michele Maione 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. */ #pragma once #include <atomic> #include <chrono> #include <iostream> #include <sstream> #include <string> #include <thread> #include <vector> using namespace std; using namespace chrono; namespace TSP { namespace Base { class TSP { protected: // precalculated unsigned int POWER2[31] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824 }; const vector<vector<float>> distance; const unsigned short numberOfNodes; time_point<system_clock> begin; atomic<unsigned short> currentCardinality = 0; atomic<unsigned short> maxCardinality = 1; atomic<bool> programEnded = false; atomic<bool> writingBuffer = false; protected: unsigned int Powered2Code(const vector<unsigned short> &S); unsigned int Powered2Code(const vector<unsigned short> &S, const unsigned short exclude); unsigned int Powered2Code(const unsigned int code, const unsigned short exclude); void ETL(); void ETLw(); template <class T> static T generateRandomNumber(const T startRange, const T endRange, const T limit); virtual void Solve(float &opt, string &path) = 0; public: TSP(const vector<vector<float>> &DistanceMatrix2D); void Run(); void SilentSolve(float &opt, string &path); static vector<vector<float>> New_RND_Distances(const unsigned short Size_of_RandomDistanceCosts); }; } }
40.390625
559
0.755126
[ "vector" ]
45dd781206837e119c11c709a00dd4dc19b8f017
3,268
cpp
C++
indel_analysis/indelmap/indelmap.cpp
kaskamal/SelfTarget
c0bff0f11f4e69bafd80a1fa4d36b0f9689b9af7
[ "MIT" ]
20
2018-08-27T01:27:02.000Z
2022-03-07T07:12:56.000Z
indel_analysis/indelmap/indelmap.cpp
kaskamal/SelfTarget
c0bff0f11f4e69bafd80a1fa4d36b0f9689b9af7
[ "MIT" ]
6
2019-01-18T19:54:52.000Z
2021-03-19T23:56:28.000Z
indel_analysis/indelmap/indelmap.cpp
kaskamal/SelfTarget
c0bff0f11f4e69bafd80a1fa4d36b0f9689b9af7
[ "MIT" ]
14
2018-10-12T21:31:31.000Z
2021-11-08T08:32:40.000Z
/*######################################################################### # Read Mapper for self-target maps # - Bespoke aligner allowing for crispr edits but otherwise only small (1-2bp) # insertions/deletions and mutations. #########################################################################*/ int main(int argc, char *argv[]); #include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <vector> #include <string> #include <map> #include <ctime> #include "indel.h" #include "oligo.h" #include "readmap.h" #include "version.h" int main(int argc, char *argv[]) { if (argc != 5 && argc != 6 && argc != 7) { std::cout << std::endl << "Usage:" << std::endl; std::cout << "indelmap.exe <fastq_file> <exp_oligo_file> <output_file> <barcode_check_only (1 or 0)> <(opt) max_cut_dist (default 4)> <(opt)barcode_idx_file>" << std::endl << std::endl; exit(1); } std::string fastq_file = argv[1]; std::string exp_oligo_file = argv[2]; std::string output_filename = argv[3]; int barcode_check_only = atoi(argv[4]); int max_cut_dist = 4; if(argc >= 6) max_cut_dist = atoi(argv[5]); std::vector<barcode_t> barcode_lookups; if (argc >= 7) { std::string barcode_file = argv[6]; loadBarcodeIdxs(barcode_lookups, barcode_file); }else loadDefaultBarcodes(barcode_lookups); //Read in the expected oligos and create barcode hashes std::vector<Oligo*> oligo_lookup; loadOligoLookup(oligo_lookup, exp_oligo_file); //Load the barcode lookups std::vector<barcode_t>::iterator it = barcode_lookups.begin(); for (; it != barcode_lookups.end(); ++it) { buildBarcodeLookup((*it).second, (*it).first, oligo_lookup); } //Set up the output std::ofstream ofs(output_filename.c_str(), std::fstream::out ); ofs << "@@@Git Commit: " << GIT_COMMIT_HASH << std::endl; //Map the fasta or fastq reads bool is_fastq = (fastq_file[fastq_file.length() - 1] == 'q'); std::ifstream ifs(fastq_file.c_str(), std::ifstream::in); if (!ifs.good()) { std::cout << "Trouble opening fastq file " << fastq_file.c_str(); } while (ifs.good()) { std::string hline, sline, nullline; getline(ifs, hline); //read id if (!ifs.good()) break; getline(ifs, sline); //Sequence if (is_fastq) { //else Fasta if (!ifs.good()) break; getline(ifs, nullline); //Ignore if (!ifs.good()) break; getline(ifs, nullline); //Ignore } if (hline[0] != '@' && hline[0] != '>') { std::cout << "Invalid read input...expecting line starting with > or @" << std::endl; break; } clock_t begin_time = clock(); int num_checked = 0, used_barcode = 0; std::string indel, muts; std::string oligo_id = getBestOligoIdForRead(sline, oligo_lookup, barcode_lookups, indel, muts, barcode_check_only, max_cut_dist, &num_checked, &used_barcode); clock_t end_time = clock(); double elapsed_secs = double(end_time - begin_time) / CLOCKS_PER_SEC; ofs << hline.substr(1,hline.length()) << '\t' << oligo_id << '\t' << indel << '\t' << muts << '\t' << elapsed_secs << "\t" << num_checked << "\t" << used_barcode << std::endl; } ofs.close(); //Free the oligo memory std::vector<Oligo*>::iterator ito = oligo_lookup.begin(); for (; ito != oligo_lookup.end(); ++ito) delete *ito; return(0); }
33.690722
187
0.632497
[ "vector" ]
45dfb85c7a910012828479a932952ff681c78479
20,074
cpp
C++
src/ukf.cpp
ikcGitHub/CarND-Term2-P2-Unscented-Kalman-Filter-Project
0507132e7b56319fc5400e0659fae1244d087d9a
[ "MIT" ]
null
null
null
src/ukf.cpp
ikcGitHub/CarND-Term2-P2-Unscented-Kalman-Filter-Project
0507132e7b56319fc5400e0659fae1244d087d9a
[ "MIT" ]
null
null
null
src/ukf.cpp
ikcGitHub/CarND-Term2-P2-Unscented-Kalman-Filter-Project
0507132e7b56319fc5400e0659fae1244d087d9a
[ "MIT" ]
1
2020-03-31T15:22:51.000Z
2020-03-31T15:22:51.000Z
#include "ukf.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Initializes Unscented Kalman filter * This is scaffolding, do not modify */ UKF::UKF() { //cout << "UKF() started." << endl; // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd(5); // initial covariance matrix P_ = MatrixXd(5, 5); // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 2; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 0.3; //DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer. // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer. /** TODO: Complete the initialization. See ukf.h for other member properties. Hint: one or more values initialized above might be wildly off... */ ///* initially set to false, set to true in first call of ProcessMeasurement is_initialized_ = false; // Set state dimension n_x_ = 5; // Set augmented dimension n_aug_ = 7; // Define spreading parameter lambda_ = 3 - n_aug_; // Create predicted sigma points matrix Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1); ///* time when the state is true, in us time_us_ = 0.0; // Create vector for weights weights_ = VectorXd(2 * n_aug_ + 1); // Set weights // Initialize the first element weights_(0) = lambda_ / (lambda_ + n_aug_); // Initialize the rest of elements int i = 0; for (i = 1; i < 2 * n_aug_ + 1; i++) { weights_(i) = 0.5 / (n_aug_ + lambda_); } //// Set measurement dimension, radar can measure r, phi, and r_dot //int n_z = 3; // Create radar covariance matrix R_radar_ = MatrixXd(3, 3); R_radar_ << std_radr_ * std_radr_, 0, 0, 0, std_radphi_ * std_radphi_, 0, 0, 0, std_radrd_ * std_radrd_; // Create lidar covariance matrix R_lidar_ = MatrixXd(2, 2); R_lidar_ << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_; ///* the current NIS for radar NIS_radar_ = 0.0; ///* the current NIS for laser NIS_laser_ = 0.0; //cout << "n_aug_ is " << n_aug_ << endl; //cout << "n_x_ is " << n_x_ << endl; //cout << "UKF() completed." << endl; } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { /** TODO: Complete this function! Make sure you switch between lidar and radar measurements. */ /***************************************************************************** * Initialization ****************************************************************************/ // TODO : Check if data is initialized ? if (!is_initialized_){ /** TODO: * Initialize the state ekf_.x_ with the first measurement. * Create the covariance matrix. * Remember: you'll need to convert radar from polar to cartesian coordinates. */ //cout << "Initialization started." << endl; //// Initialize state //x_ << 0.0, // 0.0, // 0.0, // 0.0, // 0.0; // Initialize covariance matrix P_ << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1; if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { /** Convert radar from polar to cartesian coordinates and initialize state. */ double rho = meas_package.raw_measurements_[0]; // range double phi = meas_package.raw_measurements_[1]; // bearing double rho_dot = meas_package.raw_measurements_[2]; // velocity of rho double px = rho * cos(phi); // position x double py = rho * sin(phi); // position y double vx = rho_dot * cos(phi); // velocity x double vy = rho_dot * sin(phi); // velocity y double v = sqrt(vx * vx + vy * vy); // velocity x_ << px, py, v, 0, 0; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER){ /** Initialize state. */ double px = meas_package.raw_measurements_[0]; // position x double py = meas_package.raw_measurements_[1]; // position y x_ << px, py, 0, 0, 0; } // Initial measurement timestamp time_us_ = meas_package.timestamp_; // done initializing, no need to predict or update is_initialized_ = true; //cout << "Initialization completed." << endl; //cout << "x_ is " << x_ << endl; //cout << "n_aug_ is " << n_aug_ << endl; //cout << "n_x_ is " << n_x_ << endl; return; } /***************************************************************************** * Prediction ****************************************************************************/ // TODO : Call predition step with calculated time interval // Calculate time interval dt double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; // Update measurement timestamp time_us_ = meas_package.timestamp_; // Call prediction //cout << "Prediction started." << endl; Prediction(dt); //cout << "Prediction completed." << endl; /***************************************************************************** * Update ****************************************************************************/ // TODO : Call update step with given senser type if (meas_package.sensor_type_ == MeasurementPackage::RADAR && use_radar_) { //cout << "UpdateRadar started." << endl; UpdateRadar(meas_package); //cout << "UpdateRadar completed." << endl; } else if (meas_package.sensor_type_ == MeasurementPackage::LASER && use_laser_) { //cout << "UpdateLidar started." << endl; UpdateLidar(meas_package); //cout << "UpdateLidar completed." << endl; } } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { /** TODO: Complete this function! Estimate the object's location. Modify the state vector, x_. Predict sigma points, the state, and the state covariance matrix. */ ///***************************************************************************** //* Generate Sigma Points //****************************************************************************/ //// TODO: Generate sigma points //// Create sigma point matrix //MatrixXd Xsig = MatrixXd(n_x_, 2 * n_x_ + 1); //// Calculate square root of P //MatrixXd A = P_.llt().matrixL(); //// Set lambda for sigma points //lambda_ = 3 - n_x_; //// Set sigma points as columns of matrix Xsig //Xsig.col(0) = x_; //int i = 0; //float sig_sqrt = sqrt(lambda_ + n_x_); //for (i = 0; i < n_x_; i++) { // Xsig.col(i + 1) = x_ + A.col(i) * sig_sqrt; // Xsig.col(i + 1 + n_x_) = x_ - A.col(i) * sig_sqrt; //} /***************************************************************************** * Augment Sigma Points ****************************************************************************/ // TODO : Augment Sigma Points //cout << "Augment sigma points started." << endl; // Create augmented mean vector //cout << "n_aug_ is " << n_aug_ << endl; //cout << "n_x_ is " << n_x_ << endl; VectorXd x_aug = VectorXd(n_aug_); // Create augmented state covariance MatrixXd P_aug = MatrixXd(n_aug_, n_aug_); // Create augmented sigma point matrix MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1); //// Set lambda for augmented sigma points //lambda_ = 3 - n_aug_; // Create augmented mean state //cout << "x_aug started." << endl; x_aug.fill(0.0); //cout << "Filled with 0.0" << x_aug << endl; x_aug.head(n_x_) = x_; //cout << "Filled with x_" << x_aug << endl; x_aug(5) = 0; x_aug(6) = 0; // Create augmented covariance matrix //cout << "P_aug started." << endl; P_aug.fill(0.0); P_aug.topLeftCorner(n_x_, n_x_) = P_; P_aug(5, 5) = std_a_ * std_a_; P_aug(6, 6) = std_yawdd_ * std_yawdd_; // Create square root matrix MatrixXd L = P_aug.llt().matrixL(); //create augmented sigma points //cout << "Xsig_aug started." << endl; Xsig_aug.col(0) = x_aug; int i = 0; double sig_sqrt = sqrt(lambda_ + n_aug_); for (i = 0; i < n_aug_; i++) { Xsig_aug.col(i + 1) = x_aug + L.col(i) * sig_sqrt; Xsig_aug.col(i + 1 + n_aug_) = x_aug - L.col(i) * sig_sqrt; } /***************************************************************************** * Predict Sigma Points ****************************************************************************/ // TODO : Predict sigma points //cout << "Predict sigma points started." << endl; //int i = 0; for (i = 0; i < 2 * n_aug_ + 1; i++) { // Read values from current state vector double p_x = Xsig_aug(0, i); double p_y = Xsig_aug(1, i); double v = Xsig_aug(2, i); double yaw = Xsig_aug(3, i); double yawd = Xsig_aug(4, i); double nu_a = Xsig_aug(5, i); double nu_yawdd = Xsig_aug(6, i); // Initialize predicted state double px_p, py_p; // Avoid division by zero if (fabs(yawd) > 0.001) { px_p = p_x + v / yawd * ( sin(yaw + yawd * delta_t) - sin(yaw)); py_p = p_y + v / yawd * (-cos(yaw + yawd * delta_t) + cos(yaw)); } else { px_p = p_x + v * delta_t * cos(yaw); py_p = p_y + v * delta_t * sin(yaw); } //predict sigma points double v_p = v; double yaw_p = yaw + yawd * delta_t; double yawd_p = yawd; // Add Noise px_p += 0.5 * nu_a * delta_t * delta_t * cos(yaw); py_p += 0.5 * nu_a * delta_t * delta_t * sin(yaw); v_p += nu_a * delta_t; yaw_p += 0.5 * nu_yawdd * delta_t * delta_t; yawd_p += nu_yawdd * delta_t; //write predicted sigma points into right column Xsig_pred_(0, i) = px_p; Xsig_pred_(1, i) = py_p; Xsig_pred_(2, i) = v_p; Xsig_pred_(3, i) = yaw_p; Xsig_pred_(4, i) = yawd_p; } /***************************************************************************** * Calculate mean and variance ****************************************************************************/ // TODO : Calculate mean // TODO : Calculate variance // TODO : Normalize angles //cout << "Predict state mean and variance started." << endl; // Predict state mean //for (i = 0; i < 2 * n_aug_ + 1; i++) { // x_ += weights_(i) * Xsig_pred_.col(i); //} x_ = Xsig_pred_ * weights_; //cout << "Predict state mean and variance midpoint." << endl; // Predict state covariance matrix P_.fill(0.0); for (i = 0; i < 2 * n_aug_ + 1; i++) { VectorXd x_diff = Xsig_pred_.col(i) - x_; while (x_diff(3) > M_PI) { x_diff(3) -= 2.0 * M_PI; } while (x_diff(3) < -M_PI) { x_diff(3) += 2.0 * M_PI; } P_ += weights_(i) * x_diff * x_diff.transpose(); } //cout << "Predict state mean and variance completed." << endl; } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use lidar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the lidar NIS. */ // TODO : Extract data from measurement // TODO : Generate measurement sigma points // TODO : Update predicted measurement mean // TODO : Update predicted measurement covariance // TODO : Add noise // TODO : Create cross covariance matrix // TODO : Calculate Kalman gain Kalman // TODO : Calculate residual error // TODO : Normalize angles // TODO : Update state mean vector // TODO : Update state covariance matrix // TODO : Update NIS Lidar /***************************************************************************** * Predict lidar measurement ****************************************************************************/ //set measurement dimension, lidar can measure position x and position y int n_z = 2; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1); Zsig = Xsig_pred_.block(0, 0, n_z, 2 * n_aug_ + 1); //mean predicted measurement VectorXd z_pred = VectorXd(n_z); //measurement covariance matrix S MatrixXd S = MatrixXd(n_z, n_z); // //transform sigma points into measurement space //int i = 0; //for (i = 0; i < 2 * n_aug_ + 1; i++) { // // Read values from current state vector // double p_x = Xsig_pred_(0, i); // double p_y = Xsig_pred_(1, i); // double v = Xsig_pred_(2, i); // double yaw = Xsig_pred_(3, i); // double v1 = cos(yaw) * v; // double v2 = sin(yaw) * v; // // Update measurement model // Zsig(0, i) = sqrt(p_x * p_x + p_y * p_y); // r // Zsig(1, i) = atan2(p_y, p_x); // phi // Zsig(2, i) = (p_x * v1 + p_y * v2) / sqrt(p_x * p_x + p_y * p_y); // r_dot //} //calculate mean predicted measurement z_pred.fill(0.0); int i = 0; for (i = 0; i < 2 * n_aug_ + 1; i++) { z_pred += weights_(i) * Zsig.col(i); } //calculate innovation covariance matrix S S.fill(0.0); for (i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points // Calculate the residual VectorXd z_diff = Zsig.col(i) - z_pred; //// Normalize angle //while (z_diff(1) > M_PI) { // z_diff(1) -= 2.0 * M_PI; //} //while (z_diff(1) < -M_PI) { // z_diff(1) += 2.0 * M_PI; //} S += weights_(i) * z_diff * z_diff.transpose(); } // Add measurement noise to covariance matrix S += R_lidar_; /***************************************************************************** * UKF update lidar measurement ****************************************************************************/ //create example vector for incoming radar measurement VectorXd z = meas_package.raw_measurements_; //create matrix for cross correlation Tc MatrixXd Tc = MatrixXd(n_x_, n_z); //calculate cross correlation matrix Tc.fill(0.0); //int i = 0; for (i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points // Calculate the residual on z VectorXd z_diff = Zsig.col(i) - z_pred; //// Normalize angle //while (z_diff(1) > M_PI) { // z_diff(1) -= 2.0 * M_PI; //} //while (z_diff(1) < -M_PI) { // z_diff(1) += 2.0 * M_PI; //} // Calculate the difference on state VectorXd x_diff = Xsig_pred_.col(i) - x_; //// Normalize angle //while (x_diff(3) > M_PI) { // x_diff(3) -= 2.0 * M_PI; //} //while (x_diff(3) < -M_PI) { // x_diff(3) += 2.0 * M_PI; //} Tc += weights_(i) * x_diff * z_diff.transpose(); } //calculate Kalman gain K; MatrixXd K = Tc * S.inverse(); //update state mean and covariance matrix // Calculate the residual on z VectorXd z_diff = z - z_pred; //// Normalize angle //while (z_diff(1) > M_PI) { // z_diff(1) -= 2.0 * M_PI; //} //while (z_diff(1) < -M_PI) { // z_diff(1) += 2.0 * M_PI; //} // Update state mean and covariance matrix x_ += K * z_diff; P_ -= K * S * K.transpose(); // Calculate NIS update NIS_laser_ = z_diff.transpose() * S.inverse() * z_diff; } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use radar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the radar NIS. */ // TODO : Extract data from measurement // TODO : Generate measurement sigma points // TODO : Update predicted measurement mean // TODO : Update predicted measurement covariance // TODO : Add noise // TODO : Create cross covariance matrix // TODO : Calculate Kalman gain Kalman // TODO : Calculate residual error // TODO : Normalize angles // TODO : Update state mean vector // TODO : Update state covariance matrix // TODO : Update NIS Radar /***************************************************************************** * Predict radar measurement ****************************************************************************/ //set measurement dimension, radar can measure r, phi, and r_dot int n_z = 3; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1); //mean predicted measurement VectorXd z_pred = VectorXd(n_z); //measurement covariance matrix S MatrixXd S = MatrixXd(n_z, n_z); //transform sigma points into measurement space int i = 0; for (i = 0; i < 2 * n_aug_ + 1; i++) { // Read values from current state vector double p_x = Xsig_pred_(0, i); double p_y = Xsig_pred_(1, i); double v = Xsig_pred_(2, i); double yaw = Xsig_pred_(3, i); double v1 = cos(yaw) * v; double v2 = sin(yaw) * v; // Update measurement model Zsig(0, i) = sqrt(p_x * p_x + p_y * p_y); // r Zsig(1, i) = atan2(p_y, p_x); // phi Zsig(2, i) = (p_x * v1 + p_y * v2) / sqrt(p_x * p_x + p_y * p_y); // r_dot } //calculate mean predicted measurement z_pred.fill(0.0); for (i = 0; i < 2 * n_aug_ + 1; i++) { z_pred += weights_(i) * Zsig.col(i); } //calculate innovation covariance matrix S S.fill(0.0); for (i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points // Calculate the residual VectorXd z_diff = Zsig.col(i) - z_pred; // Normalize angle while (z_diff(1) > M_PI) { z_diff(1) -= 2.0 * M_PI; } while (z_diff(1) < -M_PI) { z_diff(1) += 2.0 * M_PI; } S += weights_(i) * z_diff * z_diff.transpose(); } // Add measurement noise to covariance matrix S += R_radar_; /***************************************************************************** * UKF update radar measurement ****************************************************************************/ //create example vector for incoming radar measurement VectorXd z = meas_package.raw_measurements_; //create matrix for cross correlation Tc MatrixXd Tc = MatrixXd(n_x_, n_z); //calculate cross correlation matrix Tc.fill(0.0); //int i = 0; for (i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points // Calculate the residual on z VectorXd z_diff = Zsig.col(i) - z_pred; // Normalize angle while (z_diff(1) > M_PI) { z_diff(1) -= 2.0 * M_PI; } while (z_diff(1) < -M_PI) { z_diff(1) += 2.0 * M_PI; } // Calculate the difference on state VectorXd x_diff = Xsig_pred_.col(i) - x_; // Normalize angle while (x_diff(3) > M_PI) { x_diff(3) -= 2.0 * M_PI; } while (x_diff(3) < -M_PI) { x_diff(3) += 2.0 * M_PI; } Tc += weights_(i) * x_diff * z_diff.transpose(); } //calculate Kalman gain K; MatrixXd K = Tc * S.inverse(); //update state mean and covariance matrix // Calculate the residual on z VectorXd z_diff = z - z_pred; // Normalize angle while (z_diff(1) > M_PI) { z_diff(1) -= 2.0 * M_PI; } while (z_diff(1) < -M_PI) { z_diff(1) += 2.0 * M_PI; } // Update state mean and covariance matrix x_ += K * z_diff; P_ -= K * S * K.transpose(); // Calculate NIS update NIS_radar_ = z_diff.transpose() * S.inverse() * z_diff; }
28.233474
95
0.561921
[ "object", "vector", "model", "transform" ]
45eb318704cb389276449f108f23ac0c519817db
10,841
cpp
C++
src/devices/cpu/mb86235/mb86235.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/cpu/mb86235/mb86235.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/cpu/mb86235/mb86235.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Angelo Salese, ElSemi, Ville Linde /******************************************************************************** * * MB86235 "TGPx4" (c) Fujitsu * * Written by Angelo Salese & ElSemi * * TODO: * - rewrite ALU integer/floating point functions, use templates etc; * - move post-opcodes outside of the execute_op() function, like increment_prp() * (needed if opcode uses fifo in/out); * - rewrite fifo hookups, remove them from the actual opcodes. * - use a phase system for the execution, like do_alu() being separated * from control(); * - illegal delay slots unsupported, and no idea about what is supposed to happen; * - externalize PDR / DDR (error LED flags on Model 2); * - instruction cycles; * - pipeline (four instruction executed per cycle!) * ********************************************************************************/ #include "emu.h" #include "mb86235.h" #include "mb86235fe.h" #include "mb86235d.h" #include "debugger.h" #define ENABLE_DRC 0 #define CACHE_SIZE (1 * 1024 * 1024) #define COMPILE_BACKWARDS_BYTES 128 #define COMPILE_FORWARDS_BYTES 512 #define COMPILE_MAX_INSTRUCTIONS ((COMPILE_BACKWARDS_BYTES/4) + (COMPILE_FORWARDS_BYTES/4)) #define COMPILE_MAX_SEQUENCE 64 DEFINE_DEVICE_TYPE(MB86235, mb86235_device, "mb86235", "Fujitsu MB86235 \"TGPx4\"") void mb86235_device::internal_abus(address_map &map) { map(0x000000, 0x0003ff).ram(); } void mb86235_device::internal_bbus(address_map &map) { map(0x000000, 0x0003ff).ram(); } /* Execute cycles */ void mb86235_device::execute_run() { #if ENABLE_DRC run_drc(); #else uint64_t opcode; while(m_core->icount > 0) { uint32_t curpc; curpc = check_previous_op_stall() ? m_core->cur_fifo_state.pc : m_core->pc; debugger_instruction_hook(curpc); opcode = m_pcache.read_qword(curpc); m_core->ppc = curpc; if(m_core->delay_slot == true) { m_core->pc = m_core->delay_pc; m_core->delay_slot = false; } else handle_single_step_execution(); execute_op(opcode >> 32, opcode & 0xffffffff); m_core->icount--; } #endif } void mb86235_device::device_start() { space(AS_PROGRAM).cache(m_pcache); space(AS_PROGRAM).specific(m_program); space(AS_DATA).specific(m_dataa); space(AS_IO).specific(m_datab); m_core = (mb86235_internal_state *)m_cache.alloc_near(sizeof(mb86235_internal_state)); memset(m_core, 0, sizeof(mb86235_internal_state)); #if ENABLE_DRC // init UML generator uint32_t umlflags = 0; m_drcuml = std::make_unique<drcuml_state>(*this, m_cache, umlflags, 1, 24, 0); // add UML symbols m_drcuml->symbol_add(&m_core->pc, sizeof(m_core->pc), "pc"); m_drcuml->symbol_add(&m_core->icount, sizeof(m_core->icount), "icount"); for (int i = 0; i < 8; i++) { char buf[10]; sprintf(buf, "aa%d", i); m_drcuml->symbol_add(&m_core->aa[i], sizeof(m_core->aa[i]), buf); sprintf(buf, "ab%d", i); m_drcuml->symbol_add(&m_core->ab[i], sizeof(m_core->ab[i]), buf); sprintf(buf, "ma%d", i); m_drcuml->symbol_add(&m_core->ma[i], sizeof(m_core->ma[i]), buf); sprintf(buf, "mb%d", i); m_drcuml->symbol_add(&m_core->mb[i], sizeof(m_core->mb[i]), buf); sprintf(buf, "ar%d", i); m_drcuml->symbol_add(&m_core->ar[i], sizeof(m_core->ar[i]), buf); } m_drcuml->symbol_add(&m_core->flags.az, sizeof(m_core->flags.az), "flags_az"); m_drcuml->symbol_add(&m_core->flags.an, sizeof(m_core->flags.an), "flags_an"); m_drcuml->symbol_add(&m_core->flags.av, sizeof(m_core->flags.av), "flags_av"); m_drcuml->symbol_add(&m_core->flags.au, sizeof(m_core->flags.au), "flags_au"); m_drcuml->symbol_add(&m_core->flags.ad, sizeof(m_core->flags.ad), "flags_ad"); m_drcuml->symbol_add(&m_core->flags.zc, sizeof(m_core->flags.zc), "flags_zc"); m_drcuml->symbol_add(&m_core->flags.il, sizeof(m_core->flags.il), "flags_il"); m_drcuml->symbol_add(&m_core->flags.nr, sizeof(m_core->flags.nr), "flags_nr"); m_drcuml->symbol_add(&m_core->flags.zd, sizeof(m_core->flags.zd), "flags_zd"); m_drcuml->symbol_add(&m_core->flags.mn, sizeof(m_core->flags.mn), "flags_mn"); m_drcuml->symbol_add(&m_core->flags.mz, sizeof(m_core->flags.mz), "flags_mz"); m_drcuml->symbol_add(&m_core->flags.mv, sizeof(m_core->flags.mv), "flags_mv"); m_drcuml->symbol_add(&m_core->flags.mu, sizeof(m_core->flags.mu), "flags_mu"); m_drcuml->symbol_add(&m_core->flags.md, sizeof(m_core->flags.md), "flags_md"); m_drcuml->symbol_add(&m_core->arg0, sizeof(m_core->arg0), "arg0"); m_drcuml->symbol_add(&m_core->arg1, sizeof(m_core->arg1), "arg1"); m_drcuml->symbol_add(&m_core->arg2, sizeof(m_core->arg2), "arg2"); m_drcuml->symbol_add(&m_core->arg3, sizeof(m_core->arg3), "arg3"); m_drcuml->symbol_add(&m_core->alutemp, sizeof(m_core->alutemp), "alutemp"); m_drcuml->symbol_add(&m_core->multemp, sizeof(m_core->multemp), "multemp"); m_drcuml->symbol_add(&m_core->pcp, sizeof(m_core->pcp), "pcp"); m_drcfe = std::make_unique<mb86235_frontend>(this, COMPILE_BACKWARDS_BYTES, COMPILE_FORWARDS_BYTES, COMPILE_MAX_SEQUENCE); for (int i = 0; i < 8; i++) { m_regmap[i] = uml::mem(&m_core->aa[i]); m_regmap[i + 8] = uml::mem(&m_core->ab[i]); m_regmap[i + 16] = uml::mem(&m_core->ma[i]); m_regmap[i + 24] = uml::mem(&m_core->mb[i]); } #endif // Register state for debugger state_add(MB86235_PC, "PC", m_core->pc).formatstr("%08X"); state_add(MB86235_AR0, "AR0", m_core->ar[0]).formatstr("%08X"); state_add(MB86235_AR1, "AR1", m_core->ar[1]).formatstr("%08X"); state_add(MB86235_AR2, "AR2", m_core->ar[2]).formatstr("%08X"); state_add(MB86235_AR3, "AR3", m_core->ar[3]).formatstr("%08X"); state_add(MB86235_AR4, "AR4", m_core->ar[4]).formatstr("%08X"); state_add(MB86235_AR5, "AR5", m_core->ar[5]).formatstr("%08X"); state_add(MB86235_AR6, "AR6", m_core->ar[6]).formatstr("%08X"); state_add(MB86235_AR7, "AR7", m_core->ar[7]).formatstr("%08X"); state_add(MB86235_AA0, "AA0", m_core->aa[0]).formatstr("%08X"); state_add(MB86235_AA1, "AA1", m_core->aa[1]).formatstr("%08X"); state_add(MB86235_AA2, "AA2", m_core->aa[2]).formatstr("%08X"); state_add(MB86235_AA3, "AA3", m_core->aa[3]).formatstr("%08X"); state_add(MB86235_AA4, "AA4", m_core->aa[4]).formatstr("%08X"); state_add(MB86235_AA5, "AA5", m_core->aa[5]).formatstr("%08X"); state_add(MB86235_AA6, "AA6", m_core->aa[6]).formatstr("%08X"); state_add(MB86235_AA7, "AA7", m_core->aa[7]).formatstr("%08X"); state_add(MB86235_AB0, "AB0", m_core->ab[0]).formatstr("%08X"); state_add(MB86235_AB1, "AB1", m_core->ab[1]).formatstr("%08X"); state_add(MB86235_AB2, "AB2", m_core->ab[2]).formatstr("%08X"); state_add(MB86235_AB3, "AB3", m_core->ab[3]).formatstr("%08X"); state_add(MB86235_AB4, "AB4", m_core->ab[4]).formatstr("%08X"); state_add(MB86235_AB5, "AB5", m_core->ab[5]).formatstr("%08X"); state_add(MB86235_AB6, "AB6", m_core->ab[6]).formatstr("%08X"); state_add(MB86235_AB7, "AB7", m_core->ab[7]).formatstr("%08X"); state_add(MB86235_MA0, "MA0", m_core->ma[0]).formatstr("%08X"); state_add(MB86235_MA1, "MA1", m_core->ma[1]).formatstr("%08X"); state_add(MB86235_MA2, "MA2", m_core->ma[2]).formatstr("%08X"); state_add(MB86235_MA3, "MA3", m_core->ma[3]).formatstr("%08X"); state_add(MB86235_MA4, "MA4", m_core->ma[4]).formatstr("%08X"); state_add(MB86235_MA5, "MA5", m_core->ma[5]).formatstr("%08X"); state_add(MB86235_MA6, "MA6", m_core->ma[6]).formatstr("%08X"); state_add(MB86235_MA7, "MA7", m_core->ma[7]).formatstr("%08X"); state_add(MB86235_MB0, "MB0", m_core->mb[0]).formatstr("%08X"); state_add(MB86235_MB1, "MB1", m_core->mb[1]).formatstr("%08X"); state_add(MB86235_MB2, "MB2", m_core->mb[2]).formatstr("%08X"); state_add(MB86235_MB3, "MB3", m_core->mb[3]).formatstr("%08X"); state_add(MB86235_MB4, "MB4", m_core->mb[4]).formatstr("%08X"); state_add(MB86235_MB5, "MB5", m_core->mb[5]).formatstr("%08X"); state_add(MB86235_MB6, "MB6", m_core->mb[6]).formatstr("%08X"); state_add(MB86235_MB7, "MB7", m_core->mb[7]).formatstr("%08X"); state_add(MB86235_ST, "ST", m_core->st).formatstr("%08X"); state_add(MB86235_EB, "EB", m_core->eb).formatstr("%08X"); state_add(MB86235_EO, "EO", m_core->eo).formatstr("%08X"); state_add(MB86235_SP, "SP", m_core->sp).formatstr("%08X"); state_add(MB86235_RPC, "RPC", m_core->rpc).formatstr("%08X"); state_add(MB86235_LPC, "LPC", m_core->lpc).formatstr("%08X"); state_add(MB86235_PDR, "PDR", m_core->pdr).formatstr("%08X"); state_add(MB86235_DDR, "DDR", m_core->ddr).formatstr("%08X"); state_add(MB86235_MOD, "MOD", m_core->mod).formatstr("%04X"); state_add(MB86235_PRP, "PRP", m_core->prp).formatstr("%02X"); state_add(MB86235_PWP, "PWP", m_core->pwp).formatstr("%02X"); state_add(STATE_GENPC, "GENPC", m_core->pc ).noshow(); state_add(STATE_GENPCBASE, "CURPC", m_core->pc).noshow(); set_icountptr(m_core->icount); m_core->fp0 = 0.0f; save_pointer(NAME(m_core->pr), 24); } void mb86235_device::device_reset() { #if ENABLE_DRC flush_cache(); #endif m_core->pc = 0; m_core->delay_pc = 0; m_core->ppc = 0; m_core->delay_slot = false; } #if 0 void mb86235_cpu_device::execute_set_input(int irqline, int state) { switch(irqline) { case MB86235_INT_INTRM: m_intrm_pending = (state == ASSERT_LINE); m_intrm_state = state; break; case MB86235_RESET: if (state == ASSERT_LINE) m_reset_pending = 1; m_reset_state = state; break; case MB86235_INT_INTR: if (state == ASSERT_LINE) m_intr_pending = 1; m_intr_state = state; break; } } #endif mb86235_device::mb86235_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : cpu_device(mconfig, MB86235, tag, owner, clock) , m_program_config("program", ENDIANNESS_LITTLE, 64, 32, -3) , m_dataa_config("data_a", ENDIANNESS_LITTLE, 32, 24, -2, address_map_constructor(FUNC(mb86235_device::internal_abus), this)) , m_datab_config("data_b", ENDIANNESS_LITTLE, 32, 10, -2, address_map_constructor(FUNC(mb86235_device::internal_bbus), this)) , m_fifoin(*this, finder_base::DUMMY_TAG) , m_fifoout0(*this, finder_base::DUMMY_TAG) , m_fifoout1(*this, finder_base::DUMMY_TAG) , m_cache(CACHE_SIZE + sizeof(mb86235_internal_state)) , m_drcuml(nullptr) , m_drcfe(nullptr) { } mb86235_device::~mb86235_device() { } device_memory_interface::space_config_vector mb86235_device::memory_space_config() const { return space_config_vector { std::make_pair(AS_PROGRAM, &m_program_config), std::make_pair(AS_DATA, &m_dataa_config), std::make_pair(AS_IO, &m_datab_config) }; } void mb86235_device::state_string_export(const device_state_entry &entry, std::string &str) const { switch (entry.index()) { case STATE_GENFLAGS: str = string_format("?"); break; } } std::unique_ptr<util::disasm_interface> mb86235_device::create_disassembler() { return std::make_unique<mb86235_disassembler>(); }
35.661184
126
0.687206
[ "model" ]
340201ed96bac05b719557ffacc1a5bdc3c7c6b1
2,181
cpp
C++
Vector01.cpp
wedusk101/CPP
0221e272b7d71569967c685e3f99bbeb7930f823
[ "MIT" ]
1
2020-07-20T04:35:41.000Z
2020-07-20T04:35:41.000Z
Vector01.cpp
wedusk101/CPP
0221e272b7d71569967c685e3f99bbeb7930f823
[ "MIT" ]
null
null
null
Vector01.cpp
wedusk101/CPP
0221e272b7d71569967c685e3f99bbeb7930f823
[ "MIT" ]
2
2017-05-22T00:13:03.000Z
2020-07-20T04:34:50.000Z
//Vector01.cpp #include <iostream> #include "Vector.h" using namespace std; int main() { double x = 0.0, y = 0.0, z = 0.0; int choice = 0, flag = 0; Vector v1, v2; cout<<"This program implements a class Vector with the following basic operations."<<endl; do { cout<<"1. Create a vector."<<endl; cout<<"2. Display a vector."<<endl; cout<<"3. Get the magnitude of a vector."<<endl; cout<<"4. Get the dot product of two vectors."<<endl; cout<<"5. EXIT"<<endl; cout<<"Please enter your choice."<<endl; cin>>choice; switch(choice) { case 1: cout<<"Please enter the value of the x component."<<endl; cin>>x; cout<<"Please enter the value of the y component."<<endl; cin>>y; cout<<"Please enter the value of the z component."<<endl; cin>>z; v1.initVector(x, y ,z); flag = 1; cout<<"Vector created successfully."<<endl; break; case 2: { if(flag == 0) { cout<<"First create a vector! Operation aborted."<<endl; break; } v1.display(); } break; case 3: { if(flag == 0) { cout<<"First create a vector! Operation aborted."<<endl; break; } cout<<"The magnitude of the vector is "<<v1.magnitude()<<" units."<<endl; } break; case 4: { if(flag == 0) { cout<<"First create a vector! Operation aborted."<<endl; break; } cout<<"Please create a second vector."<<endl; cout<<"Please enter the value of the x component."<<endl; cin>>x; cout<<"Please enter the value of the y component."<<endl; cin>>y; cout<<"Please enter the value of the z component."<<endl; cin>>z; v2.initVector(x, y ,z); cout<<"vector created successfully."<<endl; cout<<"The dot product of the vectors is "<<v1.dotProduct(v2)<<" ."<<endl; } break; case 5: cout<<"Thank you."<<endl; break; default: cout<<"Invalid input!"<<endl; break; } }while(choice != 5); return 0; }
26.597561
92
0.528198
[ "vector" ]
3408f3d87c64825a5722dad9f028df87aea0ac1a
3,776
cpp
C++
src/rendering/projector.cpp
brspnnggrt/engine
2fa2a10bca5245c248642c9d43c50756d24b7f38
[ "MIT" ]
null
null
null
src/rendering/projector.cpp
brspnnggrt/engine
2fa2a10bca5245c248642c9d43c50756d24b7f38
[ "MIT" ]
null
null
null
src/rendering/projector.cpp
brspnnggrt/engine
2fa2a10bca5245c248642c9d43c50756d24b7f38
[ "MIT" ]
1
2021-07-29T03:07:35.000Z
2021-07-29T03:07:35.000Z
#include "projector.h" #include <math.h> namespace Engene { namespace Rendering { Projector::Projector(float scaling, Math::Vec3 translation, Math::Vec3 viewUpVector) : scaling(scaling), translation(translation), viewUpVector(viewUpVector) { } Math::Mat4 Projector::CreateTranslationMatrix(float x, float y, float z) { Math::Mat4 matrix = { 1.0f , 0.0f , 0.0f , x , 0.0f , 1.0f , 0.0f , y , 0.0f , 0.0f , 1.0f , z , 0.0f , 0.0f , 0.0f , 1.0f }; return matrix; } Math::Mat4 Projector::CreateRotationMatrix(Axis axis, float theta) { switch (axis) { case X: { // Rotation over angle theta around X-axis Math::Mat4 matrix = { 1.0f, 0.0f , 0.0f , 0.0f, 0.0f, cosf(theta) , -sinf(theta) , 0.0f, 0.0f, sinf(theta) , cosf(theta) , 0.0f, 0.0f, 0.0f , 0.0f , 1.0f }; return matrix; } case Y: { // Rotation over angle theta around Y-axis Math::Mat4 matrix = { cosf(theta) , 0.0f, sinf(theta) , 0.0f, 0.0f , 1.0f, 0.0f , 0.0f, -sinf(theta) , 0.0f, cosf(theta) , 0.0f, 0.0f , 0.0f, 0.0f , 1.0f }; return matrix; } case Z: { // Rotation over angle theta around Z-axis Math::Mat4 matrix = { cosf(theta) , -sinf(theta) , 0.0f , 0.0f, sinf(theta) , cosf(theta) , 0.0f , 0.0f, 0.0f , 0.0f , 1.0f , 0.0f, 0.0f , 0.0f , 0.0f , 1.0f }; return matrix; } } } Math::Mat4 Projector::CreateScalingMatrix(float scale) { Math::Mat4 matrix = { scale, 0.0f , 0.0f , 0.0f, 0.0f , scale, 0.0f , 0.0f, 0.0f , 0.0f , scale, 0.0f, 0.0f , 0.0f , 0.0f , 1.0f }; return matrix; }; Math::Mat4 Projector::CreateProjectionMatrix(float d, float z) { Math::Mat4 matrix = { -d/z , 0.0f , 0.0f , 0.0f, 0.0f , -d/z , 0.0f , 0.0f, 0.0f , 0.0f , -d/z , 0.0f, 0.0f , 0.0f , 0.0f , 1.0f }; return matrix; } Math::Vec3 Projector::Project(Math::Vec3 vector, Math::Vec3 objectLocation, Math::Vec3 viewingLocation) { // Convert to world coordinate system vector *= Projector::CreateTranslationMatrix(objectLocation.x, objectLocation.y, objectLocation.z); // Where do you want the object from which this vector is part of? // Convert to viewing coordinate system Math::Mat4 translateViewPoint = Projector::CreateTranslationMatrix(-viewingLocation.x, -viewingLocation.y, -viewingLocation.z); // Where are you looking from? Math::Vec3 w = Math::Vec3::GetUnitVector(viewingLocation); Math::Vec3 u = Math::Vec3::CrossProduct(viewUpVector, w); u = Math::Vec3::GetUnitVector(u); Math::Vec3 v = Math::Vec3::GetUnitVector(viewUpVector); Math::Mat4 r = { u.x , u.y , u.z , 0 , v.x , v.y , v.z , 0 , w.x , w.y , w.z , 0 , 0 , 0 , 0 , 1 }; vector *= r * translateViewPoint; // Convert to 2D coordinate system (perspective projection from 3D to 2D) vector *= Projector::CreateProjectionMatrix(2.0f, vector.z); // Apply scaling & translation vector *= Projector::CreateScalingMatrix(scaling); vector *= Projector::CreateTranslationMatrix(translation.x, translation.y, translation.z); // Can be used to center to screen return vector; } } // namespace Rendering } // namespace Engene
30.208
170
0.521186
[ "object", "vector", "3d" ]
3423f8cc21c70a8bb8e8a1342f304e042e14ecaf
1,037
cpp
C++
acwing/1501.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
null
null
null
acwing/1501.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
null
null
null
acwing/1501.cpp
zyzisyz/OJ
55221a55515231182b6bd133edbdb55501a565fc
[ "Apache-2.0" ]
2
2020-01-01T13:49:08.000Z
2021-03-06T06:54:26.000Z
#include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std; long n, k; vector<int> add(vector<int> num){ int n = num.size(); vector<int> re = num; vector<int> res; reverse(re.begin(), re.end()); int carry = 0; for(int i=0; i<n; i++){ int tmp = carry+num[i]+re[i]; carry = 0; if(tmp>=10){ carry = 1; tmp = tmp%10; } res.push_back(tmp); } if(carry) res.push_back(1); reverse(res.begin(), res.end()); return res; } bool judge(vector<int> nums){ auto re = nums; reverse(re.begin(), re.end()); if(nums==re) return true; else return false; } int main(void){ cin>>n>>k; if(n<=9){ cout<<n<<endl; cout<<0<<endl; return 0; } vector<int> num; while(n){ num.push_back(n%10); n = n/10; } reverse(num.begin(), num.end()); vector<int> res; for(int i=1; i<=k; i++){ res = add(num); if(judge(res)){ for(auto it:res) cout<<it; cout<<endl; cout<<i<<endl; return 0; } num = res; } for(auto it:res) cout<<it; cout<<endl; cout<<k<<endl; }
14.205479
33
0.580521
[ "vector" ]
342997ec6ccb26ba95138384b6e36f1ddabad68b
4,934
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/MeshOperations/MeshValidation_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.ProBuilder.MeshOperations.MeshValidation #include "UnityEngine/ProBuilder/MeshOperations/MeshValidation.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<TResult, T> template<typename TResult, typename T> class Func_2; // Forward declaring type: Func`2<TResult, T> template<typename TResult, typename T> class Func_2; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IEnumerable`1<T> template<typename T> class IEnumerable_1; } // Forward declaring namespace: UnityEngine::ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: Face class Face; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder.MeshOperations namespace UnityEngine::ProBuilder::MeshOperations { // Autogenerated type: UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c class MeshValidation::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c <>9 static UnityEngine::ProBuilder::MeshOperations::MeshValidation::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c <>9 static void _set_$$9(UnityEngine::ProBuilder::MeshOperations::MeshValidation::$$c* value); // Get static field: static public System.Func`2<UnityEngine.ProBuilder.Triangle,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__4_0 static System::Func_2<UnityEngine::ProBuilder::Triangle, System::Collections::Generic::IEnumerable_1<int>*>* _get_$$9__4_0(); // Set static field: static public System.Func`2<UnityEngine.ProBuilder.Triangle,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__4_0 static void _set_$$9__4_0(System::Func_2<UnityEngine::ProBuilder::Triangle, System::Collections::Generic::IEnumerable_1<int>*>* value); // Get static field: static public System.Func`2<UnityEngine.ProBuilder.Triangle,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__4_1 static System::Func_2<UnityEngine::ProBuilder::Triangle, System::Collections::Generic::IEnumerable_1<int>*>* _get_$$9__4_1(); // Set static field: static public System.Func`2<UnityEngine.ProBuilder.Triangle,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__4_1 static void _set_$$9__4_1(System::Func_2<UnityEngine::ProBuilder::Triangle, System::Collections::Generic::IEnumerable_1<int>*>* value); // Get static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__7_0 static System::Func_2<UnityEngine::ProBuilder::Face*, System::Collections::Generic::IEnumerable_1<int>*>* _get_$$9__7_0(); // Set static field: static public System.Func`2<UnityEngine.ProBuilder.Face,System.Collections.Generic.IEnumerable`1<System.Int32>> <>9__7_0 static void _set_$$9__7_0(System::Func_2<UnityEngine::ProBuilder::Face*, System::Collections::Generic::IEnumerable_1<int>*>* value); // static private System.Void .cctor() // Offset: 0x100C6A0 static void _cctor(); // System.Collections.Generic.IEnumerable`1<System.Int32> <EnsureFacesAreComposedOfContiguousTriangles>b__4_0(UnityEngine.ProBuilder.Triangle x) // Offset: 0x100C710 System::Collections::Generic::IEnumerable_1<int>* $EnsureFacesAreComposedOfContiguousTriangles$b__4_0(UnityEngine::ProBuilder::Triangle x); // System.Collections.Generic.IEnumerable`1<System.Int32> <EnsureFacesAreComposedOfContiguousTriangles>b__4_1(UnityEngine.ProBuilder.Triangle x) // Offset: 0x100C73C System::Collections::Generic::IEnumerable_1<int>* $EnsureFacesAreComposedOfContiguousTriangles$b__4_1(UnityEngine::ProBuilder::Triangle x); // System.Collections.Generic.IEnumerable`1<System.Int32> <RemoveUnusedVertices>b__7_0(UnityEngine.ProBuilder.Face x) // Offset: 0x100C768 System::Collections::Generic::IEnumerable_1<int>* $RemoveUnusedVertices$b__7_0(UnityEngine::ProBuilder::Face* x); // public System.Void .ctor() // Offset: 0x100C708 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static MeshValidation::$$c* New_ctor(); }; // UnityEngine.ProBuilder.MeshOperations.MeshValidation/<>c } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::MeshOperations::MeshValidation::$$c*, "UnityEngine.ProBuilder.MeshOperations", "MeshValidation/<>c"); #pragma pack(pop)
63.25641
149
0.758816
[ "object" ]
3433975ba4af81c7b3ffe3a02de4da9e2a5daca0
5,114
hpp
C++
include/elemental/blas-like/level3/TwoSidedTrmm.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
include/elemental/blas-like/level3/TwoSidedTrmm.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
include/elemental/blas-like/level3/TwoSidedTrmm.hpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef BLAS_TWOSIDEDTRMM_HPP #define BLAS_TWOSIDEDTRMM_HPP namespace elem { namespace internal { template<typename T> inline void TwoSidedTrmmLUnb( UnitOrNonUnit diag, Matrix<T>& A, const Matrix<T>& L ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrmmLUnb"); #endif // Use the Variant 4 algorithm // (which annoyingly requires conjugations for the Her2) const int n = A.Height(); const int lda = A.LDim(); const int ldl = L.LDim(); T* ABuffer = A.Buffer(); const T* LBuffer = L.LockedBuffer(); std::vector<T> a10Conj( n ), l10Conj( n ); for( int j=0; j<n; ++j ) { const int a21Height = n - (j+1); // Extract and store the diagonal values of A and L const T alpha11 = ABuffer[j+j*lda]; const T lambda11 = ( diag==UNIT ? 1 : LBuffer[j+j*ldl] ); // a10 := a10 + (alpha11/2)l10 T* a10 = &ABuffer[j]; const T* l10 = &LBuffer[j]; for( int k=0; k<j; ++k ) a10[k*lda] += (alpha11/2)*l10[k*ldl]; // A00 := A00 + (a10' l10 + l10' a10) T* A00 = ABuffer; for( int k=0; k<j; ++k ) a10Conj[k] = Conj(a10[k*lda]); for( int k=0; k<j; ++k ) l10Conj[k] = Conj(l10[k*ldl]); blas::Her2( 'L', j, T(1), &a10Conj[0], 1, &l10Conj[0], 1, A00, lda ); // a10 := a10 + (alpha11/2)l10 for( int k=0; k<j; ++k ) a10[k*lda] += (alpha11/2)*l10[k*ldl]; // a10 := conj(lambda11) a10 if( diag != UNIT ) for( int k=0; k<j; ++k ) a10[k*lda] *= Conj(lambda11); // alpha11 := alpha11 * |lambda11|^2 ABuffer[j+j*lda] *= Conj(lambda11)*lambda11; // A20 := A20 + a21 l10 T* a21 = &ABuffer[(j+1)+j*lda]; T* A20 = &ABuffer[j+1]; blas::Geru( a21Height, j, T(1), a21, 1, l10, ldl, A20, lda ); // a21 := lambda11 a21 if( diag != UNIT ) for( int k=0; k<a21Height; ++k ) a21[k] *= lambda11; } } template<typename T> inline void TwoSidedTrmmUUnb( UnitOrNonUnit diag, Matrix<T>& A, const Matrix<T>& U ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrmmUUnb"); #endif // Use the Variant 4 algorithm const int n = A.Height(); const int lda = A.LDim(); const int ldu = U.LDim(); T* ABuffer = A.Buffer(); const T* UBuffer = U.LockedBuffer(); for( int j=0; j<n; ++j ) { const int a21Height = n - (j+1); // Extract and store the diagonal values of A and U const T alpha11 = ABuffer[j+j*lda]; const T upsilon11 = ( diag==UNIT ? 1 : UBuffer[j+j*ldu] ); // a01 := a01 + (alpha11/2)u01 T* a01 = &ABuffer[j*lda]; const T* u01 = &UBuffer[j*ldu]; for( int k=0; k<j; ++k ) a01[k] += (alpha11/2)*u01[k]; // A00 := A00 + (u01 a01' + a01 u01') T* A00 = ABuffer; blas::Her2( 'U', j, T(1), u01, 1, a01, 1, A00, lda ); // a01 := a01 + (alpha11/2)u01 for( int k=0; k<j; ++k ) a01[k] += (alpha11/2)*u01[k]; // a01 := conj(upsilon11) a01 if( diag != UNIT ) for( int k=0; k<j; ++k ) a01[k] *= Conj(upsilon11); // A02 := A02 + u01 a12 T* a12 = &ABuffer[j+(j+1)*lda]; T* A02 = &ABuffer[(j+1)*lda]; blas::Geru( j, a21Height, T(1), u01, 1, a12, lda, A02, lda ); // alpha11 := alpha11 * |upsilon11|^2 ABuffer[j+j*lda] *= Conj(upsilon11)*upsilon11; // a12 := upsilon11 a12 if( diag != UNIT ) for( int k=0; k<a21Height; ++k ) a12[k*lda] *= upsilon11; } } } // namespace internal template<typename T> inline void LocalTwoSidedTrmm ( UpperOrLower uplo, UnitOrNonUnit diag, DistMatrix<T,STAR,STAR>& A, const DistMatrix<T,STAR,STAR>& B ) { #ifndef RELEASE CallStackEntry entry("LocalTwoSidedTrmm"); #endif TwoSidedTrmm( uplo, diag, A.Matrix(), B.LockedMatrix() ); } } // namespace elem #include "./TwoSidedTrmm/LVar4.hpp" #include "./TwoSidedTrmm/UVar4.hpp" namespace elem { template<typename T> inline void TwoSidedTrmm ( UpperOrLower uplo, UnitOrNonUnit diag, Matrix<T>& A, const Matrix<T>& B ) { #ifndef RELEASE CallStackEntry entry("TwoSidedTrmm"); #endif if( uplo == LOWER ) internal::TwoSidedTrmmLVar4( diag, A, B ); else internal::TwoSidedTrmmUVar4( diag, A, B ); } template<typename T> inline void TwoSidedTrmm ( UpperOrLower uplo, UnitOrNonUnit diag, DistMatrix<T>& A, const DistMatrix<T>& B ) { #ifndef RELEASE CallStackEntry entry("TwoSidedTrmm"); #endif if( uplo == LOWER ) internal::TwoSidedTrmmLVar4( diag, A, B ); else internal::TwoSidedTrmmUVar4( diag, A, B ); } } // namespace elem #endif // ifndef BLAS_TWOSIDEDTRMM_HPP
27.643243
77
0.559445
[ "vector" ]
343923f5dcfe2bea5acec15b7c69c164ac64a7c2
4,181
hpp
C++
segmatch/include/segmatch/segmenters/smoothness_constraints_segmenter.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
771
2018-04-21T06:47:18.000Z
2022-03-30T11:49:32.000Z
segmatch/include/segmatch/segmenters/smoothness_constraints_segmenter.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
111
2018-04-22T10:11:50.000Z
2022-03-21T02:16:12.000Z
segmatch/include/segmatch/segmenters/smoothness_constraints_segmenter.hpp
Oofs/segmap
98f1fddc15b863c781b78f59c65487be5e0dc497
[ "BSD-3-Clause" ]
287
2018-04-21T06:43:23.000Z
2022-03-24T17:45:05.000Z
#ifndef SEGMATCH_SMOOTHNESS_CONSTRAINTS_SEGMENTER_HPP_ #define SEGMATCH_SMOOTHNESS_CONSTRAINTS_SEGMENTER_HPP_ #include <string> #include "segmatch/parameters.hpp" #include "segmatch/common.hpp" #include "segmatch/segmented_cloud.hpp" #include "segmatch/segmenters/segmenter.hpp" namespace segmatch { // Forward declaration to speed up compilation time. class SegmentedCloud; /// \brief Region growing segmenter with smoothness constraints. Implementation of the approach /// described in "Segmentation of point clouds using smoothness constraint", T. Rabbania, /// F. A. van den Heuvelb, G. Vosselmanc. template<typename ClusteredPointT> class SmoothnessConstraintsSegmenter : public Segmenter<ClusteredPointT> { public: typedef pcl::PointCloud<ClusteredPointT> ClusteredCloud; static_assert(pcl::traits::has_xyz<ClusteredPointT>::value, "RegionGrowingSegmenter requires ClusteredPointT to contain XYZ " "coordinates."); /// \brief Initializes a new instance of the SmoothnessConstraintsSegmenter class. /// \param params The parameters of the segmenter.m explicit SmoothnessConstraintsSegmenter(const SegmenterParameters& params); /// \brief Cluster the given point cloud, writing the found segments in the segmented cloud. /// If cluster IDs change, the \c cluster_ids_to_segment_ids mapping is updated accordingly. /// \param normals The normal vectors of the point cloud. This can be an empty cloud if the /// the segmenter doesn't require normals. /// \param is_point_modified Indicates for each point if it has been modified such that its /// cluster assignment may change. /// \param cloud The point cloud that must be segmented. /// \param points_neighbors_provider Object providing nearest neighbors information. /// \param segmented_cloud Cloud to which the valid segments will be added. /// \param cluster_ids_to_segment_ids Mapping between cluster IDs and segment IDs. Cluster /// \c i generates segment \c cluster_ids_to_segments_ids[i]. If /// \c cluster_ids_to_segments_ids[i] is equal to zero, then the cluster does not contain enough /// points to be considered a segment. /// \param renamed_segments Vectors containing segments that got a new ID, e.g. after merging /// two or more segments. The ordering of the vector represents the sequence of renaming /// operations. The first ID in each pair is the renamed segments, the second ID is the new /// segment ID. void segment(const PointNormals& normals, const std::vector<bool>& is_point_modified, ClusteredCloud& cloud, PointsNeighborsProvider<MapPoint>& points_neighbors_provider, SegmentedCloud& segmented_cloud, std::vector<Id>& cluster_ids_to_segment_ids, std::vector<std::pair<Id, Id>>& renamed_segments) override; private: // Identify a cluster starting from the specified seed using the region-growing rules. int growRegionFromSeed(const PointNormals& normals, int seed, int cluster_id, PointsNeighborsProvider<MapPoint>& points_neighbors_provider, std::vector<int>& point_cluster_ids) const; // Determine if it's allowed to grow from a seed to a point. bool canGrowToPoint(const PointNormals& normals, int seed_index, int neighbor_index) const; // Determine if a point satisfies the requirements for being used as a seed. bool canPointBeSeed(const PclNormal& point_normal) const; // Transfer the segments to the segmented cloud. void storeSegments(const ClusteredCloud& cloud, const std::vector<int>& point_cluster_ids, const std::vector<int>& number_of_points_in_clusters, SegmentedCloud& segmented_cloud) const; // Parameters and shortcuts. const SegmenterParameters params_; const int min_segment_size_; const int max_segment_size_; const float angle_threshold_; const float curvature_threshold_; const float cosine_threshold_; const float radius_for_growing_; static constexpr int kUnassignedClusterId = -1; }; // class SmoothnessConstraintsSegmenter } // namespace segmatch #endif // SEGMATCH_SMOOTHNESS_CONSTRAINTS_SEGMENTER_HPP_
48.616279
99
0.758192
[ "object", "vector" ]
34392d1f81248dcf6029ba61334f6b9a5bc75bf3
1,139
cpp
C++
hackerrank/practice/data_structures/advanced/cube_summation__isp_tree.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/data_structures/advanced/cube_summation__isp_tree.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/data_structures/advanced/cube_summation__isp_tree.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/cube-summation #include "common/geometry/d3/base.h" #include "common/geometry/d3/point_io.h" #include "common/geometry/d3/vector.h" #include "common/geometry/kdtree/d3/isp_tree.h" #include "common/geometry/kdtree/info/sum.h" #include "common/stl/base.h" #include <string> using TPoint = geometry::d3::Point<unsigned>; using TVector = geometry::d3::Vector<unsigned>; using TTree = geometry::kdtree::D3ISPTree< unsigned, int64_t, geometry::kdtree::idata::None, geometry::kdtree::info::Sum<int64_t, geometry::kdtree::info::None>>; int main_cube_summation__isp_tree() { unsigned T, N, M; TPoint p1, p2; TVector v1(1, 1, 1); cin >> T; TTree tree; for (unsigned it = 0; it < T; ++it) { cin >> N >> M; tree.Init(TPoint(0, 0, 0), TPoint(N + 1, N + 1, N + 1)); for (unsigned im = 0; im < M; ++im) { string s; cin >> s; if (s == "UPDATE") { int64_t v; cin >> p1 >> v; tree.Set(p1, v); } else if (s == "QUERY") { cin >> p1 >> p2; cout << tree.GetInfo(p1, p2 + v1).sum << endl; } } } return 0; }
27.119048
72
0.597015
[ "geometry", "vector" ]
3443d4f34af328b60c484997f16bf3060f4cd20c
7,136
cpp
C++
IHMCPerception/third-party/kindr/test/rotations/eigen/LocalAngularVelocityTest.cpp
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
170
2016-02-01T18:58:50.000Z
2022-03-17T05:28:01.000Z
IHMCPerception/third-party/kindr/test/rotations/eigen/LocalAngularVelocityTest.cpp
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
162
2016-01-29T17:04:29.000Z
2022-02-10T16:25:37.000Z
IHMCPerception/third-party/kindr/test/rotations/eigen/LocalAngularVelocityTest.cpp
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
83
2016-01-28T22:49:01.000Z
2022-03-28T03:11:24.000Z
/* Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm * 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 Autonomous Systems Lab, ETH Zurich 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 Christian Gehring, Hannes Sommer, Paul Furgale, * Remo Diethelm 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 <iostream> #include <Eigen/Core> #include <gtest/gtest.h> #include "kindr/rotations/RotationDiffEigen.hpp" #include "kindr/common/gtest_eigen.hpp" namespace rot = kindr::rotations::eigen_impl; template <typename Implementation> struct LocalAngularVelocityTest: public ::testing::Test { typedef Implementation LocalAngularVelocity; typedef typename LocalAngularVelocity::Scalar Scalar; typedef Eigen::Matrix<Scalar, 3, 1> Vector3; Vector3 eigenVector3vZero = Vector3::Zero(); Vector3 eigenVector3v1 = Vector3(1.1, 2.2, 3.3); Vector3 eigenVector3v2 = Vector3(10,20,30); Vector3 eigenVector3v3 = Vector3(1,2,3); Vector3 eigenVector3vAdd2And3 = Vector3(11,22,33); Vector3 eigenVector3vSubtract3from2 = Vector3(9,18,27); LocalAngularVelocityTest() {} }; typedef ::testing::Types< rot::LocalAngularVelocityAD, rot::LocalAngularVelocityAF, rot::LocalAngularVelocityPD, rot::LocalAngularVelocityPF > LocalAngularVelocityTypes; TYPED_TEST_CASE(LocalAngularVelocityTest, LocalAngularVelocityTypes); TYPED_TEST(LocalAngularVelocityTest, testConstructors) { typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity; // default constructor LocalAngularVelocity angVel1; ASSERT_EQ(this->eigenVector3vZero.x(), angVel1.x()); ASSERT_EQ(this->eigenVector3vZero.y(), angVel1.y()); ASSERT_EQ(this->eigenVector3vZero.z(), angVel1.z()); // constructor with three values (x,y,z) LocalAngularVelocity angVel2(this->eigenVector3v1(0),this->eigenVector3v1(1),this->eigenVector3v1(2)); ASSERT_EQ(this->eigenVector3v1.x(), angVel2.x()); ASSERT_EQ(this->eigenVector3v1.y(), angVel2.y()); ASSERT_EQ(this->eigenVector3v1.z(), angVel2.z()); // constructor with Eigen vector LocalAngularVelocity angVel3(this->eigenVector3v1); ASSERT_EQ(this->eigenVector3v1.x(), angVel3.x()); ASSERT_EQ(this->eigenVector3v1.y(), angVel3.y()); ASSERT_EQ(this->eigenVector3v1.z(), angVel3.z()); // constructor with LocalAngularVelocity LocalAngularVelocity angVel4(angVel3); ASSERT_EQ(this->eigenVector3v1.x(), angVel4.x()); ASSERT_EQ(this->eigenVector3v1.y(), angVel4.y()); ASSERT_EQ(this->eigenVector3v1.z(), angVel4.z()); } TYPED_TEST(LocalAngularVelocityTest, testGetters) { typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity; // toImplementation LocalAngularVelocity angVel3(this->eigenVector3v1); ASSERT_EQ(this->eigenVector3v1.x(), angVel3.toImplementation()(0)); ASSERT_EQ(this->eigenVector3v1.y(), angVel3.toImplementation()(1)); ASSERT_EQ(this->eigenVector3v1.z(), angVel3.toImplementation()(2)); LocalAngularVelocity angVel2; angVel2.x() = this->eigenVector3v1.x(); angVel2.y() = this->eigenVector3v1.y(); angVel2.z() = this->eigenVector3v1.z(); ASSERT_EQ(this->eigenVector3v1.x(), angVel2.x()); ASSERT_EQ(this->eigenVector3v1.y(), angVel2.y()); ASSERT_EQ(this->eigenVector3v1.z(), angVel2.z()); } TYPED_TEST(LocalAngularVelocityTest, testSetters) { typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity; // setZero() LocalAngularVelocity angVel1(this->eigenVector3v1(0),this->eigenVector3v1(1),this->eigenVector3v1(2)); angVel1.setZero(); ASSERT_EQ(this->eigenVector3vZero.x(), angVel1.x()); ASSERT_EQ(this->eigenVector3vZero.y(), angVel1.y()); ASSERT_EQ(this->eigenVector3vZero.z(), angVel1.z()); } TYPED_TEST(LocalAngularVelocityTest, testAddition) { typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity; const LocalAngularVelocity angVel2(this->eigenVector3v2); const LocalAngularVelocity angVel3(this->eigenVector3v3); // addition LocalAngularVelocity velAdd = angVel2+angVel3; ASSERT_EQ(this->eigenVector3vAdd2And3.x(), velAdd.x()); ASSERT_EQ(this->eigenVector3vAdd2And3.y(), velAdd.y()); ASSERT_EQ(this->eigenVector3vAdd2And3.z(), velAdd.z()); // addition and assignment LocalAngularVelocity velAddandAssign(this->eigenVector3v2); velAddandAssign += angVel3; ASSERT_EQ(this->eigenVector3vAdd2And3.x(), velAddandAssign.x()); ASSERT_EQ(this->eigenVector3vAdd2And3.y(), velAddandAssign.y()); ASSERT_EQ(this->eigenVector3vAdd2And3.z(), velAddandAssign.z()); // subtract LocalAngularVelocity velSubtract = angVel2-angVel3; ASSERT_EQ(this->eigenVector3vSubtract3from2.x(), velSubtract.x()); ASSERT_EQ(this->eigenVector3vSubtract3from2.y(), velSubtract.y()); ASSERT_EQ(this->eigenVector3vSubtract3from2.z(), velSubtract.z()); // subtract and assignment LocalAngularVelocity velSubtractandAssign(this->eigenVector3v2); velSubtractandAssign -= angVel3; ASSERT_EQ(this->eigenVector3vSubtract3from2.x(), velSubtractandAssign.x()); ASSERT_EQ(this->eigenVector3vSubtract3from2.y(), velSubtractandAssign.y()); ASSERT_EQ(this->eigenVector3vSubtract3from2.z(), velSubtractandAssign.z()); } TYPED_TEST(LocalAngularVelocityTest, testMultiplication) { typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity; const LocalAngularVelocity angVel2(this->eigenVector3v2); const LocalAngularVelocity angVel3(this->eigenVector3v3); // multiplication 1 LocalAngularVelocity mult1 = angVel3 * 10.0; ASSERT_EQ(angVel2.x(), mult1.x()); ASSERT_EQ(angVel2.y(), mult1.y()); ASSERT_EQ(angVel2.z(), mult1.z()); // multiplication 2 LocalAngularVelocity mult2 = 10.0 * angVel3; ASSERT_EQ(angVel2.x(), mult2.x()); ASSERT_EQ(angVel2.y(), mult2.y()); ASSERT_EQ(angVel2.z(), mult2.z()); }
37.957447
104
0.759249
[ "vector" ]
34447efc7e455929ff01a39517f4a19d1ce93fde
17,386
cpp
C++
frameworks-ext/base/core/jni/android_bluetooth_HeadsetBase.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks-ext/base/core/jni/android_bluetooth_HeadsetBase.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks-ext/base/core/jni/android_bluetooth_HeadsetBase.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* ** Copyright 2006, The Android Open Source Project ** ** 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. */ #define LOG_TAG "BT HSHFP" #include "android_bluetooth_common.h" #include "android_runtime/AndroidRuntime.h" #include "JNIHelp.h" #include "jni.h" #include "utils/Log.h" #include "utils/misc.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/uio.h> #include <sys/poll.h> #ifdef HAVE_BLUETOOTH #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm.h> #include <bluetooth/sco.h> #endif namespace android { #ifdef HAVE_BLUETOOTH static jfieldID field_mNativeData; static jfieldID field_mAddress; static jfieldID field_mRfcommChannel; static jfieldID field_mTimeoutRemainingMs; typedef struct { jstring address; const char *c_address; int rfcomm_channel; int last_read_err; int rfcomm_sock; int rfcomm_connected; // -1 in progress, 0 not connected, 1 connected int rfcomm_sock_flags; } native_data_t; static inline native_data_t * get_native_data(JNIEnv *env, jobject object) { return (native_data_t *)(env->GetIntField(object, field_mNativeData)); } static const char CRLF[] = "\xd\xa"; static const int CRLF_LEN = 2; static inline int write_error_check(int fd, const char* line, int len) { int ret; errno = 0; ret = write(fd, line, len); if (ret < 0) { ALOGE("%s: write() failed: %s (%d)", __FUNCTION__, strerror(errno), errno); return -1; } if (ret != len) { ALOGE("%s: write() only wrote %d of %d bytes", __FUNCTION__, ret, len); return -1; } return 0; } static int send_line(int fd, const char* line) { int nw; int len = strlen(line); int llen = len + CRLF_LEN * 2 + 1; char *buffer = (char *)calloc(llen, sizeof(char)); snprintf(buffer, llen, "%s%s%s", CRLF, line, CRLF); if (write_error_check(fd, buffer, llen - 1)) { free(buffer); return -1; } free(buffer); return 0; } static void mask_eighth_bit(char *line) { for (;;line++) { if (0 == *line) return; *line &= 0x7F; } } static const char* get_line(int fd, char *buf, int len, int timeout_ms, int *err) { char *bufit=buf; int fd_flags = fcntl(fd, F_GETFL, 0); struct pollfd pfd; again: *bufit = 0; pfd.fd = fd; pfd.events = POLLIN; *err = errno = 0; int ret = TEMP_FAILURE_RETRY(poll(&pfd, 1, timeout_ms)); if (ret < 0) { ALOGE("poll() error\n"); *err = errno; return NULL; } if (ret == 0) { return NULL; } if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) { ALOGW("RFCOMM poll() returned success (%d), " "but with an unexpected revents bitmask: %#x\n", ret, pfd.revents); errno = EIO; *err = errno; return NULL; } while ((int)(bufit - buf) < (len - 1)) { errno = 0; int rc = TEMP_FAILURE_RETRY(read(fd, bufit, 1)); if (!rc) break; if (rc < 0) { if (errno == EBUSY) { ALOGI("read() error %s (%d): repeating read()...", strerror(errno), errno); goto again; } *err = errno; ALOGE("read() error %s (%d)", strerror(errno), errno); return NULL; } if (*bufit=='\xd') { break; } if (*bufit=='\xa') bufit = buf; else bufit++; } *bufit = 0; // According to ITU V.250 section 5.1, IA5 7 bit chars are used, // the eighth bit or higher bits are ignored if they exists // We mask out only eighth bit, no higher bit, since we do char // string here, not wide char. // We added this processing due to 2 real world problems. // 1 BMW 2005 E46 which sends binary junk // 2 Audi 2010 A3, dial command use 0xAD (soft-hyphen) as number // formater, which was rejected by the AT handler mask_eighth_bit(buf); return buf; } #endif static void classInitNative(JNIEnv* env, jclass clazz) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH field_mNativeData = get_field(env, clazz, "mNativeData", "I"); field_mAddress = get_field(env, clazz, "mAddress", "Ljava/lang/String;"); field_mTimeoutRemainingMs = get_field(env, clazz, "mTimeoutRemainingMs", "I"); field_mRfcommChannel = get_field(env, clazz, "mRfcommChannel", "I"); #endif } static void initializeNativeDataNative(JNIEnv* env, jobject object, jint socketFd) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH native_data_t *nat = (native_data_t *)calloc(1, sizeof(native_data_t)); if (NULL == nat) { ALOGE("%s: out of memory!", __FUNCTION__); return; } env->SetIntField(object, field_mNativeData, (jint)nat); nat->address = (jstring)env->NewGlobalRef(env->GetObjectField(object, field_mAddress)); nat->c_address = env->GetStringUTFChars(nat->address, NULL); nat->rfcomm_channel = env->GetIntField(object, field_mRfcommChannel); nat->rfcomm_sock = socketFd; nat->rfcomm_connected = socketFd >= 0; if (nat->rfcomm_connected) ALOGI("%s: ALREADY CONNECTED!", __FUNCTION__); #endif } static void cleanupNativeDataNative(JNIEnv* env, jobject object) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH native_data_t *nat = (native_data_t *)env->GetIntField(object, field_mNativeData); env->ReleaseStringUTFChars(nat->address, nat->c_address); env->DeleteGlobalRef(nat->address); if (nat) free(nat); #endif } static jboolean connectNative(JNIEnv *env, jobject obj) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH int lm; struct sockaddr_rc addr; native_data_t *nat = get_native_data(env, obj); nat->rfcomm_sock = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); if (nat->rfcomm_sock < 0) { ALOGE("%s: Could not create RFCOMM socket: %s\n", __FUNCTION__, strerror(errno)); return JNI_FALSE; } if (debug_no_encrypt()) { lm = RFCOMM_LM_AUTH; } else { lm = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT; } if (lm && setsockopt(nat->rfcomm_sock, SOL_RFCOMM, RFCOMM_LM, &lm, sizeof(lm)) < 0) { ALOGE("%s: Can't set RFCOMM link mode", __FUNCTION__); close(nat->rfcomm_sock); return JNI_FALSE; } memset(&addr, 0, sizeof(struct sockaddr_rc)); get_bdaddr(nat->c_address, &addr.rc_bdaddr); addr.rc_channel = nat->rfcomm_channel; addr.rc_family = AF_BLUETOOTH; nat->rfcomm_connected = 0; while (nat->rfcomm_connected == 0) { if (connect(nat->rfcomm_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { if (errno == EINTR) continue; ALOGE("%s: connect() failed: %s\n", __FUNCTION__, strerror(errno)); close(nat->rfcomm_sock); nat->rfcomm_sock = -1; return JNI_FALSE; } else { nat->rfcomm_connected = 1; } } return JNI_TRUE; #else return JNI_FALSE; #endif } static jint connectAsyncNative(JNIEnv *env, jobject obj) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH struct sockaddr_rc addr; native_data_t *nat = get_native_data(env, obj); if (nat->rfcomm_connected) { ALOGV("RFCOMM socket is already connected or connection is in progress."); return 0; } if (nat->rfcomm_sock < 0) { int lm; nat->rfcomm_sock = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); if (nat->rfcomm_sock < 0) { ALOGE("%s: Could not create RFCOMM socket: %s\n", __FUNCTION__, strerror(errno)); return -1; } if (debug_no_encrypt()) { lm = RFCOMM_LM_AUTH; } else { lm = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT; } if (lm && setsockopt(nat->rfcomm_sock, SOL_RFCOMM, RFCOMM_LM, &lm, sizeof(lm)) < 0) { ALOGE("%s: Can't set RFCOMM link mode", __FUNCTION__); close(nat->rfcomm_sock); return -1; } ALOGI("Created RFCOMM socket fd %d.", nat->rfcomm_sock); } memset(&addr, 0, sizeof(struct sockaddr_rc)); get_bdaddr(nat->c_address, &addr.rc_bdaddr); addr.rc_channel = nat->rfcomm_channel; addr.rc_family = AF_BLUETOOTH; if (nat->rfcomm_sock_flags >= 0) { nat->rfcomm_sock_flags = fcntl(nat->rfcomm_sock, F_GETFL, 0); if (fcntl(nat->rfcomm_sock, F_SETFL, nat->rfcomm_sock_flags | O_NONBLOCK) >= 0) { int rc; nat->rfcomm_connected = 0; errno = 0; rc = connect(nat->rfcomm_sock, (struct sockaddr *)&addr, sizeof(addr)); if (rc >= 0) { nat->rfcomm_connected = 1; ALOGI("async connect successful"); return 0; } else if (rc < 0) { if (errno == EINPROGRESS || errno == EAGAIN) { ALOGI("async connect is in progress (%s)", strerror(errno)); nat->rfcomm_connected = -1; return 0; } else { ALOGE("async connect error: %s (%d)", strerror(errno), errno); close(nat->rfcomm_sock); nat->rfcomm_sock = -1; return -errno; } } } // fcntl(nat->rfcomm_sock ...) } // if (nat->rfcomm_sock_flags >= 0) #endif return -1; } static jint waitForAsyncConnectNative(JNIEnv *env, jobject obj, jint timeout_ms) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH struct sockaddr_rc addr; native_data_t *nat = get_native_data(env, obj); env->SetIntField(obj, field_mTimeoutRemainingMs, timeout_ms); if (nat->rfcomm_connected > 0) { ALOGI("RFCOMM is already connected!"); return 1; } if (nat->rfcomm_sock >= 0 && nat->rfcomm_connected == 0) { ALOGI("Re-opening RFCOMM socket."); close(nat->rfcomm_sock); nat->rfcomm_sock = -1; } int ret = connectAsyncNative(env, obj); if (ret < 0) { ALOGI("Failed to re-open RFCOMM socket!"); return ret; } if (nat->rfcomm_sock >= 0) { /* Do an asynchronous select() */ int n; fd_set rset, wset; struct timeval to; FD_ZERO(&rset); FD_ZERO(&wset); FD_SET(nat->rfcomm_sock, &rset); FD_SET(nat->rfcomm_sock, &wset); if (timeout_ms >= 0) { to.tv_sec = timeout_ms / 1000; to.tv_usec = 1000 * (timeout_ms % 1000); } n = select(nat->rfcomm_sock + 1, &rset, &wset, NULL, (timeout_ms < 0 ? NULL : &to)); if (timeout_ms > 0) { jint remaining = to.tv_sec*1000 + to.tv_usec/1000; ALOGV("Remaining time %ldms", (long)remaining); env->SetIntField(obj, field_mTimeoutRemainingMs, remaining); } if (n <= 0) { if (n < 0) { ALOGE("select() on RFCOMM socket: %s (%d)", strerror(errno), errno); return -errno; } return 0; } /* n must be equal to 1 and either rset or wset must have the file descriptor set. */ ALOGV("select() returned %d.", n); if (FD_ISSET(nat->rfcomm_sock, &rset) || FD_ISSET(nat->rfcomm_sock, &wset)) { /* A trial async read() will tell us if everything is OK. */ { char ch; errno = 0; int nr = TEMP_FAILURE_RETRY(read(nat->rfcomm_sock, &ch, 1)); /* It should be that nr != 1 because we just opened a socket and we haven't sent anything over it for the other side to respond... but one can't be paranoid enough. */ if (nr >= 0 || errno != EAGAIN) { ALOGE("RFCOMM async connect() error: %s (%d), nr = %d\n", strerror(errno), errno, nr); /* Clear the rfcomm_connected flag to cause this function to re-create the socket and re-attempt the connect() the next time it is called. */ nat->rfcomm_connected = 0; /* Restore the blocking properties of the socket. */ fcntl(nat->rfcomm_sock, F_SETFL, nat->rfcomm_sock_flags); close(nat->rfcomm_sock); nat->rfcomm_sock = -1; return -errno; } } /* Restore the blocking properties of the socket. */ fcntl(nat->rfcomm_sock, F_SETFL, nat->rfcomm_sock_flags); ALOGI("Successful RFCOMM socket connect."); nat->rfcomm_connected = 1; return 1; } } else ALOGE("RFCOMM socket file descriptor %d is bad!", nat->rfcomm_sock); #endif return -1; } static void disconnectNative(JNIEnv *env, jobject obj) { ALOGV("%s", __FUNCTION__); #ifdef HAVE_BLUETOOTH native_data_t *nat = get_native_data(env, obj); if (nat->rfcomm_sock >= 0) { close(nat->rfcomm_sock); nat->rfcomm_sock = -1; nat->rfcomm_connected = 0; } #endif } static void pretty_log_urc(const char *urc) { size_t i; bool in_line_break = false; char *buf = (char *)calloc(strlen(urc) + 1, sizeof(char)); strcpy(buf, urc); for (i = 0; i < strlen(buf); i++) { switch(buf[i]) { case '\r': case '\n': in_line_break = true; buf[i] = ' '; break; default: if (in_line_break) { in_line_break = false; buf[i-1] = '\n'; } } } IF_ALOGV() ALOG(LOG_VERBOSE, "Bluetooth AT sent", "%s", buf); free(buf); } static jboolean sendURCNative(JNIEnv *env, jobject obj, jstring urc) { #ifdef HAVE_BLUETOOTH native_data_t *nat = get_native_data(env, obj); if (nat->rfcomm_connected) { const char *c_urc = env->GetStringUTFChars(urc, NULL); jboolean ret = send_line(nat->rfcomm_sock, c_urc) == 0 ? JNI_TRUE : JNI_FALSE; if (ret == JNI_TRUE) pretty_log_urc(c_urc); env->ReleaseStringUTFChars(urc, c_urc); return ret; } #endif return JNI_FALSE; } static jstring readNative(JNIEnv *env, jobject obj, jint timeout_ms) { #ifdef HAVE_BLUETOOTH { native_data_t *nat = get_native_data(env, obj); if (nat->rfcomm_connected) { char buf[256]; const char *ret = get_line(nat->rfcomm_sock, buf, sizeof(buf), timeout_ms, &nat->last_read_err); return ret ? env->NewStringUTF(ret) : NULL; } return NULL; } #else return NULL; #endif } static jint getLastReadStatusNative(JNIEnv *env, jobject obj) { #ifdef HAVE_BLUETOOTH { native_data_t *nat = get_native_data(env, obj); if (nat->rfcomm_connected) return (jint)nat->last_read_err; return 0; } #else return 0; #endif } static JNINativeMethod sMethods[] = { /* name, signature, funcPtr */ {"classInitNative", "()V", (void*)classInitNative}, {"initializeNativeDataNative", "(I)V", (void *)initializeNativeDataNative}, {"cleanupNativeDataNative", "()V", (void *)cleanupNativeDataNative}, {"connectNative", "()Z", (void *)connectNative}, {"connectAsyncNative", "()I", (void *)connectAsyncNative}, {"waitForAsyncConnectNative", "(I)I", (void *)waitForAsyncConnectNative}, {"disconnectNative", "()V", (void *)disconnectNative}, {"sendURCNative", "(Ljava/lang/String;)Z", (void *)sendURCNative}, {"readNative", "(I)Ljava/lang/String;", (void *)readNative}, {"getLastReadStatusNative", "()I", (void *)getLastReadStatusNative}, }; int register_android_bluetooth_HeadsetBase(JNIEnv *env) { return AndroidRuntime::registerNativeMethods(env, "android/bluetooth/HeadsetBase", sMethods, NELEM(sMethods)); } } /* namespace android */
30.609155
86
0.561199
[ "object" ]
451764003bf270991eaf7919b571e3d405437384
2,397
cpp
C++
src/TrainTractionCalculation.cpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
src/TrainTractionCalculation.cpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
src/TrainTractionCalculation.cpp
Yaohui1996/Yaohui-Master-Thesis
e76f92990c2ce641f3394e7dad789543421878bd
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <string> #include <vector> #include "TractionCalculator.hpp" using namespace std; using namespace yaohui; int main() { TractionCalculator traction_calculator; // traction_calculator.calculate_power_time_data_0_to_40(); traction_calculator.show(); cout << traction_calculator.v_P_limit() << endl; cout << traction_calculator.time_to_P_limit() << endl; // 加速阶段 auto W_map = traction_calculator.accelerating_stage_W(30.0); vector<double> W_acc_stage(30, 0.0); // 加速阶段每一秒钟内做功的值 for (const auto &item : W_map) { size_t index = floor(item.first); W_acc_stage.at(index) += (item.second / 1000.0); // (kJ) } for (size_t i = 0; i != W_acc_stage.size(); ++i) { cout << "区间: " << i << " 做功: " << W_acc_stage.at(i) << endl; } // 输出用能关系表 ofstream of; of.open("W_consume.csv", std::ios::out); if (!of.is_open()) { cout << "文件[W_consume.csv]打开失败!" << endl; } // 写入数据 for (const auto &p : W_map) { of << to_string(p.first) << "," << to_string(p.second) << "\n"; } of.close(); // 输出用能关系曲线(按秒) of.open("W_consume_second.csv", std::ios::out); if (!of.is_open()) { cout << "文件[W_consume_second.csv]打开失败!" << endl; } // 写入数据 for (const auto &item : W_acc_stage) { of << to_string(item) << "\n"; } of.close(); // 再生制动阶段 auto W_brake_map = traction_calculator.brake_stage_W(15); vector<double> W_brake_stage(15, 0.0); // 制动阶段每一秒内产生的再生能量(kJ) for (const auto &item : W_brake_map) { size_t index = floor(item.first); W_brake_stage.at(index) += (item.second / 1000.0); } // 反转 std::reverse(W_brake_stage.begin(), W_brake_stage.end()); for (size_t i = 0; i != W_brake_stage.size(); ++i) { cout << "区间: " << i << " 再生能量: " << W_brake_stage.at(i) << endl; } // 输出用能关系表 of.open("W_produce.csv", std::ios::out); if (!of.is_open()) { cout << "文件[W_produce.csv]打开失败!" << endl; } // 写入数据 for (const auto &p : W_brake_map) { of << to_string(15.0 - p.first) << "," << to_string(p.second) << "\n"; } of.close(); // 输出用能关系曲线(按秒) of.open("W_produce_second.csv", std::ios::out); if (!of.is_open()) { cout << "文件[W_consume_second.csv]打开失败!" << endl; } // 写入数据 for (const auto &item : W_brake_stage) { of << to_string(item) << "\n"; } of.close(); return 0; }
26.054348
74
0.610763
[ "vector" ]
4518b28713c9d3b933bcbe44a43728e054cc492a
23,927
cpp
C++
external/openglcts/modules/glesext/texture_cube_map_array/esextcTextureCubeMapArraySubImage3D.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
external/openglcts/modules/glesext/texture_cube_map_array/esextcTextureCubeMapArraySubImage3D.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
external/openglcts/modules/glesext/texture_cube_map_array/esextcTextureCubeMapArraySubImage3D.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2014-2016 The Khronos Group 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. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /*! * \file esextcTextureCubeMapArraySubImage3D.cpp * \brief Texture Cube Map Array SubImage3D (Test 5) */ /*-------------------------------------------------------------------*/ #include "esextcTextureCubeMapArraySubImage3D.hpp" #include "gluContextInfo.hpp" #include "gluDefs.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuTestLog.hpp" #include <string.h> namespace glcts { const glw::GLuint TextureCubeMapArraySubImage3D::m_n_components = 4; const glw::GLuint TextureCubeMapArraySubImage3D::m_n_dimensions = 3; const glw::GLuint TextureCubeMapArraySubImage3D::m_n_resolutions = 4; const glw::GLuint TextureCubeMapArraySubImage3D::m_n_storage_type = 2; /* Helper arrays for tests configuration */ /* Different texture resolutions */ const glw::GLuint resolutions[TextureCubeMapArraySubImage3D::m_n_resolutions] [TextureCubeMapArraySubImage3D::m_n_dimensions] = { /* Width , Height, Depth */ { 32, 32, 12 }, { 64, 64, 12 }, { 16, 16, 18 }, { 16, 16, 24 } }; /* Location of dimension in array with texture resolutions */ enum Dimensions_Location { DL_WIDTH = 0, DL_HEIGHT = 1, DL_DEPTH = 2 }; /** Constructor * * @param context Test context * @param name Test case's name * @param description Test case's description */ TextureCubeMapArraySubImage3D::TextureCubeMapArraySubImage3D(Context& context, const ExtParameters& extParams, const char* name, const char* description) : TestCaseBase(context, extParams, name, description) , m_read_fbo_id(0) , m_pixel_buffer_id(0) , m_tex_cube_map_array_id(0) , m_tex_2d_id(0) { /* Nothing to be done here */ } /** Initialize test case */ void TextureCubeMapArraySubImage3D::initTest(void) { /* Check if texture_cube_map_array extension is supported */ if (!m_is_texture_cube_map_array_supported) { throw tcu::NotSupportedError(TEXTURE_CUBE_MAP_ARRAY_EXTENSION_NOT_SUPPORTED, "", __FILE__, __LINE__); } /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.genFramebuffers(1, &m_read_fbo_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Error generating frame buffer object!"); gl.bindFramebuffer(GL_READ_FRAMEBUFFER, m_read_fbo_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Error binding frame buffer object!"); } /** Deinitialize test case */ void TextureCubeMapArraySubImage3D::deinit(void) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Reset GLES configuration */ gl.bindFramebuffer(GL_READ_FRAMEBUFFER, 0); /* Delete GLES objects */ if (m_read_fbo_id != 0) { gl.deleteFramebuffers(1, &m_read_fbo_id); m_read_fbo_id = 0; } /* Delete pixel unpack buffer */ deletePixelUnpackBuffer(); /* Delete cube map array texture */ deleteCubeMapArrayTexture(); /* Delete 2D texture */ delete2DTexture(); /* Deinitialize base class */ TestCaseBase::deinit(); } /** Executes the test. * * Sets the test result to QP_TEST_RESULT_FAIL if the test failed, QP_TEST_RESULT_PASS otherwise. * * Note the function throws exception should an error occur! * * @return STOP if the test has finished, CONTINUE to indicate iterate() should be called once again. */ tcu::TestCase::IterateResult TextureCubeMapArraySubImage3D::iterate() { initTest(); glw::GLboolean test_passed = true; /* Execute test throught all storage types */ for (glw::GLuint storage_index = 0; storage_index < m_n_storage_type; ++storage_index) { /* Execute test throught all texture resolutions */ for (glw::GLuint resolution_index = 0; resolution_index < m_n_resolutions; ++resolution_index) { glw::GLuint width = resolutions[resolution_index][DL_WIDTH]; glw::GLuint height = resolutions[resolution_index][DL_HEIGHT]; glw::GLuint depth = resolutions[resolution_index][DL_DEPTH]; configureCubeMapArrayTexture(width, height, depth, static_cast<STORAGE_TYPE>(storage_index), 0); /* A single whole layer-face at index 0 should be replaced (both functions) */ SubImage3DCopyParams copy_params; copy_params.init(0, 0, 0, width, height, 1); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); configure2DTexture(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); testCopyTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); delete2DTexture(); /* A region of a layer-face at index 0 should be replaced (both functions) */ copy_params.init(width / 2, height / 2, 0, width / 2, height / 2, 1); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); configure2DTexture(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); testCopyTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); delete2DTexture(); /* 6 layer-faces, making up a single layer, should be replaced (glTexSubImage3D() only) */ copy_params.init(0, 0, 0, width, height, 6); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); /* 6 layer-faces, making up two different layers (for instance: three last layer-faces of layer 1 and three first layer-faces of layer 2) should be replaced (glTexSubImage3D() only) */ copy_params.init(0, 0, 3, width, height, 6); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); /* 6 layer-faces, making up a single layer, should be replaced (glTexSubImage3D() only), but limited to a quad */ copy_params.init(width / 2, height / 2, 0, width / 2, height / 2, 6); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); /* 6 layer-faces, making up two different layers (for instance: three last layer-faces of layer 1 and three first layer-faces of layer 2) should be replaced (glTexSubImage3D() only), but limited to a quad */ copy_params.init(width / 2, height / 2, 3, width / 2, height / 2, 6); configureDataBuffer(width, height, depth, copy_params, 0); configurePixelUnpackBuffer(copy_params); testTexSubImage3D(width, height, depth, copy_params, test_passed); deletePixelUnpackBuffer(); deleteCubeMapArrayTexture(); } } if (test_passed) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } /** Resizes data buffer and fills it with values * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @param copy_params - data structure specifying which region of the data store to replace * @param clear_value - value with which to fill the data buffer outside of region specified by copy_params */ void TextureCubeMapArraySubImage3D::configureDataBuffer(glw::GLuint width, glw::GLuint height, glw::GLuint depth, const SubImage3DCopyParams& copy_params, glw::GLuint clear_value) { glw::GLuint index = 0; m_copy_data_buffer.assign(copy_params.m_width * copy_params.m_height * copy_params.m_depth * m_n_components, clear_value); for (glw::GLuint zoffset = copy_params.m_zoffset; zoffset < copy_params.m_zoffset + copy_params.m_depth; ++zoffset) { for (glw::GLuint yoffset = copy_params.m_yoffset; yoffset < copy_params.m_yoffset + copy_params.m_height; ++yoffset) { for (glw::GLuint xoffset = copy_params.m_xoffset; xoffset < copy_params.m_xoffset + copy_params.m_width; ++xoffset) { for (glw::GLuint component = 0; component < m_n_components; ++component) { m_copy_data_buffer[index++] = (zoffset * width * height + yoffset * width + xoffset) * m_n_components + component; } } } } m_expected_data_buffer.assign(width * height * depth * m_n_components, clear_value); for (glw::GLuint zoffset = copy_params.m_zoffset; zoffset < copy_params.m_zoffset + copy_params.m_depth; ++zoffset) { for (glw::GLuint yoffset = copy_params.m_yoffset; yoffset < copy_params.m_yoffset + copy_params.m_height; ++yoffset) { for (glw::GLuint xoffset = copy_params.m_xoffset; xoffset < copy_params.m_xoffset + copy_params.m_width; ++xoffset) { glw::GLuint* data_pointer = &m_expected_data_buffer[(zoffset * width * height + yoffset * width + xoffset) * m_n_components]; for (glw::GLuint component = 0; component < m_n_components; ++component) { data_pointer[component] = (zoffset * width * height + yoffset * width + xoffset) * m_n_components + component; } } } } } /** Creates a pixel unpack buffer that will be used as data source for filling a region of cube map array texture with data * @param copy_params - data structure specifying which region of the data store to replace */ void TextureCubeMapArraySubImage3D::configurePixelUnpackBuffer(const SubImage3DCopyParams& copy_params) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* generate buffer for pixel unpack buffer */ gl.genBuffers(1, &m_pixel_buffer_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not generate buffer object!"); /* bind buffer to PIXEL_UNPACK_BUFFER binding point */ gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, m_pixel_buffer_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not bind buffer object!"); /* fill buffer with data */ gl.bufferData(GL_PIXEL_UNPACK_BUFFER, copy_params.m_width * copy_params.m_height * copy_params.m_depth * m_n_components * sizeof(glw::GLuint), &m_copy_data_buffer[0], GL_STATIC_READ); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not fill buffer object's data store with data!"); gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not bind buffer object!"); } /** Creates cube map array texture and fills it with data * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @param storType - mutable or immutable storage type * @param clear_value - value with which to initialize the texture's data store */ void TextureCubeMapArraySubImage3D::configureCubeMapArrayTexture(glw::GLuint width, glw::GLuint height, glw::GLuint depth, STORAGE_TYPE storType, glw::GLuint clear_value) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.genTextures(1, &m_tex_cube_map_array_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Error generating texture object!"); gl.bindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, m_tex_cube_map_array_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Error binding texture object!"); /* used glTexImage3D() method if texture should be MUTABLE */ if (storType == ST_MUTABLE) { gl.texParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Error setting texture parameter."); gl.texParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAX_LEVEL, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Error setting texture parameter."); DataBufferVec data_buffer(width * height * depth * m_n_components, clear_value); gl.texImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, GL_RGBA32UI, width, height, depth, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, &data_buffer[0]); GLU_EXPECT_NO_ERROR(gl.getError(), "Error allocating texture object's data store"); } /* used glTexStorage3D() method if texture should be IMMUTABLE */ else { gl.texStorage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 1, GL_RGBA32UI, width, height, depth); GLU_EXPECT_NO_ERROR(gl.getError(), "Error allocating texture object's data store"); clearCubeMapArrayTexture(width, height, depth, clear_value); } } /** Fills cube map array texture's data store with data * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @param clear_value - value with which to fill the texture's data store */ void TextureCubeMapArraySubImage3D::clearCubeMapArrayTexture(glw::GLuint width, glw::GLuint height, glw::GLuint depth, glw::GLuint clear_value) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); DataBufferVec data_buffer(width * height * depth * m_n_components, clear_value); gl.texSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, 0, 0, 0, width, height, depth, GL_RGBA_INTEGER, GL_UNSIGNED_INT, &data_buffer[0]); GLU_EXPECT_NO_ERROR(gl.getError(), "Error filling texture object's data store with data"); } /** Creates 2D texture that will be used as data source by the glCopyTexSubImage3D call * @param copy_params - data structure specifying which region of the data store to replace */ void TextureCubeMapArraySubImage3D::configure2DTexture(const SubImage3DCopyParams& copy_params) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.genTextures(1, &m_tex_2d_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not generate texture object!"); gl.bindTexture(GL_TEXTURE_2D, m_tex_2d_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not bind texture object!"); gl.texStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32UI, copy_params.m_width, copy_params.m_height); GLU_EXPECT_NO_ERROR(gl.getError(), "Error allocating texture object's data store"); gl.texSubImage2D(GL_TEXTURE_2D, 0, 0, 0, copy_params.m_width, copy_params.m_height, GL_RGBA_INTEGER, GL_UNSIGNED_INT, &m_copy_data_buffer[0]); GLU_EXPECT_NO_ERROR(gl.getError(), "Error filling texture object's data store with data"); } /** Replaces region of cube map array texture's data store using texSubImage3D function * @param copy_params - data structure specifying which region of the data store to replace * @param data_pointer - pointer to the data that should end up in the specified region of the data store */ void TextureCubeMapArraySubImage3D::texSubImage3D(const SubImage3DCopyParams& copy_params, const glw::GLuint* data_pointer) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.texSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, copy_params.m_xoffset, copy_params.m_yoffset, copy_params.m_zoffset, copy_params.m_width, copy_params.m_height, copy_params.m_depth, GL_RGBA_INTEGER, GL_UNSIGNED_INT, data_pointer); GLU_EXPECT_NO_ERROR(gl.getError(), "Error filling texture object's data store with data"); } /** Replaces region of cube map array texture's data store using copyTexSubImage3D function * @param copy_params - data structure specifying which region of the data store to replace */ void TextureCubeMapArraySubImage3D::copyTexSubImage3D(const SubImage3DCopyParams& copy_params) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.framebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_tex_2d_id, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not attach texture object to framebuffer's attachment"); checkFramebufferStatus(GL_READ_FRAMEBUFFER); gl.copyTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, copy_params.m_xoffset, copy_params.m_yoffset, copy_params.m_zoffset, 0, 0, copy_params.m_width, copy_params.m_height); GLU_EXPECT_NO_ERROR(gl.getError(), "Error filling texture object's data store with data"); } /** Compares the region of data specified by copy_params taken from the cube map array texture's data store with * the reference data stored in m_data_buffer. * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @return - true if the result of comparison is that the regions contain the same data, false otherwise */ bool TextureCubeMapArraySubImage3D::checkResults(glw::GLuint width, glw::GLuint height, glw::GLuint depth) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); glw::GLuint n_elements = width * height * depth * m_n_components; DataBufferVec result_data_buffer(n_elements, 0); for (glw::GLuint layer_nr = 0; layer_nr < depth; ++layer_nr) { /* attach one layer to framebuffer's attachment */ gl.framebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_tex_cube_map_array_id, 0, layer_nr); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not attach texture object to framebuffer's attachment"); /* check framebuffer status */ checkFramebufferStatus(GL_READ_FRAMEBUFFER); /* read data from the texture */ gl.readPixels(0, 0, width, height, GL_RGBA_INTEGER, GL_UNSIGNED_INT, &result_data_buffer[layer_nr * width * height * m_n_components]); GLU_EXPECT_NO_ERROR(gl.getError(), "Could not read pixels from framebuffer's attachment!"); } return memcmp(&result_data_buffer[0], &m_expected_data_buffer[0], n_elements * sizeof(glw::GLuint)) == 0; } /** Perform a full test of testTexSubImage3D function on cube map array texture, both with client pointer and pixel unpack buffer * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @param copy_params - data structure specifying which region of the cube map array to test * @param test_passed - a boolean variable set to false if at any stage of the test we experience wrong result */ void TextureCubeMapArraySubImage3D::testTexSubImage3D(glw::GLuint width, glw::GLuint height, glw::GLuint depth, const SubImage3DCopyParams& copy_params, glw::GLboolean& test_passed) { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); clearCubeMapArrayTexture(width, height, depth, 0); texSubImage3D(copy_params, &m_copy_data_buffer[0]); if (!checkResults(width, height, depth)) { m_testCtx.getLog() << tcu::TestLog::Message << "glTexSubImage3D failed to copy data to texture cube map array's data store from client's memory\n" << "Texture Cube Map Array Dimensions (width, height, depth) " << "(" << width << "," << height << "," << depth << ")\n" << "Texture Cube Map Array Offsets (xoffset, yoffset, zoffset) " << "(" << copy_params.m_xoffset << "," << copy_params.m_yoffset << "," << copy_params.m_zoffset << ")\n" << "Texture Cube Map Array Copy Size (width, height, depth) " << "(" << copy_params.m_width << "," << copy_params.m_height << "," << copy_params.m_depth << ")\n" << tcu::TestLog::EndMessage; test_passed = false; } clearCubeMapArrayTexture(width, height, depth, 0); gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, m_pixel_buffer_id); GLU_EXPECT_NO_ERROR(gl.getError(), "Error binding buffer object!"); texSubImage3D(copy_params, 0); if (!checkResults(width, height, depth)) { m_testCtx.getLog() << tcu::TestLog::Message << "glTexSubImage3D failed to copy data to texture cube map " "array's data store from GL_PIXEL_UNPACK_BUFFER\n" << "Texture Cube Map Array Dimensions (width, height, depth) " << "(" << width << "," << height << "," << depth << ")\n" << "Texture Cube Map Array Offsets (xoffset, yoffset, zoffset) " << "(" << copy_params.m_xoffset << "," << copy_params.m_yoffset << "," << copy_params.m_zoffset << ")\n" << "Texture Cube Map Array Copy Size (width, height, depth) " << "(" << copy_params.m_width << "," << copy_params.m_height << "," << copy_params.m_depth << ")\n" << tcu::TestLog::EndMessage; test_passed = false; } gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "Error binding buffer object!"); } /** Perform a full test of copyTexSubImage3D function on cube map array texture * @param width - width of the texture * @param height - height of the texture * @param depth - depth of the texture * @param copy_params - data structure specifying which region of the cube map array to test * @param test_passed - a boolean variable set to false if at any stage of the test we experience wrong result */ void TextureCubeMapArraySubImage3D::testCopyTexSubImage3D(glw::GLuint width, glw::GLuint height, glw::GLuint depth, const SubImage3DCopyParams& copy_params, glw::GLboolean& test_passed) { clearCubeMapArrayTexture(width, height, depth, 0); copyTexSubImage3D(copy_params); if (!checkResults(width, height, depth)) { m_testCtx.getLog() << tcu::TestLog::Message << "glCopyTexSubImage3D failed to copy data to texture cube map array's data store\n" << "Texture Cube Map Array Dimensions (width, height, depth) " << "(" << width << "," << height << "," << depth << ")\n" << "Texture Cube Map Array Offsets (xoffset, yoffset, zoffset) " << "(" << copy_params.m_xoffset << "," << copy_params.m_yoffset << "," << copy_params.m_zoffset << ")\n" << "Texture Cube Map Array Copy Size (width, height, depth) " << "(" << copy_params.m_width << "," << copy_params.m_height << "," << copy_params.m_depth << ")\n" << tcu::TestLog::EndMessage; test_passed = false; } } /** Delete pixel unpack buffer */ void TextureCubeMapArraySubImage3D::deletePixelUnpackBuffer() { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Reset GLES configuration */ gl.bindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); /* Delete buffer object */ if (m_pixel_buffer_id != 0) { gl.deleteBuffers(1, &m_pixel_buffer_id); m_pixel_buffer_id = 0; } } /** Delete cube map array texture */ void TextureCubeMapArraySubImage3D::deleteCubeMapArrayTexture() { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Reset GLES configuration */ gl.bindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0); /* Delete texture object */ if (m_tex_cube_map_array_id != 0) { gl.deleteTextures(1, &m_tex_cube_map_array_id); m_tex_cube_map_array_id = 0; } } /* Delete 2D texture that had been used as data source by the glCopyTexSubImage3D call */ void TextureCubeMapArraySubImage3D::delete2DTexture() { /* Get GL entry points */ const glw::Functions& gl = m_context.getRenderContext().getFunctions(); /* Reset GLES configuration */ gl.bindTexture(GL_TEXTURE_2D, 0); /* Delete texture object */ if (m_tex_2d_id != 0) { gl.deleteTextures(1, &m_tex_2d_id); m_tex_2d_id = 0; } } } // namespace glcts
39.54876
129
0.71413
[ "object" ]
452183244844cc3042fcbca30137cd68d37b9995
16,677
cpp
C++
utils/threads/thread_pool.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
1
2018-07-10T13:36:38.000Z
2018-07-10T13:36:38.000Z
utils/threads/thread_pool.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
null
null
null
utils/threads/thread_pool.cpp
ppearson/ImaginePartial
9871b052f2edeb023e2845578ad69c25c5baf7d2
[ "Apache-2.0" ]
null
null
null
/* Imagine Copyright 2011-2012 Peter Pearson. 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 "thread_pool.h" #include <algorithm> #include <cstring> // for memset #include <cassert> #include "global_context.h" #include "utils/logger.h" namespace Imagine { ThreadPoolTask::ThreadPoolTask() : m_pThreadPool(nullptr) { } void ThreadPoolTask::setThreadPool(ThreadPool* pThreadPool) { m_pThreadPool = pThreadPool; } bool ThreadPoolTask::isActive() const { return m_pThreadPool->isActive(); } TaskBundle::TaskBundle() : m_size(0) { memset(m_pTasks, 0, sizeof(ThreadPoolTask*) * kTASK_BUNDLE_SIZE); } void TaskBundle::clear() { memset(m_pTasks, 0, sizeof(ThreadPoolTask*) * kTASK_BUNDLE_SIZE); m_size = 0; } ThreadController::ThreadController(unsigned int threads) : m_numberOfThreads(threads), m_activeThreads(0) { // set the number of available threads to 1 (available) in the bitset - the remainder // are 0 m_bsThreadsAvailable.reset(); m_threadAvailable.reset(); for (unsigned int i = 0; i < m_numberOfThreads; i++) { m_bsThreadsAvailable.set(i, true); } } bool ThreadController::isActive(unsigned int thread) { m_lock.lock(); bool isAvailable = false; if (!m_bsThreadsAvailable.test(thread)) { isAvailable = true; } m_lock.unlock(); return isAvailable; } unsigned int ThreadController::threadsActive() const { return m_activeThreads; } unsigned int ThreadController::threadsAvailable() const { return m_numberOfThreads - m_activeThreads; } int ThreadController::getThread() { int thread = -1; // first see if there's already a free one m_lock.lock(); if (m_bsThreadsAvailable.any()) { for (unsigned int i = 0; i < m_numberOfThreads; i++) { if (m_bsThreadsAvailable.test(i)) { thread = i; m_bsThreadsAvailable.set(i, false); m_activeThreads++; break; } } m_lock.unlock(); } else { m_lock.unlock(); m_threadAvailable.wait(); m_lock.lock(); // find the thread that's available for (unsigned int i = 0; i < m_numberOfThreads; i++) { if (m_bsThreadsAvailable.test(i)) { thread = i; m_bsThreadsAvailable.set(i, false); m_activeThreads++; break; } } m_threadAvailable.reset(); m_lock.unlock(); } return thread; } // this assumes there are threads available... int ThreadController::getThreadNoLock() { int thread = -1; m_lock.lock(); if (m_bsThreadsAvailable.any()) { for (unsigned int i = 0; i < m_numberOfThreads; i++) { if (m_bsThreadsAvailable.test(i)) { thread = i; m_bsThreadsAvailable.set(i, false); m_activeThreads++; break; } } } m_lock.unlock(); return thread; } void ThreadController::freeThread(unsigned int thread) { if (thread >= m_numberOfThreads) return; m_lock.lock(); m_bsThreadsAvailable.set(thread, true); m_activeThreads--; m_lock.unlock(); m_threadAvailable.broadcast(); } ThreadPoolThread::ThreadPoolThread(ThreadPool* pThreadPool, unsigned int threadID, Thread::ThreadPriority priority) : Thread(priority), m_pTask(nullptr), m_pTaskBundle(nullptr), m_bundleIndex(0), m_bundleSize(0), m_pThreadPool(pThreadPool), m_threadID(threadID) { } ThreadPoolThread::~ThreadPoolThread() { if (m_pTaskBundle) { delete m_pTaskBundle; m_pTaskBundle = nullptr; } } void ThreadPoolThread::run() { if (m_pTaskBundle) runTaskBundle(); else runSingleTask(); } void ThreadPoolThread::runSingleTask() { assert(m_pThreadPool); // while we have a task... while (m_pTask) { // call ThreadPool subclass's doTask method if (m_pThreadPool->doTask(m_pTask, m_threadID)) { // task is done, so remove it m_pThreadPool->deleteTask(m_pTask, false); m_pTask = nullptr; } else { // re-add the task m_pThreadPool->addTask(m_pTask); m_pTask = nullptr; } m_pThreadPool->taskDone(); if (m_isRunning && m_pThreadPool) { // to save constantly creating and destroying loads of threads, try and reuse them if there's work to do... m_pTask = m_pThreadPool->getNextTask(); } } // otherwise, free the thread m_pThreadPool->freeThread(m_threadID); } void ThreadPoolThread::runTaskBundle() { assert(m_pThreadPool); ThreadPoolTask* pTask = nullptr; while (m_isRunning) { // while we've got tasks in our local bundle... while (m_bundleSize > 0 && m_pThreadPool) { pTask = m_pTaskBundle->m_pTasks[m_bundleIndex]; if (m_pThreadPool->doTask(pTask, m_threadID)) { // task is done, so remove it m_pThreadPool->deleteTask(pTask, false); m_pTaskBundle->m_pTasks[m_bundleIndex] = nullptr; m_pTask = nullptr; } else { m_requeueTasks.m_pTasks.emplace_back(pTask); } m_pThreadPool->taskDone(); m_bundleIndex++; m_bundleSize--; } if (m_isRunning) { // we've run out of tasks in our bundle, so see if there are any more available for us m_pTaskBundle->clear(); m_bundleIndex = 0; m_pThreadPool->addRequeuedTasks(m_requeueTasks); m_bundleSize = m_pThreadPool->getNextTaskBundle(m_pTaskBundle); if (m_bundleSize == 0) { // there aren't any left to do... break; } } } // otherwise, free the thread m_pThreadPool->freeThread(m_threadID); } TaskBundle* ThreadPoolThread::createTaskBundle() { m_pTaskBundle = new TaskBundle(); return m_pTaskBundle; } void ThreadPoolThread::deleteTasksInBundle() { if (!m_pTaskBundle) return; for (unsigned int i = 0; i < m_bundleSize; i++) { ThreadPoolTask* pTask = m_pTaskBundle->m_pTasks[i]; if (pTask) delete pTask; } } ThreadPool::ThreadPool(unsigned int threads, bool useBundles) : m_controller(threads), m_pAsyncFinishThread(nullptr), m_numberOfThreads(threads), m_setAffinity(false), m_lowPriorityThreads(false), m_useBundles(useBundles), m_startedThreads(0), m_isActive(false), m_wasCancelled(false), m_originalNumberOfTasks(0) { for (unsigned int i = 0; i < m_numberOfThreads; i++) { if (m_useBundles) { m_aRequeuedTasks.emplace_back(new RequeuedTasks()); } } m_threadBundleSizeThreshold1 = kTASK_BUNDLE_SIZE * m_numberOfThreads; m_threadBundleSizeThreshold2 = m_threadBundleSizeThreshold1 / 2; } ThreadPool::~ThreadPool() { deleteThreadsAndRequeuedTasks(); if (m_pAsyncFinishThread) { delete m_pAsyncFinishThread; m_pAsyncFinishThread = nullptr; } } void ThreadPool::addTask(ThreadPoolTask* pTask) { m_lock.lock(); pTask->setThreadPool(this); m_aTasks.emplace_back(pTask); m_lock.unlock(); } void ThreadPool::requeueTask(ThreadPoolTask* pTask, unsigned int threadID) { RequeuedTasks* pRQT = m_aRequeuedTasks[threadID]; pRQT->m_pTasks.emplace_back(pTask); } void ThreadPool::addTaskNoLock(ThreadPoolTask* pTask) { pTask->setThreadPool(this); m_aTasks.emplace_back(pTask); } ThreadPoolTask* ThreadPool::getNextTask() { ThreadPoolTask* pTask = nullptr; m_lock.lock(); if (!m_aTasks.empty()) { pTask = m_aTasks.front(); m_aTasks.pop_front(); } m_lock.unlock(); return pTask; } unsigned int ThreadPool::getNextTaskBundle(TaskBundle* pBundle) { unsigned int bundleSize = 0; m_lock.lock(); bundleSize = getNextTaskBundleInternal(pBundle); m_lock.unlock(); return bundleSize; } void ThreadPool::startPool(unsigned int flags) { deleteThreads(); int threadID = -1; m_originalNumberOfTasks = m_aTasks.size(); m_fOriginalNumberOfTasks = (float)m_originalNumberOfTasks; m_invOriginalNumTasks = 1.0f / m_fOriginalNumberOfTasks; unsigned int threadsToStart = m_numberOfThreads; if (!(flags & POOL_FORCE_ALL_THREADS)) { // don't bother creating more threads than there are tasks if that is the case... threadsToStart = std::min(m_originalNumberOfTasks, m_numberOfThreads); } unsigned int threadsCreated = 0; m_wasCancelled = false; m_isActive = true; m_finishedEvent.reset(); // TODO: there is a mis-match here between the thread objects created along with // the tasks popped for them, and the actual number of threads that were started m_lock.lock(); if (!(flags & POOL_ALLOW_START_EMPTY) && m_aTasks.empty()) { // currently, the assumption is that tasks will exist at this point (although the infrastructure can technically cope with tasks being added later), // so... GlobalContext::instance().getLogger().error("Empty task queue detected."); assert(!m_aTasks.empty()); } bool shouldCreateBundleThreads = m_useBundles && (m_originalNumberOfTasks > m_numberOfThreads * 2); Thread::ThreadPriority newThreadPriority = Thread::ePriorityNormal; if (m_lowPriorityThreads) { newThreadPriority = Thread::ePriorityLow; } m_aThreads.resize(m_numberOfThreads); memset(m_aThreads.data(), 0, sizeof(ThreadPoolThread*) * m_numberOfThreads); if (!shouldCreateBundleThreads) { for (unsigned int j = 0; j < threadsToStart; j++) { // TODO: there could be a miss-match here... threadID = m_controller.getThreadNoLock(); if (threadID != -1) { ThreadPoolThread* pThread = new ThreadPoolThread(this, threadID, newThreadPriority); if (!pThread) { // TODO: something more robust here... continue; } if (m_setAffinity) { pThread->setAffinity(j); } ThreadPoolTask* pTask = getNextTaskInternal(); pThread->setTask(pTask); // TODO: again, there could be a miss-match here... m_aThreads[threadID] = pThread; threadsCreated ++; } else { // something weird happened // fprintf(stderr, "Couldn't start thread: %u\n", j); Thread::sleep(1); } } } else { for (unsigned int j = 0; j < threadsToStart; j++) { threadID = m_controller.getThreadNoLock(); if (threadID != -1) { ThreadPoolThread* pThread = new ThreadPoolThread(this, threadID, newThreadPriority); if (!pThread) { // TOOD: continue; } if (m_setAffinity) { pThread->setAffinity(j); } TaskBundle* pTB = pThread->createTaskBundle(); unsigned int numTasks = getNextTaskBundleInternal(pTB); pThread->setTaskBundleSize(numTasks); m_aThreads[threadID] = pThread; threadsCreated ++; } else { // something weird happened Thread::sleep(1); } } } m_lock.unlock(); unsigned int threadsStarted = 0; // start them - this is best done in its own loop for (unsigned int i = 0; i < threadsCreated; i++) { ThreadPoolThread* pThread = m_aThreads[i]; if (pThread) { if (pThread->start()) { threadsStarted++; } else { // indicate that it's not actually active m_controller.freeThread(i); } } } m_startedThreads = threadsStarted; // if we don't want to wait for completion, just early exit here... if (!(flags & POOL_WAIT_FOR_COMPLETION)) { if (flags & POOL_ASYNC_COMPLETION_EVENT) { if (!m_pAsyncFinishThread) { m_pAsyncFinishThread = new AsyncFinishEventWaitThread(this); } m_pAsyncFinishThread->start(); } return; } // otherwise... // now need to make sure any active threads have finished before we go out of scope for (unsigned int i = 0; i < m_startedThreads; i++) { if (m_controller.isActive(i)) { ThreadPoolThread* pThread = m_aThreads[i]; pThread->waitForCompletion(); } } m_finishedEvent.signal(); m_lock.lock(); std::deque<ThreadPoolTask*>::iterator it = m_aTasks.begin(); for (; it != m_aTasks.end(); ++it) { delete *it; } m_aTasks.clear(); m_lock.unlock(); m_isActive = false; } void ThreadPool::externalFinished() { // now need to make sure any active threads have finished before we go out of scope for (unsigned int i = 0; i < m_numberOfThreads; i++) { // Note: It's important here that threads actually finish the work they're doing // and signal the controller that they've finished, so that there are no // race conditions if (m_controller.isActive(i)) { ThreadPoolThread* pThread = m_aThreads[i]; pThread->waitForCompletion(); } } m_finishedEvent.signal(); } void ThreadPool::addRequeuedTasks(RequeuedTasks& rqt) { if (rqt.m_pTasks.empty()) return; m_lock.lock(); std::deque<ThreadPoolTask*>::iterator it = rqt.m_pTasks.begin(); for (; it != rqt.m_pTasks.end(); ++it) { ThreadPoolTask* pTask = *it; m_aTasks.emplace_back(pTask); } rqt.m_pTasks.clear(); m_lock.unlock(); } void ThreadPool::deleteThreads() { std::vector<ThreadPoolThread*>::iterator itThread = m_aThreads.begin(); for (; itThread != m_aThreads.end(); ++itThread) { ThreadPoolThread* pThread = *itThread; if (pThread) delete pThread; } m_aThreads.clear(); } void ThreadPool::deleteThreadsAndRequeuedTasks() { std::vector<ThreadPoolThread*>::iterator itThread = m_aThreads.begin(); for (; itThread != m_aThreads.end(); ++itThread) { ThreadPoolThread* pThread = *itThread; if (pThread) delete pThread; } m_aThreads.clear(); std::vector<RequeuedTasks*>::iterator itRequeuedTasks = m_aRequeuedTasks.begin(); for (; itRequeuedTasks != m_aRequeuedTasks.end(); ++itRequeuedTasks) { RequeuedTasks* pRQT = *itRequeuedTasks; if (pRQT) delete pRQT; } m_aRequeuedTasks.clear(); } void ThreadPool::deleteTask(ThreadPoolTask* pTask, bool lockAndRemoveFromQueue) { if (lockAndRemoveFromQueue) { // safely delete the task, so that we don't try and delete it later // TODO: this is needed, but might be slow in some cases, although thanks to tasks being re-used for things like // rendering, it probably isn't *that* bad... m_lock.lock(); std::deque<ThreadPoolTask*>::iterator itFind = std::find(m_aTasks.begin(), m_aTasks.end(), pTask); if (itFind != m_aTasks.end()) { m_aTasks.erase(itFind); } m_lock.unlock(); } delete pTask; } void ThreadPool::terminate() { if (!m_isActive) { return; } m_wasCancelled = true; m_isActive = false; for (unsigned int i = 0; i < m_numberOfThreads; i++) { if (m_controller.isActive(i)) { Thread* pThread = m_aThreads[i]; pThread->stop(false); // Note: The idea here is that it's up to threads to tell the controller they're finished, // so it's important that Thread::Wait } } m_finishedEvent.wait(); // as Thread::waitForCompletion()'s pthread_join() doesn't seem to work properly when // there's already something joining on it (in POSIX it's undefined behaviour), just delete all the tasks and wait for the threads // to kill themselves m_lock.lock(); std::deque<ThreadPoolTask*>::iterator it = m_aTasks.begin(); for (; it != m_aTasks.end(); ++it) { delete *it; } m_aTasks.clear(); m_lock.unlock(); } bool ThreadPool::isActive() const { return m_isActive; } bool ThreadPool::wasCancelled() const { return m_wasCancelled; } void ThreadPool::freeThread(unsigned int threadID) { m_controller.freeThread(threadID); } void ThreadPool::clearTasks() { } // assumes mutex is already held... ThreadPoolTask* ThreadPool::getNextTaskInternal() { ThreadPoolTask* pTask = m_aTasks.front(); m_aTasks.pop_front(); return pTask; } // assumes mutex is already held... unsigned int ThreadPool::getNextTaskBundleInternal(TaskBundle* pBundle) { // check we've got enough tasks to go around unsigned int tasksPending = m_aTasks.size(); if (tasksPending >= m_threadBundleSizeThreshold1) { // TODO: spread out the tasks we take, so that we still get a linear progression of tiles... unsigned int tasksAdded = 0; for (unsigned int i = 0; i < kTASK_BUNDLE_SIZE; i++) { ThreadPoolTask* pTask = m_aTasks.front(); m_aTasks.pop_front(); pBundle->m_pTasks[i] = pTask; tasksAdded ++; } pBundle->m_size = tasksAdded; return tasksAdded; } else if (tasksPending > m_threadBundleSizeThreshold2) { unsigned int tasksAdded = 0; for (unsigned int i = 0; i < kTASK_BUNDLE_SIZE / 2; i++) { ThreadPoolTask* pTask = m_aTasks.front(); m_aTasks.pop_front(); pBundle->m_pTasks[i] = pTask; tasksAdded ++; } pBundle->m_size = tasksAdded; return tasksAdded; } else if (tasksPending > 0) { ThreadPoolTask* pTask = m_aTasks.front(); m_aTasks.pop_front(); pBundle->m_pTasks[0] = pTask; pBundle->m_size = 1; return 1; } else { return 0; } } void ThreadPool::AsyncFinishEventWaitThread::run() { m_pThreadPool->externalFinished(); } } // namespace Imagine
20.288321
150
0.697308
[ "vector" ]
4527123f70457d95b41e13a497b4b9af0da2344d
3,393
cpp
C++
ruby/audio/oss.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
ruby/audio/oss.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
ruby/audio/oss.cpp
libretro-mirrors/higan
8617711ea2c201a33442266945dc7ed186e9d695
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/soundcard.h> //OSSv4 features: define fallbacks for OSSv3 (where these ioctls are ignored) #ifndef SNDCTL_DSP_COOKEDMODE #define SNDCTL_DSP_COOKEDMODE _IOW('P', 30, int) #endif #ifndef SNDCTL_DSP_POLICY #define SNDCTL_DSP_POLICY _IOW('P', 45, int) #endif struct AudioOSS : Audio { AudioOSS() { initialize(); } ~AudioOSS() { terminate(); } auto availableDevices() -> string_vector { string_vector devices; devices.append("/dev/dsp"); for(auto& device : directory::files("/dev/", "dsp?*")) devices.append(string{"/dev/", device}); return devices; } auto availableFrequencies() -> vector<double> { return {44100.0, 48000.0, 96000.0}; } auto availableLatencies() -> vector<uint> { return {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; } auto availableChannels() -> vector<uint> { return {1, 2}; } auto ready() -> bool { return _ready; } auto device() -> string { return _device; } auto blocking() -> bool { return _blocking; } auto channels() -> uint { return _channels; } auto frequency() -> double { return _frequency; } auto latency() -> uint { return _latency; } auto setDevice(string device) -> bool { if(_device == device) return true; _device = device; return initialize(); } auto setBlocking(bool blocking) -> bool { if(_blocking == blocking) return true; _blocking = blocking; updateBlocking(); return true; } auto setChannels(uint channels) -> bool { if(_channels == channels) return true; _channels = channels; return initialize(); } auto setFrequency(double frequency) -> bool { if(_frequency == frequency) return true; _frequency = frequency; return initialize(); } auto setLatency(uint latency) -> bool { if(_latency == latency) return true; _latency = latency; return initialize(); } auto output(const double samples[]) -> void { if(!ready()) return; for(auto n : range(_channels)) { auto sample = (uint16_t)sclamp<16>(samples[n] * 32767.0); auto unused = write(_fd, &sample, 2); } } private: auto initialize() -> bool { terminate(); if(!availableDevices().find(_device)) { _device = availableDevices().left(); } _fd = open(_device, O_WRONLY, O_NONBLOCK); if(_fd < 0) return false; int cooked = 1; ioctl(_fd, SNDCTL_DSP_COOKEDMODE, &cooked); //policy: 0 = minimum latency (higher CPU usage); 10 = maximum latency (lower CPU usage) int policy = min(10, _latency); ioctl(_fd, SNDCTL_DSP_POLICY, &policy); int channels = _channels; ioctl(_fd, SNDCTL_DSP_CHANNELS, &channels); ioctl(_fd, SNDCTL_DSP_SETFMT, &_format); int frequency = _frequency; ioctl(_fd, SNDCTL_DSP_SPEED, &frequency); updateBlocking(); return _ready = true; } auto terminate() -> void { _ready = false; if(_fd < 0) return; close(_fd); _fd = -1; } auto updateBlocking() -> void { if(!_ready) return; auto flags = fcntl(_fd, F_GETFL); if(flags < 0) return; _blocking ? flags &=~ O_NONBLOCK : flags |= O_NONBLOCK; fcntl(_fd, F_SETFL, flags); } bool _ready = false; string _device; bool _blocking = true; uint _channels = 2; double _frequency = 48000.0; uint _latency = 2; int _fd = -1; int _format = AFMT_S16_LE; };
24.948529
99
0.636899
[ "vector" ]
4527dc438f0c3ce79fe2bb3871303aa8024f57e5
14,380
cpp
C++
OrbitGl/ThreadTrack.cpp
MagicPoncho/orbit
c92d2f64ad3caeef0e41ee04719d84217820b9f8
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/ThreadTrack.cpp
MagicPoncho/orbit
c92d2f64ad3caeef0e41ee04719d84217820b9f8
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/ThreadTrack.cpp
MagicPoncho/orbit
c92d2f64ad3caeef0e41ee04719d84217820b9f8
[ "BSD-2-Clause" ]
null
null
null
#include "ThreadTrack.h" #include <limits> #include "Capture.h" #include "EventTrack.h" #include "GlCanvas.h" #include "OrbitUnreal.h" #include "Systrace.h" #include "TimeGraph.h" #include "absl/flags/flag.h" #include "absl/strings/str_format.h" // TODO: Remove this flag once we have a way to toggle the display return values ABSL_FLAG(bool, show_return_values, false, "Show return values on time slices"); //----------------------------------------------------------------------------- ThreadTrack::ThreadTrack(TimeGraph* time_graph, uint32_t thread_id) { time_graph_ = time_graph; m_ID = thread_id; text_renderer_ = time_graph->GetTextRenderer(); thread_id_ = thread_id; num_timers_ = 0; min_time_ = std::numeric_limits<TickType>::max(); max_time_ = std::numeric_limits<TickType>::min(); event_track_ = std::make_shared<EventTrack>(time_graph); event_track_->SetThreadId(thread_id); } //----------------------------------------------------------------------------- void ThreadTrack::Draw(GlCanvas* canvas, bool picking) { float track_height = GetHeight(); float track_width = canvas->GetWorldWidth(); SetPos(canvas->GetWorldTopLeftX(), m_Pos[1]); SetSize(track_width, track_height); Track::Draw(canvas, picking); // Event track float event_track_height = time_graph_->GetLayout().GetEventTrackHeight(); event_track_->SetPos(m_Pos[0], m_Pos[1]); event_track_->SetSize(track_width, event_track_height); event_track_->Draw(canvas, picking); } //----------------------------------------------------------------------------- std::string GetExtraInfo(const Timer& timer) { std::string info; static bool show_return_value = absl::GetFlag(FLAGS_show_return_values); if (!Capture::IsCapturing() && timer.GetType() == Timer::UNREAL_OBJECT) { info = "[" + ws2s(GOrbitUnreal.GetObjectNames()[timer.m_UserData[0]]) + "]"; } else if (show_return_value && (timer.GetType() == Timer::NONE)) { info = absl::StrFormat("[%lu]", timer.m_UserData[0]); } return info; } //----------------------------------------------------------------------------- void ThreadTrack::UpdatePrimitives(uint64_t min_tick, uint64_t max_tick) { event_track_->UpdatePrimitives(min_tick, max_tick); Batcher* batcher = &time_graph_->GetBatcher(); TextRenderer* text_renderer = time_graph_->GetTextRenderer(); GlCanvas* canvas = time_graph_->GetCanvas(); const TimeGraphLayout& layout = time_graph_->GetLayout(); const TextBox& scene_box = canvas->GetSceneBox(); float min_x = scene_box.GetPosX(); double time_window_us = time_graph_->GetTimeWindowUs(); float world_start_x = canvas->GetWorldTopLeftX(); float world_width = canvas->GetWorldWidth(); double inv_time_window = 1.0 / time_window_us; std::vector<std::shared_ptr<TimerChain>> depth_chain = GetTimers(); for (auto& text_boxes : depth_chain) { if (text_boxes == nullptr) continue; for (TextBox& text_box : *text_boxes) { const Timer& timer = text_box.GetTimer(); if (!(min_tick > timer.m_End || max_tick < timer.m_Start)) { double start = time_graph_->GetUsFromTick(timer.m_Start); double end = time_graph_->GetUsFromTick(timer.m_End); double elapsed = end - start; double normalized_start = start * inv_time_window; double normalized_length = elapsed * inv_time_window; bool is_core = timer.IsType(Timer::CORE_ACTIVITY); float y_offset = 0; if (!is_core) { y_offset = m_Pos[1] - layout.GetEventTrackHeight() - layout.GetSpaceBetweenTracksAndThread() - layout.GetTextBoxHeight() * (timer.m_Depth + 1); } else { y_offset = layout.GetCoreOffset(timer.m_Processor); } float box_height = !is_core ? layout.GetTextBoxHeight() : layout.GetTextCoresHeight(); float world_timer_start_x = float(world_start_x + normalized_start * world_width); float world_timer_width = float(normalized_length * world_width); Vec2 pos(world_timer_start_x, y_offset); Vec2 size(world_timer_width, box_height); text_box.SetPos(pos); text_box.SetSize(size); if (!is_core) { time_graph_->UpdateThreadDepth(timer.m_TID, timer.m_Depth + 1); UpdateDepth(timer.m_Depth + 1); } else { UpdateDepth(timer.m_Processor + 1); } bool is_context_switch = timer.IsType(Timer::THREAD_ACTIVITY); bool is_visible_width = normalized_length * canvas->getWidth() > 1; bool is_same_pid_as_target = is_core && Capture::GTargetProcess != nullptr ? timer.m_PID == Capture::GTargetProcess->GetID() : true; bool is_same_tid_as_selected = is_core && (timer.m_TID == Capture::GSelectedThreadId); bool is_inactive = (!is_context_switch && timer.m_FunctionAddress && (!Capture::GVisibleFunctionsMap.empty() && Capture::GVisibleFunctionsMap[timer.m_FunctionAddress] == nullptr)) || (Capture::GSelectedThreadId != 0 && is_core && !is_same_tid_as_selected); bool is_selected = &text_box == Capture::GSelectedTextBox; const unsigned char g = 100; Color grey(g, g, g, 255); static Color selection_color(0, 128, 255, 255); Color col = time_graph_->GetTimesliceColor(timer); if (is_selected) { col = selection_color; } else if (!is_same_tid_as_selected && (is_inactive || !is_same_pid_as_target)) { col = grey; } text_box.SetColor(col[0], col[1], col[2]); static int oddAlpha = 210; if (!(timer.m_Depth & 0x1)) { col[3] = oddAlpha; } float z = is_inactive ? GlCanvas::Z_VALUE_BOX_INACTIVE : GlCanvas::Z_VALUE_BOX_ACTIVE; if (is_visible_width) { Box box; box.m_Vertices[0] = Vec3(pos[0], pos[1], z); box.m_Vertices[1] = Vec3(pos[0], pos[1] + size[1], z); box.m_Vertices[2] = Vec3(pos[0] + size[0], pos[1] + size[1], z); box.m_Vertices[3] = Vec3(pos[0] + size[0], pos[1], z); Color colors[4]; Fill(colors, col); static float coeff = 0.94f; Vec3 dark = Vec3(col[0], col[1], col[2]) * coeff; colors[1] = Color((unsigned char)dark[0], (unsigned char)dark[1], (unsigned char)dark[2], (unsigned char)col[3]); colors[0] = colors[1]; batcher->AddBox(box, colors, PickingID::BOX, &text_box); if (!is_context_switch && text_box.GetText().empty()) { double elapsed_millis = ((double)elapsed) * 0.001; std::string time = GetPrettyTime(elapsed_millis); Function* func = Capture::GSelectedFunctionsMap[timer.m_FunctionAddress]; text_box.SetElapsedTimeTextLength(time.length()); const char* name = nullptr; if (func) { std::string extra_info = GetExtraInfo(timer); name = func->PrettyName().c_str(); std::string text = absl::StrFormat( "%s %s %s", name, extra_info.c_str(), time.c_str()); text_box.SetText(text); } else if (timer.m_Type == Timer::INTROSPECTION) { std::string text = absl::StrFormat("%s %s", time_graph_->GetStringManager() ->Get(timer.m_UserData[0]) .value_or(""), time.c_str()); text_box.SetText(text); } else if (timer.m_Type == Timer::GPU_ACTIVITY) { std::string text = absl::StrFormat("%s; submitter: %d %s", time_graph_->GetStringManager() ->Get(timer.m_UserData[0]) .value_or(""), timer.m_SubmitTID, time.c_str()); text_box.SetText(text); } else if (!SystraceManager::Get().IsEmpty()) { text_box.SetText(SystraceManager::Get().GetFunctionName( timer.m_FunctionAddress)); } else if (!Capture::IsCapturing()) { // GZoneNames is populated when capturing, prevent race // by accessing it only when not capturing. auto it = Capture::GZoneNames.find(timer.m_FunctionAddress); if (it != Capture::GZoneNames.end()) { name = it->second.c_str(); std::string text = absl::StrFormat("%s %s", name, time.c_str()); text_box.SetText(text); } } } if (!is_core) { static Color s_Color(255, 255, 255, 255); const Vec2& box_pos = text_box.GetPos(); const Vec2& box_size = text_box.GetSize(); float pos_x = std::max(box_pos[0], min_x); float max_size = box_pos[0] + box_size[0] - pos_x; text_renderer->AddTextTrailingCharsPrioritized( text_box.GetText().c_str(), pos_x, text_box.GetPosY() + 1.f, GlCanvas::Z_VALUE_TEXT, s_Color, text_box.GetElapsedTimeTextLength(), max_size); } } else { Line line; line.m_Beg = Vec3(pos[0], pos[1], z); line.m_End = Vec3(pos[0], pos[1] + size[1], z); Color colors[2]; Fill(colors, col); batcher->AddLine(line, colors, PickingID::LINE, &text_box); } } } } } //----------------------------------------------------------------------------- void ThreadTrack::OnDrag(int x, int y) { Track::OnDrag(x, y); } //----------------------------------------------------------------------------- void ThreadTrack::OnTimer(const Timer& timer) { if (timer.m_Type != Timer::CORE_ACTIVITY) { UpdateDepth(timer.m_Depth + 1); } TextBox text_box(Vec2(0, 0), Vec2(0, 0), "", Color(255, 0, 0, 255)); text_box.SetTimer(timer); std::shared_ptr<TimerChain> timer_chain = timers_[timer.m_Depth]; if (timer_chain == nullptr) { timer_chain = std::make_shared<TimerChain>(); timers_[timer.m_Depth] = timer_chain; } timer_chain->push_back(text_box); ++num_timers_; if (timer.m_Start < min_time_) min_time_ = timer.m_Start; if (timer.m_End > max_time_) max_time_ = timer.m_End; } //----------------------------------------------------------------------------- float ThreadTrack::GetHeight() const { TimeGraphLayout& layout = time_graph_->GetLayout(); return layout.GetTextBoxHeight() * GetDepth() + layout.GetSpaceBetweenTracksAndThread() + layout.GetEventTrackHeight() + layout.GetTrackBottomMargin(); } //----------------------------------------------------------------------------- std::vector<std::shared_ptr<TimerChain>> ThreadTrack::GetTimers() { std::vector<std::shared_ptr<TimerChain>> timers; ScopeLock lock(mutex_); for (auto& pair : timers_) { timers.push_back(pair.second); } return timers; } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetFirstAfterTime(TickType time, uint32_t depth) const { std::shared_ptr<TimerChain> text_boxes = GetTimers(depth); if (text_boxes == nullptr) return nullptr; // TODO: do better than linear search... for (TextBox& text_box : *text_boxes) { if (text_box.GetTimer().m_Start > time) { return &text_box; } } return nullptr; } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetFirstBeforeTime(TickType time, uint32_t depth) const { std::shared_ptr<TimerChain> text_boxes = GetTimers(depth); if (text_boxes == nullptr) return nullptr; TextBox* text_box = nullptr; // TODO: do better than linear search... for (TextBox& box : *text_boxes) { if (box.GetTimer().m_Start > time) { return text_box; } text_box = &box; } return nullptr; } //----------------------------------------------------------------------------- std::shared_ptr<TimerChain> ThreadTrack::GetTimers(uint32_t depth) const { ScopeLock lock(mutex_); auto it = timers_.find(depth); if (it != timers_.end()) return it->second; return nullptr; } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetLeft(TextBox* text_box) const { const Timer& timer = text_box->GetTimer(); if (timer.m_TID == thread_id_) { std::shared_ptr<TimerChain> timers = GetTimers(timer.m_Depth); if (timers) return timers->GetElementBefore(text_box); } return nullptr; } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetRight(TextBox* text_box) const { const Timer& timer = text_box->GetTimer(); if (timer.m_TID == thread_id_) { std::shared_ptr<TimerChain> timers = GetTimers(timer.m_Depth); if (timers) return timers->GetElementAfter(text_box); } return nullptr; } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetUp(TextBox* text_box) const { const Timer& timer = text_box->GetTimer(); return GetFirstBeforeTime(timer.m_Start, timer.m_Depth - 1); } //----------------------------------------------------------------------------- const TextBox* ThreadTrack::GetDown(TextBox* text_box) const { const Timer& timer = text_box->GetTimer(); return GetFirstAfterTime(timer.m_Start, timer.m_Depth + 1); } //----------------------------------------------------------------------------- std::vector<std::shared_ptr<TimerChain>> ThreadTrack::GetAllChains() { std::vector<std::shared_ptr<TimerChain>> chains; for (const auto& pair : timers_) { chains.push_back(pair.second); } return chains; } //----------------------------------------------------------------------------- void ThreadTrack::SetEventTrackColor(Color color) { ScopeLock lock(mutex_); event_track_->SetColor(color); }
37.842105
80
0.554868
[ "vector" ]
453a4ab86d96165d1df660b5370067aea7dbe103
590
cpp
C++
diff/multi_array.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
7
2017-11-10T05:18:30.000Z
2021-04-29T15:38:25.000Z
diff/multi_array.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
diff/multi_array.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
#include <future> #include <thread> #include <mutex> #include <condition_variable> #include <chrono> #include <random> #include <iostream> #include <exception> #include<iostream> #include<vector> #include<map> #include<set> #include<list> #include<vector> #include<queue> #include<algorithm> #include "boost/multi_array.hpp" typedef boost::multi_array<double, 3> array_type; array_type A(boost::extents[3][4] [2]); double ar [3][4] [2]; int main(int argc, char* argv[]) { int s1 = sizeof(A);// 160 ?? int s2 = sizeof(ar); // 192 return 0; }
18.4375
51
0.649153
[ "vector" ]
453ec6379a578b504d428a2bbcb28f348dbac050
6,784
cpp
C++
src/tools/SxRhoRep.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/tools/SxRhoRep.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/tools/SxRhoRep.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #include <SxPAWRho.h> #include <SxCLI.h> #include <SxGrid.h> int main(int argc, char **argv) { initSPHInXMath (); SxCLI cli(argc, argv); cli.authors = "C. Freysoldt"; cli.preUsageMessage = "This add-on creates a supercell mesh file."; SxString meshIn = cli.option ("-i|--input","file","file").toString ("rho.sxb"); SxString outFile = cli.option ("-o|--output","file","file").toString (); // --- definition SxMatrix3<Int> repMatrix; int simpleRep = cli.newGroup ("simple repetition"); SxVector3<Int> diag (cli.option ("-r|--repeat","3 numbers", "repetition along current cell vectors") .toIntList3 ("x,")); SxMesh3D finalMesh(0,0,0); if (cli.option ("-m|--mesh","3 numbers", "final mesh").exists ()) { finalMesh = SxVector3<Int>(cli.last ().toIntList3 ("x,")); } /* int trueRep = cli.newGroup ("3dimensional repetition"); cli.excludeGroup (simpleRep); SxVector3<Int> col1 (cli.option ("--a1","vector", "new a1 in relative coordinates") .toIntList3 ()), col2 (cli.option ("--a2","vector", "new a2 in relative coordinates") .toIntList3 ()), col3 (cli.option ("--a3","vector", "new a3 in relative coordinates") .toIntList3 ()); */ if (!cli.error) { if (cli.groupAvailable (simpleRep)) { if (diag.product () <= 0) { cout << "Illegal repetition factors " << diag << endl; cli.setError (); } /* } else if (cli.groupAvailable (trueRep)) { repMatrix = SxMatrix3<Int> (col1, col2, col3).transpose (); cout << repMatrix << endl; if (repMatrix.determinant () == 0) { cout << "Illegal repetition matrix with zero determinant." << endl; cli.setError (); } */ } else { cout << "no repetition given!" << endl; cli.setError (); } } cli.newGroup ("PAW"); bool paw = cli.option ("--paw", "PAW density").toBool (); SxString structFile = cli.option ("--structure", "sx file", "repeated structure file for PAW. Needed for atom sorting") .toString (); cli.finalize (); SxRBasis R; SxBinIO io; SxMesh3D mesh; try { io.open (meshIn, SxBinIO::BINARY_READ_ONLY); io.read ("dim", &mesh); R.cell.read (io); R.fft3d.mesh = mesh; R.fft3d.meshSize = mesh.product (); } catch (SxException e) { e.print (); SX_EXIT; } SxRho rho(io, &R); int nMeshes = int(rho.rhoR.getSize ()); // --- expand mesh data SxMesh3D newMesh = mesh * diag; for (int iMesh = 0; iMesh < nMeshes; ++iMesh) { SxMeshR newRho (newMesh.product ()); for (int x = 0; x < newMesh(0); ++x) { for (int y = 0; y < newMesh(1); ++y) { for (int z = 0; z < newMesh(2); ++z) { newRho (newMesh.getMeshIdx (x, y, z, SxMesh3D::Positive)) = rho(iMesh)(mesh.getMeshIdx (x, y, z, SxMesh3D::Unknown)); } } } rho(iMesh)=newRho; } R.cell = SxCell (R.cell.basis(0) * diag(0), R.cell.basis(1) * diag(1), R.cell.basis(2) * diag(2)); R.fft3d.mesh = newMesh; R.fft3d.meshSize = newMesh.product (); if (finalMesh.product () > 0 && finalMesh != newMesh) { SxFFT3d repFFT(SxFFT::Reverse, newMesh, R.cell.volume), finalFFT(SxFFT::Forward, finalMesh, R.cell.volume); int nMesh1 = newMesh.product (), nMesh2 = finalMesh.product (); SX_LOOP(iMesh) { cout << "Interpolating mesh " << (iMesh+1) << "..." << endl; SxDiracVec<Complex16> rhoR = rho(iMesh); SxDiracVec<Complex16> rhoG1(nMesh1), rhoG2(nMesh2); repFFT.fftReverse (nMesh1, rhoR.elements, rhoG1.elements); rhoG2.set (0.); for (int x = -finalMesh(0)/2; 2 * x < finalMesh(0); x++) { if (abs(x) * 2 >= newMesh(0)) continue; for (int y = 0; y < finalMesh(1); y++) { if (abs(y) * 2 >= newMesh(1)) continue; for (int z = 0; z < finalMesh(2); z++) { if (abs(z) * 2 >= newMesh(2)) continue; rhoG2(finalMesh.getMeshIdx(x,y,z,SxMesh3D::Origin)) = rhoG1(newMesh.getMeshIdx(x,y,z,SxMesh3D::Origin)); } } } rhoR.resize (nMesh2); finalFFT.fftForward (nMesh2, rhoG2.elements, rhoR.elements); rho(iMesh) = rhoR; } R.fft3d.mesh = finalMesh; R.fft3d.meshSize = nMesh2; } if (paw) { SxPAWRho pawRho; SxAtomicStructure strNew, strOrig; try { SxParser parser; strNew = SxAtomicStructure(&*parser.read (structFile, "std/structure.std")); pawRho.Dij.readRho (io); strOrig.read (io); } catch (SxException e) { e.print (); SX_EXIT; } pawRho.pwRho = rho; if ((strNew.cell - R.cell).absSqr ().sum () > 1e-10) { cout << "Mismatch between cell in " << structFile << " and repeated rho:" << endl; cout << structFile << ": " << strNew << endl; cout << "repeated rho: " << R.cell << endl; SX_QUIT; } SxGBasis G; G.fft3d.resize (1); G.fft3d(0).mesh.set (0); G.structPtr = &strNew; R.registerGBasis (G); SxGrid grid(strOrig, 10); SxRadMat newDij; newDij.resize (strNew.atomInfo, nMeshes); SX_LOOP2(is,ia) { int origIdx = strOrig.find (strNew.getAtom(is,ia), grid); if (origIdx < 0) { cout << "Atom not found: " << strNew.getAtom(is,ia) << endl; SX_QUIT; } int iaOrig, isOrig = strOrig.getISpecies (origIdx, &iaOrig); SX_LOOP(iSpin) newDij(iSpin, is,ia) = pawRho.Dij(iSpin, isOrig,iaOrig); } pawRho.Dij = newDij; pawRho.writeRho (outFile); } else { rho.writeRho (outFile); } io.close (); return 0; }
33.092683
85
0.497642
[ "mesh", "vector" ]
454069d4ba562dac65f1d9fde242bac0bf96ecce
8,752
cpp
C++
Engine/Systems/FileSystem.cpp
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
Engine/Systems/FileSystem.cpp
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
Engine/Systems/FileSystem.cpp
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
#include "FileSystem.h" #include "..\\Graphics\\AdapterReader.h" #include "..\\Graphics\Shaders.h" #include "..\Editor\Editor.h" #include "..\Graphics\Graphics.h" #include "..\\Components\MeshRenderComponent.h" #include "..\\Components\\EditorSelectionComponent.h" #include "..\Components\LuaScriptComponent.h" #include "..\Components\RigidBodyComponent.h" #include "..\Graphics\Material.h" #include "..\Objects\Player.h" #include "json.h" #include "rapidjson/document.h" #include "rapidjson/filewritestream.h" #include "rapidjson/istreamwrapper.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/ostreamwrapper.h" #include "rapidjson/prettywriter.h" #include <map> bool FileSystem::Initialize(Engine* engine) { m_pEngine = engine; return true; } bool FileSystem::LoadSceneFromJSON(const std::string& sceneLocation, Scene* scene, ID3D11Device* device, ID3D11DeviceContext* deviceContext) { // Load document from file and verify it was found rapidjson::Document masterDocument; if (!json::load(sceneLocation.c_str(), masterDocument)) { ErrorLogger::Log("Failed to load scene from JSON file."); return false; } // Parse scene name std::string sceneName; json::get_string(masterDocument, "SceneName", sceneName); // Find something that says 'SceneName' and load sceneName variable scene->SetSceneName(sceneName); ID* id = nullptr; Entity* entity = nullptr; // Physics system static int colliderTag = 1; // Load objects const rapidjson::Value& sceneObjects = masterDocument["Objects"]; // Arr for (rapidjson::SizeType o = 0; o < sceneObjects.Size(); o++) { const rapidjson::Value& object = sceneObjects[o]; // Current object in Objects array (unique entity, perform calls on this object) std::string objectType; json::get_string(object, "Type", objectType); if (objectType == "Entity") { if (entity == nullptr) { id = new ID(); entity = new Entity(scene, (*id)); } } else if (objectType == "Player") { if (entity == nullptr) { id = new ID(); entity = new Player(scene, (*id)); m_pEngine->SetPlayer(dynamic_cast<Player*>(entity)); } } //else if (objectType == "Light") // TODO: Add light class //{ // if (entity != nullptr) // { // id = new ID(); // entity = new Entity(scene, (*id)); // //dynamic_cast<Light*>(entity); // } //} entity->GetID().SetType(objectType); std::string objectName; json::get_string(object, "Name", objectName); entity->GetID().SetName(objectName); entity->GetID().SetTag("Untagged"); #pragma region Load Transform // Loop through Transform array float px, py, pz; float rx, ry, rz; float sx, sy, sz; const rapidjson::Value& transform = sceneObjects[o]["Transform"]; // At spot o in the sceneObjects array (Number of spots is how ever many objects are in the scene) const rapidjson::Value& position = transform[0]["Position"]; for (rapidjson::SizeType p = 0; p < position.Size(); p++) { json::get_float(position[p], "x", px); json::get_float(position[p], "y", py); json::get_float(position[p], "z", pz); } const rapidjson::Value& rotation = transform[1]["Rotation"]; for (rapidjson::SizeType r = 0; r < rotation.Size(); r++) { json::get_float(rotation[r], "x", rx); json::get_float(rotation[r], "y", ry); json::get_float(rotation[r], "z", rz); } const rapidjson::Value& scale = transform[2]["Scale"]; for (rapidjson::SizeType s = 0; s < scale.Size(); s++) { json::get_float(scale[s], "x", sx); json::get_float(scale[s], "y", sy); json::get_float(scale[s], "z", sz); } /*const rapidjson::Value& position = transform[0]["Position"]; json::get_float(position[0], "x", px); json::get_float(position[0], "y", py); json::get_float(position[0], "z", pz); const rapidjson::Value& rotation = transform[1]["Rotation"]; json::get_float(rotation[0], "x", rx); json::get_float(rotation[0], "y", ry); json::get_float(rotation[0], "z", rz); const rapidjson::Value& scale = transform[2]["Scale"]; json::get_float(scale[0], "x", sx); json::get_float(scale[0], "y", sy); json::get_float(scale[0], "z", sz);*/ entity->GetTransform().SetPosition(DirectX::XMFLOAT3(px, py, pz)); entity->GetTransform().SetRotation(rx, ry, rz); entity->GetTransform().SetScale(sx, sy, sz); #pragma endregion Load Entity Transform // Loop through Components array const rapidjson::Value& allComponents = object["Components"]; // Gets json array of all components // MESH RENDERER const rapidjson::Value& meshRenderer = allComponents[0]["MeshRenderer"]; bool foundModel = false; std::string model_FilePath; MeshRenderer* mr = nullptr; json::get_string(meshRenderer[0], "Model", model_FilePath); if (model_FilePath != "NONE" && !foundModel) foundModel = true; if (foundModel) { mr = entity->AddComponent<MeshRenderer>(); mr->InitFromJSON(entity, meshRenderer); // Determine what kind of material the object posseses // so they can be drawn in the apropriat order in the render pipeline if (mr->GetModel()->GetMaterial()->GetMaterialFlags() == Material::eFlags::FOLIAGE) scene->GetRenderManager().AddFoliageObject(mr); if (mr->GetModel()->GetMaterial()->GetMaterialFlags() == Material::eFlags::NOFLAGS) scene->GetRenderManager().AddOpaqueObject(mr); if (mr->GetModel()->GetMaterial()->GetMaterialFlags() == Material::eFlags::WATER) scene->GetRenderManager().AddFoliageObject(mr); } entity->SetHasMeshRenderer(foundModel); // LUA SCRIPT(s) const rapidjson::Value& luaScript = allComponents[1]["LuaScript"]; LuaScript* ls = entity->AddComponent<LuaScript>(); ls->InitFromJSON(entity, luaScript); scene->GetLuaManager().AddScript(ls); // EDITOR SELECTION const rapidjson::Value& editorSelection = allComponents[2]["EditorSelection"]; bool canBeSelected = false; std::string mode; json::get_string(editorSelection[0], "Mode", mode); if (mode != "OFF") canBeSelected = true; if (canBeSelected) entity->AddComponent<EditorSelection>()->InitFromJSON(entity, editorSelection); entity->SetHasEditorSelection(canBeSelected); // RIGID BODY if (scene->IsPhysicsEnabled()) { const rapidjson::Value& rigidBody = allComponents[3]["RigidBody"]; std::string hasPhysics; RigidBody* ps = nullptr; json::get_string(rigidBody[0], "ColliderType", hasPhysics); if (hasPhysics != "NONE") { ps = entity->AddComponent<RigidBody>(); ps->InitFromJSON(entity, rigidBody); ps->SetColliderTag(colliderTag); colliderTag++; scene->GetPhysicsSystem().AddEntity(ps); } } scene->AddEntity(entity); id = nullptr; entity = nullptr; }// End Load Entity //const rapidjson::Value& worldObjects = masterDocument["World"]; // Arr //for (rapidjson::SizeType o = 0; o < worldObjects.Size(); o++) //{ // const rapidjson::Value& object = worldObjects[o]; // Current object in Objects array (unique entity, perform calls on this object) // std::string objectType; // json::get_string(object, "Type", objectType); // if (objectType == "Sky") // { // if (entity == nullptr) // { // id = new ID(); // entity = new Entity(scene, (*id)); // } // const rapidjson::Value& allComponents = object["Components"]; // Gets json array of all components // // MESH RENDERER // const rapidjson::Value& meshRenderer = allComponents[0]["MeshRenderer"]; // bool foundModel = false; // std::string model_FilePath; // json::get_string(meshRenderer[0], "Model", model_FilePath); // if (model_FilePath != "NONE" && !foundModel) // foundModel = true; // if (foundModel) // entity->AddComponent<MeshRenderer>()->InitFromJSON(entity, meshRenderer); // Graphics::Instance()->SetSkybox(entity); // Graphics::Instance()->InitSkybox(); // break; // } //} return true; } bool FileSystem::WriteSceneToJSON(Scene* scene) { using namespace rapidjson; StringBuffer sb; PrettyWriter<StringBuffer> writer(sb); writer.StartObject(); // Start File writer.Key("SceneName"); writer.String(scene->GetSceneName().c_str()); writer.Key("Objects"); writer.StartArray();// Start Objects std::list<Entity*>::iterator iter; for (iter = scene->GetAllEntities()->begin(); iter != scene->GetAllEntities()->end(); iter++) { if ((*iter)->CanBeJSONSaved()) (*iter)->WriteToJSON(writer); } writer.EndArray(); // End Objects writer.EndObject(); // End File // Final Export std::string sceneName = "..\\Assets\\Scenes\\NewScene\\" + scene->GetSceneName() + ".json"; DEBUGLOG("[FileSystem] " + sceneName); std::ofstream offstream(sceneName.c_str()); offstream << sb.GetString(); if (!offstream.good()) ErrorLogger::Log("Failed to write to json file"); return true; }
30.708772
166
0.675503
[ "mesh", "render", "object", "model", "transform" ]
4543a528b5555d518e07d60bba2bc4a416b5edab
1,901
cc
C++
src/object/primitive/sphere.cc
QRWells/Cherry
4f771dd12297810ee44f165e7c397b97f71f4519
[ "MIT" ]
null
null
null
src/object/primitive/sphere.cc
QRWells/Cherry
4f771dd12297810ee44f165e7c397b97f71f4519
[ "MIT" ]
null
null
null
src/object/primitive/sphere.cc
QRWells/Cherry
4f771dd12297810ee44f165e7c397b97f71f4519
[ "MIT" ]
null
null
null
// Copyright (c) 2021 QRWells. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. // // This file is part of Project Cherry. // File Name : sphere.cpp // Author : QRWells // Created at : 2021/08/26 18:46 // Description : #include "object/primitive/sphere.h" #include "core/material.h" #include "utility/algorithm.h" #include "utility/constant.h" #include "utility/random.h" namespace cherry { auto Sphere::Intersect(const Ray& ray, Intersection& intersection) const -> bool { auto const kL = ray.origin - center_; auto const kA = ray.direction.Norm2(); auto const kB = 2 * ray.direction.Dot(kL); auto const kC = kL.Norm2() - radius2_; double t0 = 0; double t1 = 0; if (!SolveQuadratic(kA, kB, kC, t0, t1)) return false; if (t0 < 1e-2) t0 = t1; if (t0 < 1e-1) return false; Intersection result; result.coordinate = math::Vector3d(ray.origin + ray.direction * t0); result.normal = math::Vector3d(result.coordinate - center_).Normalized(); result.material = this->material_; result.distance = t0; intersection = result; return true; } auto Sphere::GetBounds() -> Box { auto const kR = math::Vector3d(radius_); return {center_ - kR, center_ + kR}; } void Sphere::Sample(Intersection& pos, double& pdf) { double const kTheta = PI_TIMES_2 * GetRandomDouble(); double const kPhi = PI * GetRandomDouble(); math::Vector3d const kDir(std::cos(kPhi), std::sin(kPhi) * std::cos(kTheta), std::sin(kPhi) * std::sin(kTheta)); pos.coordinate = center_ + radius_ * kDir; pos.normal = kDir; pos.material = material_; pdf = 1.0 / GetSurfaceArea(); } auto Sphere::HasEmission() const -> bool { return material_->GetEmission().Norm2() > EPSILON; } auto Sphere::GetSurfaceArea() const -> double { return radius2_ * PI_TIMES_4; } } // namespace cherry
32.775862
79
0.676486
[ "object" ]
45465207d235563b13d35d112872f96303d77198
1,547
cpp
C++
src/shell/token_count.cpp
stanford-cs242/lean
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
[ "Apache-2.0" ]
null
null
null
src/shell/token_count.cpp
stanford-cs242/lean
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
[ "Apache-2.0" ]
null
null
null
src/shell/token_count.cpp
stanford-cs242/lean
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
[ "Apache-2.0" ]
3
2021-11-22T12:13:18.000Z
2022-02-21T06:26:40.000Z
#include <fstream> #include <iostream> #include "frontends/lean/scanner.h" #include "kernel/environment.h" #include "library/io_state.h" #include "init/init.h" #include "kernel/standard_kernel.h" #include "frontends/lean/token_table.h" #include "frontends/lean/parser_config.h" int main(int argc, char** argv) { if (argc == 1) { std::cout << "Missing argument file" << std::endl; return 1; } std::filebuf fb; std::string path(argv[1]); if (!fb.open(path, std::ios::in)) { std::cout << "Fail to open " << argv[1] << std::endl; return 1; } std::istream istr(&fb); std::vector<std::string> new_tokens = {"∨", "∃", "↦", "*", "=", "ℕ", "∧", ";", "<|>"}; lean::initialize(); lean::environment env = lean::mk_environment(); for (std::string& tok : new_tokens) { env = lean::add_token(env, lean::token_entry(tok)); } lean::scanner scanner(istr); lean::buffer<lean::token> buffer; int count = 0; while (true) { lean::token tok = lean::read_tokens( env, lean::get_global_ios(), scanner, buffer, true); if (tok.kind() == lean::token_kind::Eof) { break; } else if (tok.kind() == lean::token_kind::CommandKeyword) { count += 1; // std::cout << tok.get_token_info().token() << std::endl; } } count += buffer.size(); std::cout << count << std::endl; return 0; }
28.127273
88
0.525533
[ "vector" ]
4546e2e5fecc17321e8126485022b4ac30876747
3,177
cc
C++
lite/demo/cxx/train_demo/cplus_train/data_reader.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/demo/cxx/train_demo/cplus_train/data_reader.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/demo/cxx/train_demo/cplus_train/data_reader.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "include/data_reader.h" #include <limits> using std::string; using std::vector; int FEATURE_NUM = 13; float rate = 0.8; int get_samples(string line, vector<float>* feature, float* label) { std::istringstream reader(line); std::vector<float> numbers; do { // read as many numbers as possible. for (float number; reader >> number;) { numbers.push_back(number); } // consume and discard token from stream. if (reader.fail()) { reader.clear(); std::string token; reader >> token; } } while (!reader.eof()); assert(numbers.size() == FEATURE_NUM + 1); for (int i = 0; i < FEATURE_NUM; i++) { feature->push_back(numbers[i]); } *label = numbers[FEATURE_NUM]; return 0; } int normalize(const vector<vector<float>>& origin_features, vector<vector<float>>* features, float rate) { int inf = std::numeric_limits<int>::max(); vector<float> min_vec(FEATURE_NUM, static_cast<float>(inf)); vector<float> max_vec(FEATURE_NUM, -(static_cast<float>(inf))); vector<float> sum_vec(FEATURE_NUM, 0); vector<float> avg_vec(FEATURE_NUM, 0); for (int i = 0; i < origin_features.size(); i++) { for (int j = 0; j < FEATURE_NUM; j++) { min_vec[j] = min(min_vec[j], origin_features[i][j]); max_vec[j] = max(max_vec[j], origin_features[i][j]); sum_vec[j] += origin_features[i][j]; } } for (int i = 0; i < FEATURE_NUM; i++) { avg_vec[i] = sum_vec[i] / origin_features.size(); } for (int i = 0; i < origin_features.size() * rate - 1; i++) { vector<float> feat; for (int j = 0; j < FEATURE_NUM; j++) { feat.push_back((origin_features[i][j] - avg_vec[j]) / (max_vec[j] - min_vec[j])); } features->push_back(feat); } } int read_samples(const string fname, vector<vector<float>>* features, vector<float>* labels) { fstream fin; fin.open(fname); if (!static_cast<bool>(fin)) { return 1; } vector<vector<float>> origin_features; vector<string> lines; string line; while (getline(fin, line)) { lines.push_back(line); } fin.close(); for (int i = 0; i < lines.size(); i++) { vector<float> feat; float lbl = 0; get_samples(lines[i], &feat, &lbl); origin_features.push_back(feat); if (i < lines.size() * rate - 1) { labels->push_back(lbl); } } cout << "finish read fata" << endl; normalize(origin_features, features, rate); assert(features->size() == labels->size()); return 0; }
28.881818
75
0.62921
[ "vector" ]
45490464296ca08d8bc7847b265b9ca6ffb62618
2,390
cpp
C++
base/Image.cpp
rsburke4/Raymarcher
ae9edd033122d2e0c28946ee6bfb165d18ad67ef
[ "MIT" ]
null
null
null
base/Image.cpp
rsburke4/Raymarcher
ae9edd033122d2e0c28946ee6bfb165d18ad67ef
[ "MIT" ]
null
null
null
base/Image.cpp
rsburke4/Raymarcher
ae9edd033122d2e0c28946ee6bfb165d18ad67ef
[ "MIT" ]
null
null
null
#include "Image.h" #include <iostream> using namespace std; using namespace lux; const float Image::interpolatedValue( float x, float y, int c ) const { int ix, iy, iix, iiy; float wx, wy, wwx, wwy; interpolationCoefficients( x, y, wx, wwx, wy, wwy, ix, iix, iy, iiy ); float v = value( ix, iy, c ) * wx * wy + value( iix, iy, c ) * wwx * wy + value( ix, iiy, c ) * wx * wwy + value( iix, iiy, c ) * wwx * wwy; return v; } std::vector<float> Image::interpolatedPixel( float x, float y ) const { int ix, iy, iix, iiy; float wx, wy, wwx, wwy; interpolationCoefficients( x, y, wx, wwx, wy, wwy, ix, iix, iy, iiy ); std::vector<float> pix; for( size_t c=0;c<Depth();c++ ) { float v = value( ix, iy, c ) * wx * wy + value( iix, iy, c ) * wwx * wy + value( ix, iiy, c ) * wx * wwy + value( iix, iiy, c ) * wwx * wwy; pix.push_back( v ); } return pix; } void imageLinearInterpolation( float x, float dx, int nx, int& i, int& ii, float& w, float& ww, bool isperiodic ) { float r = x/dx; i = r; if( !isperiodic ) { if( i >= 0 && i < nx ) { ii = i + 1; w = r-i; ww = 1.0 - w; if( ii >= nx ) { ii = nx-1; } } else { i = ii = 0; w = ww = 0; } } else { w = r-i; while( i < 0 ){ i += nx; } while( i >= nx ){ i -= nx; } ii = i+1; ww = 1.0 - w; if( ii >= nx ){ ii -= nx; } } } void Image::interpolationCoefficients( float x, float y, float& wx, float& wwx, float& wy, float& wwy, int& ix, int& iix, int& iy, int& iiy ) const { imageLinearInterpolation( x, 1.0/Width(), Width(), ix, iix, wx, wwx, false ); imageLinearInterpolation( y, 1.0/Height(), Height(), iy, iiy, wy, wwy, false ); } void lux::setPixel( Image& img, int x, int y, std::vector<float>& value ) { size_t nb = ( value.size() < img.Depth() ) ? value.size() : img.Depth(); for( size_t i=0;i<nb;i++ ) { img.value( x, y, i ) = value[i]; } } vector<float> Image::getdata1d(){ vector<float> data1d; for(size_t i = 0; i < data.size(); i++){ for(size_t j = 0; j < data[i].size(); j++){ data1d.push_back(data[i][j]); } } return data1d; }
23.203883
113
0.488285
[ "vector" ]
454b1ddc37dc85369215401941e5f63c4fd6ae2d
570
hpp
C++
Framework/Geometries/Polyhedron.hpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
3
2019-06-07T15:29:45.000Z
2019-11-11T01:26:12.000Z
Framework/Geometries/Polyhedron.hpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
null
null
null
Framework/Geometries/Polyhedron.hpp
kiorisyshen/newbieGameEngine
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
[ "MIT" ]
null
null
null
#pragma once #include "Geometry.hpp" namespace newbieGE { struct Polyhedron : public Geometry { FaceSet Faces; Polyhedron() : Geometry(GeometryType::kPolyhydron) { } // GetAabb returns the axis aligned bounding box in the coordinate frame of the given transform trans. void GetAabb(const Matrix4X4f &trans, Vector3f &aabbMin, Vector3f &aabbMax) const final; void AddFace(PointList vertices, const PointPtr &inner_point); void AddTetrahedron(const PointList vertices); }; } // namespace newbieGE
27.142857
106
0.685965
[ "geometry", "transform" ]
454c39a787ea0fb8919524c5155eb83fb67754f8
8,121
cpp
C++
03_Tutorial/T02_XMCocos2D/Source/Test/TestNetwork.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
03_Tutorial/T02_XMCocos2D/Source/Test/TestNetwork.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
03_Tutorial/T02_XMCocos2D/Source/Test/TestNetwork.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File TestNetwork.cpp * Author Young-Hwan Mun * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 cocos2d-x.org * * http://www.cocos2d-x.org * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * Contact Email: xmsoft77@gmail.com * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "TestNetwork.h" KDvoid TestNetwork::onEnter ( KDvoid ) { TestBasic::onEnter ( ); const CCSize& tLyrSize = this->getContentSize ( ); CCLabelTTF* pLabel = CCLabelTTF::create ( "Http Request Test", "fonts/arial.ttf", 28 ); pLabel->setPosition ( ccp ( tLyrSize.cx / 2, tLyrSize.cy - 150 ) ); this->addChild ( pLabel, 0 ); // Get CCMenuItemLabel* pItemGet = CCMenuItemLabel::create ( CCLabelTTF::create ( "Test Get", "fonts/arial.ttf", 22 ), this, menu_selector ( TestNetwork::onMenuGetTestClicked ) ); pItemGet->setPosition ( ccp ( tLyrSize.cx / 2, tLyrSize.cy - 200 ) ); // Post CCMenuItemLabel* pItemPost = CCMenuItemLabel::create ( CCLabelTTF::create ( "Test Post", "fonts/arial.ttf", 22 ), this, menu_selector ( TestNetwork::onMenuPostTestClicked ) ); pItemPost->setPosition ( ccp ( tLyrSize.cx / 2, tLyrSize.cy - 250 ) ); // Post Binary CCMenuItemLabel* pItemPostBinary = CCMenuItemLabel::create ( CCLabelTTF::create ( "Test Post Binary", "fonts/arial.ttf", 22 ), this, menu_selector ( TestNetwork::onMenuPostBinaryTestClicked ) ); pItemPostBinary->setPosition ( ccp ( tLyrSize.cx / 2, tLyrSize.cy - 300 ) ); CCMenu* pMenuRequest = CCMenu::create ( pItemGet, pItemPost, pItemPostBinary, KD_NULL ); this->addChild ( pMenuRequest ); // Response Code Label m_pLabel = CCLabelTTF::create ( "HTTP Status Code", "fonts/Marker Felt.ttf", 32, CCSizeZero, kCCTextAlignmentLeft ); m_pLabel->setPosition ( ccp ( tLyrSize.cx / 2, tLyrSize.cy - 350 ) ); this->addChild ( m_pLabel ); } KDvoid TestNetwork::onExit ( KDvoid ) { CCHttpClient::getInstance ( )->destroyInstance ( ); TestBasic::onExit ( ); } KDvoid TestNetwork::onMenuGetTestClicked ( CCObject* pSender ) { CCHttpClient* pHttpClient = CCHttpClient::getInstance ( ); CCHttpRequest* pRequest = KD_NULL; // test 1 pRequest = new CCHttpRequest ( ); pRequest->setUrl ( "http://just-make-this-request-failed.com" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpGet ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); pRequest->setTag ( "GET test1" ); pHttpClient->send ( pRequest ); pRequest->release ( ); // test 2 pRequest = new CCHttpRequest ( ); // required fields pRequest->setUrl ( "http://www.httpbin.org/ip" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpGet ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); // optional fields pRequest->setTag ( "GET test2" ); pHttpClient->send ( pRequest ); // don't forget to release it, pair to new pRequest->release ( ); // test 3 pRequest = new CCHttpRequest ( ); pRequest->setUrl ( "http://www.httpbin.org/get" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpGet ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); pRequest->setTag ( "GET test3" ); pHttpClient->send ( pRequest ); pRequest->release ( ); // waiting m_pLabel->setString ( "waiting..." ); } KDvoid TestNetwork::onMenuPostTestClicked ( CCObject* pSender ) { CCHttpClient* pHttpClient = CCHttpClient::getInstance ( ); CCHttpRequest* pRequest = KD_NULL; const KDchar* szPostData = KD_NULL; // test 1 pRequest = new CCHttpRequest ( ); pRequest->setUrl ( "http://www.httpbin.org/post" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpPost ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); // write the post data szPostData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; pRequest->setRequestData ( szPostData, kdStrlen ( szPostData ) ); pRequest->setTag ( "POST test1" ); pHttpClient->send ( pRequest ); pRequest->release ( ); // test 2: set Content-Type pRequest = new CCHttpRequest ( ); pRequest->setUrl ( "http://www.httpbin.org/post" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpPost ); std::vector<std::string> aHeaders; aHeaders.push_back ( "Content-Type: application/json; charset=utf-8" ); pRequest->setHeaders ( aHeaders ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); // write the post data szPostData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest"; pRequest->setRequestData ( szPostData, kdStrlen ( szPostData ) ); pRequest->setTag ( "POST test2" ); pHttpClient->send ( pRequest ); pRequest->release ( ); // waiting m_pLabel->setString ( "waiting..." ); } KDvoid TestNetwork::onMenuPostBinaryTestClicked ( CCObject* pSender ) { CCHttpRequest* pRequest = new CCHttpRequest ( ); pRequest->setUrl ( "http://www.httpbin.org/post" ); pRequest->setRequestType ( CCHttpRequest::kCCHttpPost ); pRequest->setResponseCallback ( this, callfuncND_selector ( TestNetwork::onHttpRequestCompleted ) ); // write the post data KDchar szPostData [ 22 ] = "binary=hello\0\0cocos2d"; // including \0, the strings after \0 should not be cut in response pRequest->setRequestData ( szPostData, 22 ); pRequest->setTag ( "POST Binary test" ); CCHttpClient::getInstance ( )->send ( pRequest ); pRequest->release ( ); // waiting m_pLabel->setString ( "waiting..." ); } KDvoid TestNetwork::onHttpRequestCompleted ( CCNode* pSender, KDvoid* pData ) { CCHttpResponse* pResponse = (CCHttpResponse*) pData; if ( !pResponse ) { return; } // You can get original request type from: response->request->reqType if ( 0 != kdStrlen ( pResponse->getHttpRequest ( )->getTag ( ) ) ) { CCLOG ( "%s completed", pResponse->getHttpRequest ( )->getTag ( ) ); } KDint nStatusCode = pResponse->getResponseCode ( ); m_pLabel->setString ( ccszf ( "HTTP Status Code: %d, tag = %s", nStatusCode, pResponse->getHttpRequest ( )->getTag ( ) ) ); CCLOG ( "response code: %d", nStatusCode ); if ( !pResponse->isSucceed ( ) ) { CCLOG ( "response failed" ); CCLOG ( "error buffer: %s", pResponse->getErrorBuffer ( ) ); return; } // dump data std::vector<KDchar>* pBuffer = pResponse->getResponseData ( ); std::string sOutput = "Http Test, dump data: "; for ( KDuint i = 0; i < pBuffer->size ( ); i++ ) { sOutput.push_back ( (*pBuffer)[ i ] ); } CCLOG ( sOutput.c_str ( ) ); }
35.77533
127
0.62677
[ "vector" ]
4566e84e78be32e51abbb2f8f9296f0ad23b0b67
7,047
cpp
C++
src/PredFinder/db/PlayerDB.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/PredFinder/db/PlayerDB.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/PredFinder/db/PlayerDB.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
/** * Functionality for reading NFL world knowledge. * * @file PlayerDB.cpp * @author nward@bbn.com * @date 2010.08.17 **/ #include "Generic/common/leak_detection.h" #include "Generic/common/SessionLogger.h" #include "Generic/sqlite/SqliteDB.h" #include "PlayerDB.h" #include "boost/foreach.hpp" #include "boost/lexical_cast.hpp" #include "boost/algorithm/string/replace.hpp" #include <iostream> /** * Read the sqlite database from the specified * location into cached tables. * * @param db_location Path to the sqlite .db file. If string is empty, db will not be loaded. * * @author nward@bbn.com * @date 2010.08.17 **/ PlayerDB::PlayerDB(const std::string db_location) { // Ignore unspecified parameter if (db_location == "") return; // Open the database SessionLogger::info("LEARNIT") << "Reading NFL player database " << db_location << "..." << std::endl; SqliteDB db(db_location); // Populate the player lookup table Table_ptr player_roster = db.exec( L"SELECT roster.season, team.ontology_uri, player.name, player.uri " L"FROM roster, team, player " L"WHERE roster.player = player.id AND roster.team = team.id AND team.ontology_uri IS NOT NULL" ); BOOST_FOREACH(std::vector<std::wstring> roster_row, *player_roster) { // Get the values from the database int season = boost::lexical_cast<int>(roster_row[0]); std::wstring team_uri = roster_row[1]; std::wstring player_name = roster_row[2]; std::wstring player_uri = boost::replace_first_copy(roster_row[3], L"http://www.footballdb.com/players/", L"fdb:"); // Make sure this season has an entry std::pair<SeasonMap::iterator, bool> season_insert = _players_by_team_and_season.insert(SeasonMap::value_type(season, StringVectorMap())); // Make sure this team has an entry std::pair<StringVectorMap::iterator, bool> team_insert = season_insert.first->second.insert(StringVectorMap::value_type(team_uri, std::vector<std::pair<std::wstring,std::wstring> >())); // Append this player team_insert.first->second.push_back(std::pair<std::wstring, std::wstring>(player_name, player_uri)); } SessionLogger::info("LEARNIT") << " Found " << player_roster->size() << " roster entries over " << _players_by_team_and_season.size() << " seasons" << std::endl; } /** * Finds all of the teams this player could be a member of, * optionally restricted by season. Multiple returns are allowed, * since some players trade mid-season, and some players share the same name. * * @param player The string name of the player to check for. * @param season The optional NFL season year to restrict by. * @return A map from player URIs to a set of team URIs; for most situations, * with a unique player name and season restriction, this will be one pair. * * @author nward@bbn.com * @date 2010.08.17 **/ PlayerResultMap PlayerDB::get_teams_for_player(const std::wstring & player, int season) const { // Result map PlayerResultMap result; // Check if a season was specified if (season != -1) { // Get the season's team map SeasonMap::const_iterator season_i = _players_by_team_and_season.find(season); if (season_i != _players_by_team_and_season.end()) { // Loop through this season's team rosters looking for this player BOOST_FOREACH(StringVectorMap::value_type team_roster, season_i->second) { // Loop through this team roster looking for this player for (std::vector<std::pair<std::wstring, std::wstring> >::iterator roster_i = team_roster.second.begin(); roster_i != team_roster.second.end(); roster_i++) { // Check if this is a matching player if (roster_i->first == player) { // Associate this player URI and team URI std::pair<PlayerResultMap::iterator, bool> team_insert = result.insert(PlayerResultMap::value_type(roster_i->second, std::set<std::wstring>())); team_insert.first->second.insert(team_roster.first); } } } } } else { BOOST_FOREACH(SeasonMap::value_type season_teams, _players_by_team_and_season) { // Loop through this season's team rosters looking for this player BOOST_FOREACH(StringVectorMap::value_type team_roster, season_teams.second) { // Loop through this team roster looking for this player for (std::vector<std::pair<std::wstring, std::wstring> >::iterator roster_i = team_roster.second.begin(); roster_i != team_roster.second.end(); roster_i++) { // Check if this is a matching player if (roster_i->first == player) { // Associate this player URI and team URI std::pair<PlayerResultMap::iterator, bool> team_insert = result.insert(PlayerResultMap::value_type(roster_i->second, std::set<std::wstring>())); team_insert.first->second.insert(team_roster.first); } } } } } // Done return result; } /** * Finds all of the unique player URIs that could match the * specified player name assuming that play for a particular team. * Multiple returns are allowed since some players share the * same name, even on the same team in the same season, although * it's unlikely. * * @param player The string name of the player to check for. * @param team The optional NFL team URI to restrict by. * @param season The optional NFL season year to restrict by. * @return A vector of player URIs; for most situations, its * length will be 1. * * @author nward@bbn.com * @date 2010.08.17 **/ std::vector<std::wstring> PlayerDB::get_uris_for_player(const std::wstring & player, const std::wstring & team, int season) const { // Result vector std::vector<std::wstring> player_uris; // Find all URI/team combinations for this player name PlayerResultMap player_team_results = get_teams_for_player(player, season); // If a team was specified, restrict the URI search to that if (team != L"") { BOOST_FOREACH(PlayerResultMap::value_type player_team, player_team_results) { // See if this player played for this team std::set<std::wstring>::iterator team_i = player_team.second.find(team); if (team_i != player_team.second.end()) { player_uris.push_back(player_team.first); } } } else { // Just use all of the URIs found BOOST_FOREACH(PlayerResultMap::value_type player_team, player_team_results) { player_uris.push_back(player_team.first); } } // Done return player_uris; } /** * Checks if a player played for a particular team at some point. * * @param player The string name of the player to check for. * @param team The NFL team URI to check for. * @param season The optional NFL season year to restrict by. * @return True if the player played for that team ever, or in * the specified season. * * @author nward@bbn.com * @date 2010.08.17 **/ bool PlayerDB::is_player_on_team(const std::wstring & player, const std::wstring & team, int season) const { // Just check for emptiness of the URI table return get_uris_for_player(player, team, season).size() != 0; }
40.268571
188
0.702143
[ "vector" ]
456c3033f2b6eba0f4f02905ef9bf1aa915736f9
17,519
cpp
C++
gdal/gcore/gdalrasterblock.cpp
flippmoke/gdal
5b74f8a539c66b841e80a339854507ebe7cc1b8c
[ "MIT" ]
2
2015-07-24T16:16:34.000Z
2015-07-24T16:16:37.000Z
gdal/gcore/gdalrasterblock.cpp
flippmoke/gdal
5b74f8a539c66b841e80a339854507ebe7cc1b8c
[ "MIT" ]
null
null
null
gdal/gcore/gdalrasterblock.cpp
flippmoke/gdal
5b74f8a539c66b841e80a339854507ebe7cc1b8c
[ "MIT" ]
null
null
null
/****************************************************************************** * $Id$ * * Project: GDAL Core * Purpose: Implementation of GDALRasterBlock class and related global * raster block cache management. * Author: Frank Warmerdam, warmerdam@pobox.com * ********************************************************************** * Copyright (c) 1998, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2008-2013, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gdal_priv.h" #include "cpl_multiproc.h" CPL_CVSID("$Id$"); /************************************************************************/ /* GDALSetCacheMax() */ /************************************************************************/ /** * \brief Set maximum cache memory. * * This function sets the maximum amount of memory that GDAL is permitted * to use for GDALRasterBlock caching. The unit of the value is bytes. * * The maximum value is 2GB, due to the use of a signed 32 bit integer. * Use GDALSetCacheMax64() to be able to set a higher value. * * @param nNewSizeInBytes the maximum number of bytes for caching. */ void CPL_STDCALL GDALSetCacheMax( int nNewSizeInBytes ) { GetGDALRasterBlockManager()->SetCacheMax(nNewSizeInBytes); } /************************************************************************/ /* GDALSetCacheMax64() */ /************************************************************************/ /** * \brief Set maximum cache memory. * * This function sets the maximum amount of memory that GDAL is permitted * to use for GDALRasterBlock caching. The unit of the value is bytes. * * Note: On 32 bit platforms, the maximum amount of memory that can be addressed * by a process might be 2 GB or 3 GB, depending on the operating system * capabilities. This function will not make any attempt to check the * consistency of the passed value with the effective capabilities of the OS. * * @param nNewSizeInBytes the maximum number of bytes for caching. * * @since GDAL 1.8.0 */ void CPL_STDCALL GDALSetCacheMax64( GIntBig nNewSizeInBytes ) { GetGDALRasterBlockManager()->SetCacheMax(nNewSizeInBytes); } /************************************************************************/ /* GDALGetCacheMax() */ /************************************************************************/ /** * \brief Get maximum cache memory. * * Gets the maximum amount of memory available to the GDALRasterBlock * caching system for caching GDAL read/write imagery. * * The first type this function is called, it will read the GDAL_CACHEMAX * configuation option to initialize the maximum cache memory. * * This function cannot return a value higher than 2 GB. Use * GDALGetCacheMax64() to get a non-truncated value. * * @return maximum in bytes. */ int CPL_STDCALL GDALGetCacheMax() { GIntBig nRes = GetGDALRasterBlockManager()->GetCacheMax(); if (nRes > INT_MAX) { static int bHasWarned = FALSE; if (!bHasWarned) { CPLError(CE_Warning, CPLE_AppDefined, "Cache max value doesn't fit on a 32 bit integer. " "Call GDALGetCacheMax64() instead"); bHasWarned = TRUE; } nRes = INT_MAX; } return (int)nRes; } /************************************************************************/ /* GDALGetCacheMax64() */ /************************************************************************/ /** * \brief Get maximum cache memory. * * Gets the maximum amount of memory available to the GDALRasterBlock * caching system for caching GDAL read/write imagery. * * The first type this function is called, it will read the GDAL_CACHEMAX * configuation option to initialize the maximum cache memory. * * @return maximum in bytes. * * @since GDAL 1.8.0 */ GIntBig CPL_STDCALL GDALGetCacheMax64() { return GetGDALRasterBlockManager()->GetCacheMax(); } /************************************************************************/ /* GDALGetCacheUsed() */ /************************************************************************/ /** * \brief Get cache memory used. * * @return the number of bytes of memory currently in use by the * GDALRasterBlock memory caching. */ int CPL_STDCALL GDALGetCacheUsed() { GIntBig nCacheUsed = GetGDALRasterBlockManager()->GetCacheUsed(); if (nCacheUsed > INT_MAX) { static int bHasWarned = FALSE; if (!bHasWarned) { CPLError(CE_Warning, CPLE_AppDefined, "Cache used value doesn't fit on a 32 bit integer. " "Call GDALGetCacheUsed64() instead"); bHasWarned = TRUE; } return INT_MAX; } return (int)nCacheUsed; } /************************************************************************/ /* GDALGetCacheUsed64() */ /************************************************************************/ /** * \brief Get cache memory used. * * @return the number of bytes of memory currently in use by the * GDALRasterBlock memory caching. * * @since GDAL 1.8.0 */ GIntBig CPL_STDCALL GDALGetCacheUsed64() { return GetGDALRasterBlockManager()->GetCacheUsed(); } /************************************************************************/ /* GDALFlushCacheBlock() */ /* */ /* The workhorse of cache management! */ /************************************************************************/ /** * \brief Try to flush one cached raster block * * This function will search the first unlocked raster block and will * flush it to release the associated memory. * * @return TRUE if one block was flushed, FALSE if there are no cached blocks * or if they are currently locked. */ int CPL_STDCALL GDALFlushCacheBlock() { return GetGDALRasterBlockManager()->FlushCacheBlock(); } /************************************************************************/ /* ==================================================================== */ /* GDALRasterBlock */ /* ==================================================================== */ /************************************************************************/ /** * \class GDALRasterBlock "gdal_priv.h" * * GDALRasterBlock objects hold one block of raster data for one band * that is currently stored in the GDAL raster cache. The cache holds * some blocks of raster data for zero or more GDALRasterBand objects * across zero or more GDALDataset objects in a global raster cache with * a least recently used (LRU) list and an upper cache limit (see * GDALSetCacheMax()) under which the cache size is normally kept. * * Some blocks in the cache may be modified relative to the state on disk * (they are marked "Dirty") and must be flushed to disk before they can * be discarded. Other (Clean) blocks may just be discarded if their memory * needs to be recovered. * * In normal situations applications do not interact directly with the * GDALRasterBlock - instead it it utilized by the RasterIO() interfaces * to implement caching. * * Some driver classes are implemented in a fashion that completely avoids * use of the GDAL raster cache (and GDALRasterBlock) though this is not very * common. */ /************************************************************************/ /* GDALRasterBlock() */ /************************************************************************/ /** * @brief GDALRasterBlock Constructor * * Normally only called from GDALRasterBand::GetLockedBlockRef(). * * @param poBandIn the raster band used as source of raster block * being constructed. * * @param nXOffIn the horizontal block offset, with zero indicating * the left most block, 1 the next block and so forth. * * @param nYOffIn the vertical block offset, with zero indicating * the top most block, 1 the next block and so forth. */ GDALRasterBlock::GDALRasterBlock( GDALRasterBand *poBandIn, int nXOffIn, int nYOffIn, GDALRasterBlockManager *poManagerIn ) { CPLAssert( NULL != poBandIn ); poBand = poBandIn; poManager = poManagerIn; poBand->GetBlockSize( &nXSize, &nYSize ); eType = poBand->GetRasterDataType(); pData = NULL; bDirty = FALSE; bAttachedToCache = FALSE; bAttachedToBand = FALSE; bDelete = FALSE; nLockCount = 0; poNext = poPrevious = NULL; nXOff = nXOffIn; nYOff = nYOffIn; } /************************************************************************/ /* ~GDALRasterBlock() */ /************************************************************************/ /** * Block destructor. * * Normally called from GDALRasterBand::FlushBlock(). */ GDALRasterBlock::~GDALRasterBlock() { if( pData != NULL ) { VSIFree( pData ); } CPLAssert( nLockCount == 0 ); } /************************************************************************/ /* AddLock() */ /************************************************************************/ /** * Add a usage lock to the block. */ void GDALRasterBlock::AddLock() { CPLMutexHolderD( &(poBand->hBandMutex) ); nLockCount++; } /************************************************************************/ /* DropLock() */ /************************************************************************/ /** * Remove a lock from the block. */ void GDALRasterBlock::DropLock() { int bDeleteNow = FALSE; { CPLMutexHolderD( &(poBand->hBandMutex) ); nLockCount--; CPLAssert( nLockCount >= 0 ); if ( nLockCount == 0 && bDelete ) { if ( bAttachedToCache ) Detach(); if ( bAttachedToBand ) poBand->UnadoptBlock(nXOff, nYOff); bDeleteNow = TRUE; } } if ( bDeleteNow ) { if ( bDirty ) Write(); delete this; } } /************************************************************************/ /* Detach() */ /************************************************************************/ /** * Remove block from cache. * * This method removes the current block from the linked list used to keep * track of all cached blocks in order of age. It does not affect whether * the block is referenced by a GDALRasterBand nor does it destroy or flush * the block. */ void GDALRasterBlock::Detach() { CPLMutexHolderD( &(poManager->hRBMMutex) ); int nSizeInBytes; if ( bAttachedToCache ) { nSizeInBytes = nXSize * nYSize * (GDALGetDataTypeSize(eType)/8); poManager->nCacheUsed -= nSizeInBytes; } else { return; } bAttachedToCache = FALSE; if( poManager->poOldest == this ) poManager->poOldest = poPrevious; if( poManager->poNewest == this ) { poManager->poNewest = poNext; } if( poPrevious != NULL ) poPrevious->poNext = poNext; if( poNext != NULL ) poNext->poPrevious = poPrevious; poPrevious = NULL; poNext = NULL; } /************************************************************************/ /* Write() */ /************************************************************************/ /** * Force writing of the current block, if dirty. * * The block is written using GDALRasterBand::IWriteBlock() on it's * corresponding band object. Even if the write fails the block will * be marked clean. * * @return CE_None otherwise the error returned by IWriteBlock(). */ CPLErr GDALRasterBlock::Write() { if ( !GetDirty() ) return CE_None; CPLMutexHolderD( poBand->GetRWMutex() ); if( !GetDirty() ) return CE_None; if( poBand == NULL ) return CE_Failure; MarkClean(); if (poBand->eFlushBlockErr == CE_None) return poBand->IWriteBlock( nXOff, nYOff, pData ); else return poBand->eFlushBlockErr; } /************************************************************************/ /* Touch() */ /************************************************************************/ /** * Push block to top of LRU (least-recently used) list. * * This method is normally called when a block is used to keep track * that it has been recently used. */ void GDALRasterBlock::Touch() { int nSizeInBytes; CPLMutexHolderD( &(poManager->hRBMMutex) ); if ( bDelete ) return; if ( !bAttachedToCache ) { nSizeInBytes = nXSize * nYSize * (GDALGetDataTypeSize(eType)/8); poManager->nCacheUsed += nSizeInBytes; bAttachedToCache = TRUE; } if( poManager->poNewest == this ) return; if( poManager->poOldest == this ) poManager->poOldest = this->poPrevious; if( poPrevious != NULL ) poPrevious->poNext = poNext; if( poNext != NULL ) poNext->poPrevious = poPrevious; poPrevious = NULL; poNext = (GDALRasterBlock *) poManager->poNewest; if( poManager->poNewest != NULL ) { CPLAssert( poManager->poNewest->poPrevious == NULL ); poManager->poNewest->poPrevious = this; } poManager->poNewest = this; if( poManager->poOldest == NULL ) { CPLAssert( poPrevious == NULL && poNext == NULL ); poManager->poOldest = this; } #ifdef ENABLE_DEBUG poManager->Verify(); #endif } /************************************************************************/ /* Internalize() */ /************************************************************************/ /** * Allocate memory for block. * * This method allocates memory for the block, and attempts to flush other * blocks, if necessary, to bring the total cache size back within the limits. * * @return CE_None on success or CE_Failure if memory allocation fails. */ CPLErr GDALRasterBlock::Internalize() { void *pNewData; int nSizeInBytes; /* No risk of overflow as it is checked in GDALRasterBand::InitBlockInfo() */ nSizeInBytes = nXSize * nYSize * (GDALGetDataTypeSize(eType) / 8); pNewData = VSIMalloc( nSizeInBytes ); if( pNewData == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "GDALRasterBlock::Internalize : Out of memory allocating %d bytes.", nSizeInBytes); return( CE_Failure ); } if( pData != NULL ) memcpy( pNewData, pData, nSizeInBytes ); pData = pNewData; return( CE_None ); } /************************************************************************/ /* MarkDirty() */ /************************************************************************/ /** * Mark the block as modified. * * A dirty block is one that has been modified and will need to be written * to disk before it can be flushed. */ void GDALRasterBlock::MarkDirty() { //CPLMutexHolderD( &(poBand->hBandMutex) ); bDirty = TRUE; } /************************************************************************/ /* MarkClean() */ /************************************************************************/ /** * Mark the block as unmodified. * * A dirty block is one that has been modified and will need to be written * to disk before it can be flushed. */ void GDALRasterBlock::MarkClean() { //CPLMutexHolderD( &(poBand->hBandMutex) ); bDirty = FALSE; }
30.362218
86
0.503853
[ "object" ]
456cdb91748da7b24fe782da508cf26a2a85c20e
8,109
inl
C++
source/gts/include/gts/containers/VectorImpl_STL.inl
jeffhammond/GTS-GamesTaskScheduler
70a3031268968c4bdec3189cfdd3795b22cadf4e
[ "MIT" ]
1
2020-11-11T13:10:08.000Z
2020-11-11T13:10:08.000Z
source/gts/include/gts/containers/VectorImpl_STL.inl
JulianoCristian/GTS-GamesTaskScheduler
269aaced42b111c32b1c15bd748ae2058a3dc10a
[ "MIT" ]
null
null
null
source/gts/include/gts/containers/VectorImpl_STL.inl
JulianoCristian/GTS-GamesTaskScheduler
269aaced42b111c32b1c15bd748ae2058a3dc10a
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * 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. ******************************************************************************/ //------------------------------------------------------------------------------ template<typename T, typename TAlloc> Vector<T, TAlloc>::Vector(size_t count, const TAlloc& alloc) : m_vec(count, T(), alloc) { } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> Vector<T, TAlloc>::Vector(size_t count, T const& fill, const TAlloc& alloc) : m_vec(count, fill, alloc) { } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::iterator Vector<T, TAlloc>::begin() { return m_vec.begin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_iterator Vector<T, TAlloc>::begin() const { return m_vec.begin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_iterator Vector<T, TAlloc>::cbegin() const { return m_vec.cbegin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::iterator Vector<T, TAlloc>::end() { return m_vec.end(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_iterator Vector<T, TAlloc>::end() const { return m_vec.end(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_iterator Vector<T, TAlloc>::cend() const { return m_vec.cend(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::reverse_iterator Vector<T, TAlloc>::rbegin() { return m_vec.rbegin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_reverse_iterator Vector<T, TAlloc>::rbegin() const { return m_vec.rbegin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_reverse_iterator Vector<T, TAlloc>::crbegin() const { return m_vec.crbegin(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::reverse_iterator Vector<T, TAlloc>::rend() { return m_vec.rend(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_reverse_iterator Vector<T, TAlloc>::rend() const { return m_vec.rend(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> typename Vector<T, TAlloc>::const_reverse_iterator Vector<T, TAlloc>::crend() const { return m_vec.crend(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T& Vector<T, TAlloc>::operator[](size_t pos) { return m_vec[pos]; } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T const& Vector<T, TAlloc>::operator[](size_t pos) const { return m_vec[pos]; } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T& Vector<T, TAlloc>::back() { return m_vec.back(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T const& Vector<T, TAlloc>::back() const { return m_vec.back(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T& Vector<T, TAlloc>::front() { return m_vec.front(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T const& Vector<T, TAlloc>::front() const { return m_vec.front(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::push_back(T const& val) { m_vec.push_back(val); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::push_back(T&& val) { m_vec.push_back(std::move(val)); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::pop_back() { m_vec.pop_back(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::resize(size_t count) { m_vec.resize(count); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::resize(size_t count, T const& val) { m_vec.resize(count, val); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::reserve(size_t count) { m_vec.reserve(count); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::clear() { m_vec.clear(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> void Vector<T, TAlloc>::shrink_to_fit() { m_vec.shrink_to_fit(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T* Vector<T, TAlloc>::data() { return m_vec.data(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> T const* Vector<T, TAlloc>::data() const { return m_vec.data(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> bool Vector<T, TAlloc>::empty() const { return m_vec.empty(); } //------------------------------------------------------------------------------ template<typename T, typename TAlloc> size_t Vector<T, TAlloc>::size() const { return m_vec.size(); }
32.963415
86
0.45357
[ "vector" ]
4574c3d58a3a29950303d438c1e6d2c8e03c5359
28,216
cpp
C++
examples/basic/skeletalanimation.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
1
2017-08-17T15:28:24.000Z
2017-08-17T15:28:24.000Z
examples/basic/skeletalanimation.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
examples/basic/skeletalanimation.cpp
ChristophLGDV/Vulkan
390023982000b0d58031383779faf83d94be13dd
[ "MIT" ]
null
null
null
/* * Vulkan Example - Skeletal animation * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "vulkanExampleBase.h" #include <glm/gtc/type_ptr.hpp> // Vertex layout used in this example struct Vertex { glm::vec3 pos; glm::vec3 normal; glm::vec2 uv; glm::vec3 color; // Max. four bones per vertex float boneWeights[4]; uint32_t boneIDs[4]; }; std::vector<vkx::VertexLayout> vertexLayout = { vkx::VertexLayout::VERTEX_LAYOUT_POSITION, vkx::VertexLayout::VERTEX_LAYOUT_NORMAL, vkx::VertexLayout::VERTEX_LAYOUT_UV, vkx::VertexLayout::VERTEX_LAYOUT_COLOR, vkx::VertexLayout::VERTEX_LAYOUT_DUMMY_VEC4, vkx::VertexLayout::VERTEX_LAYOUT_DUMMY_VEC4 }; // Maximum number of bones per mesh // Must not be higher than same const in skinning shader #define MAX_BONES 64 // Maximum number of bones per vertex #define MAX_BONES_PER_VERTEX 4 // Skinned mesh class // Per-vertex bone IDs and weights struct VertexBoneData { std::array<uint32_t, MAX_BONES_PER_VERTEX> IDs; std::array<float, MAX_BONES_PER_VERTEX> weights; // Ad bone weighting to vertex info void add(uint32_t boneID, float weight) { for (uint32_t i = 0; i < MAX_BONES_PER_VERTEX; i++) { if (weights[i] == 0.0f) { IDs[i] = boneID; weights[i] = weight; return; } } } }; // Stores information on a single bone struct BoneInfo { aiMatrix4x4 offset; aiMatrix4x4 finalTransformation; BoneInfo() { offset = aiMatrix4x4(); finalTransformation = aiMatrix4x4(); }; }; class SkinnedMesh { public: // Bone related stuff // Maps bone name with index std::map<std::string, uint32_t> boneMapping; // Bone details std::vector<BoneInfo> boneInfo; // Number of bones present uint32_t numBones = 0; // Root inverese transform matrix aiMatrix4x4 globalInverseTransform; // Per-vertex bone info std::vector<VertexBoneData> bones; // Bone transformations std::vector<aiMatrix4x4> boneTransforms; // Modifier for the animation float animationSpeed = 0.75f; // Currently active animation aiAnimation* pAnimation; // Vulkan buffers vkx::MeshBuffer meshBuffer; // Reference to assimp mesh // Required for animation vkx::MeshLoader* meshLoader; // Set active animation by index void setAnimation(uint32_t animationIndex) { assert(animationIndex < meshLoader->pScene->mNumAnimations); pAnimation = meshLoader->pScene->mAnimations[animationIndex]; } // Load bone information from ASSIMP mesh void loadBones(uint32_t meshIndex, const aiMesh* pMesh, std::vector<VertexBoneData>& Bones) { for (uint32_t i = 0; i < pMesh->mNumBones; i++) { uint32_t index = 0; assert(pMesh->mNumBones <= MAX_BONES); std::string name(pMesh->mBones[i]->mName.data); if (boneMapping.find(name) == boneMapping.end()) { // Bone not present, add new one index = numBones; numBones++; BoneInfo bone; boneInfo.push_back(bone); boneInfo[index].offset = pMesh->mBones[i]->mOffsetMatrix; boneMapping[name] = index; } else { index = boneMapping[name]; } for (uint32_t j = 0; j < pMesh->mBones[i]->mNumWeights; j++) { uint32_t vertexID = meshLoader->m_Entries[meshIndex].vertexBase + pMesh->mBones[i]->mWeights[j].mVertexId; Bones[vertexID].add(index, pMesh->mBones[i]->mWeights[j].mWeight); } } boneTransforms.resize(numBones); } // Recursive bone transformation for given animation time void update(float time) { float TicksPerSecond = (float)(meshLoader->pScene->mAnimations[0]->mTicksPerSecond != 0 ? meshLoader->pScene->mAnimations[0]->mTicksPerSecond : 25.0f); float TimeInTicks = time * TicksPerSecond; float AnimationTime = fmod(TimeInTicks, (float)meshLoader->pScene->mAnimations[0]->mDuration); aiMatrix4x4 identity = aiMatrix4x4(); readNodeHierarchy(AnimationTime, meshLoader->pScene->mRootNode, identity); for (uint32_t i = 0; i < boneTransforms.size(); i++) { boneTransforms[i] = boneInfo[i].finalTransformation; } } private: // Find animation for a given node const aiNodeAnim* findNodeAnim(const aiAnimation* animation, const std::string nodeName) { for (uint32_t i = 0; i < animation->mNumChannels; i++) { const aiNodeAnim* nodeAnim = animation->mChannels[i]; if (std::string(nodeAnim->mNodeName.data) == nodeName) { return nodeAnim; } } return nullptr; } // Returns a 4x4 matrix with interpolated translation between current and next frame aiMatrix4x4 interpolateTranslation(float time, const aiNodeAnim* pNodeAnim) { aiVector3D translation; if (pNodeAnim->mNumPositionKeys == 1) { translation = pNodeAnim->mPositionKeys[0].mValue; } else { uint32_t frameIndex = 0; for (uint32_t i = 0; i < pNodeAnim->mNumPositionKeys - 1; i++) { if (time < (float)pNodeAnim->mPositionKeys[i + 1].mTime) { frameIndex = i; break; } } aiVectorKey currentFrame = pNodeAnim->mPositionKeys[frameIndex]; aiVectorKey nextFrame = pNodeAnim->mPositionKeys[(frameIndex + 1) % pNodeAnim->mNumPositionKeys]; float delta = (time - (float)currentFrame.mTime) / (float)(nextFrame.mTime - currentFrame.mTime); const aiVector3D& start = currentFrame.mValue; const aiVector3D& end = nextFrame.mValue; translation = (start + delta * (end - start)); } aiMatrix4x4 mat; aiMatrix4x4::Translation(translation, mat); return mat; } // Returns a 4x4 matrix with interpolated rotation between current and next frame aiMatrix4x4 interpolateRotation(float time, const aiNodeAnim* pNodeAnim) { aiQuaternion rotation; if (pNodeAnim->mNumRotationKeys == 1) { rotation = pNodeAnim->mRotationKeys[0].mValue; } else { uint32_t frameIndex = 0; for (uint32_t i = 0; i < pNodeAnim->mNumRotationKeys - 1; i++) { if (time < (float)pNodeAnim->mRotationKeys[i + 1].mTime) { frameIndex = i; break; } } aiQuatKey currentFrame = pNodeAnim->mRotationKeys[frameIndex]; aiQuatKey nextFrame = pNodeAnim->mRotationKeys[(frameIndex + 1) % pNodeAnim->mNumRotationKeys]; float delta = (time - (float)currentFrame.mTime) / (float)(nextFrame.mTime - currentFrame.mTime); const aiQuaternion& start = currentFrame.mValue; const aiQuaternion& end = nextFrame.mValue; aiQuaternion::Interpolate(rotation, start, end, delta); rotation.Normalize(); } aiMatrix4x4 mat(rotation.GetMatrix()); return mat; } // Returns a 4x4 matrix with interpolated scaling between current and next frame aiMatrix4x4 interpolateScale(float time, const aiNodeAnim* pNodeAnim) { aiVector3D scale; if (pNodeAnim->mNumScalingKeys == 1) { scale = pNodeAnim->mScalingKeys[0].mValue; } else { uint32_t frameIndex = 0; for (uint32_t i = 0; i < pNodeAnim->mNumScalingKeys - 1; i++) { if (time < (float)pNodeAnim->mScalingKeys[i + 1].mTime) { frameIndex = i; break; } } aiVectorKey currentFrame = pNodeAnim->mScalingKeys[frameIndex]; aiVectorKey nextFrame = pNodeAnim->mScalingKeys[(frameIndex + 1) % pNodeAnim->mNumScalingKeys]; float delta = (time - (float)currentFrame.mTime) / (float)(nextFrame.mTime - currentFrame.mTime); const aiVector3D& start = currentFrame.mValue; const aiVector3D& end = nextFrame.mValue; scale = (start + delta * (end - start)); } aiMatrix4x4 mat; aiMatrix4x4::Scaling(scale, mat); return mat; } // Get node hierarchy for current animation time void readNodeHierarchy(float AnimationTime, const aiNode* pNode, const aiMatrix4x4& ParentTransform) { std::string NodeName(pNode->mName.data); aiMatrix4x4 NodeTransformation(pNode->mTransformation); const aiNodeAnim* pNodeAnim = findNodeAnim(pAnimation, NodeName); if (pNodeAnim) { // Get interpolated matrices between current and next frame aiMatrix4x4 matScale = interpolateScale(AnimationTime, pNodeAnim); aiMatrix4x4 matRotation = interpolateRotation(AnimationTime, pNodeAnim); aiMatrix4x4 matTranslation = interpolateTranslation(AnimationTime, pNodeAnim); NodeTransformation = matTranslation * matRotation * matScale; } aiMatrix4x4 GlobalTransformation = ParentTransform * NodeTransformation; if (boneMapping.find(NodeName) != boneMapping.end()) { uint32_t BoneIndex = boneMapping[NodeName]; boneInfo[BoneIndex].finalTransformation = globalInverseTransform * GlobalTransformation * boneInfo[BoneIndex].offset; } for (uint32_t i = 0; i < pNode->mNumChildren; i++) { readNodeHierarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation); } } }; class VulkanExample : public vkx::ExampleBase { public: struct { vkx::Texture colorMap; vkx::Texture floor; } textures; struct { vk::PipelineVertexInputStateCreateInfo inputState; std::vector<vk::VertexInputBindingDescription> bindingDescriptions; std::vector<vk::VertexInputAttributeDescription> attributeDescriptions; } vertices; SkinnedMesh *skinnedMesh; struct { vkx::UniformData vsScene; vkx::UniformData floor; } uniformData; struct UboVS { glm::mat4 projection; glm::mat4 model; glm::mat4 bones[MAX_BONES]; glm::vec4 lightPos = glm::vec4(0.0f, -250.0f, 250.0f, 1.0); glm::vec4 viewPos; } uboVS; struct UboFloor { glm::mat4 projection; glm::mat4 model; glm::vec4 lightPos = glm::vec4(0.0, 0.0f, -25.0f, 1.0); glm::vec4 viewPos; glm::vec2 uvOffset; } uboFloor; struct { vk::Pipeline skinning; vk::Pipeline texture; } pipelines; struct { vkx::MeshBuffer floor; } meshes; vk::PipelineLayout pipelineLayout; vk::DescriptorSet descriptorSet; vk::DescriptorSetLayout descriptorSetLayout; struct { vk::DescriptorSet skinning; vk::DescriptorSet floor; } descriptorSets; float runningTime = 0.0f; VulkanExample() : vkx::ExampleBase(ENABLE_VALIDATION) { camera.type = camera.lookat; camera.setZoom(-150.0f); zoomSpeed = 2.5f; rotationSpeed = 0.5f; camera.setRotation({ -25.5f, 128.5f, 180.0f }); title = "Vulkan Example - Skeletal animation"; } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class device.destroyPipeline(pipelines.skinning); device.destroyPipelineLayout(pipelineLayout); device.destroyDescriptorSetLayout(descriptorSetLayout); textures.colorMap.destroy(); uniformData.vsScene.destroy(); // Destroy and free mesh resources skinnedMesh->meshBuffer.destroy(); delete(skinnedMesh->meshLoader); delete(skinnedMesh); } void updateDrawCommandBuffer(const vk::CommandBuffer& cmdBuffer) { cmdBuffer.setViewport(0, vkx::viewport(size)); cmdBuffer.setScissor(0, vkx::rect2D(size)); // Skinned mesh cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.skinning); cmdBuffer.bindVertexBuffers(VERTEX_BUFFER_BIND_ID, skinnedMesh->meshBuffer.vertices.buffer, { 0 }); cmdBuffer.bindIndexBuffer(skinnedMesh->meshBuffer.indices.buffer, 0, vk::IndexType::eUint32); cmdBuffer.drawIndexed(skinnedMesh->meshBuffer.indexCount, 1, 0, 0, 0); // Floor cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSets.floor, nullptr); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.texture); cmdBuffer.bindVertexBuffers(VERTEX_BUFFER_BIND_ID, meshes.floor.vertices.buffer, { 0 }); cmdBuffer.bindIndexBuffer(meshes.floor.indices.buffer, 0, vk::IndexType::eUint32); cmdBuffer.drawIndexed(meshes.floor.indexCount, 1, 0, 0, 0); } // Load a mesh based on data read via assimp // The other example will use the VulkanMesh loader which has some additional functionality for loading meshes void loadMesh() { skinnedMesh = new SkinnedMesh(); skinnedMesh->meshLoader = new vkx::MeshLoader(); #if defined(__ANDROID__) skinnedMesh->meshLoader->assetManager = androidApp->activity->assetManager; #endif skinnedMesh->meshLoader->load(getAssetPath() + "models/goblin.dae", 0); skinnedMesh->setAnimation(0); // Setup bones // One vertex bone info structure per vertex skinnedMesh->bones.resize(skinnedMesh->meshLoader->numVertices); // Store global inverse transform matrix of root node skinnedMesh->globalInverseTransform = skinnedMesh->meshLoader->pScene->mRootNode->mTransformation; skinnedMesh->globalInverseTransform.Inverse(); // Load bones (weights and IDs) for (uint32_t m = 0; m < skinnedMesh->meshLoader->m_Entries.size(); m++) { aiMesh *paiMesh = skinnedMesh->meshLoader->pScene->mMeshes[m]; if (paiMesh->mNumBones > 0) { skinnedMesh->loadBones(m, paiMesh, skinnedMesh->bones); } } // Generate vertex buffer std::vector<Vertex> vertexBuffer; // Iterate through all meshes in the file // and extract the vertex information used in this demo for (uint32_t m = 0; m < skinnedMesh->meshLoader->m_Entries.size(); m++) { for (uint32_t i = 0; i < skinnedMesh->meshLoader->m_Entries[m].Vertices.size(); i++) { Vertex vertex; vertex.pos = skinnedMesh->meshLoader->m_Entries[m].Vertices[i].m_pos; vertex.pos.y = -vertex.pos.y; vertex.normal = skinnedMesh->meshLoader->m_Entries[m].Vertices[i].m_normal; vertex.uv = skinnedMesh->meshLoader->m_Entries[m].Vertices[i].m_tex; vertex.color = skinnedMesh->meshLoader->m_Entries[m].Vertices[i].m_color; // Fetch bone weights and IDs for (uint32_t j = 0; j < MAX_BONES_PER_VERTEX; j++) { vertex.boneWeights[j] = skinnedMesh->bones[skinnedMesh->meshLoader->m_Entries[m].vertexBase + i].weights[j]; vertex.boneIDs[j] = skinnedMesh->bones[skinnedMesh->meshLoader->m_Entries[m].vertexBase + i].IDs[j]; } vertexBuffer.push_back(vertex); } } uint32_t vertexBufferSize = vertexBuffer.size() * sizeof(Vertex); // Generate index buffer from loaded mesh file std::vector<uint32_t> indexBuffer; for (uint32_t m = 0; m < skinnedMesh->meshLoader->m_Entries.size(); m++) { uint32_t indexBase = indexBuffer.size(); for (uint32_t i = 0; i < skinnedMesh->meshLoader->m_Entries[m].Indices.size(); i++) { indexBuffer.push_back(skinnedMesh->meshLoader->m_Entries[m].Indices[i] + indexBase); } } uint32_t indexBufferSize = indexBuffer.size() * sizeof(uint32_t); skinnedMesh->meshBuffer.indexCount = indexBuffer.size(); skinnedMesh->meshBuffer.vertices = stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, vertexBuffer); skinnedMesh->meshBuffer.indices = stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, indexBuffer); } void loadTextures() { textures.colorMap = textureLoader->loadTexture( getAssetPath() + "textures/goblin_bc3.ktx", vk::Format::eBc3UnormBlock); textures.floor = textureLoader->loadTexture( getAssetPath() + "textures/pattern_35_bc3.ktx", vk::Format::eBc3UnormBlock); } void loadMeshes() { meshes.floor = ExampleBase::loadMesh(getAssetPath() + "models/plane_z.obj", vertexLayout, 512.0f); } void setupVertexDescriptions() { // Binding description vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0] = vkx::vertexInputBindingDescription(VERTEX_BUFFER_BIND_ID, sizeof(Vertex), vk::VertexInputRate::eVertex); // Attribute descriptions // Describes memory layout and shader positions vertices.attributeDescriptions.resize(6); // Location 0 : Position vertices.attributeDescriptions[0] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, vk::Format::eR32G32B32Sfloat, 0); // Location 1 : Normal vertices.attributeDescriptions[1] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, vk::Format::eR32G32B32Sfloat, sizeof(float) * 3); // Location 2 : Texture coordinates vertices.attributeDescriptions[2] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, vk::Format::eR32G32Sfloat, sizeof(float) * 6); // Location 3 : Color vertices.attributeDescriptions[3] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, vk::Format::eR32G32B32Sfloat, sizeof(float) * 8); // Location 4 : Bone weights vertices.attributeDescriptions[4] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 4, vk::Format::eR32G32B32A32Sfloat, sizeof(float) * 11); // Location 5 : Bone IDs vertices.attributeDescriptions[5] = vkx::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 5, vk::Format::eR32G32B32A32Sint, sizeof(float) * 15); vertices.inputState = vk::PipelineVertexInputStateCreateInfo(); vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { // Example uses one ubo and one combined image sampler std::vector<vk::DescriptorPoolSize> poolSizes = { vkx::descriptorPoolSize(vk::DescriptorType::eUniformBuffer, 2), vkx::descriptorPoolSize(vk::DescriptorType::eCombinedImageSampler, 2), }; vk::DescriptorPoolCreateInfo descriptorPoolInfo = vkx::descriptorPoolCreateInfo(poolSizes.size(), poolSizes.data(), 2); descriptorPool = device.createDescriptorPool(descriptorPoolInfo); } void setupDescriptorSetLayout() { std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Vertex shader uniform buffer vkx::descriptorSetLayoutBinding( vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eVertex, 0), // Binding 1 : Fragment shader combined sampler vkx::descriptorSetLayoutBinding( vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1), }; vk::DescriptorSetLayoutCreateInfo descriptorLayout = vkx::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), setLayoutBindings.size()); descriptorSetLayout = device.createDescriptorSetLayout(descriptorLayout); vk::PipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vkx::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); pipelineLayout = device.createPipelineLayout(pPipelineLayoutCreateInfo); } void setupDescriptorSet() { vk::DescriptorSetAllocateInfo allocInfo = vkx::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); descriptorSet = device.allocateDescriptorSets(allocInfo)[0]; vk::DescriptorImageInfo texDescriptor = vkx::descriptorImageInfo(textures.colorMap.sampler, textures.colorMap.view, vk::ImageLayout::eGeneral); std::vector<vk::WriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Vertex shader uniform buffer vkx::writeDescriptorSet( descriptorSet, vk::DescriptorType::eUniformBuffer, 0, &uniformData.vsScene.descriptor), // Binding 1 : Color map vkx::writeDescriptorSet( descriptorSet, vk::DescriptorType::eCombinedImageSampler, 1, &texDescriptor) }; device.updateDescriptorSets(writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); // Floor descriptorSets.floor = device.allocateDescriptorSets(allocInfo)[0]; texDescriptor.imageView = textures.floor.view; texDescriptor.sampler = textures.floor.sampler; writeDescriptorSets.clear(); // Binding 0 : Vertex shader uniform buffer writeDescriptorSets.push_back( vkx::writeDescriptorSet(descriptorSets.floor, vk::DescriptorType::eUniformBuffer, 0, &uniformData.floor.descriptor)); // Binding 1 : Color map writeDescriptorSets.push_back( vkx::writeDescriptorSet(descriptorSets.floor, vk::DescriptorType::eCombinedImageSampler, 1, &texDescriptor)); device.updateDescriptorSets(writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { vk::PipelineInputAssemblyStateCreateInfo inputAssemblyState = vkx::pipelineInputAssemblyStateCreateInfo(vk::PrimitiveTopology::eTriangleList, vk::PipelineInputAssemblyStateCreateFlags(), VK_FALSE); vk::PipelineRasterizationStateCreateInfo rasterizationState = vkx::pipelineRasterizationStateCreateInfo(vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise); vk::PipelineColorBlendAttachmentState blendAttachmentState = vkx::pipelineColorBlendAttachmentState(); vk::PipelineColorBlendStateCreateInfo colorBlendState = vkx::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); vk::PipelineDepthStencilStateCreateInfo depthStencilState = vkx::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, vk::CompareOp::eLessOrEqual); vk::PipelineViewportStateCreateInfo viewportState = vkx::pipelineViewportStateCreateInfo(1, 1); vk::PipelineMultisampleStateCreateInfo multisampleState = vkx::pipelineMultisampleStateCreateInfo(vk::SampleCountFlagBits::e1); std::vector<vk::DynamicState> dynamicStateEnables = { vk::DynamicState::eViewport, vk::DynamicState::eScissor }; vk::PipelineDynamicStateCreateInfo dynamicState = vkx::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), dynamicStateEnables.size()); // Skinned rendering pipeline std::array<vk::PipelineShaderStageCreateInfo, 2> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/skeletalanimation/mesh.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/skeletalanimation/mesh.frag.spv", vk::ShaderStageFlagBits::eFragment); vk::GraphicsPipelineCreateInfo pipelineCreateInfo = vkx::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); pipelines.skinning = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; shaderStages[0] = loadShader(getAssetPath() + "shaders/skeletalanimation/texture.vert.spv", vk::ShaderStageFlagBits::eVertex); shaderStages[1] = loadShader(getAssetPath() + "shaders/skeletalanimation/texture.frag.spv", vk::ShaderStageFlagBits::eFragment); pipelines.texture = device.createGraphicsPipelines(pipelineCache, pipelineCreateInfo, nullptr)[0]; } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Vertex shader uniform buffer block uniformData.vsScene = createUniformBuffer(uboVS); // Floor uniformData.floor = createUniformBuffer(uboFloor); updateUniformBuffers(true); } void updateUniformBuffers(bool viewChanged) { if (viewChanged) { uboFloor.projection = uboVS.projection = getProjection(); uboFloor.model = uboVS.model = glm::scale(glm::rotate(camera.matrices.view, glm::radians(90.0f), glm::vec3(1, 0, 0)), glm::vec3(0.025f)); uboFloor.viewPos = uboVS.viewPos = glm::vec4(0.0f, 0.0f, -camera.position.z, 0.0f); uboFloor.model = glm::translate(uboFloor.model, glm::vec3(0.0f, 0.0f, -1800.0f)); } // Update bones skinnedMesh->update(runningTime); for (uint32_t i = 0; i < skinnedMesh->boneTransforms.size(); i++) { uboVS.bones[i] = glm::transpose(glm::make_mat4(&skinnedMesh->boneTransforms[i].a1)); } uniformData.vsScene.copy(uboVS); // Update floor animation uboFloor.uvOffset.t -= 0.5f * skinnedMesh->animationSpeed * frameTimer; uniformData.floor.copy(uboFloor); } void prepare() { ExampleBase::prepare(); loadTextures(); loadMesh(); loadMeshes(); setupVertexDescriptions(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); updateDrawCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); if (!paused) { runningTime += frameTimer * skinnedMesh->animationSpeed; updateUniformBuffers(false); } } virtual void viewChanged() { updateUniformBuffers(true); } void changeAnimationSpeed(float delta) { skinnedMesh->animationSpeed += delta; std::cout << "Animation speed = " << skinnedMesh->animationSpeed << std::endl; } void keyPressed(uint32_t key) override { switch (key) { case GLFW_KEY_KP_ADD: case GLFW_KEY_KP_SUBTRACT: changeAnimationSpeed((key == GLFW_KEY_KP_ADD) ? 0.1f : -0.1f); break; } } }; RUN_EXAMPLE(VulkanExample)
39.352859
159
0.649702
[ "mesh", "render", "vector", "model", "transform" ]
4574f59636ae6441f83bb1ed23fe566c6ee3101b
1,498
cpp
C++
libcore/luni/src/main/native/java_lang_invoke_MethodHandle.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
41
2019-09-06T01:37:29.000Z
2022-02-21T01:03:03.000Z
libcore/luni/src/main/native/java_lang_invoke_MethodHandle.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
null
null
null
libcore/luni/src/main/native/java_lang_invoke_MethodHandle.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
15
2019-09-06T09:36:41.000Z
2022-03-08T06:47:21.000Z
/* * Copyright (C) 2016 The Android Open Source Project * * 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 <nativehelper/JniConstants.h> #include <nativehelper/JNIHelp.h> static void MethodHandle_invokeExact(JNIEnv* env, jobject, jobjectArray) { jniThrowException(env, "java/lang/UnsupportedOperationException", "MethodHandle.invokeExact cannot be invoked reflectively."); } static void MethodHandle_invoke(JNIEnv* env, jobject, jobjectArray) { jniThrowException(env, "java/lang/UnsupportedOperationException", "MethodHandle.invoke cannot be invoked reflectively."); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(MethodHandle, invokeExact, "([Ljava/lang/Object;)Ljava/lang/Object;"), NATIVE_METHOD(MethodHandle, invoke, "([Ljava/lang/Object;)Ljava/lang/Object;"), }; void register_java_lang_invoke_MethodHandle(JNIEnv* env) { jniRegisterNativeMethods(env, "java/lang/invoke/MethodHandle", gMethods, NELEM(gMethods)); }
39.421053
94
0.751001
[ "object" ]
457905af260d8b5ae433730ee736d46176d369ba
1,200
cpp
C++
maximun_unsorted_sorted.cpp
the-artemis/ads
2f93616e52f113befceaed29d8ad9892d44ce290
[ "MIT" ]
null
null
null
maximun_unsorted_sorted.cpp
the-artemis/ads
2f93616e52f113befceaed29d8ad9892d44ce290
[ "MIT" ]
null
null
null
maximun_unsorted_sorted.cpp
the-artemis/ads
2f93616e52f113befceaed29d8ad9892d44ce290
[ "MIT" ]
2
2021-10-06T13:34:01.000Z
2021-10-06T13:45:40.000Z
#include<iostream> #include <bits/stdc++.h> #include<math.h> using namespace std; // Question 581 LeetCode vector<int> solve(vector<int> &arr) { int l = arr.size(); int i=0; int j =l-1; int min_ = INT32_MAX; int max_ = INT32_MIN; for(;i<l-1;++i) { if(arr[i]>arr[i+1]) { break; } } if(i==l-1) { vector<int> temp{-1}; return temp; } for(;j>=0;j--) { if(arr[j-1]>arr[j]) { break; } } for(int k =i+1;k<=j;k++) { if(arr[k]>max_) { max_ = arr[k]; } if(arr[k]<min_) { min_ = arr[k]; } } for(int k=0;k<i;k++) { if(arr[k]>min_) { i=k; break; } } for(int k=l-1;k>=j+1;k--) { if(arr[k]<max_) { j=k; break; } } vector<int> out{i,j}; cout<<out[0]<<" "<<out[1]<<endl; return out; } int main() { vector<int> arr{2,1}; solve(arr); return 0; }
15.584416
37
0.345
[ "vector" ]
457c86370c2ca5eebb08681c8990b32487bc8868
5,517
hpp
C++
Crisp/ShadingLanguage/Expressions.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Crisp/ShadingLanguage/Expressions.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Crisp/ShadingLanguage/Expressions.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include "Visitor.hpp" #include "Token.hpp" #include <memory> #include <vector> namespace crisp::sl { struct Expression { virtual ~Expression() {} template <typename T> inline T* as() { return static_cast<T*>(this); } virtual void accept(Visitor& visitor) = 0; }; using ExpressionPtr = std::unique_ptr<Expression>; struct Literal : public Expression { Literal(TokenType type, std::any value) : type(type), value(value) {} TokenType type; std::any value; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct ArraySpecifier : public Expression { ArraySpecifier() : expr(nullptr) {} ArraySpecifier(ExpressionPtr expr) : expr(std::move(expr)) {} ExpressionPtr expr; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct TypeSpecifier : public Expression { TypeSpecifier(Token typeToken) : type(typeToken) {} Token type; std::vector<std::unique_ptr<ArraySpecifier>> arraySpecifiers; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct Variable : public Expression { Variable(Token name) : name(name) {} Token name; std::vector<std::unique_ptr<ArraySpecifier>> arraySpecifiers; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct TypeQualifier : public Expression { TypeQualifier(Token qualifier) : qualifier(qualifier) {} Token qualifier; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct SubroutineQualifier : public TypeQualifier { SubroutineQualifier(Token name) : TypeQualifier(name) {} SubroutineQualifier(Token name, std::vector<ExpressionPtr>&& exprs) : TypeQualifier(name), exprs(std::move(exprs)) {} std::vector<ExpressionPtr> exprs; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct LayoutQualifier : public TypeQualifier { LayoutQualifier(Token name) : TypeQualifier(name) {} LayoutQualifier(Token name, std::vector<ExpressionPtr>&& exprs) : TypeQualifier(name), ids(std::move(exprs)) {} std::vector<ExpressionPtr> ids; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct FullType : public Expression { std::vector<std::unique_ptr<TypeQualifier>> qualifiers; std::unique_ptr<TypeSpecifier> specifier; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct UnaryExpr : public Expression { UnaryExpr(Token op, ExpressionPtr expr) : op(op), expr(std::move(expr)) {} ExpressionPtr expr; Token op; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct BinaryExpr : public Expression { ExpressionPtr left; ExpressionPtr right; Token op; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct ConditionalExpr : public Expression { ExpressionPtr test; ExpressionPtr thenExpr; ExpressionPtr elseExpr; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct ListExpr : public Expression { std::string name; std::vector<ExpressionPtr> expressions; ListExpr(std::string name) : name(name) {} ListExpr(std::string name, std::vector<ExpressionPtr>&& exprs) : name(name), expressions(std::move(exprs)) {} template <typename BaseType> ListExpr(std::string name, std::vector<BaseType>&& exprs) : name(name) { for (auto& e : exprs) expressions.push_back(std::move(e)); } virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct GroupingExpr : public Expression { ExpressionPtr expr; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct StructSpecifier : public TypeSpecifier { StructSpecifier(Token typeName) : TypeSpecifier(typeName) {} Token structName; std::vector<std::unique_ptr<StructFieldDeclaration>> fields; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct ParameterDeclaration : public Expression { std::unique_ptr<FullType> fullType; std::unique_ptr<Variable> var; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; struct FunctionPrototype : public Expression { std::unique_ptr<FullType> fullType; Token name; std::vector<std::unique_ptr<ParameterDeclaration>> params; virtual void accept(Visitor& visitor) override { visitor.visit(*this); } }; }
24.303965
125
0.578938
[ "vector" ]
458bec407bb5e326fbe4711710e80fe7a5fe0231
1,066
cpp
C++
backup/2/interviewbit/c++/sorted-array-to-balanced-bst.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/interviewbit/c++/sorted-array-to-balanced-bst.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/interviewbit/c++/sorted-array-to-balanced-bst.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/interviewbit/sorted-array-to-balanced-bst.html . TreeNode *toBST(const vector<int> &nums, int begin, int end) { if (begin > end) { return NULL; } int middle = (begin + end) / 2; TreeNode *root = new TreeNode(nums[middle]); TreeNode *left = toBST(nums, begin, middle - 1); TreeNode *right = toBST(nums, middle + 1, end); root->left = left; root->right = right; return root; } TreeNode *Solution::sortedArrayToBST(const vector<int> &A) { return toBST(A, 0, A.size() - 1); }
48.454545
345
0.69606
[ "vector" ]
458fa59757d419df86a1f0190676892c504b5e27
1,057
hpp
C++
Shared/Database/OpenTransactions.hpp
perandersson/everstore-server
6d5372a4bb9fa20f39870f7aa3875f6228cb3fd8
[ "Apache-2.0" ]
2
2016-10-31T03:28:48.000Z
2016-11-10T09:22:14.000Z
Shared/Database/OpenTransactions.hpp
perandersson/everstore-server
6d5372a4bb9fa20f39870f7aa3875f6228cb3fd8
[ "Apache-2.0" ]
8
2015-11-07T15:10:59.000Z
2019-04-07T09:16:05.000Z
Shared/Database/OpenTransactions.hpp
perandersson/everstore-server
6d5372a4bb9fa20f39870f7aa3875f6228cb3fd8
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2019 West Coast Code AB. All rights reserved. // #ifndef EVERSTORE_OPENTRANSACTIONS_HPP #define EVERSTORE_OPENTRANSACTIONS_HPP #include "Transaction.h" /** * Type that helps us keeping track of all opened transactions */ class OpenTransactions { public: OpenTransactions() = default; ~OpenTransactions(); /** * Open a new transaction for the supplied journal * * @param journal * @return A unique ID for the journal that represents this transaction */ TransactionID open(Journal* journal); /** * Retrieve the transaction with the given id * * @param id The transaction ID * @return The transaction if found; <code>nullptr</code> otherwise */ Transaction* get(TransactionID id); /** * Close the supplied transaction * * @param id The transaction ID */ void close(TransactionID id); /** * Method called whenever a new transaction is committed */ void onTransactionCommitted(Bits::Type changes); private: vector<Transaction*> mTransactions; }; #endif //EVERSTORE_OPENTRANSACTIONS_HPP
19.574074
72
0.723746
[ "vector" ]
4595dea4ed06923584df15f27c34fa08611651a5
3,879
cc
C++
mojo/public/cpp/bindings/tests/test_helpers_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
mojo/public/cpp/bindings/tests/test_helpers_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
mojo/public/cpp/bindings/tests/test_helpers_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.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 "base/macros.h" #include "base/test/scoped_task_environment.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/message_pipe.h" #include "mojo/public/cpp/system/wait.h" #include "mojo/public/interfaces/bindings/tests/ping_service.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace mojo { namespace { class TestHelperTest : public testing::Test { public: TestHelperTest() = default; ~TestHelperTest() override = default; private: base::test::ScopedTaskEnvironment task_environment_; DISALLOW_COPY_AND_ASSIGN(TestHelperTest); }; class PingImpl : public test::PingService { public: explicit PingImpl(test::PingServiceRequest request) : binding_(this, std::move(request)) {} ~PingImpl() override = default; bool pinged() const { return pinged_; } // test::PingService: void Ping(const PingCallback& callback) override { pinged_ = true; callback.Run(); } private: bool pinged_ = false; Binding<test::PingService> binding_; DISALLOW_COPY_AND_ASSIGN(PingImpl); }; class EchoImpl : public test::EchoService { public: explicit EchoImpl(test::EchoServiceRequest request) : binding_(this, std::move(request)) {} ~EchoImpl() override = default; // test::EchoService: void Echo(const std::string& message, const EchoCallback& callback) override { callback.Run(message); } private: Binding<test::EchoService> binding_; DISALLOW_COPY_AND_ASSIGN(EchoImpl); }; class TrampolineImpl : public test::HandleTrampoline { public: explicit TrampolineImpl(test::HandleTrampolineRequest request) : binding_(this, std::move(request)) {} ~TrampolineImpl() override = default; // test::HandleTrampoline: void BounceOne(ScopedMessagePipeHandle one, const BounceOneCallback& callback) override { callback.Run(std::move(one)); } void BounceTwo(ScopedMessagePipeHandle one, ScopedMessagePipeHandle two, const BounceTwoCallback& callback) override { callback.Run(std::move(one), std::move(two)); } private: Binding<test::HandleTrampoline> binding_; DISALLOW_COPY_AND_ASSIGN(TrampolineImpl); }; TEST_F(TestHelperTest, AsyncWaiter) { test::PingServicePtr ping; PingImpl ping_impl(MakeRequest(&ping)); test::PingServiceAsyncWaiter wait_for_ping(ping.get()); EXPECT_FALSE(ping_impl.pinged()); wait_for_ping.Ping(); EXPECT_TRUE(ping_impl.pinged()); test::EchoServicePtr echo; EchoImpl echo_impl(MakeRequest(&echo)); test::EchoServiceAsyncWaiter wait_for_echo(echo.get()); const std::string kTestString = "a machine that goes 'ping'"; std::string response; wait_for_echo.Echo(kTestString, &response); EXPECT_EQ(kTestString, response); test::HandleTrampolinePtr trampoline; TrampolineImpl trampoline_impl(MakeRequest(&trampoline)); test::HandleTrampolineAsyncWaiter wait_for_trampoline(trampoline.get()); MessagePipe pipe; ScopedMessagePipeHandle handle0, handle1; WriteMessageRaw(pipe.handle0.get(), kTestString.data(), kTestString.size(), nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE); wait_for_trampoline.BounceOne(std::move(pipe.handle0), &handle0); wait_for_trampoline.BounceTwo(std::move(handle0), std::move(pipe.handle1), &handle0, &handle1); // Verify that our pipe handles are the same as the original pipe. Wait(handle1.get(), MOJO_HANDLE_SIGNAL_READABLE); std::vector<uint8_t> payload; ReadMessageRaw(handle1.get(), &payload, nullptr, MOJO_READ_MESSAGE_FLAG_NONE); std::string original_message(payload.begin(), payload.end()); EXPECT_EQ(kTestString, original_message); } } // namespace } // namespace mojo
30.069767
80
0.731374
[ "vector" ]
4599f78d1b558184d649f74e510f6563a90c11c4
3,008
cxx
C++
src/TreeTools/Printer.cxx
JeneLitsch/GameDataNotation
c20ffdb633d90c5760bb96334a8a06cd3d665552
[ "MIT" ]
null
null
null
src/TreeTools/Printer.cxx
JeneLitsch/GameDataNotation
c20ffdb633d90c5760bb96334a8a06cd3d665552
[ "MIT" ]
null
null
null
src/TreeTools/Printer.cxx
JeneLitsch/GameDataNotation
c20ffdb633d90c5760bb96334a8a06cd3d665552
[ "MIT" ]
null
null
null
#include "Printer.hxx" #include <iostream> #include "Object.hxx" #include "Array.hxx" #include "StringTools.hxx" namespace GDN { Printer::Printer(bool pretty){ this->pretty = pretty; } void Printer::visitValue(Value & val){ //add int to str if(auto content = val.getInt()){ if(content->format == Value::IntFormat::DEC) { this->add(std::to_string(content->val)); } else if(content->format == Value::IntFormat::BIN) { this->add("0b" + StringTools::toBin(static_cast<std::uint64_t>(content->val))); } else if(content->format == Value::IntFormat::HEX) { this->add("0x" + StringTools::toHex(static_cast<std::uint64_t>(content->val))); } } //TODO handle inf und nan //add float without exponent to str else if(auto content = val.getFloat()){ this->add(std::to_string(*content)); } //add string with "" to str else if(auto content = val.getString()){ this->add("\"" + *content + "\""); } //add boolean to str else if(auto content = val.getBool()){ this->add(((*content)?"true":"false")); } //add object to str else if(auto content = val.getObject()){ content->accept(*this); } //add array to str else if(auto content = val.getArray()){ content->accept(*this); } // TODO add hex and bin //automatic conversion of unknown data to null else { this->add("null"); } } void Printer::visitObject(Object & obj){ this->add("{"); this->depth++; bool firstLine = true; for(auto & el : obj){ //comma for previous line this->comma(firstLine); //for pretty printing this->add(newline()); this->add(this->indent()); //key this->add("\"" + el.first + "\" : "); //process child object el.second.accept(*this); } this->add(newline()); this->depth--; this->add(this->indent()); this->add("}"); } void Printer::visitArray(Array & arr){ this->add("["); this->depth++; bool firstLine = true; for(auto & el : arr){ //comma for previous line this->comma(firstLine); //for pretty printing this->add(newline()); this->add(this->indent()); //process child object el.accept(*this); } this->add(newline()); this->depth--; this->add(this->indent()); this->add("]"); } //returns a couple tabs if pretty is acivated std::string Printer::indent(){ if(pretty){ return std::string(static_cast<unsigned long>(4*depth), ' '); } else { return ""; } } // returns a new line if pretty printing is activated std::string Printer::newline(){ if(pretty){ return "\n"; } else { return ""; } } //add "," to previous line //its only done if the current line is not te first //to prevent trailing ","s void Printer::comma(bool & firstLine){ if(firstLine){ firstLine = false; } else{ this->add(","); } } void Printer::clear(){ this->str = ""; } std::string Printer::get() const{ return this->str; } void Printer::add(const std::string & str){ this->str += str; } }
17.904762
83
0.601064
[ "object" ]
45a148bc80ef630eb948f32144a8e5d947947f13
2,619
cpp
C++
plugins/community/repos/TheXOR/src/mplex.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/TheXOR/src/mplex.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/TheXOR/src/mplex.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "common.hpp" #include "mplex.hpp" namespace rack_plugin_TheXOR { void Mplex::on_loaded() { load(); } void Mplex::load() { set_output(0); } void Mplex::set_output(int n) { cur_sel = n; for(int k = 0; k < NUM_MPLEX_INPUTS; k++) { lights[LED_1 + k].value = k == cur_sel ? LVL_ON : LVL_OFF; } } void Mplex::step() { if(upTrigger.process(params[BTDN].value + inputs[INDN].value)) { if(++cur_sel >= NUM_MPLEX_INPUTS) cur_sel = 0; set_output(cur_sel); } else if(dnTrigger.process(params[BTUP].value + inputs[INUP].value)) { if(--cur_sel < 0) cur_sel = NUM_MPLEX_INPUTS-1; set_output(cur_sel); } outputs[OUT_1].value = inputs[IN_1 + cur_sel].value; } MplexWidget::MplexWidget(Mplex *module) : ModuleWidget(module) { box.size = Vec(10 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(plugin, "res/modules/mplex.svg"))); addChild(panel); } addChild(Widget::create<ScrewBlack>(Vec(RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(Widget::create<ScrewBlack>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(Widget::create<ScrewBlack>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addParam(ParamWidget::create<BefacoPushBig>(Vec(mm2px(25.322), yncscape(85.436, 8.999)), module, Mplex::BTUP, 0.0, 1.0, 0.0)); addParam(ParamWidget::create<BefacoPushBig>(Vec(mm2px(25.322), yncscape(33.452, 8.999)), module, Mplex::BTDN, 0.0, 1.0, 0.0)); addInput(Port::create<PJ301BPort>(Vec(mm2px(25.694), yncscape(71.230, 8.255)), Port::INPUT, module, Mplex::INUP)); addInput(Port::create<PJ301BPort>(Vec(mm2px(25.694), yncscape(49.014, 8.255)), Port::INPUT, module, Mplex::INDN)); addOutput(Port::create<PJ301GPort>(Vec(mm2px(40.045), yncscape(60.122, 8.255)), Port::OUTPUT, module, Mplex::OUT_1)); float y = 105.068f; float x = 3.558f; float led_x = 13.843f; float y_offs = y - 108.108f; float delta_y = 92.529f - 105.068f; for(int k = 0; k < NUM_MPLEX_INPUTS; k++) { addInput(Port::create<PJ301GRPort>(Vec(mm2px(x), yncscape(y, 8.255)), Port::INPUT, module, Mplex::IN_1 + k)); addChild(ModuleLightWidget::create<SmallLight<RedLight>>(Vec(mm2px(led_x), yncscape(y-y_offs, 2.176)), module, Mplex::LED_1 + k)); y += delta_y; if(k == 3) y -= 2.117f; } } } // namespace rack_plugin_TheXOR using namespace rack_plugin_TheXOR; RACK_PLUGIN_MODEL_INIT(TheXOR, Mplex) { return Model::create<Mplex, MplexWidget>("TheXOR", "Mplex", "Mplex", SWITCH_TAG); }
30.811765
132
0.693394
[ "model" ]
45aaa23ec93734de59848f316f4432316fa4b9cf
11,822
cpp
C++
src/afk/Afk.cpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
src/afk/Afk.cpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
src/afk/Afk.cpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
#include "afk/Afk.hpp" #include <memory> #include <string> #include <utility> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/string_cast.hpp> #include "afk/asset/AssetFactory.hpp" #include "afk/component/AgentComponent.hpp" #include "afk/component/AnimComponent.hpp" #include "afk/component/GameObject.hpp" #include "afk/component/ScriptsComponent.hpp" #include "afk/component/TagComponent.hpp" #include "afk/debug/Assert.hpp" #include "afk/io/Log.hpp" #include "afk/io/ModelSource.hpp" #include "afk/physics/PhysicsBody.hpp" #include "afk/physics/RigidBodyType.hpp" #include "afk/physics/shape/Box.hpp" #include "afk/physics/shape/Sphere.hpp" #include "afk/renderer/ModelRenderSystem.hpp" #include "afk/script/Bindings.hpp" #include "afk/script/LuaInclude.hpp" using namespace std::string_literals; using glm::vec3; using glm::vec4; using Afk::Engine; using Afk::Event; using Afk::Texture; using Action = Afk::Event::Action; using Movement = Afk::Camera::Movement; auto Engine::initialize() -> void { afk_assert(!this->is_initialized, "Engine already initialized"); this->renderer.initialize(); this->event_manager.initialize(this->renderer.window); // this->renderer.set_wireframe(true); // load the navmesh before adding components to things // init crowds with the navmesh // then add components this->ui.initialize(this->renderer.window); this->lua = luaL_newstate(); luaL_openlibs(this->lua); Afk::add_engine_bindings(this->lua); this->terrain_manager.initialize(); const int terrain_width = 128; const int terrain_length = 128; this->terrain_manager.generate_terrain(terrain_width, terrain_length, 0.05f, 7.5f); this->renderer.load_model(this->terrain_manager.get_model()); auto terrain_entity = registry.create(); auto terrain_transform = Transform{terrain_entity}; terrain_transform.translation = glm::vec3{0.0f, -10.0f, 0.0f}; registry.assign<Afk::ModelSource>(terrain_entity, terrain_entity, terrain_manager.get_model().file_path, "shader/terrain.prog"); registry.assign<Afk::Model>(terrain_entity, terrain_entity, terrain_manager.get_model()); registry.assign<Afk::Transform>(terrain_entity, terrain_transform); registry.assign<Afk::PhysicsBody>(terrain_entity, terrain_entity, &this->physics_body_system, terrain_transform, 0.3f, 0.0f, 0.0f, 0.0f, true, Afk::RigidBodyType::STATIC, this->terrain_manager.height_map); auto terrain_tags = TagComponent{terrain_entity}; terrain_tags.tags.insert(TagComponent::Tag::TERRAIN); registry.assign<Afk::TagComponent>(terrain_entity, terrain_tags); auto box_entity = registry.create(); auto box_transform = Transform{box_entity}; box_transform.translation = glm::vec3{0.0f, -15.0f, 0.0f}; box_transform.scale = glm::vec3(5.0f); auto box_model = Model(box_entity, "res/model/box/box.obj"); this->renderer.load_model(box_model); registry.assign<Afk::ModelSource>(box_entity, box_entity, box_model.file_path, "shader/default.prog"); registry.assign<Afk::Model>(box_entity, box_model); registry.assign<Afk::Transform>(box_entity, box_transform); registry.assign<Afk::PhysicsBody>( box_entity, box_entity, &this->physics_body_system, box_transform, 0.3f, 0.0f, 0.0f, 0.0f, true, Afk::RigidBodyType::STATIC, Afk::Box(0.9f, 0.9f, 0.9f)); auto box_tags = TagComponent{terrain_entity}; box_tags.tags.insert(TagComponent::Tag::TERRAIN); registry.assign<Afk::TagComponent>(box_entity, box_tags); // auto basketball = // std::get<Asset::Asset::Object>( Afk::Asset::game_asset_factory("asset/basketball.lua"); //.data) // .ent; // nav mesh needs to be generated BEFORE agents, otherwise agents may be added to the nav mesh this->nav_mesh_manager.initialise("res/gen/navmesh/human.nmesh"); // this->nav_mesh_manager.initialise("res/gen/navmesh/solo_navmesh.bin", this->terrain_manager.get_model().meshes[0], terrain_transform); this->crowds.init(this->nav_mesh_manager.get_nav_mesh()); auto camera_transform = Transform{camera_entity}; camera_transform.translation = glm::vec3{0.0f, 50.0f, 0.0f}; registry.assign<Afk::Transform>(camera_entity, camera_transform); registry.assign<Afk::PhysicsBody>(camera_entity, camera_entity, &this->physics_body_system, camera_transform, 0.0f, 0.3f, 0.3f, 100.0f, true, Afk::RigidBodyType::DYNAMIC, Afk::Sphere(0.75f)); auto camera_tags = TagComponent{terrain_entity}; camera_tags.tags.insert(TagComponent::Tag::PLAYER); registry.assign<Afk::TagComponent>(camera_entity, camera_tags); registry .assign<Afk::ScriptsComponent>(camera_entity, camera_entity, this->lua) .add_script("script/component/health.lua", &this->event_manager) .add_script("script/component/handle_collision_events.lua", &this->event_manager) .add_script("script/component/camera_keyboard_jetpack_control.lua", &this->event_manager) .add_script("script/component/camera_mouse_control.lua", &this->event_manager) .add_script("script/component/debug.lua", &this->event_manager); std::vector<entt::entity> agents{}; for (std::size_t i = 0; i < 20; ++i) { agents.push_back(registry.create()); dtCrowdAgentParams p = {}; p.radius = .1f; p.maxSpeed = 1; p.maxAcceleration = 1; p.height = 1; auto agent_transform = Afk::Transform{agents[i]}; agent_transform.translation = {5 - (i / 10.f), -10, 5 - (i / 10.f)}; agent_transform.scale = {.1f, .1f, .1f}; registry.assign<Afk::Transform>(agents[i], agent_transform); registry.assign<Afk::ModelSource>(agents[i], agents[i], "res/model/man/man.glb", "shader/animation.prog"); registry.assign<Afk::AI::AgentComponent>(agents[i], agents[i], agent_transform.translation, p); registry.assign<Afk::PhysicsBody>( agents[i], agents[i], &this->physics_body_system, agent_transform, 0.3f, 0.0f, 0.0f, 0.0f, true, Afk::RigidBodyType::STATIC, Afk::Capsule{0.3f, 1.0f}); registry.assign<Afk::AnimComponent>( agents[i], agents[i], Afk::AnimComponent::Status::Playing, "Walk", 0.0f); } registry.get<Afk::AI::AgentComponent>(agents[0]).move_to({25, -5, 25}); registry.get<Afk::AI::AgentComponent>(agents[1]).chase(camera_entity, 10.f); registry.get<Afk::AI::AgentComponent>(agents[2]).flee(camera_entity, 10.f); const Afk::AI::Path path = {{2.8f, -9.f, 3.f}, {14.f, -8.f, 4.f}, {20.f, -10.f, -3.5f}}; registry.get<Afk::AI::AgentComponent>(agents[3]).path(path, 2.f); for (std::size_t ag = 4; ag < 20; ++ag) { registry.get<Afk::AI::AgentComponent>(agents[ag]).wander(glm::vec3{0.f, 0.f, 0.f}, 20.f, 5.f); } std::vector<GameObject> deathboxes = {}; for (auto i = 0; i < 5; i++) { deathboxes.push_back(registry.create()); auto deathbox_tags = TagComponent{deathboxes[i]}; deathbox_tags.tags.insert(TagComponent::Tag::DEATHZONE); registry.assign<Afk::TagComponent>(deathboxes[i], deathbox_tags); } auto &deathbox_transform = registry.assign<Afk::Transform>(deathboxes[0], Transform{}); deathbox_transform.translation = glm::vec3{0.0f, -30.0f, 0.0f}; deathbox_transform.scale = glm::vec3(10000.0f, 0.1f, 10000.0f); registry.assign<Afk::PhysicsBody>(deathboxes[0], deathboxes[0], &this->physics_body_system, deathbox_transform, 0.0f, 0.0f, 0.0f, 0.0f, false, Afk::RigidBodyType::STATIC, Afk::Box(1.0f, 1.0f, 1.0f)); deathbox_transform = registry.assign<Afk::Transform>(deathboxes[1], Transform{}); deathbox_transform.translation = glm::vec3{-((terrain_width+1)/2.0), 0.0f, 0.0f}; deathbox_transform.scale = glm::vec3(0.1f, 10000.0f, 10000.0f); registry.assign<Afk::PhysicsBody>(deathboxes[1], deathboxes[1], &this->physics_body_system, deathbox_transform, 0.0f, 0.0f, 0.0f, 0.0f, false, Afk::RigidBodyType::STATIC, Afk::Box(1.0f, 1.0f, 1.0f)); deathbox_transform = registry.assign<Afk::Transform>(deathboxes[2], Transform{}); deathbox_transform.translation = glm::vec3{(terrain_width-1)/2.0, 0.0f, 0.0f}; deathbox_transform.scale = glm::vec3(0.1f, 10000.0f, 10000.0f); registry.assign<Afk::PhysicsBody>(deathboxes[2], deathboxes[2], &this->physics_body_system, deathbox_transform, 0.0f, 0.0f, 0.0f, 0.0f, false, Afk::RigidBodyType::STATIC, Afk::Box(1.0f, 1.0f, 1.0f)); deathbox_transform = registry.assign<Afk::Transform>(deathboxes[3], Transform{}); deathbox_transform.translation = glm::vec3{0.0f, 0.0f, -((terrain_width+1)/2.0)}; deathbox_transform.scale = glm::vec3(10000.0f, 10000.0f, 0.1f); registry.assign<Afk::PhysicsBody>(deathboxes[3], deathboxes[3], &this->physics_body_system, deathbox_transform, 0.0f, 0.0f, 0.0f, 0.0f, false, Afk::RigidBodyType::STATIC, Afk::Box(1.0f, 1.0f, 1.0f)); deathbox_transform = registry.assign<Afk::Transform>(deathboxes[4], Transform{}); deathbox_transform.translation = glm::vec3{0.0f, 0.0f, (terrain_width-1)/2.0}; deathbox_transform.scale = glm::vec3(10000.0f, 10000.0f, 0.1f); registry.assign<Afk::PhysicsBody>(deathboxes[4], deathboxes[4], &this->physics_body_system, deathbox_transform, 0.0f, 0.0f, 0.0f, 0.0f, false, Afk::RigidBodyType::STATIC, Afk::Box(1.0f, 1.0f, 1.0f)); this->difficulty_manager.init(AI::DifficultyManager::Difficulty::NORMAL); this->is_initialized = true; } auto Engine::get() -> Engine & { static auto instance = Engine{}; return instance; } auto Engine::exit() -> void { lua_close(this->lua); this->is_running = false; } auto Engine::render() -> void { Afk::queue_models(&this->registry, &this->renderer); this->renderer.clear_screen({135.0f, 206.0f, 235.0f, 1.0f}); this->ui.prepare(); this->renderer.draw(); this->event_manager.pump_render(); this->ui.draw(); this->renderer.swap_buffers(); } auto Engine::update() -> void { this->event_manager.pump_events(); this->crowds.update(this->get_delta_time()); for (auto &agent_ent : this->registry.view<Afk::AI::AgentComponent>()) { auto &agent = this->registry.get<Afk::AI::AgentComponent>(agent_ent); agent.update(); } if (glfwWindowShouldClose(this->renderer.window)) { this->is_running = false; } if (this->ui.show_menu) { glfwSetInputMode(this->renderer.window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(this->renderer.window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } // this->update_camera(); this->physics_body_system.update(&this->registry, this->get_delta_time()); ++this->frame_count; this->last_update = Afk::Engine::get_time(); } auto Engine::get_time() -> float { return static_cast<float>(glfwGetTime()); } auto Engine::get_delta_time() -> float { return this->get_time() - this->last_update; } auto Engine::get_is_running() const -> bool { return this->is_running; }
44.611321
140
0.64879
[ "mesh", "render", "object", "shape", "vector", "model", "transform" ]
45b3f02bc6f0e626a4ad62c238f42a7b219d0462
3,445
hpp
C++
include/dish2/services/CollectiveHarvestingService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
29
2019-02-04T02:39:52.000Z
2022-01-28T10:06:26.000Z
include/dish2/services/CollectiveHarvestingService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
95
2020-02-22T19:48:14.000Z
2021-09-14T19:17:53.000Z
include/dish2/services/CollectiveHarvestingService.hpp
mmore500/dishtiny
9fcb52c4e56c74a4e17f7d577143ed40c158c92e
[ "MIT" ]
6
2019-11-19T10:13:09.000Z
2021-03-25T17:35:32.000Z
#pragma once #ifndef DISH2_SERVICES_COLLECTIVEHARVESTINGSERVICE_HPP_INCLUDE #define DISH2_SERVICES_COLLECTIVEHARVESTINGSERVICE_HPP_INCLUDE #include <algorithm> #include <cmath> #include <set> #include <utility> #include "../../../third-party/conduit/include/uitsl/math/shift_mod.hpp" #include "../cell/cardinal_iterators/KinGroupAgeWrapper.hpp" #include "../cell/cardinal_iterators/ResourceStockpileWrapper.hpp" #include "../config/cfg.hpp" #include "../debug/LogScope.hpp" namespace dish2 { /** * Perform kin group collective resource harvest for single cell. * * Calculates the total amount of resource collectively harvested to this cell * by the cell's kin group. This amount increases with quorum count and * saturates at `OPTIMAL_QUORUM_COUNT`. Adds the harvested amount to the cell's * resource stockpile. */ class CollectiveHarvestingService { template<typename Cell> static float CalcHarvest( const Cell& cell, const size_t lev ) { const size_t optimum = cfg.OPTIMAL_QUORUM_COUNT()[lev]; const size_t quorum_count = cell.cell_quorum_state.GetNumKnownQuorumBits( lev ); emp_assert( quorum_count ); const size_t effective_count = std::min( optimum, // subtract 1 from quorum count for self, being cautious about overflow // TODO only subtract if self has a quorum bit set quorum_count - static_cast<bool>( quorum_count ) ); return cfg.BASE_HARVEST_RATE() * effective_count; } public: static bool ShouldRun( const size_t update, const bool alive ) { const size_t freq = dish2::cfg.COLLECTIVE_HARVESTING_SERVICE_FREQUENCY(); return alive && freq > 0 && uitsl::shift_mod( update, freq ) == 0; } template<typename Cell> static void DoService( Cell& cell ) { const dish2::LogScope guard{ "collective harvesting service", "TODO", 3 }; using spec_t = typename Cell::spec_t; // check resource stockpile consistency emp_assert(( std::set< typename dish2::ResourceStockpileWrapper<spec_t>::value_type >( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>() ).size() == 1 )); // how much resource have we harvested? float harvest{}; for (size_t lev{}; lev < spec_t::NLEV; ++lev) { harvest += CalcHarvest<Cell>( cell, lev ); } emp_assert( std::isfinite( harvest ), harvest ); // update stockpiles to reflect harvested amount std::transform( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), [harvest](const auto cur) { return cur + harvest; } ); // check resource stockpile consistency emp_assert(( std::set<typename dish2::ResourceStockpileWrapper<spec_t>::value_type >( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>() ).size() == 1 )); emp_assert( std::none_of( cell.template begin<dish2::ResourceStockpileWrapper<spec_t>>(), cell.template end<dish2::ResourceStockpileWrapper<spec_t>>(), []( const auto val ){ return std::isnan( val ); } ), harvest ); } }; } // namespace dish2 #endif // #ifndef DISH2_SERVICES_COLLECTIVEHARVESTINGSERVICE_HPP_INCLUDE
31.036036
79
0.701887
[ "transform" ]
45be52e2fa2fd0111edc5758fed8e01ce8d601ee
6,974
cpp
C++
src/geode/mesh/core/surface_edges.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
64
2019-08-02T14:31:01.000Z
2022-03-30T07:46:50.000Z
src/geode/mesh/core/surface_edges.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
395
2019-08-02T17:15:10.000Z
2022-03-31T15:10:27.000Z
src/geode/mesh/core/surface_edges.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
8
2019-08-19T21:32:15.000Z
2022-03-06T18:41:10.000Z
/* * Copyright (c) 2019 - 2021 Geode-solutions * * 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 <geode/mesh/core/surface_edges.h> #include <algorithm> #include <stack> #include <bitsery/brief_syntax/array.h> #include <geode/basic/attribute_manager.h> #include <geode/basic/bitsery_archive.h> #include <geode/basic/detail/mapping_after_deletion.h> #include <geode/basic/pimpl_impl.h> #include <geode/geometry/bounding_box.h> #include <geode/geometry/vector.h> #include <geode/mesh/builder/surface_mesh_builder.h> #include <geode/mesh/core/detail/facet_edges_impl.h> #include <geode/mesh/core/mesh_factory.h> #include <geode/mesh/core/polygonal_surface.h> namespace { template < geode::index_t dimension > void check_edge_id( const geode::SurfaceEdges< dimension >& edges, const geode::index_t edge_id ) { geode_unused( edges ); geode_unused( edge_id ); OPENGEODE_ASSERT( edge_id < edges.nb_edges(), "[check_edge_id] Trying to access an invalid edge" ); } } // namespace namespace geode { template < index_t dimension > class SurfaceEdges< dimension >::Impl : public detail::FacetEdgesImpl< dimension > { friend class bitsery::Access; public: Impl() = default; Impl( const SurfaceMesh< dimension >& surface ) { for( const auto p : Range{ surface.nb_polygons() } ) { for( const auto e : LRange{ surface.nb_polygon_edges( p ) } ) { this->find_or_create_edge( surface.polygon_edge_vertices( { p, e } ) ); } } } private: template < typename Archive > void serialize( Archive& archive ) { archive.ext( *this, DefaultGrowable< Archive, Impl >{}, []( Archive& a, Impl& impl ) { a.ext( impl, bitsery::ext::BaseClass< detail::FacetEdgesImpl< dimension > >{} ); } ); } }; template < index_t dimension > SurfaceEdges< dimension >::SurfaceEdges() { } template < index_t dimension > SurfaceEdges< dimension >::SurfaceEdges( const SurfaceMesh< dimension >& surface ) : impl_{ surface } { } template < index_t dimension > SurfaceEdges< dimension >::~SurfaceEdges() // NOLINT { } template < index_t dimension > index_t SurfaceEdges< dimension >::find_or_create_edge( std::array< index_t, 2 > edge_vertices ) { return impl_->find_or_create_edge( std::move( edge_vertices ) ); } template < index_t dimension > const std::array< index_t, 2 >& SurfaceEdges< dimension >::edge_vertices( index_t edge_id ) const { check_edge_id( *this, edge_id ); return impl_->edge_vertices( edge_id ); } template < index_t dimension > void SurfaceEdges< dimension >::update_edge_vertices( absl::Span< const index_t > old2new, SurfaceEdgesKey ) { impl_->update_edge_vertices( old2new ); } template < index_t dimension > void SurfaceEdges< dimension >::update_edge_vertex( std::array< index_t, 2 > edge_vertices, index_t edge_vertex_id, index_t new_vertex_id, SurfaceEdgesKey ) { impl_->update_edge_vertex( std::move( edge_vertices ), edge_vertex_id, new_vertex_id ); } template < index_t dimension > void SurfaceEdges< dimension >::remove_edge( std::array< index_t, 2 > edge_vertices, SurfaceEdgesKey ) { impl_->remove_edge( std::move( edge_vertices ) ); } template < index_t dimension > std::vector< index_t > SurfaceEdges< dimension >::delete_edges( const std::vector< bool >& to_delete, SurfaceEdgesKey ) { return impl_->delete_edges( to_delete ); } template < index_t dimension > std::vector< index_t > SurfaceEdges< dimension >::remove_isolated_edges( SurfaceEdgesKey ) { return impl_->remove_isolated_edges(); } template < index_t dimension > void SurfaceEdges< dimension >::overwrite_edges( const SurfaceEdges< dimension >& from, SurfaceEdgesKey ) { impl_->overwrite_edges( *from.impl_ ); } template < index_t dimension > index_t SurfaceEdges< dimension >::nb_edges() const { return edge_attribute_manager().nb_elements(); } template < index_t dimension > bool SurfaceEdges< dimension >::isolated_edge( index_t edge_id ) const { check_edge_id( *this, edge_id ); return impl_->isolated_edge( edge_id ); } template < index_t dimension > absl::optional< index_t > SurfaceEdges< dimension >::edge_from_vertices( const std::array< index_t, 2 >& vertices ) const { return impl_->find_edge( vertices ); } template < index_t dimension > AttributeManager& SurfaceEdges< dimension >::edge_attribute_manager() const { return impl_->edge_attribute_manager(); } template < index_t dimension > template < typename Archive > void SurfaceEdges< dimension >::serialize( Archive& archive ) { archive.ext( *this, DefaultGrowable< Archive, SurfaceEdges >{}, []( Archive& a, SurfaceEdges& edges ) { a.object( edges.impl_ ); } ); } template class opengeode_mesh_api SurfaceEdges< 2 >; template class opengeode_mesh_api SurfaceEdges< 3 >; SERIALIZE_BITSERY_ARCHIVE( opengeode_mesh_api, SurfaceEdges< 2 > ); SERIALIZE_BITSERY_ARCHIVE( opengeode_mesh_api, SurfaceEdges< 3 > ); } // namespace geode
33.052133
81
0.627473
[ "mesh", "geometry", "object", "vector" ]
45c467d9bd358917711511a74ea57e9950132ec6
5,252
cpp
C++
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Array.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
192
2016-03-23T04:33:24.000Z
2022-03-28T14:41:06.000Z
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Array.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
9
2017-03-08T14:45:16.000Z
2021-09-06T09:28:47.000Z
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Array.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
56
2016-03-22T20:37:08.000Z
2022-03-28T12:20:47.000Z
#include "System.Private.CoreLib.h" namespace CoreLib { namespace System { namespace _ = ::CoreLib::System; // Method : System.Array.InternalCreate(void*, int, int*, int*) _::Array* Array::InternalCreate(void* elementType, int32_t rank, int32_t* pLengths, int32_t* pLowerBounds) { throw 3221274624U; } // Method : System.Array.Copy(System.Array, int, System.Array, int, int, bool) void Array::Copy(_::Array* sourceArray, int32_t sourceIndex, _::Array* destinationArray, int32_t destinationIndex, int32_t length, bool reliable) { if (length == 0) { return; } if (sourceArray == nullptr || destinationArray == nullptr) { throw __new<_::ArgumentNullException>(); } if (length < 0) { throw __new<_::InvalidOperationException>(); } if (sourceIndex < 0 || destinationIndex < 0) { throw __new<_::IndexOutOfRangeException>(); } if (sourceIndex + length > sourceArray->get_Length() || destinationIndex + length > destinationArray->get_Length()) { throw __new<_::IndexOutOfRangeException>(); } _::TypedReference elemref; int32_t index = sourceIndex; sourceArray->InternalGetReference(static_cast<void*>(&elemref), 1, &index); auto pSrc = (int8_t*)(void*)elemref.Value; index = destinationIndex; destinationArray->InternalGetReference(static_cast<void*>(&elemref), 1, &index); auto pDest = (int8_t*)(void*)elemref.Value; auto elementSize = sourceArray->__array_element_size(); std::memcpy(pDest, pSrc, length * elementSize); } // Method : System.Array.Clear(System.Array, int, int) void Array::Clear(_::Array* array, int32_t index, int32_t length) { if (length == 0) { return; } if (array == nullptr) { throw __new<_::ArgumentNullException>(); } if (length < 0) { throw __new<_::InvalidOperationException>(); } if (index < 0) { throw __new<_::IndexOutOfRangeException>(); } if (index + length > array->get_Length()) { throw __new<_::IndexOutOfRangeException>(); } _::TypedReference elemref; array->InternalGetReference(static_cast<void*>(&elemref), 1, &index); auto pSrc = (int8_t*)(void*)elemref.Value; auto elementSize = array->__array_element_size(); std::memset(pSrc, 0, length * elementSize); } // Method : System.Array.InternalGetReference(void*, int, int*) void Array::InternalGetReference(void* elemRef, int32_t rank, int32_t* pIndices) { throw 3221274624U; } // Method : System.Array.InternalSetValue(void*, object) void Array::InternalSetValue(void* target, object* value) { if (target == nullptr) { throw __new<_::ArgumentNullException>(u"target"_s); } auto typedRef = reinterpret_cast<_::TypedReference*>(target); try { ((__methods_table*)(void*)(typedRef->Type))->__unbox_to((void*)typedRef->Value, value); } catch (_::InvalidCastException*) { throw __new<_::ArgumentException>(); } } // Method : System.Array.Length.get int32_t Array::get_Length() { throw 3221274624U; } // Method : System.Array.LongLength.get int64_t Array::get_LongLength() { throw 3221274624U; } // Method : System.Array.GetLength(int) int32_t Array::GetLength(int32_t dimension) { throw 3221274624U; } // Method : System.Array.Rank.get int32_t Array::get_Rank() { throw 3221274624U; } // Method : System.Array.GetUpperBound(int) int32_t Array::GetUpperBound(int32_t dimension) { throw 3221274624U; } // Method : System.Array.GetLowerBound(int) int32_t Array::GetLowerBound(int32_t dimension) { throw 3221274624U; } // Method : System.Array.GetDataPtrOffsetInternal() int32_t Array::GetDataPtrOffsetInternal() { throw 3221274624U; } // Method : System.Array.TrySZBinarySearch(System.Array, int, int, object, out int) bool Array::TrySZBinarySearch_Out(_::Array* sourceArray, int32_t sourceIndex, int32_t count, object* value, int32_t& retVal) { throw 3221274624U; } // Method : System.Array.TrySZIndexOf(System.Array, int, int, object, out int) bool Array::TrySZIndexOf_Out(_::Array* sourceArray, int32_t sourceIndex, int32_t count, object* value, int32_t& retVal) { throw 3221274624U; } // Method : System.Array.TrySZLastIndexOf(System.Array, int, int, object, out int) bool Array::TrySZLastIndexOf_Out(_::Array* sourceArray, int32_t sourceIndex, int32_t count, object* value, int32_t& retVal) { throw 3221274624U; } // Method : System.Array.TrySZReverse(System.Array, int, int) bool Array::TrySZReverse(_::Array* array, int32_t index, int32_t count) { throw 3221274624U; } // Method : System.Array.TrySZSort(System.Array, System.Array, int, int) bool Array::TrySZSort(_::Array* keys, _::Array* items, int32_t left, int32_t right) { throw 3221274624U; } // Method : System.Array.Initialize() void Array::Initialize() { throw 3221274624U; } }} namespace CoreLib { namespace System { namespace _ = ::CoreLib::System; }}
26.39196
149
0.651371
[ "object" ]
68fc556bfc05b70d5a1e7c9b19408b55a509948a
4,623
cpp
C++
fdf-cpp/Photos/All/PhotosInfoAlgorithm.cpp
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
fdf-cpp/Photos/All/PhotosInfoAlgorithm.cpp
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
fdf-cpp/Photos/All/PhotosInfoAlgorithm.cpp
valgarn/fraud-detection-framework
52ce63a41af42de541354f32a3fb4bae773f2f86
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 The Fraud Detection Framework Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND< either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include <iostream> #include <math.h> #include <vector> #include <set> #include "PhotosInfoAlgorithm.h" typedef float float32_t; using namespace std; using namespace cv; using namespace Photos::All; using namespace Photos::Jpeg; bool PhotosInfoAlgorithm::isBlur(Mat image) { Mat imageGrey; cvtColor(image, imageGrey, CV_BGR2GRAY); resize(imageGrey, imageGrey, Size(1000, 1000), 0, 0, INTER_CUBIC); Mat dst2; image.copyTo(dst2); Mat laplacianImage; dst2.convertTo(laplacianImage, CV_8UC1); Laplacian(imageGrey, laplacianImage, CV_8U); Mat laplacianImage8bit; laplacianImage.convertTo(laplacianImage8bit, CV_8UC1); unsigned char *pixels = laplacianImage8bit.data; // 16777216 = 256*256*256 int maxLap = -16777216; for (unsigned long i = 0; i < (laplacianImage8bit.elemSize()*laplacianImage8bit.total()); i++) { if (pixels[i] > maxLap) { maxLap = pixels[i]; } } int threshold = 69; return (maxLap <= threshold); } int PhotosInfoAlgorithm::getBlur(Mat image) { Mat imageGrey; cvtColor(image, imageGrey, CV_BGR2GRAY); Mat dst2; image.copyTo(dst2); Mat laplacianImage; dst2.convertTo(laplacianImage, CV_8UC1); Laplacian(imageGrey, laplacianImage, CV_8U); Mat laplacianImage8bit; laplacianImage.convertTo(laplacianImage8bit, CV_8UC1); unsigned char *pixels = laplacianImage8bit.data; // 16777216 = 256*256*256 int maxLap = -16777216; for (unsigned long i = 0; i < (laplacianImage8bit.elemSize()*laplacianImage8bit.total()); i++) { if (pixels[i] > maxLap) { maxLap = pixels[i]; } } return maxLap; } SuspiciousInfo *PhotosInfoAlgorithm::check(const char *filename) { SuspiciousInfo *result = new SuspiciousInfo(this->getMethod()); result->setProbability(0.0); try { if (PhotosInfoAlgorithm::isFileExists(filename)) { ifstream ifs(filename, ios::binary | ios::ate); // Will we use very big jpegs? int length = ifs.tellg(); unsigned char *jpeg = new unsigned char[length]; ifs.seekg(0, ios::beg); ifs.read((char *)jpeg, length); string message = ""; int quality = JpegTools::getQuality(jpeg, length, message); delete[] jpeg; bool isJpeg = quality > 0; Mat image = imread(filename, CV_LOAD_IMAGE_COLOR); bool isBlur = this->isBlur(image); ostringstream json; string s = filename; string::size_type i = s.find_last_of(PATH_SEPARATOR); if (i != string::npos) s = s.substr(i+1); json << "{ \"Filename\": \"" << (s.length() < 49 ? s : s.substr(44)) << "\", \"Version\": \"" << this->config->VERSION << "\", \"isBlur\": " << (isBlur ? "true" : "false") << ", \"isJpeg\": " << (isJpeg ? "true" : "false") << ", \"Quality\": " << quality << ", \"Width\": " << image.cols << ", \"Height\": " << image.rows << ", \"Channels\": " << image.channels() << "}"; result->setComments(json.str().c_str()); } else { result->setErrorCode(SuspiciousInfo::ERROR_MISSING_FILE); result->setComments("ERROR_MISSING_FILE"); } } catch (const std::runtime_error &re) { std::exception_ptr p = std::current_exception(); result->setErrorCode(SuspiciousInfo::ERROR_UNKNOWN); result->setComments(re.what()); } catch (const std::exception &ex) { std::exception_ptr p = std::current_exception(); result->setErrorCode(SuspiciousInfo::ERROR_UNKNOWN); result->setComments(ex.what()); } catch (...) { result->setProbability(0.0); result->setErrorCode(SuspiciousInfo::ERROR_UNKNOWN); result->setComments(currentExceptionTypeName()); } return result->generateResult(); }
34.759398
143
0.619079
[ "vector" ]
68fcb26dc7a8eec7e6b5e41509170bb3b9d7f5ea
322
hpp
C++
include/NasNas/core/graphics/Renderable.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
148
2020-04-08T13:45:34.000Z
2022-01-29T13:52:10.000Z
include/NasNas/core/graphics/Renderable.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
5
2020-09-15T12:34:31.000Z
2022-02-14T20:59:12.000Z
include/NasNas/core/graphics/Renderable.hpp
Madour/NasNas
c6072d3d34116eca4ebff41899e14141d3009c03
[ "Zlib" ]
3
2020-10-03T22:35:20.000Z
2020-10-05T04:55:45.000Z
// Created by Modar Nasser on 21/04/2021. #pragma once #include <vector> namespace ns { class App; class Renderable { friend App; protected: Renderable(); virtual ~Renderable(); virtual void render() = 0; private: static std::vector<Renderable*> list; }; }
15.333333
45
0.57764
[ "render", "vector" ]
68ff2c1dc1ad0861862397eee3dd581471735754
5,782
cpp
C++
Cube/cube_source/src/clientextras.cpp
joseppi/Wwise
2da5fb892e3f8bf7b836f05e27118186f39d79de
[ "MIT" ]
null
null
null
Cube/cube_source/src/clientextras.cpp
joseppi/Wwise
2da5fb892e3f8bf7b836f05e27118186f39d79de
[ "MIT" ]
null
null
null
Cube/cube_source/src/clientextras.cpp
joseppi/Wwise
2da5fb892e3f8bf7b836f05e27118186f39d79de
[ "MIT" ]
null
null
null
// clientextras.cpp: stuff that didn't fit in client.cpp or clientgame.cpp :) #include "cube.h" // render players & monsters // very messy ad-hoc handling of animation frames, should be made more configurable // D D D D' D D D D' A A' P P' I I' R, R' E L J J' int frame[] = { 178, 184, 190, 137, 183, 189, 197, 164, 46, 51, 54, 32, 0, 0, 40, 1, 162, 162, 67, 168 }; int range[] = { 6, 6, 8, 28, 1, 1, 1, 1, 8, 19, 4, 18, 40, 1, 6, 15, 1, 1, 1, 1 }; void renderclient(dynent *d, bool team, char *mdlname, bool hellpig, float scale) { int n = 3; float speed = 100.0f; float mz = d->o.z-d->eyeheight+1.55f*scale; int basetime = -((AkIntPtr)d&0xFFF); if(d->state==CS_DEAD) { int r; if(hellpig) { n = 2; r = range[3]; } else { n = (AkIntPtr)d%3; r = range[n]; }; basetime = (int) d->lastaction; int t = (int) ( lastmillis-d->lastaction ); if(t<0 || t>20000) return; if(t>(r-1)*100) { n += 4; if(t>(r+10)*100) { t -= (r+10)*100; mz -= t*t/10000000000.0f*t; }; }; if(mz<-1000) return; } else if(d->state==CS_EDITING) n = 16; else if(d->state==CS_LAGGED) n = 17; else if(d->GetMonsterState()==M_ATTACKING) n = 8; else if (d->GetMonsterState() == M_PAIN) n = 10; else if((!d->move && !d->strafe) || !d->moving) n = 12; else if(!d->onfloor && d->timeinair>100) n = 18; else { n = 14; speed = 1200/d->maxspeed*scale; if(hellpig) speed = 300/d->maxspeed; }; if(hellpig) { n++; scale *= 32; mz -= 1.9f; }; rendermodel(mdlname, frame[n], range[n], 0, 1.5f, d->o.x, mz, d->o.y, d->yaw+90, d->pitch/2, team, scale, speed, 0, (float)basetime, d, hellpig); }; extern int democlientnum; void renderclients() { // local player // we don't actually render its model, so we need to handle the footsteps separately if ( ( player1->move || player1->strafe ) && ( player1->onfloor || player1->timeinair<=100 ) ) { // see above table int frame = 40, range = 6; int basetime = -((AkIntPtr)player1&0xFFF); float speed = 1200/player1->maxspeed; int time = (int)lastmillis-basetime; int fr1 = (int)(time/speed); fr1 = fr1%range+frame; int fr2 = fr1+1; if(fr2>=frame+range) fr2 = frame; if ( player1->lastanimframe != fr2 ) { if ( fr2 == 41 // left foot || fr2 == 44 ) // right foot ) { monsterfootstep( player1, fr2 == 44 ); } player1->lastanimframe = fr2; } } // network players loopv(players) { dynent *d; if((d = players[i]) && (!demoplayback || i!=democlientnum)) renderclient(d, isteam(player1->team, d->team), "monster/ogro", false, 1.0f); } }; // creation of scoreboard pseudo-menu bool scoreson = false; void showscores(bool on) { scoreson = on; menuset(((int)on)-1); }; struct sline { string s; }; vector<sline> scorelines; void renderscore(dynent *d) { sprintf_sd(lag)("%d", d->plag); sprintf_sd(name) ("(%s)", d->name); sprintf_s(scorelines.add().s)("%d\t%s\t%d\t%s\t%s", d->frags, d->state==CS_LAGGED ? "LAG" : lag, d->ping, d->team, d->state==CS_DEAD ? name : d->name); menumanual(0, scorelines.length()-1, scorelines.last().s); }; const int maxteams = 4; char *teamname[maxteams]; int teamscore[maxteams], teamsused; string teamscores; int timeremain = 0; void addteamscore(dynent *d) { if(!d) return; loopi(teamsused) if(strcmp(teamname[i], d->team)==0) { teamscore[i] += d->frags; return; }; if(teamsused==maxteams) return; teamname[teamsused] = d->team; teamscore[teamsused++] = d->frags; }; void renderscores() { if(!scoreson) return; scorelines.setsize(0); if(!demoplayback) renderscore(player1); loopv(players) if(players[i]) renderscore(players[i]); sortmenu(0, scorelines.length()); if(m_teammode) { teamsused = 0; loopv(players) addteamscore(players[i]); if(!demoplayback) addteamscore(player1); teamscores[0] = 0; loopj(teamsused) { sprintf_sd(sc)("[ %s: %d ]", teamname[j], teamscore[j]); strcat_s(teamscores, sc); }; menumanual(0, scorelines.length(), ""); menumanual(0, scorelines.length()+1, teamscores); }; }; // sendmap/getmap commands, should be replaced by more intuitive map downloading void sendmap(char *mapname) { if(*mapname) save_world(mapname); changemap(mapname); mapname = getclientmap(); int mapsize; uchar *mapdata = readmap(mapname, &mapsize); if(!mapdata) return; ENetPacket *packet = enet_packet_create(NULL, MAXTRANS + mapsize, ENET_PACKET_FLAG_RELIABLE); uchar *start = packet->data; uchar *p = start+2; putint(p, SV_SENDMAP); sendstring(mapname, p); putint(p, mapsize); if(65535 - (p - start) < mapsize) { conoutf("map %s is too large to send", mapname); free(mapdata); enet_packet_destroy(packet); return; }; memcpy(p, mapdata, mapsize); p += mapsize; free(mapdata); *(ushort *)start = ENET_HOST_TO_NET_16(p-start); enet_packet_resize(packet, p-start); sendpackettoserv(packet); conoutf("sending map %s to server...", mapname); sprintf_sd(msg)("[map %s uploaded to server, \"getmap\" to receive it]", mapname); toserver(msg); } void getmap() { ENetPacket *packet = enet_packet_create(NULL, MAXTRANS, ENET_PACKET_FLAG_RELIABLE); uchar *start = packet->data; uchar *p = start+2; putint(p, SV_RECVMAP); *(ushort *)start = ENET_HOST_TO_NET_16(p-start); enet_packet_resize(packet, p-start); sendpackettoserv(packet); conoutf("requesting map from server..."); } COMMAND(sendmap, ARG_1STR); COMMAND(getmap, ARG_NONE);
29.804124
155
0.598236
[ "render", "vector", "model" ]
68ffe90aa40241bb292df3a8a003a289e671a316
1,878
cpp
C++
Chapter_3_Problem_Solving_Paradigms/Dynamic_Programming/kattis_watersheds.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_3_Problem_Solving_Paradigms/Dynamic_Programming/kattis_watersheds.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_3_Problem_Solving_Paradigms/Dynamic_Programming/kattis_watersheds.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/**Kattis - watersheds * Relatively easy dp, the state is the position and the transition is to set the value of the pos to * the value of the pos where the water flows to if the pos is not a sink or to the next value if the pos * is a sink. * * Time: O(hw), Space: O(hw) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<int> vi; #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int h, w, num_sinks; int dr[] = {-1, 0, 0, 1}; // North, West, East, South int dc[] = {0, -1, 1, 0}; vector<vector<int>> grid, memo; int dp(int r, int c){ if (memo[r][c] != -1) return memo [r][c]; int smallest_dir = -1, cur_smallest = grid[r][c]; for (int i=0; i<4; i++){ int nr = r + dr[i]; int nc = c + dc[i]; if (nr < 0 || nr >= h || nc < 0 || nc >= w) continue; if (grid[nr][nc] < cur_smallest){ smallest_dir = i; cur_smallest = grid[nr][nc]; } } if (smallest_dir == -1){ // sink return memo[r][c] = num_sinks++; } return memo[r][c] = dp(r + dr[smallest_dir], c + dc[smallest_dir]); } int main(){ int num_tc; cin >> num_tc; for (int tc=0; tc<num_tc; tc++){ cout << "Case #" << tc+1 << ":\n"; cin >> h >> w; grid.assign(h, vi(w, 0)); memo.assign(h, vi(w, -1)); num_sinks = 0; for (int r=0; r<h; r++){ for (int c=0; c<w; c++){ cin >> grid[r][c]; } } for (int r=0; r<h; r++){ for (int c=0; c<w; c++){ cout << (char)('a'+dp(r, c)) << " "; } cout << endl; } } return 0; }
28.454545
105
0.503195
[ "vector" ]
ec0163206c5f5a0558f512d06bd472339ea86935
1,587
cpp
C++
Libraries/YukariProcessing/TaskAppendTransformedClouds.cpp
DanNixon/Yukari
da3e599477302c241b438ca44d6711fdd68b6ef8
[ "MIT" ]
null
null
null
Libraries/YukariProcessing/TaskAppendTransformedClouds.cpp
DanNixon/Yukari
da3e599477302c241b438ca44d6711fdd68b6ef8
[ "MIT" ]
null
null
null
Libraries/YukariProcessing/TaskAppendTransformedClouds.cpp
DanNixon/Yukari
da3e599477302c241b438ca44d6711fdd68b6ef8
[ "MIT" ]
3
2020-04-04T12:58:43.000Z
2020-06-01T21:47:22.000Z
/** @file */ #include "TaskAppendTransformedClouds.h" #include <pcl/common/transforms.h> #include <pcl/io/pcd_io.h> using namespace Yukari::Common; namespace Yukari { namespace Processing { TaskAppendTransformedClouds::TaskAppendTransformedClouds(const boost::filesystem::path &path) : IFrameProcessingTask(path) , m_logger(LoggingService::Instance().getLogger("TaskAppendTransformedClouds")) , m_worldCloud() { } int TaskAppendTransformedClouds::process(Task t) { if (!(t.cloud && t.imuFrame)) { m_logger->error("Do not have both cloud and IMU frame"); return 1; } CloudPtr inputCloud(new Cloud()); /* Transform cloud */ m_logger->trace("Transforming cloud by IMU"); pcl::transformPointCloud(*t.cloud, *inputCloud, t.imuFrame->toCloudTransform()); if (!m_worldCloud) { /* If this is the first recored cloud simply set it as the "world" cloud */ m_worldCloud = CloudPtr(new Cloud(*inputCloud)); } else { /* Add translated cloud to world cloud */ *m_worldCloud += *inputCloud; } return 0; } int TaskAppendTransformedClouds::onStop() { if (!m_worldCloud) { m_logger->warn("No world cloud, nothing saved"); return 1; } /* Generate filename */ boost::filesystem::path cloudFilename = m_outputDirectory / "world_cloud.pcd"; /* Save world cloud */ m_logger->trace("Saving world point cloud: {}", cloudFilename); pcl::io::savePCDFileBinaryCompressed(cloudFilename.string(), *m_worldCloud); return 0; } } }
23.686567
95
0.659735
[ "transform" ]
ec0b731c84a6dccce9d5d3d71db95c5392621cbd
3,227
hpp
C++
src/core/platform.hpp
RonRahaman/nekRS
ffc02bca33ece6ba3330c4ee24565b1c6b5f7242
[ "BSD-3-Clause" ]
1
2022-03-02T17:58:31.000Z
2022-03-02T17:58:31.000Z
src/core/platform.hpp
neams-th-coe/nekRS
5d2c8ab3d14b3fb16db35682336a1f96000698bb
[ "BSD-3-Clause" ]
null
null
null
src/core/platform.hpp
neams-th-coe/nekRS
5d2c8ab3d14b3fb16db35682336a1f96000698bb
[ "BSD-3-Clause" ]
1
2019-09-10T20:12:48.000Z
2019-09-10T20:12:48.000Z
#ifndef platform_hpp_ #define platform_hpp_ #include <occa.hpp> #include <vector> #include <mpi.h> #include "nrssys.hpp" #include "timer.hpp" class setupAide; class linAlg_t; class deviceVector_t{ public: // allow implicit conversion between this and the underlying occa::memory object operator occa::memory&(){ return o_vector; } // allow implicit conversion between this and kernelArg (for passing to kernels) operator occa::kernelArg(){ return o_vector; } deviceVector_t(const dlong _vectorSize, const dlong _nVectors, const dlong _wordSize, std::string _vectorName = ""); occa::memory& at(const int); private: occa::memory o_vector; std::vector<occa::memory> slices; const dlong vectorSize; const dlong nVectors; const dlong wordSize; const std::string vectorName; }; struct memPool_t{ void allocate(const dlong offset, const dlong fields); dfloat* slice0, *slice1, *slice2, *slice3, *slice4, *slice5, *slice6, *slice7; dfloat* slice9, *slice12, *slice15, *slice18, *slice19; dfloat* ptr; }; struct deviceMemPool_t{ void allocate(memPool_t& hostMemory, const dlong offset, const dlong fields); occa::memory slice0, slice1, slice2, slice3, slice4, slice5, slice6, slice7; occa::memory slice9, slice12, slice15, slice18, slice19; occa::memory o_ptr; long long bytesAllocated; }; class device_t : public occa::device{ public: device_t(setupAide& options, MPI_Comm comm); MPI_Comm comm; occa::kernel buildNativeKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props) const; occa::kernel buildKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props) const; occa::kernel buildKernel(const std::string &filename, const std::string &kernelName, const occa::properties &props, MPI_Comm comm) const; occa::memory malloc(const dlong Nbytes, const void* src = nullptr, const occa::properties& properties = occa::properties()); occa::memory malloc(const dlong Nbytes, const occa::properties& properties); occa::memory malloc(const dlong Nwords, const dlong wordSize, occa::memory src); occa::memory malloc(const dlong Nwords, const dlong wordSize); int id() const { return _device_id; } private: dlong bufferSize; int _device_id; void* _buffer; }; struct comm_t{ comm_t(MPI_Comm); MPI_Comm mpiComm; int mpiRank; int mpiCommSize; }; struct platform_t{ setupAide& options; int warpSize; device_t device; occa::properties kernelInfo; timer::timer_t timer; comm_t comm; linAlg_t* linAlg; memPool_t mempool; deviceMemPool_t o_mempool; void create_mempool(const dlong offset, const dlong fields); platform_t(setupAide& _options, MPI_Comm _comm); static platform_t* getInstance(setupAide& _options, MPI_Comm _comm){ if(!singleton) singleton = new platform_t(_options, _comm); return singleton; } static platform_t* getInstance(){ return singleton; } private: static platform_t * singleton; }; #endif
33.614583
128
0.690425
[ "object", "vector" ]
ec0dff2bde8d116e711042b106689f4fc6ecdb25
797
cpp
C++
0680-Split String/0680-Split String.cpp
nmdis1999/LintCode-1
316fa395c9a6de9bfac1d9c9cf58acb5ffb384a6
[ "MIT" ]
77
2017-12-30T13:33:37.000Z
2022-01-16T23:47:08.000Z
0601-0700/0680-Split String/0680-Split String.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
1
2018-05-14T14:15:40.000Z
2018-05-14T14:15:40.000Z
0601-0700/0680-Split String/0680-Split String.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
39
2017-12-07T14:36:25.000Z
2022-03-10T23:05:37.000Z
class Solution { public: /* * @param : a string to be split * @return: all possible split string array */ vector<vector<string>> splitString(string& s) { // write your code here vector<vector<string>> result; vector<string> path; dfs(s, 0, path, result); return result; } private: void dfs(string& s, int start, vector<string>& path, vector<vector<string>>& result) { if (start == s.size()) { result.push_back(path); return; } for (int i = start; i < s.size() && i < start + 2; ++i) { string str = s.substr(start, i - start + 1); path.push_back(str); dfs(s, i + 1, path, result); path.pop_back(); } } };
26.566667
90
0.498118
[ "vector" ]
ec2950e05f41f805348cfa69d6bbfcffb41e6110
799
cpp
C++
src/hdlAst/hdlStmIf.cpp
the-moog/hdlConvertor
5c8f5c6bf2bdceddf0c8cf6b5213d1b56b358f00
[ "MIT" ]
184
2016-08-12T14:26:52.000Z
2022-03-24T21:42:17.000Z
src/hdlAst/hdlStmIf.cpp
hdl4fpga/hdlConvertor
291991042135bf688ee2864cf7fb37d8e8a057db
[ "MIT" ]
142
2016-08-10T03:12:03.000Z
2022-03-30T17:35:06.000Z
src/hdlAst/hdlStmIf.cpp
hdl4fpga/hdlConvertor
291991042135bf688ee2864cf7fb37d8e8a057db
[ "MIT" ]
50
2016-08-06T10:38:29.000Z
2022-03-30T11:03:42.000Z
#include <hdlConvertor/hdlAst/hdlStmIf.h> namespace hdlConvertor { namespace hdlAst { HdlStmIf::HdlStmIf(std::unique_ptr<iHdlExprItem> _cond, std::unique_ptr<iHdlObj> _ifTrue) : iHdlStatement(), cond(move(_cond)), ifTrue(move(_ifTrue)) { } HdlStmIf::HdlStmIf(std::unique_ptr<iHdlExprItem> _cond, std::unique_ptr<iHdlObj> _ifTrue, std::unique_ptr<iHdlObj> _ifFalse) : iHdlStatement(), cond(move(_cond)), ifTrue(move(_ifTrue)), ifFalse( move(_ifFalse)) { } HdlStmIf::HdlStmIf(std::unique_ptr<iHdlExprItem> _cond, std::unique_ptr<iHdlObj> _ifTrue, std::vector<HdlExprAndiHdlObj> &_elseIfs, std::unique_ptr<iHdlObj> _ifFalse) : iHdlStatement(), cond(move(_cond)), ifTrue(move(_ifTrue)), elseIfs( move(_elseIfs)), ifFalse(move(_ifFalse)) { } HdlStmIf::~HdlStmIf() { } } }
25.774194
69
0.727159
[ "vector" ]
ec2c97d6cb3fe0b27a3f0dd4ff87710d059ae097
2,940
hxx
C++
include/sk/config/detail/propagate.hxx
sikol/sk-config
ada0c72ac5703763b1f1d9aadc2cc3850bf11acc
[ "BSL-1.0" ]
null
null
null
include/sk/config/detail/propagate.hxx
sikol/sk-config
ada0c72ac5703763b1f1d9aadc2cc3850bf11acc
[ "BSL-1.0" ]
null
null
null
include/sk/config/detail/propagate.hxx
sikol/sk-config
ada0c72ac5703763b1f1d9aadc2cc3850bf11acc
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef SK_CONFIG_DETAIL_PROPAGATE_HXX_INCLUDED #define SK_CONFIG_DETAIL_PROPAGATE_HXX_INCLUDED #include <boost/spirit/home/x3.hpp> namespace sk::config::detail { // T <- T void propagate_value(auto &/*ctx*/, auto &to, auto &from) { to = std::move(from); } void propagate_value(auto &ctx, auto &to, auto &from, auto /*name*/) { propagate_value(ctx, to, from); } template <typename T, typename V> struct propagate { V T::*member; propagate(V T::*member_) : member(member_) {} template <typename Context> void operator()(Context &ctx) { namespace x3 = boost::spirit::x3; propagate_value(ctx, x3::_val(ctx).*member, x3::_attr(ctx)); } }; template <typename T, typename V> propagate(V T::*) -> propagate<T, V>; template <typename T, typename V, typename U, typename W> struct propagate_named { V T::*member; W U::*name; propagate_named(V T::*member_, W U::*name_) : member(member_), name(name_) {} template <typename Context> void operator()(Context &ctx) { namespace x3 = boost::spirit::x3; propagate_value(ctx, x3::_val(ctx).*member, x3::_attr(ctx), name); } }; template <typename T, typename V, typename U, typename W> propagate_named(V T::*, W U::*) -> propagate_named<T, V, U, W>; } // namespace sk::config::detail #endif // SK_CONFIG_DETAIL_PROPAGATE_HXX_INCLUDED
37.692308
78
0.685374
[ "object" ]
ec2d41bfbabecb7166af479d2132a6f4d75cc424
15,115
cpp
C++
lib/Parser.cpp
tetsuo-cpp/descartes
0bec7a0e3075fc5d2e1190938b289e306555d7da
[ "MIT" ]
2
2021-03-07T15:09:20.000Z
2021-03-17T08:16:17.000Z
lib/Parser.cpp
tetsuo-cpp/descartes
0bec7a0e3075fc5d2e1190938b289e306555d7da
[ "MIT" ]
51
2021-03-17T08:01:14.000Z
2021-08-07T22:51:58.000Z
lib/Parser.cpp
tetsuo-cpp/descartes
0bec7a0e3075fc5d2e1190938b289e306555d7da
[ "MIT" ]
null
null
null
#include "Parser.h" #include <Ast.h> #include <cassert> namespace descartes { Parser::Parser(ILexer &lexer) : lexer(lexer), currentToken(TokenKind::Eof) { readToken(); } Block Parser::parse() { Block programBlock = parseBlock(); expectToken(TokenKind::Period); return programBlock; } SymbolTable &Parser::getSymbols() { return symbols; } void Parser::readToken() { currentToken = lexer.lex(); } bool Parser::isDone() const { return !static_cast<bool>(currentToken); } bool Parser::checkToken(TokenKind kind) { if (currentToken.kind == kind) { readToken(); return true; } return false; } void Parser::expectToken(TokenKind kind) { if (!checkToken(kind)) { #ifndef NDEBUG assert(!"Unexpected token"); #endif throw ParserError("Unexpected token"); } } Block Parser::parseBlock() { std::vector<Symbol> labelDecls; if (currentToken.kind == TokenKind::Label) labelDecls = parseLabelDecls(); std::vector<ConstDef> constDefs; if (currentToken.kind == TokenKind::Const) constDefs = parseConstDefs(); std::vector<TypeDef> typeDefs; if (currentToken.kind == TokenKind::Type) typeDefs = parseTypeDefs(); std::vector<VarDecl> varDecls; if (currentToken.kind == TokenKind::Var) varDecls = parseVarDecls(); std::vector<std::unique_ptr<Function>> functions; if (currentToken.kind == TokenKind::Function || currentToken.kind == TokenKind::Procedure) functions = parseFunctions(); expectToken(TokenKind::Begin); auto statements = parseCompoundStatement(); return Block(std::move(labelDecls), std::move(constDefs), std::move(typeDefs), std::move(varDecls), std::move(functions), std::move(statements)); } std::vector<Symbol> Parser::parseLabelDecls() { expectToken(TokenKind::Label); std::vector<Symbol> labels; while (!checkToken(TokenKind::SemiColon)) { if (!labels.empty()) expectToken(TokenKind::Comma); const auto labelName = currentToken.val; expectToken(TokenKind::Identifier); labels.push_back(symbols.make(labelName)); } return labels; } std::vector<ConstDef> Parser::parseConstDefs() { expectToken(TokenKind::Const); std::vector<ConstDef> constDefs; // This marks the beginning of a subsequent section in the block. If we see // this, then get out. while (!isDone() && currentToken.kind != TokenKind::Type && currentToken.kind != TokenKind::Var && currentToken.kind != TokenKind::Function && currentToken.kind != TokenKind::Procedure && currentToken.kind != TokenKind::Begin) { const auto identifier = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Equal); auto constExpr = parseConstExpr(); constDefs.emplace_back(symbols.make(identifier), std::move(constExpr)); expectToken(TokenKind::SemiColon); } return constDefs; } ExprPtr Parser::parseConstExpr() { return parsePrimaryExpr(); } std::vector<TypeDef> Parser::parseTypeDefs() { expectToken(TokenKind::Type); std::vector<TypeDef> typeDefs; while (!isDone() && currentToken.kind != TokenKind::Var && currentToken.kind != TokenKind::Function && currentToken.kind != TokenKind::Procedure && currentToken.kind != TokenKind::Begin) { const auto typeIdentifier = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Equal); auto type = parseType(); expectToken(TokenKind::SemiColon); typeDefs.emplace_back(symbols.make(typeIdentifier), std::move(type)); } return typeDefs; } TypePtr Parser::parseType() { const bool isPointer = checkToken(TokenKind::Hat); const auto typeString = currentToken.val; TypePtr type = nullptr; if (checkToken(TokenKind::Identifier)) type = std::make_unique<Alias>(symbols.make(typeString)); else if (checkToken(TokenKind::OpenParen)) type = parseEnum(); else if (checkToken(TokenKind::Record)) type = parseRecord(); else assert(!"Unknown type spec"); assert(type); type->isPointer = isPointer; return type; } TypePtr Parser::parseEnum() { std::vector<Symbol> enums; while (!checkToken(TokenKind::CloseParen)) { if (!enums.empty()) expectToken(TokenKind::Comma); auto enumVal = currentToken.val; expectToken(TokenKind::Identifier); enums.push_back(symbols.make(enumVal)); } return std::make_unique<Enum>(std::move(enums)); } TypePtr Parser::parseRecord() { std::vector<std::pair<Symbol, Symbol>> fields; while (!isDone() && currentToken.kind != TokenKind::End) { const auto fieldIdentifier = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Colon); const auto typeIdentifier = currentToken.val; expectToken(TokenKind::Identifier); fields.emplace_back(symbols.make(fieldIdentifier), symbols.make(typeIdentifier)); if (currentToken.kind != TokenKind::End) expectToken(TokenKind::SemiColon); } expectToken(TokenKind::End); return std::make_unique<Record>(std::move(fields)); } std::vector<VarDecl> Parser::parseVarDecls() { expectToken(TokenKind::Var); std::vector<VarDecl> varDecls; while (!isDone() && currentToken.kind != TokenKind::Function && currentToken.kind != TokenKind::Procedure && currentToken.kind != TokenKind::Begin) { auto varIdentifier = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Colon); auto typeIdentifier = currentToken.val; expectToken(TokenKind::Identifier); varDecls.emplace_back(symbols.make(varIdentifier), symbols.make(typeIdentifier)); expectToken(TokenKind::SemiColon); } return varDecls; } std::vector<std::unique_ptr<Function>> Parser::parseFunctions() { std::vector<std::unique_ptr<Function>> functions; while (!isDone() && currentToken.kind != TokenKind::Begin) { std::unique_ptr<Function> function; if (checkToken(TokenKind::Procedure)) function = parseProcedure(); else if (checkToken(TokenKind::Function)) function = parseFunction(); else throw ParserError("Expected either procedure or function"); functions.push_back(std::move(function)); } return functions; } std::unique_ptr<Function> Parser::parseProcedure() { const auto procedureName = currentToken.val; expectToken(TokenKind::Identifier); auto argsList = parseArgsList(); expectToken(TokenKind::SemiColon); auto functionBlock = parseBlock(); expectToken(TokenKind::SemiColon); // No return type for a procedure. return std::make_unique<Function>( symbols.make(procedureName), std::move(argsList), std::move(functionBlock), std::optional<Symbol>{}); } std::unique_ptr<Function> Parser::parseFunction() { const auto functionName = currentToken.val; expectToken(TokenKind::Identifier); auto argsList = parseArgsList(); expectToken(TokenKind::Colon); const auto returnType = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::SemiColon); auto functionBlock = parseBlock(); expectToken(TokenKind::SemiColon); return std::make_unique<Function>( symbols.make(functionName), std::move(argsList), std::move(functionBlock), symbols.make(returnType)); } std::vector<FunctionArg> Parser::parseArgsList() { std::vector<FunctionArg> argsList; expectToken(TokenKind::OpenParen); while (!isDone() && currentToken.kind != TokenKind::CloseParen) { if (!argsList.empty()) expectToken(TokenKind::Comma); bool isConst = checkToken(TokenKind::Const); const auto argName = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Colon); const auto argType = currentToken.val; expectToken(TokenKind::Identifier); argsList.emplace_back(symbols.make(argName), symbols.make(argType), isConst); } expectToken(TokenKind::CloseParen); return argsList; } StatementPtr Parser::parseStatement() { if (checkToken(TokenKind::Begin)) return parseCompoundStatement(); else if (checkToken(TokenKind::If)) return parseIf(); else if (checkToken(TokenKind::Case)) return parseCase(); else if (checkToken(TokenKind::Repeat)) return parseRepeat(); else if (checkToken(TokenKind::While)) return parseWhile(); else if (checkToken(TokenKind::For)) return parseFor(); else if (checkToken(TokenKind::With)) return parseWith(); else return parseIdentifierStatement(); } ExprPtr Parser::parseExpr() { return parseEquality(); } ExprPtr Parser::parseEquality() { auto lhs = parseRelational(); for (;;) { const auto tokenKind = currentToken.kind; if (checkToken(TokenKind::Equal) || checkToken(TokenKind::NotEqual)) lhs = std::make_unique<BinaryOp>(tokenKindToBinaryOpKind(tokenKind), std::move(lhs), parseRelational()); else return lhs; } } ExprPtr Parser::parseRelational() { auto lhs = parseAddition(); for (;;) { const auto tokenKind = currentToken.kind; if (checkToken(TokenKind::LessThan) || checkToken(TokenKind::GreaterThan) || checkToken(TokenKind::GreaterThanEqual) || checkToken(TokenKind::LessThanEqual)) lhs = std::make_unique<BinaryOp>(tokenKindToBinaryOpKind(tokenKind), std::move(lhs), parseAddition()); else return lhs; } } ExprPtr Parser::parseAddition() { auto lhs = parseMultiplication(); for (;;) { const auto tokenKind = currentToken.kind; if (checkToken(TokenKind::Add) || checkToken(TokenKind::Subtract)) lhs = std::make_unique<BinaryOp>(tokenKindToBinaryOpKind(tokenKind), std::move(lhs), parseMultiplication()); else return lhs; } } ExprPtr Parser::parseMultiplication() { auto lhs = parsePostfix(); for (;;) { const auto tokenKind = currentToken.kind; if (checkToken(TokenKind::Multiply) || checkToken(TokenKind::Divide)) lhs = std::make_unique<BinaryOp>(tokenKindToBinaryOpKind(tokenKind), std::move(lhs), parsePostfix()); else return lhs; } } ExprPtr Parser::parsePostfix() { auto expr = parsePrimaryExpr(); for (;;) { if (checkToken(TokenKind::Period)) { const auto memberIdentifier = currentToken.val; expectToken(TokenKind::Identifier); expr = std::make_unique<MemberRef>(std::move(expr), symbols.make(memberIdentifier)); } else return expr; } } ExprPtr Parser::parsePrimaryExpr() { switch (currentToken.kind) { case TokenKind::String: { auto stringVal = currentToken.val; expectToken(TokenKind::String); return std::make_unique<StringLiteral>(symbols.make(stringVal)); } case TokenKind::Number: { int val; try { val = std::stoi(currentToken.val); } catch (...) { // TODO: Improve reporting errors. throw ParserError("Conversion error"); } expectToken(TokenKind::Number); return std::make_unique<NumberLiteral>(val); } case TokenKind::Identifier: { const auto identifier = currentToken.val; expectToken(TokenKind::Identifier); // Check whether its a function call. if (checkToken(TokenKind::OpenParen)) { std::vector<ExprPtr> argList; while (!checkToken(TokenKind::CloseParen)) { if (!argList.empty()) expectToken(TokenKind::Comma); argList.push_back(parseExpr()); } return std::make_unique<Call>(symbols.make(identifier), std::move(argList)); } return std::make_unique<VarRef>(symbols.make(identifier)); } default: #ifndef NDEBUG assert(!"Invalid primary expr"); #endif throw ParserError("Invalid primary expr"); } } StatementPtr Parser::parseCompoundStatement() { std::vector<StatementPtr> body; while (!checkToken(TokenKind::End)) { // We could have a trailing semicolon after the last statement. // It isn't necessary but it's perfectly legal so let's check for it. if (checkToken(TokenKind::SemiColon) && checkToken(TokenKind::End)) break; body.push_back(parseStatement()); } return std::make_unique<Compound>(std::move(body)); } StatementPtr Parser::parseIf() { auto cond = parseExpr(); expectToken(TokenKind::Then); StatementPtr thenStatement = parseStatement(), elseStatement; if (checkToken(TokenKind::Else)) elseStatement = parseStatement(); return std::make_unique<If>(std::move(cond), std::move(thenStatement), std::move(elseStatement)); } StatementPtr Parser::parseCase() { auto expr = parseExpr(); expectToken(TokenKind::Of); std::vector<CaseArm> arms; while (!checkToken(TokenKind::End)) { if (!arms.empty()) expectToken(TokenKind::SemiColon); auto value = parseExpr(); expectToken(TokenKind::Colon); auto statement = parseStatement(); arms.emplace_back(std::move(value), std::move(statement)); } return std::make_unique<Case>(std::move(expr), std::move(arms)); } StatementPtr Parser::parseRepeat() { std::vector<StatementPtr> body; while (!checkToken(TokenKind::Until)) { if (checkToken(TokenKind::SemiColon) && checkToken(TokenKind::Until)) break; body.push_back(parseStatement()); } auto untilCond = parseExpr(); return std::make_unique<Repeat>(std::move(untilCond), std::move(body)); } StatementPtr Parser::parseWhile() { auto cond = parseExpr(); expectToken(TokenKind::Do); auto body = parseStatement(); return std::make_unique<While>(std::move(cond), std::move(body)); } StatementPtr Parser::parseFor() { const auto controlIdentifier = currentToken.val; expectToken(TokenKind::Identifier); expectToken(TokenKind::Assign); auto beginExpr = parseExpr(); bool to = checkToken(TokenKind::To); if (!to) expectToken(TokenKind::DownTo); auto endExpr = parseExpr(); expectToken(TokenKind::Do); auto body = parseStatement(); return std::make_unique<For>(symbols.make(controlIdentifier), std::move(beginExpr), std::move(endExpr), to, std::move(body)); } StatementPtr Parser::parseWith() { std::vector<Symbol> recordIdentifiers; while (!checkToken(TokenKind::Do)) { if (!recordIdentifiers.empty()) expectToken(TokenKind::Comma); Symbol recordSym = symbols.make(currentToken.val); expectToken(TokenKind::Identifier); recordIdentifiers.push_back(recordSym); } auto body = parseStatement(); return std::make_unique<With>(std::move(recordIdentifiers), std::move(body)); } StatementPtr Parser::parseIdentifierStatement() { // This will either be an entire function call or the left hand side of an // assignment. auto expr = parseExpr(); if (checkToken(TokenKind::Assign)) { auto rhs = parseExpr(); return std::make_unique<Assignment>(std::move(expr), std::move(rhs)); } assert(expr->getKind() == ExprKind::Call); return std::make_unique<CallStatement>(std::move(expr)); } } // namespace descartes
32.366167
80
0.678928
[ "vector" ]
ec2d8888a7f546347814ed2212277eb5d29c2acb
7,867
cpp
C++
third_party/WebKit/Source/core/svg/SVGImageElement.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/svg/SVGImageElement.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/svg/SVGImageElement.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Rob Buis <buis@kde.org> * Copyright (C) 2006 Alexander Kellett <lypanov@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "core/svg/SVGImageElement.h" #include "core/CSSPropertyNames.h" #include "core/SVGNames.h" #include "core/dom/StyleChangeReason.h" #include "core/layout/LayoutImageResource.h" #include "core/layout/svg/LayoutSVGImage.h" namespace blink { inline SVGImageElement::SVGImageElement(Document& document) : SVGGraphicsElement(SVGNames::imageTag, document), SVGURIReference(this), x_(SVGAnimatedLength::Create(this, SVGNames::xAttr, SVGLength::Create(SVGLengthMode::kWidth), CSSPropertyX)), y_(SVGAnimatedLength::Create(this, SVGNames::yAttr, SVGLength::Create(SVGLengthMode::kHeight), CSSPropertyY)), width_(SVGAnimatedLength::Create(this, SVGNames::widthAttr, SVGLength::Create(SVGLengthMode::kWidth), CSSPropertyWidth)), height_( SVGAnimatedLength::Create(this, SVGNames::heightAttr, SVGLength::Create(SVGLengthMode::kHeight), CSSPropertyHeight)), preserve_aspect_ratio_(SVGAnimatedPreserveAspectRatio::Create( this, SVGNames::preserveAspectRatioAttr)), image_loader_(SVGImageLoader::Create(this)) { AddToPropertyMap(x_); AddToPropertyMap(y_); AddToPropertyMap(width_); AddToPropertyMap(height_); AddToPropertyMap(preserve_aspect_ratio_); } DEFINE_NODE_FACTORY(SVGImageElement) DEFINE_TRACE(SVGImageElement) { visitor->Trace(x_); visitor->Trace(y_); visitor->Trace(width_); visitor->Trace(height_); visitor->Trace(preserve_aspect_ratio_); visitor->Trace(image_loader_); SVGGraphicsElement::Trace(visitor); SVGURIReference::Trace(visitor); } bool SVGImageElement::CurrentFrameHasSingleSecurityOrigin() const { if (LayoutSVGImage* layout_svg_image = ToLayoutSVGImage(GetLayoutObject())) { LayoutImageResource* layout_image_resource = layout_svg_image->ImageResource(); if (layout_image_resource->HasImage()) { if (Image* image = layout_image_resource->CachedImage()->GetImage()) return image->CurrentFrameHasSingleSecurityOrigin(); } } return true; } void SVGImageElement::CollectStyleForPresentationAttribute( const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style) { SVGAnimatedPropertyBase* property = PropertyFromAttribute(name); if (property == width_) { AddPropertyToPresentationAttributeStyle(style, property->CssPropertyId(), width_->CssValue()); } else if (property == height_) { AddPropertyToPresentationAttributeStyle(style, property->CssPropertyId(), height_->CssValue()); } else if (property == x_) { AddPropertyToPresentationAttributeStyle(style, property->CssPropertyId(), x_->CssValue()); } else if (property == y_) { AddPropertyToPresentationAttributeStyle(style, property->CssPropertyId(), y_->CssValue()); } else { SVGGraphicsElement::CollectStyleForPresentationAttribute(name, value, style); } } void SVGImageElement::SvgAttributeChanged(const QualifiedName& attr_name) { bool is_length_attribute = attr_name == SVGNames::xAttr || attr_name == SVGNames::yAttr || attr_name == SVGNames::widthAttr || attr_name == SVGNames::heightAttr; if (is_length_attribute || attr_name == SVGNames::preserveAspectRatioAttr) { SVGElement::InvalidationGuard invalidation_guard(this); if (is_length_attribute) { InvalidateSVGPresentationAttributeStyle(); SetNeedsStyleRecalc( kLocalStyleChange, StyleChangeReasonForTracing::FromAttribute(attr_name)); UpdateRelativeLengthsInformation(); } LayoutObject* object = this->GetLayoutObject(); if (!object) return; // FIXME: if isLengthAttribute then we should avoid this call if the // viewport didn't change, however since we don't have the computed // style yet we can't use updateBoundingBox/updateImageContainerSize. // See http://crbug.com/466200. MarkForLayoutAndParentResourceInvalidation(object); return; } if (SVGURIReference::IsKnownAttribute(attr_name)) { SVGElement::InvalidationGuard invalidation_guard(this); GetImageLoader().UpdateFromElement(ImageLoader::kUpdateIgnorePreviousError); return; } SVGGraphicsElement::SvgAttributeChanged(attr_name); } bool SVGImageElement::SelfHasRelativeLengths() const { return x_->CurrentValue()->IsRelative() || y_->CurrentValue()->IsRelative() || width_->CurrentValue()->IsRelative() || height_->CurrentValue()->IsRelative(); } LayoutObject* SVGImageElement::CreateLayoutObject(const ComputedStyle&) { return new LayoutSVGImage(this); } bool SVGImageElement::HaveLoadedRequiredResources() { return !GetImageLoader().HasPendingActivity(); } void SVGImageElement::AttachLayoutTree(AttachContext& context) { SVGGraphicsElement::AttachLayoutTree(context); if (LayoutSVGImage* image_obj = ToLayoutSVGImage(GetLayoutObject())) { LayoutImageResource* layout_image_resource = image_obj->ImageResource(); if (layout_image_resource->HasImage()) return; layout_image_resource->SetImageResource(GetImageLoader().GetImage()); } } Node::InsertionNotificationRequest SVGImageElement::InsertedInto( ContainerNode* root_parent) { // A previous loader update may have failed to actually fetch the image if // the document was inactive. In that case, force a re-update (but don't // clear previous errors). if (root_parent->isConnected() && !GetImageLoader().GetImage()) GetImageLoader().UpdateFromElement(ImageLoader::kUpdateNormal); return SVGGraphicsElement::InsertedInto(root_parent); } FloatSize SVGImageElement::SourceDefaultObjectSize() { if (GetLayoutObject()) return ToLayoutSVGImage(GetLayoutObject())->ObjectBoundingBox().Size(); SVGLengthContext length_context(this); return FloatSize(width_->CurrentValue()->Value(length_context), height_->CurrentValue()->Value(length_context)); } const AtomicString SVGImageElement::ImageSourceURL() const { return AtomicString(HrefString()); } void SVGImageElement::DidMoveToNewDocument(Document& old_document) { // TODO(fs): Initiate a new load (like HTMLImageElement.) GetImageLoader().ElementDidMoveToNewDocument(); SVGGraphicsElement::DidMoveToNewDocument(old_document); } } // namespace blink
38.753695
80
0.684886
[ "object" ]
ec2e86eea27b67fc11369fb0c4132d7a3331f333
520
cpp
C++
C++/horses.cpp
saurabhcommand/Hello-world
647bad9da901a52d455f05ecc37c6823c22dc77e
[ "MIT" ]
1,428
2018-10-03T15:15:17.000Z
2019-03-31T18:38:36.000Z
C++/horses.cpp
saurabhcommand/Hello-world
647bad9da901a52d455f05ecc37c6823c22dc77e
[ "MIT" ]
1,162
2018-10-03T15:05:49.000Z
2018-10-18T14:17:52.000Z
C++/horses.cpp
saurabhcommand/Hello-world
647bad9da901a52d455f05ecc37c6823c22dc77e
[ "MIT" ]
3,909
2018-10-03T15:07:19.000Z
2019-03-31T18:39:08.000Z
// Problem https://www.codechef.com/problems/HORSES #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; vector<int>v; for(int i=0;i<n;i++){ int x;cin >> x; v.push_back(x); } sort(v.begin(),v.end()); int ans = INT_MAX; for(int i=1;i<n;i++){ ans = min(ans,v[i]-v[i-1]); } cout << (ans) << endl; } return 0; }
16.25
51
0.407692
[ "vector" ]
ec3497ca4db0b305a251518df06eb0ce8a7600cb
1,868
cpp
C++
typical90/069-ColorfulBlocks2/colorful-block2.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
typical90/069-ColorfulBlocks2/colorful-block2.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
typical90/069-ColorfulBlocks2/colorful-block2.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/* 069 - Colorful Blocks 2(★3) https://atcoder.jp/contests/typical90/tasks/typical90_bq Author: Keitaro Naruse Date: 2021-12-21, 2022-01-02 MIT License */ // # Solution // - Answer = K * (K-1) * (K-2)^{N-2} // - (K-2)^n, represent n as bit and make a table #include <iostream> #include <vector> #include <bitset> const bool Debug = false; int main() { // Initialize const unsigned long long Large_Prime = 1000000007LL; const int Max_Bit = 64; // Read N and K unsigned long long N = 0LL, K = 0LL; std::cin >> N >> K; if( Debug ) { std::cerr << N << " " << K << std::endl; } // Main unsigned long long cases = K % Large_Prime; // Boundary case if( N == 1LL ) { // Do nothing ; } else if( N == 2LL ) { cases *= ( K - 1 ); cases %= Large_Prime; } else if( N > 2LL ) { cases *= ( K - 1 ); cases %= Large_Prime; std::bitset< Max_Bit > b( N - 2 ); std::vector< unsigned long long > patterns( Max_Bit, 0LL ); patterns.at( 0 ) = K - 2LL; for( int i = 1; i < Max_Bit; i ++ ) { patterns.at( i ) = patterns.at( i - 1 ) * patterns.at( i - 1 ); patterns.at( i ) %= Large_Prime; } if( Debug ) { for( int i = 0; i < Max_Bit; i ++ ) { std::cerr << patterns.at( i ) << " "; } std::cerr << std::endl; } // Main for( int i = 0; i < Max_Bit; i ++ ) { if( b[i] ) { cases *= patterns.at( i ); cases %= Large_Prime; } } } // Display result std::cout << cases << std::endl; // Finalize if( Debug ) { std::cerr << "Normally terminated." << std::endl; } return( 0 ); }
23.64557
75
0.455032
[ "vector" ]
ec349a74d2bbe606a5205946cd6d44fd348e1a56
2,666
hpp
C++
lib/prometheus/BasicPrometheusCounter.hpp
carnegie-technologies/pravala-toolkit
77dac4a910dc0692b7515a8e3b77d34eb2888256
[ "Apache-2.0" ]
null
null
null
lib/prometheus/BasicPrometheusCounter.hpp
carnegie-technologies/pravala-toolkit
77dac4a910dc0692b7515a8e3b77d34eb2888256
[ "Apache-2.0" ]
null
null
null
lib/prometheus/BasicPrometheusCounter.hpp
carnegie-technologies/pravala-toolkit
77dac4a910dc0692b7515a8e3b77d34eb2888256
[ "Apache-2.0" ]
2
2020-02-07T00:16:51.000Z
2020-02-11T15:10:45.000Z
/* * Copyright 2019 Carnegie Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "PrometheusCounter.hpp" namespace Pravala { /// @brief A basic Prometheus counter. /// A counter has a monotonically increasing value. class BasicPrometheusCounter: public PrometheusCounter { public: /// @brief A constructor for a counter without labels. /// It uses internal counter metric object. /// @param [in] timestampMode The timestamp mode the internal metric should use. /// @param [in] name The name of the metric. /// @param [in] help A description of the metric. BasicPrometheusCounter ( PrometheusMetric::TimeMode timestampMode, const String & name, const String & help = String::EmptyString ); /// @brief A constructor for a counter with labels /// @param [in] parent The parent counter metric to which to add this counter /// @param [in] labelValues A comma separated list of label values BasicPrometheusCounter ( PrometheusCounterMetric & parent, const String & labelValues ); /// @brief Destructor ~BasicPrometheusCounter(); /// @brief Increments the counter by 'value' and updates the timestamp. /// @param [in] value The value by which to increment the counter. void increment ( uint64_t value = 1 ); /// @brief Resets the counter to zero and updates the timestamp. inline void reset() { _value = 0; updateTimestamp(); } protected: virtual uint64_t getValue(); virtual uint64_t getTimestamp(); private: /// @brief The value of the counter /// @note The Prometheus specifications use non-integral (double) values which is a bit weird for a counter. /// As we don't (currently) have floating-point use-cases, we are using integral counters to improve /// performance uint64_t _value; uint64_t _timestamp; ///< The timestamp in milliseconds from the UTC epoch /// @brief Updates the timestamp void updateTimestamp(); }; }
37.027778
119
0.668042
[ "object" ]
ec399f1f74bb79d2664d79a5e7dabfe5d2c1a168
1,130
cpp
C++
472. Concatenated Words/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
472. Concatenated Words/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
472. Concatenated Words/solution.cpp
zlsun/leetcode
438d0020a701d7aa6a82eee0e46e5b11305abfda
[ "MIT" ]
null
null
null
/** 472. Concatenated Words Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Example: Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". Note: The number of elements of the given array will not exceed 10,000 The length sum of elements in the given array will not exceed 600,000. All the input string will only include lower case letters. The returned elements order does not matter. **/ #include <iostream> #include "../utils.h" using namespace std; class Solution { public: vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { } }; int main() { Solution s; return 0; }
30.540541
206
0.725664
[ "vector" ]
ec41769074d7bc4cef73c21daa10fb56b301a50f
4,360
cpp
C++
app/components/backend/gl/factories/ProgramObjectFactory.cpp
filipwasil/rearwing-glviewer
3d0289398367b6dc330eae18042497b8da2e77da
[ "MIT" ]
null
null
null
app/components/backend/gl/factories/ProgramObjectFactory.cpp
filipwasil/rearwing-glviewer
3d0289398367b6dc330eae18042497b8da2e77da
[ "MIT" ]
null
null
null
app/components/backend/gl/factories/ProgramObjectFactory.cpp
filipwasil/rearwing-glviewer
3d0289398367b6dc330eae18042497b8da2e77da
[ "MIT" ]
null
null
null
#include "ProgramObjectFactory.hpp" #include <Config.hpp> #include <Exception.hpp> #include <glad/glad.h> #include <array> #include <fstream> #include <iostream> #include <string> #include <vector> namespace { static constexpr int VALID_NUMBER_OF_SUPPORTED_BINARY_FORMATS {1}; } namespace rwc { void ProgramObjectFactory::loadShader(const char* code, unsigned int type, unsigned int programObject) { const GLuint id = glCreateShader(type); glShaderSource(id, 1, &code, nullptr); glCompileShader(id); GLint status = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &status); if (!status) { glDeleteShader(id); throw Exception{"Shader failed to load", LOCATION}; } glAttachShader(programObject, id); } std::string ProgramObjectFactory::readShader(const char* filePath) { std::ifstream file(filePath, std::ios::in); if (!file.is_open() || !file.good()) { throw Exception{std::string("File ") + filePath + " not found", LOCATION}; } return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()}; } unsigned int ProgramObjectFactory::load(const char* fsPath, const char* vsPath) { const auto fsCode = readShader(fsPath); const auto vsCode = readShader(vsPath); const GLuint id = glCreateProgram(); loadShader(vsCode.c_str(), GL_VERTEX_SHADER, id); loadShader(fsCode.c_str(), GL_FRAGMENT_SHADER, id); GLint Success {0}; glLinkProgram(id); glGetProgramiv(id, GL_LINK_STATUS, &Success); if (0 == Success) { throw Exception{getErrorMessage(id), LOCATION}; } glValidateProgram(id); glGetProgramiv(id, GL_VALIDATE_STATUS, &Success); if (0 == Success) { throw Exception{getErrorMessage(id), LOCATION}; } return id; } unsigned int ProgramObjectFactory::load(std::add_pointer_t<std::add_pointer_t<void(void)>(const char*)> getAddress, const char* pathToBinary) { glGetProgramBinaryOES = reinterpret_cast<PFNGLGETPROGRAMBINARYOESPROC>(getAddress("glGetProgramBinaryOES")); if (nullptr == glGetProgramBinaryOES) { throw Exception{"OpenGL ES extension glGetProgramBinaryOES failed to initialize", LOCATION}; } glProgramBinaryOES = reinterpret_cast<PFNGLPROGRAMBINARYOESPROC>(getAddress("glProgramBinaryOES")); if (nullptr == glProgramBinaryOES) { throw Exception{"OpenGL ES extension glProgramBinaryOES failed to initialize", LOCATION}; } return load(pathToBinary); } unsigned int ProgramObjectFactory::load(const char* pathToBinary) { GLint formats {0}; glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS_OES, &formats); if (VALID_NUMBER_OF_SUPPORTED_BINARY_FORMATS != formats) { throw Exception(std::string("Number of supported binary formats invalid: ") + std::to_string(formats), LOCATION); } std::ifstream file(pathToBinary, std::ios::binary | std::ios::ate); if (!file.is_open() || !file.good()) { throw Exception(std::string("File not found: ") + pathToBinary, LOCATION); } const auto end = file.tellg(); file.seekg(0, std::ios::beg); const auto size = std::size_t(end - file.tellg()); std::vector<char> buffer(size); if (!file.read(buffer.data(), std::streamsize(buffer.size()))) { throw Exception(std::string("File reading failed: ") + pathToBinary, LOCATION); } GLint binaryFormat {}; glGetIntegerv(GL_PROGRAM_BINARY_FORMATS_OES, &binaryFormat); GLuint progId = glCreateProgram(); glProgramBinaryOES(progId, static_cast<GLenum>(binaryFormat), buffer.data(), static_cast<GLint>(size)); GLint success {0}; glGetProgramiv(progId, GL_LINK_STATUS, &success); if (!success) { throw Exception(std::string("Failed to link binary shader: ") + pathToBinary, LOCATION); } return progId; } std::string ProgramObjectFactory::getErrorMessage(GLuint pipelineId) { GLint maxInfoLength {0}; glGetProgramiv(pipelineId, GL_INFO_LOG_LENGTH, &maxInfoLength); if ( 0 >= maxInfoLength) { throw Exception("Error message lenght returned negative value ", LOCATION); } std::vector<char> msg ( static_cast<std::vector<char>::size_type>(maxInfoLength), '\0' ); glGetProgramInfoLog(pipelineId, static_cast<GLsizei>(msg.size()), nullptr, msg.data()); return std::string(msg.begin(), msg.end()); } } // namespace rwc
32.058824
141
0.696789
[ "vector" ]
ec4d131337d3d9aa1a13277b9946016e18a0bc00
2,342
cpp
C++
src/old_src/NBD.cpp
doliinychenko/iSS
9391b8830e385c0f5f1600a1cfd1ad355ea582c5
[ "MIT" ]
4
2018-11-29T14:34:55.000Z
2020-11-25T14:44:32.000Z
src/old_src/NBD.cpp
doliinychenko/iSS
9391b8830e385c0f5f1600a1cfd1ad355ea582c5
[ "MIT" ]
1
2020-04-05T01:17:31.000Z
2020-04-05T01:17:31.000Z
src/old_src/NBD.cpp
doliinychenko/iSS
9391b8830e385c0f5f1600a1cfd1ad355ea582c5
[ "MIT" ]
6
2018-04-06T17:08:35.000Z
2020-10-19T19:10:38.000Z
// Ver. 1.4.3 // Use rand(p,r) to sample. // Can use rand() if p and r are the same as last one (~4 times faster). // p: success probability; r: number of failure #include <stdlib.h> #include <iostream> #include <vector> #include <cmath> #include "arsenal.h" #include "NBD.h" #define ZERO 1e-15 using namespace std; //---------------------------------------------------------------------- // Constructors: //---------------------------------------------------------------------- //---------------------------------------------------------------------- NBD::NBD(double p, double r) { recalculateMode(p,r); } //---------------------------------------------------------------------- double NBD::pdf(double k_in) // NBD pdf. Parameters p and r are passed through the bridge_XX private // variables. { if (k_in<0) return 0; int k = (floor)(k_in); double prefactor = binomial_coefficient(k+bridge_r-1, k); double answer = prefactor*pow(1-bridge_p,bridge_r)*pow(bridge_p,k); return answer; } //---------------------------------------------------------------------- void NBD::recalculateMode(double p, double r) // Recalculate mode and maximun corresponding to the given p and r. // Also copy p and r to the bridge_xx variables. // Furthermore, it construct the envelop functions for better sampling // efficiencies. { bridge_p = p; bridge_r = r; if (r<=1) { mode = 1e-30; maximum = pow(1-p,r); } else { mode = p*(r-1)/(1-p); // note it is not an integer here maximum = pdf(mode); } mean = p*r/(1-p); std = sqrt(p*r)/(1-p); //std /=10; // finer // fill in envelop pdf and inverse CDF // first test left boundary int step_left; for (step_left=6; step_left>0; step_left--) if (mode-std*step_left>=0) break; // then fill envelop functions constructEnvelopTab(mode, std, step_left, 6); } //---------------------------------------------------------------------- long NBD::rand() // Sample NBD with last used p and r. { if (bridge_p<ZERO) return 0; if (bridge_p+ZERO>1.0) return 0; return (long)sampleUsingPDFAndEnvelopFunc(); } //---------------------------------------------------------------------- long NBD::rand(double p, double r) // Sample NBD with parameters p and r. { if (p<ZERO) return 0; if (p+ZERO>1.0) return 0; recalculateMode(p,r); return (long)rand(); }
26.314607
79
0.520922
[ "vector" ]
ec4f5d7b6ed999c9c526ff719e22e6eaaf2ebe8c
18,984
cxx
C++
main/desktop/source/app/dispatchwatcher.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/desktop/source/app/dispatchwatcher.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/desktop/source/app/dispatchwatcher.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include "dispatchwatcher.hxx" #include <rtl/ustring.hxx> #include <tools/string.hxx> #include <comphelper/processfactory.hxx> #include <comphelper/synchronousdispatch.hxx> #include <com/sun/star/util/XCloseable.hpp> #include <com/sun/star/util/CloseVetoException.hpp> #include <com/sun/star/task/XInteractionHandler.hpp> #include <com/sun/star/util/URL.hpp> #include <com/sun/star/frame/XDesktop.hpp> #include <com/sun/star/container/XEnumeration.hpp> #include <com/sun/star/frame/XFramesSupplier.hpp> #include <com/sun/star/frame/XDispatch.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/view/XPrintable.hpp> #include <com/sun/star/frame/XDispatchProvider.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <com/sun/star/document/MacroExecMode.hpp> #include <com/sun/star/document/UpdateDocMode.hpp> #include <tools/urlobj.hxx> #include <comphelper/mediadescriptor.hxx> #include <vector> using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::view; namespace desktop { String GetURL_Impl( const String& rName, boost::optional< rtl::OUString > const & cwdUrl ); struct DispatchHolder { DispatchHolder( const URL& rURL, Reference< XDispatch >& rDispatch ) : aURL( rURL ), xDispatch( rDispatch ) {} URL aURL; rtl::OUString cwdUrl; Reference< XDispatch > xDispatch; }; Mutex* DispatchWatcher::pWatcherMutex = NULL; Mutex& DispatchWatcher::GetMutex() { if ( !pWatcherMutex ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pWatcherMutex ) pWatcherMutex = new osl::Mutex(); } return *pWatcherMutex; } // Create or get the dispatch watcher implementation. This implementation must be // a singleton to prevent access to the framework after it wants to terminate. DispatchWatcher* DispatchWatcher::GetDispatchWatcher() { static Reference< XInterface > xDispatchWatcher; static DispatchWatcher* pDispatchWatcher = NULL; if ( !xDispatchWatcher.is() ) { ::osl::MutexGuard aGuard( GetMutex() ); if ( !xDispatchWatcher.is() ) { pDispatchWatcher = new DispatchWatcher(); // We have to hold a reference to ourself forever to prevent our own destruction. xDispatchWatcher = static_cast< cppu::OWeakObject *>( pDispatchWatcher ); } } return pDispatchWatcher; } DispatchWatcher::DispatchWatcher() : m_nRequestCount(0) { } DispatchWatcher::~DispatchWatcher() { } sal_Bool DispatchWatcher::executeDispatchRequests( const DispatchList& aDispatchRequestsList, bool bNoTerminate ) { Reference< XComponentLoader > xDesktop( ::comphelper::getProcessServiceFactory()->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop")) ), UNO_QUERY ); DispatchList::const_iterator p; std::vector< DispatchHolder > aDispatches; ::rtl::OUString aAsTemplateArg( RTL_CONSTASCII_USTRINGPARAM( "AsTemplate")); for ( p = aDispatchRequestsList.begin(); p != aDispatchRequestsList.end(); p++ ) { String aPrinterName; const DispatchRequest& aDispatchRequest = *p; // create parameter array sal_Int32 nCount = 4; if ( aDispatchRequest.aPreselectedFactory.getLength() ) nCount++; // we need more properties for a print/print to request if ( aDispatchRequest.aRequestType == REQUEST_PRINT || aDispatchRequest.aRequestType == REQUEST_PRINTTO ) nCount++; Sequence < PropertyValue > aArgs( nCount ); // mark request as user interaction from outside aArgs[0].Name = ::rtl::OUString::createFromAscii("Referer"); aArgs[0].Value <<= ::rtl::OUString::createFromAscii("private:OpenEvent"); if ( aDispatchRequest.aRequestType == REQUEST_PRINT || aDispatchRequest.aRequestType == REQUEST_PRINTTO ) { aArgs[1].Name = ::rtl::OUString::createFromAscii("ReadOnly"); aArgs[2].Name = ::rtl::OUString::createFromAscii("OpenNewView"); aArgs[3].Name = ::rtl::OUString::createFromAscii("Hidden"); aArgs[4].Name = ::rtl::OUString::createFromAscii("Silent"); } else { Reference < com::sun::star::task::XInteractionHandler > xInteraction( ::comphelper::getProcessServiceFactory()->createInstance( OUString::createFromAscii("com.sun.star.task.InteractionHandler") ), com::sun::star::uno::UNO_QUERY ); aArgs[1].Name = OUString::createFromAscii( "InteractionHandler" ); aArgs[1].Value <<= xInteraction; sal_Int16 nMacroExecMode = ::com::sun::star::document::MacroExecMode::USE_CONFIG; aArgs[2].Name = OUString::createFromAscii( "MacroExecutionMode" ); aArgs[2].Value <<= nMacroExecMode; sal_Int16 nUpdateDoc = ::com::sun::star::document::UpdateDocMode::ACCORDING_TO_CONFIG; aArgs[3].Name = OUString::createFromAscii( "UpdateDocMode" ); aArgs[3].Value <<= nUpdateDoc; } if ( aDispatchRequest.aPreselectedFactory.getLength() ) { aArgs[nCount-1].Name = ::comphelper::MediaDescriptor::PROP_DOCUMENTSERVICE(); aArgs[nCount-1].Value <<= aDispatchRequest.aPreselectedFactory; } String aName( GetURL_Impl( aDispatchRequest.aURL, aDispatchRequest.aCwdUrl ) ); ::rtl::OUString aTarget( RTL_CONSTASCII_USTRINGPARAM("_default") ); if ( aDispatchRequest.aRequestType == REQUEST_PRINT || aDispatchRequest.aRequestType == REQUEST_PRINTTO ) { // documents opened for printing are opened readonly because they must be opened as a new document and this // document could be open already aArgs[1].Value <<= sal_True; // always open a new document for printing, because it must be disposed afterwards aArgs[2].Value <<= sal_True; // printing is done in a hidden view aArgs[3].Value <<= sal_True; // load document for printing without user interaction aArgs[4].Value <<= sal_True; // hidden documents should never be put into open tasks aTarget = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ); } // load the document ... if they are loadable! // Otherwise try to dispatch it ... Reference < XPrintable > xDoc; if( ( aName.CompareToAscii( ".uno" , 4 ) == COMPARE_EQUAL ) || ( aName.CompareToAscii( "slot:" , 5 ) == COMPARE_EQUAL ) || ( aName.CompareToAscii( "macro:", 6 ) == COMPARE_EQUAL ) || ( aName.CompareToAscii("vnd.sun.star.script", 19) == COMPARE_EQUAL) ) { // Attention: URL must be parsed full. Otherwise some detections on it will fail! // It doesn't matter, if parser isn't available. Because; We try loading of URL then ... URL aURL ; aURL.Complete = aName; Reference < XDispatch > xDispatcher ; Reference < XDispatchProvider > xProvider ( xDesktop, UNO_QUERY ); Reference < XURLTransformer > xParser ( ::comphelper::getProcessServiceFactory()->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.util.URLTransformer")) ), ::com::sun::star::uno::UNO_QUERY ); if( xParser.is() == sal_True ) xParser->parseStrict( aURL ); if( xProvider.is() == sal_True ) xDispatcher = xProvider->queryDispatch( aURL, ::rtl::OUString(), 0 ); if( xDispatcher.is() == sal_True ) { { ::osl::ClearableMutexGuard aGuard( GetMutex() ); // Remember request so we can find it in statusChanged! m_aRequestContainer.insert( DispatchWatcherHashMap::value_type( aURL.Complete, (sal_Int32)1 ) ); m_nRequestCount++; } // Use local vector to store dispatcher because we have to fill our request container before // we can dispatch. Otherwise it would be possible that statusChanged is called before we dispatched all requests!! aDispatches.push_back( DispatchHolder( aURL, xDispatcher )); } } else if ( ( aName.CompareToAscii( "service:" , 8 ) == COMPARE_EQUAL ) ) { // TODO: the dispatch has to be done for loadComponentFromURL as well. Please ask AS for more details. URL aURL ; aURL.Complete = aName; Reference < XDispatch > xDispatcher ; Reference < XDispatchProvider > xProvider ( xDesktop, UNO_QUERY ); Reference < XURLTransformer > xParser ( ::comphelper::getProcessServiceFactory()->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.util.URLTransformer")) ), ::com::sun::star::uno::UNO_QUERY ); if( xParser.is() == sal_True ) xParser->parseStrict( aURL ); if( xProvider.is() == sal_True ) xDispatcher = xProvider->queryDispatch( aURL, ::rtl::OUString(), 0 ); if( xDispatcher.is() == sal_True ) { try { // We have to be listener to catch errors during dispatching URLs. // Otherwise it would be possible to have an office running without an open // window!! Sequence < PropertyValue > aArgs2(1); aArgs2[0].Name = ::rtl::OUString::createFromAscii("SynchronMode"); aArgs2[0].Value <<= sal_True; Reference < XNotifyingDispatch > xDisp( xDispatcher, UNO_QUERY ); if ( xDisp.is() ) xDisp->dispatchWithNotification( aURL, aArgs2, DispatchWatcher::GetDispatchWatcher() ); else xDispatcher->dispatch( aURL, aArgs2 ); } catch ( ::com::sun::star::uno::Exception& ) { OUString aMsg = OUString::createFromAscii( "Desktop::OpenDefault() IllegalArgumentException while calling XNotifyingDispatch: "); OSL_ENSURE( sal_False, OUStringToOString(aMsg, RTL_TEXTENCODING_ASCII_US).getStr()); } } } else { INetURLObject aObj( aName ); if ( aObj.GetProtocol() == INET_PROT_PRIVATE ) aTarget = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("_default") ); // Set "AsTemplate" argument according to request type if ( aDispatchRequest.aRequestType == REQUEST_FORCENEW || aDispatchRequest.aRequestType == REQUEST_FORCEOPEN ) { sal_Int32 nIndex = aArgs.getLength(); aArgs.realloc( nIndex+1 ); aArgs[nIndex].Name = aAsTemplateArg; if ( aDispatchRequest.aRequestType == REQUEST_FORCENEW ) aArgs[nIndex].Value <<= sal_True; else aArgs[nIndex].Value <<= sal_False; } // if we are called in viewmode, open document read-only // #95425# if(aDispatchRequest.aRequestType == REQUEST_VIEW) { sal_Int32 nIndex = aArgs.getLength(); aArgs.realloc(nIndex+1); aArgs[nIndex].Name = OUString::createFromAscii("ReadOnly"); aArgs[nIndex].Value <<= sal_True; } // if we are called with -start set Start in mediadescriptor if(aDispatchRequest.aRequestType == REQUEST_START) { sal_Int32 nIndex = aArgs.getLength(); aArgs.realloc(nIndex+1); aArgs[nIndex].Name = OUString::createFromAscii("StartPresentation"); aArgs[nIndex].Value <<= sal_True; } // This is a synchron loading of a component so we don't have to deal with our statusChanged listener mechanism. try { xDoc = Reference < XPrintable >( ::comphelper::SynchronousDispatch::dispatch( xDesktop, aName, aTarget, 0, aArgs ), UNO_QUERY ); //xDoc = Reference < XPrintable >( xDesktop->loadComponentFromURL( aName, aTarget, 0, aArgs ), UNO_QUERY ); } catch ( ::com::sun::star::lang::IllegalArgumentException& iae) { OUString aMsg = OUString::createFromAscii( "Dispatchwatcher IllegalArgumentException while calling loadComponentFromURL: ") + iae.Message; OSL_ENSURE( sal_False, OUStringToOString(aMsg, RTL_TEXTENCODING_ASCII_US).getStr()); } catch (com::sun::star::io::IOException& ioe) { OUString aMsg = OUString::createFromAscii( "Dispatchwatcher IOException while calling loadComponentFromURL: ") + ioe.Message; OSL_ENSURE( sal_False, OUStringToOString(aMsg, RTL_TEXTENCODING_ASCII_US).getStr()); } if ( aDispatchRequest.aRequestType == REQUEST_OPEN || aDispatchRequest.aRequestType == REQUEST_VIEW || aDispatchRequest.aRequestType == REQUEST_START || aDispatchRequest.aRequestType == REQUEST_FORCEOPEN || aDispatchRequest.aRequestType == REQUEST_FORCENEW ) { // request is completed OfficeIPCThread::RequestsCompleted( 1 ); } else if ( aDispatchRequest.aRequestType == REQUEST_PRINT || aDispatchRequest.aRequestType == REQUEST_PRINTTO ) { if ( xDoc.is() ) { if ( aDispatchRequest.aRequestType == REQUEST_PRINTTO ) { // create the printer Sequence < PropertyValue > aPrinterArgs( 1 ); aPrinterArgs[0].Name = ::rtl::OUString::createFromAscii("Name"); aPrinterArgs[0].Value <<= ::rtl::OUString( aDispatchRequest.aPrinterName ); xDoc->setPrinter( aPrinterArgs ); } // print ( also without user interaction ) Sequence < PropertyValue > aPrinterArgs( 1 ); aPrinterArgs[0].Name = ::rtl::OUString::createFromAscii("Wait"); aPrinterArgs[0].Value <<= ( sal_Bool ) sal_True; xDoc->print( aPrinterArgs ); } else { // place error message here ... } // remove the document try { Reference < XCloseable > xClose( xDoc, UNO_QUERY ); if ( xClose.is() ) xClose->close( sal_True ); else { Reference < XComponent > xComp( xDoc, UNO_QUERY ); if ( xComp.is() ) xComp->dispose(); } } catch ( com::sun::star::util::CloseVetoException& ) { } // request is completed OfficeIPCThread::RequestsCompleted( 1 ); } } } if ( aDispatches.size() > 0 ) { // Execute all asynchronous dispatches now after we placed them into our request container! Sequence < PropertyValue > aArgs( 2 ); aArgs[0].Name = ::rtl::OUString::createFromAscii("Referer"); aArgs[0].Value <<= ::rtl::OUString::createFromAscii("private:OpenEvent"); aArgs[1].Name = ::rtl::OUString::createFromAscii("SynchronMode"); aArgs[1].Value <<= sal_True; for ( sal_uInt32 n = 0; n < aDispatches.size(); n++ ) { Reference< XDispatch > xDispatch = aDispatches[n].xDispatch; Reference < XNotifyingDispatch > xDisp( xDispatch, UNO_QUERY ); if ( xDisp.is() ) xDisp->dispatchWithNotification( aDispatches[n].aURL, aArgs, this ); else { ::osl::ClearableMutexGuard aGuard( GetMutex() ); m_nRequestCount--; aGuard.clear(); xDispatch->dispatch( aDispatches[n].aURL, aArgs ); } } } ::osl::ClearableMutexGuard aGuard( GetMutex() ); bool bEmpty = (m_nRequestCount == 0); aGuard.clear(); // No more asynchronous requests? // The requests are removed from the request container after they called back to this // implementation via statusChanged!! if ( bEmpty && !bNoTerminate /*m_aRequestContainer.empty()*/ ) { // We have to check if we have an open task otherwise we have to shutdown the office. Reference< XFramesSupplier > xTasksSupplier( xDesktop, UNO_QUERY ); aGuard.clear(); Reference< XElementAccess > xList( xTasksSupplier->getFrames(), UNO_QUERY ); if ( !xList->hasElements() ) { // We don't have any task open so we have to shutdown ourself!! Reference< XDesktop > xDesktop2( xTasksSupplier, UNO_QUERY ); if ( xDesktop2.is() ) return xDesktop2->terminate(); } } return sal_False; } void SAL_CALL DispatchWatcher::disposing( const ::com::sun::star::lang::EventObject& ) throw(::com::sun::star::uno::RuntimeException) { } void SAL_CALL DispatchWatcher::dispatchFinished( const DispatchResultEvent& ) throw( RuntimeException ) { osl::ClearableMutexGuard aGuard( GetMutex() ); sal_Int16 nCount = --m_nRequestCount; aGuard.clear(); OfficeIPCThread::RequestsCompleted( 1 ); /* // Find request in our hash map and remove it as a pending request DispatchWatcherHashMap::iterator pDispatchEntry = m_aRequestContainer.find( rEvent.FeatureURL.Complete ) ; if ( pDispatchEntry != m_aRequestContainer.end() ) { m_aRequestContainer.erase( pDispatchEntry ); aGuard.clear(); OfficeIPCThread::RequestsCompleted( 1 ); } else aGuard.clear(); */ if ( !nCount && !OfficeIPCThread::AreRequestsPending() ) { // We have to check if we have an open task otherwise we have to shutdown the office. Reference< XFramesSupplier > xTasksSupplier( ::comphelper::getProcessServiceFactory()->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop")) ), UNO_QUERY ); Reference< XElementAccess > xList( xTasksSupplier->getFrames(), UNO_QUERY ); if ( !xList->hasElements() ) { // We don't have any task open so we have to shutdown ourself!! Reference< XDesktop > xDesktop( xTasksSupplier, UNO_QUERY ); if ( xDesktop.is() ) xDesktop->terminate(); } } } }
37.150685
228
0.642962
[ "vector" ]
ec50c07d4fa2ec544ff891eadc0ca855c0a5ef47
3,026
cpp
C++
common/code/Reordering/Reorder.cpp
SoundMetrics/aris-integration-sdk
ccde2130f4067ea0e38db2e286962d9f7bfcc573
[ "MIT" ]
6
2017-11-29T20:49:21.000Z
2021-11-03T01:38:52.000Z
common/code/Reordering/Reorder.cpp
SoundMetrics/aris-integration-sdk
ccde2130f4067ea0e38db2e286962d9f7bfcc573
[ "MIT" ]
69
2017-04-10T23:48:00.000Z
2020-08-12T12:53:26.000Z
common/code/Reordering/Reorder.cpp
SoundMetrics/aris-integration-sdk
ccde2130f4067ea0e38db2e286962d9f7bfcc573
[ "MIT" ]
2
2019-05-01T16:45:39.000Z
2020-10-08T12:56:27.000Z
// Copyright (c) 2010-2017 Sound Metrics Corp. All rights reserverd. // // #include "Reorder.h" #include <assert.h> #include <cstdint> #include <cstring> #include <vector> namespace Aris { uint32_t PingModeToPingsPerFrame(uint32_t pingMode) { if (pingMode == 1) { return 3; } else if (pingMode == 3) { return 6; } else if (pingMode == 6) { return 4; } else if (pingMode == 9) { return 8; } return 0; } uint32_t PingModeToNumBeams(uint32_t pingMode) { if (pingMode == 1) { return 48; } else if (pingMode == 3) { return 96; } else if (pingMode == 6) { return 64; } else if (pingMode == 9) { return 128; } return 0; } void Reorder(ArisFrameHeader & header, uint8_t * samples) { assert(samples != nullptr); if (header.ReorderedSamples) { return; } const uint32_t samplesPerBeam = header.SamplesPerBeam; const uint32_t pingMode = header.PingMode; const uint32_t pingsPerFrame = PingModeToPingsPerFrame(pingMode); const uint32_t numBeams = PingModeToNumBeams(pingMode); const int32_t beamsPerPing = 16; const int32_t chRvMap[beamsPerPing] = {10, 2, 14, 6, 8, 0, 12, 4, 11, 3, 15, 7, 9, 1, 13, 5}; int32_t chRvMultMap[beamsPerPing]; for (uint32_t chIdx = 0; chIdx < beamsPerPing; ++chIdx) { chRvMultMap[chIdx] = chRvMap[chIdx] * pingsPerFrame; } auto inputBuf = std::vector<uint8_t>(numBeams * samplesPerBeam, 0); uint8_t * inputByte = &(inputBuf[0]); uint8_t * const outputBuf = samples; memcpy(&(inputBuf[0]), outputBuf, numBeams * samplesPerBeam); for (uint32_t pingIdx = 0; pingIdx < pingsPerFrame; ++pingIdx) { for (uint32_t sampleIdx = 0; sampleIdx < samplesPerBeam; ++sampleIdx) { const int32_t composed = sampleIdx * numBeams + pingIdx; outputBuf[composed + chRvMultMap[0]] = inputByte [0]; outputBuf[composed + chRvMultMap[1]] = inputByte [1]; outputBuf[composed + chRvMultMap[2]] = inputByte [2]; outputBuf[composed + chRvMultMap[3]] = inputByte [3]; outputBuf[composed + chRvMultMap[4]] = inputByte [4]; outputBuf[composed + chRvMultMap[5]] = inputByte [5]; outputBuf[composed + chRvMultMap[6]] = inputByte [6]; outputBuf[composed + chRvMultMap[7]] = inputByte [7]; outputBuf[composed + chRvMultMap[8]] = inputByte [8]; outputBuf[composed + chRvMultMap[9]] = inputByte [9]; outputBuf[composed + chRvMultMap[10]] = inputByte[10]; outputBuf[composed + chRvMultMap[11]] = inputByte[11]; outputBuf[composed + chRvMultMap[12]] = inputByte[12]; outputBuf[composed + chRvMultMap[13]] = inputByte[13]; outputBuf[composed + chRvMultMap[14]] = inputByte[14]; outputBuf[composed + chRvMultMap[15]] = inputByte[15]; inputByte += beamsPerPing; } } header.ReorderedSamples = 1; } }
31.852632
97
0.61302
[ "vector" ]
ec678faedc674c1a3fd7fe9b926ef6ffa25e7bb0
896
cpp
C++
BinarySearch.cpp
DPS0340/CPP_DataStructure_Algorithm
eb72f92b0087d0ef73465e18590673069624dd39
[ "MIT" ]
null
null
null
BinarySearch.cpp
DPS0340/CPP_DataStructure_Algorithm
eb72f92b0087d0ef73465e18590673069624dd39
[ "MIT" ]
null
null
null
BinarySearch.cpp
DPS0340/CPP_DataStructure_Algorithm
eb72f92b0087d0ef73465e18590673069624dd39
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; // arr은 오름차순 정렬되어있고, 같은 값을 가진 원소가 없다고 가정 // n이 존재하지 않는 경우는 없다고 가정 int bs(vector<int> arr, int n) { // 시간 복잡도 테스트용 카운터 int count = 0; const int length = arr.size(); int delta = length / 4; int index = length / 2; while(arr[index] != n) { count++; if(arr[index] < n) { index += delta; if(delta < 1) { index++; } } else { index -= delta; if(delta < 1) { index--; } } delta /= 2; } cout << "size: " << length << endl; cout << "count: " << count << endl; return index; } int main() { vector<int> arr; // 테스트 배열 초기화 for(int i=0;i<1000000;i++) { arr.push_back(i + 1); } cout << "location is: " << bs(arr, 3) << endl; return 0; }
20.363636
50
0.450893
[ "vector" ]
ec67ee836cd54834cb3cc8bd30af279d9e46918b
14,300
cc
C++
components/translate/core/browser/translate_ui_delegate.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/translate/core/browser/translate_ui_delegate.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/translate/core/browser/translate_ui_delegate.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.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. #include "components/translate/core/browser/translate_ui_delegate.h" #include <algorithm> #include "base/i18n/string_compare.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "components/translate/core/browser/language_state.h" #include "components/translate/core/browser/translate_client.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_driver.h" #include "components/translate/core/browser/translate_manager.h" #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/common/translate_constants.h" #include "components/variations/variations_associated_data.h" #include "net/base/url_util.h" #include "third_party/icu/source/i18n/unicode/coll.h" #include "third_party/metrics_proto/translate_event.pb.h" #include "ui/base/l10n/l10n_util.h" namespace { const char kDeclineTranslate[] = "Translate.DeclineTranslate"; const char kRevertTranslation[] = "Translate.RevertTranslation"; const char kPerformTranslate[] = "Translate.Translate"; const char kPerformTranslateAmpCacheUrl[] = "Translate.Translate.AMPCacheURL"; const char kNeverTranslateLang[] = "Translate.NeverTranslateLang"; const char kNeverTranslateSite[] = "Translate.NeverTranslateSite"; const char kAlwaysTranslateLang[] = "Translate.AlwaysTranslateLang"; const char kModifyOriginalLang[] = "Translate.ModifyOriginalLang"; const char kModifyTargetLang[] = "Translate.ModifyTargetLang"; const char kDeclineTranslateDismissUI[] = "Translate.DeclineTranslateDismissUI"; const char kShowErrorUI[] = "Translate.ShowErrorUI"; // Returns a Collator object which helps to sort strings in a given locale or // null if unable to find the right collator. // // TODO(hajimehoshi): Write a test for icu::Collator::createInstance. std::unique_ptr<icu::Collator> CreateCollator(const std::string& locale) { UErrorCode error = U_ZERO_ERROR; icu::Locale loc(locale.c_str()); std::unique_ptr<icu::Collator> collator( icu::Collator::createInstance(loc, error)); if (!collator || !U_SUCCESS(error)) return nullptr; collator->setStrength(icu::Collator::PRIMARY); return collator; } // Returns whether |url| fits pattern of an AMP cache url. // Note this is a copy of logic in amp_page_load_metrics_observer.cc // TODO(crbug.com/1064974) Factor out into shared utility. bool IsLikelyAmpCacheUrl(const GURL& url) { // Our heuristic to identify AMP cache URLs is to check for the presence of // the amp_js_v query param. for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) { if (it.GetKey() == "amp_js_v") return true; } return false; } } // namespace namespace translate { TranslateUIDelegate::TranslateUIDelegate( const base::WeakPtr<TranslateManager>& translate_manager, const std::string& original_language, const std::string& target_language) : translate_driver_( translate_manager->translate_client()->GetTranslateDriver()), translate_manager_(translate_manager), original_language_index_(kNoIndex), initial_original_language_index_(kNoIndex), target_language_index_(kNoIndex), prefs_(translate_manager_->translate_client()->GetTranslatePrefs()) { DCHECK(translate_driver_); DCHECK(translate_manager_); std::vector<std::string> language_codes; TranslateDownloadManager::GetSupportedLanguages( prefs_->IsTranslateAllowedByPolicy(), &language_codes); // Preparing for the alphabetical order in the locale. std::string locale = TranslateDownloadManager::GetInstance()->application_locale(); std::unique_ptr<icu::Collator> collator = CreateCollator(locale); languages_.reserve(language_codes.size()); for (std::string& language_code : language_codes) { base::string16 language_name = l10n_util::GetDisplayNameForLocale(language_code, locale, true); languages_.emplace_back(std::move(language_code), std::move(language_name)); } // Sort |languages_| in alphabetical order according to the display name. std::sort( languages_.begin(), languages_.end(), [&collator](const LanguageNamePair& lhs, const LanguageNamePair& rhs) { if (collator) { switch (base::i18n::CompareString16WithCollator(*collator, lhs.second, rhs.second)) { case UCOL_LESS: return true; case UCOL_GREATER: return false; case UCOL_EQUAL: break; } } else { // |locale| may not be supported by ICU collator (crbug/54833). In // this case, let's order the languages in UTF-8. int result = lhs.second.compare(rhs.second); if (result != 0) return result < 0; } // Matching display names will be ordered alphabetically according to // the language codes. return lhs.first < rhs.first; }); for (std::vector<LanguageNamePair>::const_iterator iter = languages_.begin(); iter != languages_.end(); ++iter) { const std::string& language_code = iter->first; if (language_code == original_language) { original_language_index_ = iter - languages_.begin(); initial_original_language_index_ = original_language_index_; } if (language_code == target_language) target_language_index_ = iter - languages_.begin(); } } TranslateUIDelegate::~TranslateUIDelegate() {} void TranslateUIDelegate::OnErrorShown(TranslateErrors::Type error_type) { DCHECK_LE(TranslateErrors::NONE, error_type); DCHECK_LT(error_type, TranslateErrors::TRANSLATE_ERROR_MAX); if (error_type == TranslateErrors::NONE) return; UMA_HISTOGRAM_ENUMERATION(kShowErrorUI, error_type, TranslateErrors::TRANSLATE_ERROR_MAX); } const LanguageState& TranslateUIDelegate::GetLanguageState() { return translate_manager_->GetLanguageState(); } size_t TranslateUIDelegate::GetNumberOfLanguages() const { return languages_.size(); } void TranslateUIDelegate::UpdateOriginalLanguageIndex(size_t language_index) { if (original_language_index_ == language_index) return; UMA_HISTOGRAM_BOOLEAN(kModifyOriginalLang, true); original_language_index_ = language_index; } void TranslateUIDelegate::UpdateOriginalLanguage( const std::string& language_code) { DCHECK(translate_manager_ != nullptr); for (size_t i = 0; i < languages_.size(); ++i) { if (languages_[i].first.compare(language_code) == 0) { UpdateOriginalLanguageIndex(i); translate_manager_->mutable_translate_event() ->set_modified_source_language(language_code); return; } } } void TranslateUIDelegate::UpdateTargetLanguageIndex(size_t language_index) { if (target_language_index_ == language_index) return; DCHECK_LT(language_index, GetNumberOfLanguages()); UMA_HISTOGRAM_BOOLEAN(kModifyTargetLang, true); target_language_index_ = language_index; } void TranslateUIDelegate::UpdateTargetLanguage( const std::string& language_code) { DCHECK(translate_manager_ != nullptr); for (size_t i = 0; i < languages_.size(); ++i) { if (languages_[i].first.compare(language_code) == 0) { UpdateTargetLanguageIndex(i); translate_manager_->mutable_translate_event() ->set_modified_target_language(language_code); return; } } } std::string TranslateUIDelegate::GetLanguageCodeAt(size_t index) const { DCHECK_LT(index, GetNumberOfLanguages()); return languages_[index].first; } base::string16 TranslateUIDelegate::GetLanguageNameAt(size_t index) const { if (index == kNoIndex) return base::string16(); DCHECK_LT(index, GetNumberOfLanguages()); return languages_[index].second; } std::string TranslateUIDelegate::GetOriginalLanguageCode() const { return (GetOriginalLanguageIndex() == kNoIndex) ? translate::kUnknownLanguageCode : GetLanguageCodeAt(GetOriginalLanguageIndex()); } std::string TranslateUIDelegate::GetTargetLanguageCode() const { return (GetTargetLanguageIndex() == kNoIndex) ? translate::kUnknownLanguageCode : GetLanguageCodeAt(GetTargetLanguageIndex()); } void TranslateUIDelegate::Translate() { if (!translate_driver_->IsIncognito()) { prefs_->ResetTranslationDeniedCount(GetOriginalLanguageCode()); prefs_->ResetTranslationIgnoredCount(GetOriginalLanguageCode()); prefs_->IncrementTranslationAcceptedCount(GetOriginalLanguageCode()); prefs_->SetRecentTargetLanguage(GetTargetLanguageCode()); } if (translate_manager_) { translate_manager_->RecordTranslateEvent( metrics::TranslateEventProto::USER_ACCEPT); translate_manager_->TranslatePage(GetOriginalLanguageCode(), GetTargetLanguageCode(), false); UMA_HISTOGRAM_BOOLEAN(kPerformTranslate, true); if (IsLikelyAmpCacheUrl(translate_driver_->GetLastCommittedURL())) UMA_HISTOGRAM_BOOLEAN(kPerformTranslateAmpCacheUrl, true); } } void TranslateUIDelegate::RevertTranslation() { if (translate_manager_) { translate_manager_->RevertTranslation(); UMA_HISTOGRAM_BOOLEAN(kRevertTranslation, true); } } void TranslateUIDelegate::TranslationDeclined(bool explicitly_closed) { if (!translate_driver_->IsIncognito()) { const std::string& language = GetOriginalLanguageCode(); if (explicitly_closed) { prefs_->ResetTranslationAcceptedCount(language); prefs_->IncrementTranslationDeniedCount(language); prefs_->UpdateLastDeniedTime(language); } else { prefs_->IncrementTranslationIgnoredCount(language); } } // Remember that the user declined the translation so as to prevent showing a // translate UI for that page again. (TranslateManager initiates translations // when getting a LANGUAGE_DETERMINED from the page, which happens when a load // stops. That could happen multiple times, including after the user already // declined the translation.) if (translate_manager_) { translate_manager_->RecordTranslateEvent( explicitly_closed ? metrics::TranslateEventProto::USER_DECLINE : metrics::TranslateEventProto::USER_IGNORE); if (explicitly_closed) translate_manager_->GetLanguageState().set_translation_declined(true); } if (explicitly_closed) { UMA_HISTOGRAM_BOOLEAN(kDeclineTranslate, true); } else { UMA_HISTOGRAM_BOOLEAN(kDeclineTranslateDismissUI, true); } } bool TranslateUIDelegate::IsLanguageBlocked() const { return prefs_->IsBlockedLanguage(GetOriginalLanguageCode()); } void TranslateUIDelegate::SetLanguageBlocked(bool value) { if (value) { prefs_->AddToLanguageList(GetOriginalLanguageCode(), /*force_blocked=*/true); if (translate_manager_) { // Translation has been blocked for this language. Capture that in the // metrics. Note that we don't capture a language being unblocked... which // is not the same as accepting a given translation for this language. translate_manager_->RecordTranslateEvent( metrics::TranslateEventProto::USER_NEVER_TRANSLATE_LANGUAGE); } } else { prefs_->UnblockLanguage(GetOriginalLanguageCode()); } UMA_HISTOGRAM_BOOLEAN(kNeverTranslateLang, value); } bool TranslateUIDelegate::IsSiteBlacklisted() const { std::string host = GetPageHost(); return !host.empty() && prefs_->IsSiteBlacklisted(host); } bool TranslateUIDelegate::CanBlacklistSite() const { return !GetPageHost().empty(); } void TranslateUIDelegate::SetSiteBlacklist(bool value) { std::string host = GetPageHost(); if (host.empty()) return; if (value) { prefs_->BlacklistSite(host); if (translate_manager_) { // Translation has been blocked for this site. Capture that in the metrics // Note that we don't capture a language being unblocked... which is not // the same as accepting a given translation for this site. translate_manager_->RecordTranslateEvent( metrics::TranslateEventProto::USER_NEVER_TRANSLATE_SITE); } } else { prefs_->RemoveSiteFromBlacklist(host); } UMA_HISTOGRAM_BOOLEAN(kNeverTranslateSite, value); } bool TranslateUIDelegate::ShouldAlwaysTranslate() const { return prefs_->IsLanguagePairWhitelisted(GetOriginalLanguageCode(), GetTargetLanguageCode()); } bool TranslateUIDelegate::ShouldAlwaysTranslateBeCheckedByDefault() const { return ShouldAlwaysTranslate(); } bool TranslateUIDelegate::ShouldShowAlwaysTranslateShortcut() const { return !translate_driver_->IsIncognito() && prefs_->GetTranslationAcceptedCount(GetOriginalLanguageCode()) >= kAlwaysTranslateShortcutMinimumAccepts; } bool TranslateUIDelegate::ShouldShowNeverTranslateShortcut() const { return !translate_driver_->IsIncognito() && prefs_->GetTranslationDeniedCount(GetOriginalLanguageCode()) >= kNeverTranslateShortcutMinimumDenials; } void TranslateUIDelegate::SetAlwaysTranslate(bool value) { const std::string& original_lang = GetOriginalLanguageCode(); const std::string& target_lang = GetTargetLanguageCode(); if (value) { prefs_->WhitelistLanguagePair(original_lang, target_lang); // A default translation mapping has been accepted for this language. // Capture that in the metrics. Note that we don't capture a language being // unmapped... which is not the same as accepting some other translation // for this language. if (translate_manager_) { translate_manager_->RecordTranslateEvent( metrics::TranslateEventProto::USER_ALWAYS_TRANSLATE_LANGUAGE); } } else { prefs_->RemoveLanguagePairFromWhitelist(original_lang, target_lang); } UMA_HISTOGRAM_BOOLEAN(kAlwaysTranslateLang, value); } std::string TranslateUIDelegate::GetPageHost() const { if (!translate_driver_->HasCurrentPage()) return std::string(); return translate_driver_->GetLastCommittedURL().HostNoBrackets(); } } // namespace translate
37.142857
80
0.732378
[ "object", "vector" ]
3f3c3e82ad913918c0bc9ed9a505f5d121e50c10
16,443
cpp
C++
libs/ofxLineaDeTiempo/src/Controller/TrackGroupController.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
31
2020-04-29T06:11:54.000Z
2021-11-10T19:14:09.000Z
libs/ofxLineaDeTiempo/src/Controller/TrackGroupController.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
11
2020-07-27T17:12:05.000Z
2021-12-01T16:33:18.000Z
libs/ofxLineaDeTiempo/src/Controller/TrackGroupController.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
null
null
null
// // TrackGroupController.cpp // tracksAndTimeTest // // Created by Roy Macdonald on 3/14/20. // // #include "LineaDeTiempo/Controller/TrackGroupController.h" #include "LineaDeTiempo/View/TrackGroupView.h" #include "LineaDeTiempo/Utils/CollectionHelper.h" // namespace ofx { namespace LineaDeTiempo { TrackGroupController::TrackGroupController(const std::string& name, TrackGroupController * parent, TimeControl* timeControl) : BaseController<TrackGroupView>(name, parent, timeControl) //,_parentGroup(parent) { } TrackGroupController::~TrackGroupController() { destroyView(); } void TrackGroupController::generateView() { if(getView()) return; auto p = dynamic_cast<TrackGroupController*>(parent()); if(p && p->getView()) { setView(p->getView()->addGroup(this)); } generateChildrenViews(this); } void TrackGroupController::destroyView() { if(getView() == nullptr) return; destroyChildrenViews(this); auto p = dynamic_cast<TrackGroupController*>(parent()); if(p && p->getView()) { if(! p->getView()->removeGroup(this )) { ofLogError("TrackGroupController::destroyView") << "Could not remove group correctly"; } setView(nullptr); } } bool TrackGroupController::removeTrack(TrackController* track) { return CollectionHelper::_remove<TrackController, TrackGroupController>( track, this, _tracksCollection); } bool TrackGroupController::removeGroup(TrackGroupController* group) { return CollectionHelper::_remove<TrackGroupController, TrackGroupController>( group,this, _groupsCollection); } TrackGroupController* TrackGroupController::add(ofxGuiGroup& guiGroup) { return add(guiGroup.getParameter().castGroup()); } TrackGroupController* TrackGroupController::add(ofParameterGroup& _parameters) { auto group = addGroup(_parameters.getName()); if(group->getId() != _parameters.getName()) { ofLogWarning("TracksPanelController::add") << "There is already another group named: \"" << _parameters.getName() << "\".\nRenamed to: \"" << group->getId() << "\"" ; _parameters.setName(group->getId()); } for(std::size_t i = 0; i < _parameters.size(); i++){ if(_parameters[i].isReadOnly()){ ofLogVerbose("TracksPanelController::add") << "Not adding parameter \""<< _parameters[i].getName() << "\" as it is read-only, which does not make much sense adding to the timeline"; continue; } string type = _parameters.getType(i); if(type == typeid(ofParameter <int32_t> ).name()) { auto p = _parameters.getInt(i);group->add(p);} else if(type == typeid(ofParameter <uint32_t> ).name()) { auto p = _parameters.get<uint32_t>(i);group->add(p);} else if(type == typeid(ofParameter <int64_t> ).name()) { auto p = _parameters.get<int64_t>(i);group->add(p);} else if(type == typeid(ofParameter <uint64_t> ).name()) { auto p = _parameters.get<uint64_t>(i);group->add(p);} else if(type == typeid(ofParameter <int8_t> ).name()) { auto p = _parameters.get<int8_t>(i);group->add(p);} else if(type == typeid(ofParameter <uint8_t> ).name()) { auto p = _parameters.get<uint8_t>(i);group->add(p);} else if(type == typeid(ofParameter <int16_t> ).name()) { auto p = _parameters.get<int16_t>(i);group->add(p);} else if(type == typeid(ofParameter <uint16_t> ).name()) { auto p = _parameters.get<uint16_t>(i);group->add(p);} else if(type == typeid(ofParameter <size_t> ).name()) { auto p = _parameters.get<size_t>(i);group->add(p);} else if(type == typeid(ofParameter <float> ).name()) { auto p = _parameters.getFloat(i);group->add(p);} else if(type == typeid(ofParameter <double> ).name()) { auto p = _parameters.get<double>(i);group->add(p);} else if(type == typeid(ofParameter <bool> ).name()) { auto p = _parameters.getBool(i);group->add(p);} else if(type == typeid(ofParameter <void> ).name()) { auto p = _parameters.getVoid(i);group->add(p);} // else if(type == typeid(ofParameter <ofVec2f> ).name()) { auto p = _parameters.get<ofVec2f>(i);group->add(p);} // else if(type == typeid(ofParameter <ofVec3f> ).name()) { auto p = _parameters.get<ofVec3f>(i);group->add(p);} // else if(type == typeid(ofParameter <ofVec4f> ).name()) { auto p = _parameters.get<ofVec4f>(i);group->add(p);} else if(type == typeid(ofParameter <glm::vec2> ).name()) { auto p = _parameters.get<glm::vec2>(i);group->add(p);} else if(type == typeid(ofParameter <glm::vec3> ).name()) { auto p = _parameters.get<glm::vec3>(i);group->add(p);} else if(type == typeid(ofParameter <glm::vec4> ).name()) { auto p = _parameters.get<glm::vec4>(i);group->add(p);} else if(type == typeid(ofParameter <ofColor> ).name()) { auto p = _parameters.getColor(i);group->add(p);} else if(type == typeid(ofParameter <ofShortColor> ).name()) { auto p = _parameters.getShortColor(i);group->add(p);} else if(type == typeid(ofParameter <ofFloatColor> ).name()) { auto p = _parameters.getFloatColor(i);group->add(p);} else if(_parameters[i].valueType() == typeid(string).name()){ ofLogVerbose("TracksPanelController::add") << "Not adding string parameter \""<< _parameters[i].getName() << "\" as it does not make much sense adding to the timeline"; } else if(type == typeid(ofParameterGroup).name()){ auto p = _parameters.getGroup(i); group->add(p); } else{ ofLogWarning("TracksPanelController::add") << "no control for parameter of type " << type; } } return group; } void TrackGroupController::fromJson(const ofJson& j) { // j["class"] = "TrackGroupController"; setId(j["name"]); if(j.count("_groupsCollection")){ auto g = j["_groupsCollection"]; if(_groupsCollection.checkJson(g)) { _makeFromJson(g); } } if(j.count("_tracksCollection")){ auto t = j["_tracksCollection"]; if(_tracksCollection.checkJson(t)) { _makeFromJson(t); } } } ofJson TrackGroupController::toJson() { ofJson j; j["class"] = "TrackGroupController"; j["name"] = getId(); // j["view"] = bool(getView()); j["_groupsCollection"] = _groupsCollection.toJson(); j["_tracksCollection"] = _tracksCollection.toJson(); return j; } void TrackGroupController::_makeFromJson(const ofJson& json) { for(auto j: json["elements"]) { if( j.count("class") > 0 && j.count("name") > 0){ auto clss = j["class"].get<std::string>(); auto name = j["name"].get<std::string>(); if(clss == "TrackGroupController") { TrackGroupController* g = getGroup(name); if(g){ g->fromJson(j); } else { addGroup(name); //} // _addGroup(name)->fromJson(j); } } else if(clss == "KeyframeTrackController_") { if(j.count("_dataTypeName")){ auto dataTypeName = j["_dataTypeName"].get<std::string>(); TrackController* t = getTrack(name); if(t) { if(dataTypeName == t->getDataTypeName()) { t->fromJson(j); } else { ofLogWarning("TrackGroupController::_makeFromJson") << "dataTypeNames differ " << dataTypeName << " != " << t->getDataTypeName(); } } else { _addTrack(name, dataTypeName)->fromJson(j); } } } else { ofLogWarning("TrackGroupController::_makeFromJson") << "unknown class: " << clss; } } else { ofLogWarning("TrackGroupController::_makeFromJson") << " malformed json. does not have name or class objects"; } } } //TrackGroupController * TrackGroupController:: _addGroup( const std::string& groupName) //{ // return addGroup<TrackGroupController>(groupName); //} TrackController* TrackGroupController:: _addTrack(const std::string& trackName, const std::string& paramType) { // if(typeid( ofRectangle).name() == paramType){ return addKeyframeTrack< ofRectangle> (trackName); } // else // if(typeid( ofColor_<char>).name() == paramType){ return addTrack< ofColor_<char>> (trackName); } // else if(typeid( ofColor_<unsigned char>).name() == paramType){ return addTrack< ofColor_<unsigned char>> (trackName); } // else if(typeid( ofColor_<short>).name() == paramType){ return addTrack< ofColor_<short>> (trackName); } // else if(typeid( ofColor_<unsigned short>).name() == paramType){ return addTrack< ofColor_<unsigned short>> (trackName); } // else if(typeid( ofColor_<int>).name() == paramType){ return addTrack< ofColor_<int>> (trackName); } // else if(typeid( ofColor_<unsigned int>).name() == paramType){ return addTrack< ofColor_<unsigned int>> (trackName); } // else if(typeid( ofColor_<long>).name() == paramType){ return addTrack< ofColor_<long>> (trackName); } // else if(typeid( ofColor_<unsigned long>).name() == paramType){ return addTrack< ofColor_<unsigned long>> (trackName); } // else if(typeid( ofColor_<float>).name() == paramType){ return addTrack< ofColor_<float>> (trackName); } // else if(typeid( ofColor_<double>).name() == paramType){ return addTrack< ofColor_<double>> (trackName); } if(typeid( ofColor).name() == paramType){ return addTrack< ofColor> (trackName); } else if(typeid( ofFloatColor).name() == paramType){ return addTrack< ofFloatColor> (trackName); } else if(typeid( ofShortColor).name() == paramType){ return addTrack< ofShortColor> (trackName); } else if(typeid( glm::vec2).name() == paramType){ return addTrack< glm::vec2> (trackName); } else if(typeid( glm::vec3).name() == paramType){ return addTrack< glm::vec3> (trackName); } else if(typeid( glm::vec4).name() == paramType){ return addTrack< glm::vec4> (trackName); } // else if(typeid( glm::quat).name() == paramType){ return addTrack< glm::quat> (trackName); } // else if(typeid( glm::mat4).name() == paramType){ return addTrack< glm::mat4> (trackName); } // else if(typeid( ofVec2f).name() == paramType){ return addTrack< ofVec2f> (trackName); } // else if(typeid( ofVec3f).name() == paramType){ return addTrack< ofVec3f> (trackName); } // else if(typeid( ofVec4f).name() == paramType){ return addTrack< ofVec4f> (trackName); } else if(typeid( bool).name() == paramType){ return addTrack< bool> (trackName); } else if(typeid( void).name() == paramType){ return addTrack< void> (trackName); } // else if(typeid( char).name() == paramType){ return addTrack< char> (trackName); } // else if(typeid( unsigned char).name() == paramType){ return addTrack< unsigned char> (trackName); } // else if(typeid( signed char).name() == paramType){ return addTrack< signed char> (trackName); } // else if(typeid( short).name() == paramType){ return addTrack< short> (trackName); } // else if(typeid( unsigned short).name() == paramType){ return addTrack< unsigned short> (trackName); } // else if(typeid( int).name() == paramType){ return addTrack< int> (trackName); } // else if(typeid( unsigned int).name() == paramType){ return addTrack< unsigned int> (trackName); } // else if(typeid( long).name() == paramType){ return addTrack< long> (trackName); } // else if(typeid( unsigned long).name() == paramType){ return addTrack< unsigned long> (trackName); } // else if(typeid( long long).name() == paramType){ return addTrack< long long> (trackName); } // else if(typeid( unsigned long long).name() == paramType){ return addTrack< unsigned long long> (trackName); } // else if(typeid( float).name() == paramType){ return addTrack< float> (trackName); } // else if(typeid( double).name() == paramType){ return addTrack< double> (trackName); } // else if(typeid( long double).name() == paramType){ return addTrack< long double> (trackName); } else if(typeid( int8_t).name() == paramType){ return addTrack< int8_t> (trackName); } else if(typeid( uint8_t).name() == paramType){ return addTrack< uint8_t> (trackName); } else if(typeid( int16_t).name() == paramType){ return addTrack< int16_t> (trackName); } else if(typeid( uint16_t).name() == paramType){ return addTrack< uint16_t> (trackName); } else if(typeid( int32_t).name() == paramType){ return addTrack< int32_t> (trackName); } else if(typeid( uint32_t).name() == paramType){ return addTrack< uint32_t> (trackName); } else if(typeid( int64_t).name() == paramType){ return addTrack< int64_t> (trackName); } else if(typeid( uint64_t).name() == paramType){ return addTrack< uint64_t> (trackName); } else if(typeid( float).name() == paramType){ return addTrack< float> (trackName); } else if(typeid( double).name() == paramType){ return addTrack< double> (trackName); } else if(typeid( size_t).name() == paramType){ return addTrack< size_t> (trackName); } // typename std::conditional<std::is_same<uint32_t, size_t>::value || std::is_same<uint64_t, size_t>::value, bool, size_t>::type>; return nullptr; } TrackGroupController * TrackGroupController::addGroup( const std::string& groupName ) { auto uniqueName = _groupsCollection.makeUniqueName(groupName, "Group"); return CollectionHelper:: _add< TrackGroupController, TrackGroupController, TrackGroupController > ( _groupsCollection, this, uniqueName, this, getTimeControl()); } bool TrackGroupController::removeGroup(const std::string& name) { return removeGroup(_groupsCollection.at(name)); } bool TrackGroupController::removeGroup(const size_t& index) { return removeGroup(_groupsCollection.at(index)); } TrackGroupController* TrackGroupController::getGroup(const std::string& name) { return _groupsCollection.at(name); } const TrackGroupController* TrackGroupController::getGroup(const std::string& name) const { return _groupsCollection.at(name); } TrackGroupController* TrackGroupController::getGroup(const size_t& index) { return _groupsCollection.at(index); } const TrackGroupController* TrackGroupController::getGroup(const size_t& index)const { return _groupsCollection.at(index); } const std::vector<TrackGroupController*>& TrackGroupController::getGroups() { return _groupsCollection.getCollection(); } const std::vector<const TrackGroupController*>& TrackGroupController::getGroups() const { return _groupsCollection.getCollection(); } size_t TrackGroupController::getNumGroups() const { return _groupsCollection.size(); } bool TrackGroupController::removeTrack(const std::string& name) { return removeTrack(_tracksCollection.at(name)); } bool TrackGroupController::removeTrack(const size_t& index) { return removeTrack(_tracksCollection.at(index)); } TrackController* TrackGroupController::getTrack(const std::string& name) { return _tracksCollection.at(name); } const TrackController* TrackGroupController::getTrack(const std::string& name) const { return _tracksCollection.at(name); } TrackController* TrackGroupController::getTrack(const size_t& index) { return _tracksCollection.at(index); } const TrackController* TrackGroupController::getTrack(const size_t& index)const { return _tracksCollection.at(index); } const std::vector<TrackController*>& TrackGroupController::getTracks() { return _tracksCollection.getCollection(); } const std::vector<const TrackController*>& TrackGroupController::getTracks() const { return _tracksCollection.getCollection(); } size_t TrackGroupController::getNumTracks() const { return _tracksCollection.size(); } } } // ofx::LineaDeTiempo
40.700495
184
0.631819
[ "vector" ]
3f44df5a32a83bdcca65a5611223eeca37282640
138
cpp
C++
Transform.cpp
OragonEfreet/he_qt_basic_view
c35c8ded7e01f7745ed3af6d27d75f6f5538bb7e
[ "Apache-2.0" ]
null
null
null
Transform.cpp
OragonEfreet/he_qt_basic_view
c35c8ded7e01f7745ed3af6d27d75f6f5538bb7e
[ "Apache-2.0" ]
1
2022-03-24T10:23:40.000Z
2022-03-24T10:23:40.000Z
Transform.cpp
OragonEfreet/he_qt_basic_view
c35c8ded7e01f7745ed3af6d27d75f6f5538bb7e
[ "Apache-2.0" ]
1
2022-01-21T08:17:39.000Z
2022-01-21T08:17:39.000Z
#include "Transform.h" Qt3DCore::QTransform *createTransform( EntityArray const &path ) { Q_UNUSED(path) return nullptr; }
19.714286
67
0.688406
[ "transform" ]
3f4c7177b72dcd4ffa692368604a380dd6adab3c
11,482
hpp
C++
mjolnir/forcefield/global/ExcludedVolumePotential.hpp
ToruNiina/Mjolnir
44435dd3afc12f5c8ea27a66d7ab282df3e588ff
[ "MIT" ]
12
2017-02-01T08:28:38.000Z
2018-08-25T15:47:51.000Z
mjolnir/forcefield/global/ExcludedVolumePotential.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
60
2019-01-14T08:11:33.000Z
2021-07-29T08:26:36.000Z
mjolnir/forcefield/global/ExcludedVolumePotential.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
8
2019-01-13T11:03:31.000Z
2021-08-01T11:38:00.000Z
#ifndef MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP #include <mjolnir/forcefield/global/ParameterList.hpp> #include <mjolnir/core/ExclusionList.hpp> #include <mjolnir/core/System.hpp> #include <mjolnir/math/math.hpp> #include <algorithm> #include <numeric> #include <memory> #include <cmath> namespace mjolnir { // excluded volume potential. // This class contains radii of the particles and calculates energy and // derivative of the potential function. // This class is an implementation of the excluded volume term used in // Clementi's off-lattice Go-like model (Clement et al., 2000) and AICG2+ model // (Li et al., 2014) // // Note: When ExcludedVolume is used with GlobalPairInteraction, `calc_force` // and `calc_energy` implemented here will not be used because we can // optimize the runtime efficiency by specializing GlobalPairInteraction. // See mjolnir/forcefield/GlobalExcludedVolumeInteraction.hpp for detail. template<typename realT> class ExcludedVolumePotential { public: using real_type = realT; struct parameter_type { real_type radius; }; static constexpr real_type default_cutoff() noexcept { return real_type(2.0); } public: ExcludedVolumePotential( const real_type cutoff, const real_type epsilon) noexcept : epsilon_(epsilon), cutoff_ratio_(cutoff), coef_at_cutoff_(std::pow(real_type(1) / cutoff, 12)) {} ~ExcludedVolumePotential() = default; ExcludedVolumePotential(const ExcludedVolumePotential&) = default; ExcludedVolumePotential(ExcludedVolumePotential&&) = default; ExcludedVolumePotential& operator=(const ExcludedVolumePotential&) = default; ExcludedVolumePotential& operator=(ExcludedVolumePotential&&) = default; real_type potential(const real_type r, const parameter_type& params) const noexcept { if(params.radius * this->cutoff_ratio_ < r){return 0;} const real_type d_r = params.radius / r; const real_type dr3 = d_r * d_r * d_r; const real_type dr6 = dr3 * dr3; return this->epsilon_ * (dr6 * dr6 - this->coef_at_cutoff_); } real_type derivative(const real_type r, const parameter_type& params) const noexcept { if(params.radius * this->cutoff_ratio_ < r){return 0;} const real_type rinv = real_type(1) / r; const real_type d_r = params.radius * rinv; const real_type dr3 = d_r * d_r * d_r; const real_type dr6 = dr3 * dr3; return real_type(-12.0) * this->epsilon_ * dr6 * dr6 * rinv; } template<typename T> void initialize(const System<T>&) noexcept {return;} template<typename T> void update(const System<T>&) noexcept {return;} // ------------------------------------------------------------------------ // It takes per-particle parameters and return the maximum cutoff length. // CombinationRule normally uses this. // Note that, pair-parameter and per-particle parameter can differ from // each other. Lorentz-Bertherot uses the same parameter_type because it is // for L-J and L-J-like potentials that has {sigma, epsilon} for each // particle and also for each pair of particles. template<typename InputIterator> real_type max_cutoff(const InputIterator first, const InputIterator last) const noexcept { static_assert(std::is_same< typename std::iterator_traits<InputIterator>::value_type, parameter_type>::value, ""); if(first == last) {return 1;} real_type max_radius = 0; for(auto iter = first; iter != last; ++iter) { const auto& parameter = *iter; max_radius = std::max(max_radius, parameter.radius); } return max_radius * 2 * cutoff_ratio_; } // It returns absolute cutoff length using pair-parameter. // `CombinationTable` uses this. real_type absolute_cutoff(const parameter_type& params) const noexcept { return params.radius * cutoff_ratio_; } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "ExcludedVolume";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. real_type& epsilon() noexcept {return this->epsilon_;} real_type epsilon() const noexcept {return this->epsilon_;} real_type cutoff_ratio() const noexcept {return cutoff_ratio_;} real_type coef_at_cutoff() const noexcept {return coef_at_cutoff_;} private: real_type epsilon_; real_type cutoff_ratio_; real_type coef_at_cutoff_; }; // Normally, this potential use the same epsilon value for all the pairs. // Moreover, this potential takes a "radius", not a "diameter", as a paraemter. // So we don't divide sigma_i + sigma_j by two. Since they are radii, just take // the sum of them. template<typename traitsT> class ExcludedVolumeParameterList final : public ParameterListBase<traitsT, ExcludedVolumePotential<typename traitsT::real_type>> { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using potential_type = ExcludedVolumePotential<real_type>; using base_type = ParameterListBase<traits_type, potential_type>; // `pair_parameter_type` is a parameter for an interacting pair. // Although it is the same type as `parameter_type` in this potential, // it can be different from normal parameter for each particle. // This enables NeighborList to cache a value to calculate forces between // the particles, e.g. by having qi * qj for pair of particles i and j. using parameter_type = typename potential_type::parameter_type; using pair_parameter_type = typename potential_type::parameter_type; using container_type = std::vector<parameter_type>; // topology stuff using system_type = System<traits_type>; using topology_type = Topology; using molecule_id_type = typename topology_type::molecule_id_type; using group_id_type = typename topology_type::group_id_type; using connection_kind_type = typename topology_type::connection_kind_type; using ignore_molecule_type = IgnoreMolecule<molecule_id_type>; using ignore_group_type = IgnoreGroup <group_id_type>; using exclusion_list_type = ExclusionList<traits_type>; public: ExcludedVolumeParameterList( const std::vector<std::pair<std::size_t, parameter_type>>& parameters, const std::map<connection_kind_type, std::size_t>& exclusions, ignore_molecule_type ignore_mol, ignore_group_type ignore_grp) : exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp)) { this->parameters_ .reserve(parameters.size()); this->participants_.reserve(parameters.size()); for(const auto& idxp : parameters) { const auto idx = idxp.first; this->participants_.push_back(idx); if(idx >= this->parameters_.size()) { this->parameters_.resize(idx+1, parameter_type{real_type(0)}); } this->parameters_.at(idx) = idxp.second; } } ~ExcludedVolumeParameterList() = default; pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept override { return pair_parameter_type{parameters_[i].radius + parameters_[j].radius}; } real_type max_cutoff_length() const noexcept override { return this->max_cutoff_length_; } void initialize(const system_type& sys, const topology_type& topol, const potential_type& pot) noexcept override { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); this->update(sys, topol, pot); // calc parameters return; } // for temperature/ionic concentration changes... void update(const system_type& sys, const topology_type& topol, const potential_type& pot) noexcept override { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); this->max_cutoff_length_ = pot.max_cutoff(parameters_.begin(), parameters_.end()); this->exclusion_list_.make(sys, topol); return; } // ----------------------------------------------------------------------- // for spatial partitions // // Here, the default implementation uses Newton's 3rd law to reduce // calculation. For an interacting pair (i, j), forces applied to i and j // are equal in magnitude and opposite in direction. So, if a pair (i, j) is // listed, (j, i) is not needed. // See implementation of VerletList, CellList and GlobalPairInteraction // for more details about the usage of these functions. std::vector<std::size_t> const& participants() const noexcept override { return participants_; } range<typename std::vector<std::size_t>::const_iterator> leading_participants() const noexcept override { return make_range(participants_.begin(), std::prev(participants_.end())); } range<typename std::vector<std::size_t>::const_iterator> possible_partners_of(const std::size_t participant_idx, const std::size_t /*particle_idx*/) const noexcept override { return make_range(participants_.begin() + participant_idx + 1, participants_.end()); } bool has_interaction(const std::size_t i, const std::size_t j) const noexcept override { return (i < j) && !exclusion_list_.is_excluded(i, j); } exclusion_list_type const& exclusion_list() const noexcept override { return exclusion_list_; // for testing } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "ExcludedVolume";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. // access to the parameters. std::vector<parameter_type>& parameters() noexcept {return parameters_;} std::vector<parameter_type> const& parameters() const noexcept {return parameters_;} base_type* clone() const override { return new ExcludedVolumeParameterList(*this); } private: real_type max_cutoff_length_; container_type parameters_; std::vector<std::size_t> participants_; exclusion_list_type exclusion_list_; }; } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> namespace mjolnir { extern template class ExcludedVolumeParameterList<SimulatorTraits<double, UnlimitedBoundary> >; extern template class ExcludedVolumeParameterList<SimulatorTraits<float, UnlimitedBoundary> >; extern template class ExcludedVolumeParameterList<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class ExcludedVolumeParameterList<SimulatorTraits<float, CuboidalPeriodicBoundary>>; } // mjolnir #endif// MJOLNIR_SEPARATE_BUILD #endif /* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL */
38.401338
101
0.663038
[ "vector", "model" ]
3f503ab8d5a32dde2dd5ee7d895f776d3695fd7d
19,632
cpp
C++
Source/WebCore/bindings/scripts/test/JS/JSTestIndexedSetterWithIdentifier.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestIndexedSetterWithIdentifier.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestIndexedSetterWithIdentifier.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "JSTestIndexedSetterWithIdentifier.h" #include "ActiveDOMObject.h" #include "DOMIsoSubspaces.h" #include "JSDOMBinding.h" #include "JSDOMConstructorNotConstructable.h" #include "JSDOMConvertNumbers.h" #include "JSDOMConvertStrings.h" #include "JSDOMExceptionHandling.h" #include "JSDOMOperation.h" #include "JSDOMWrapperCache.h" #include "ScriptExecutionContext.h" #include "WebCoreJSClientData.h" #include <JavaScriptCore/FunctionPrototype.h> #include <JavaScriptCore/HeapAnalyzer.h> #include <JavaScriptCore/JSCInlines.h> #include <JavaScriptCore/JSDestructibleObjectHeapCellType.h> #include <JavaScriptCore/PropertyNameArray.h> #include <JavaScriptCore/SubspaceInlines.h> #include <wtf/GetPtr.h> #include <wtf/PointerPreparations.h> #include <wtf/URL.h> namespace WebCore { using namespace JSC; // Functions JSC::EncodedJSValue JSC_HOST_CALL jsTestIndexedSetterWithIdentifierPrototypeFunctionIndexedSetter(JSC::JSGlobalObject*, JSC::CallFrame*); // Attributes JSC::EncodedJSValue jsTestIndexedSetterWithIdentifierConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::PropertyName); bool setJSTestIndexedSetterWithIdentifierConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::EncodedJSValue); class JSTestIndexedSetterWithIdentifierPrototype final : public JSC::JSNonFinalObject { public: using Base = JSC::JSNonFinalObject; static JSTestIndexedSetterWithIdentifierPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) { JSTestIndexedSetterWithIdentifierPrototype* ptr = new (NotNull, JSC::allocateCell<JSTestIndexedSetterWithIdentifierPrototype>(vm.heap)) JSTestIndexedSetterWithIdentifierPrototype(vm, globalObject, structure); ptr->finishCreation(vm); return ptr; } DECLARE_INFO; template<typename CellType, JSC::SubspaceAccess> static JSC::IsoSubspace* subspaceFor(JSC::VM& vm) { STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestIndexedSetterWithIdentifierPrototype, Base); return &vm.plainObjectSpace; } static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } private: JSTestIndexedSetterWithIdentifierPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) { } void finishCreation(JSC::VM&); }; STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestIndexedSetterWithIdentifierPrototype, JSTestIndexedSetterWithIdentifierPrototype::Base); using JSTestIndexedSetterWithIdentifierConstructor = JSDOMConstructorNotConstructable<JSTestIndexedSetterWithIdentifier>; template<> JSValue JSTestIndexedSetterWithIdentifierConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) { UNUSED_PARAM(vm); return globalObject.functionPrototype(); } template<> void JSTestIndexedSetterWithIdentifierConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) { putDirect(vm, vm.propertyNames->prototype, JSTestIndexedSetterWithIdentifier::prototype(vm, globalObject), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->name, jsNontrivialString(vm, "TestIndexedSetterWithIdentifier"_s), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->length, jsNumber(0), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); } template<> const ClassInfo JSTestIndexedSetterWithIdentifierConstructor::s_info = { "TestIndexedSetterWithIdentifier", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestIndexedSetterWithIdentifierConstructor) }; /* Hash table for prototype */ static const HashTableValue JSTestIndexedSetterWithIdentifierPrototypeTableValues[] = { { "constructor", static_cast<unsigned>(JSC::PropertyAttribute::DontEnum), NoIntrinsic, { (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestIndexedSetterWithIdentifierConstructor), (intptr_t) static_cast<PutPropertySlot::PutValueFunc>(setJSTestIndexedSetterWithIdentifierConstructor) } }, { "indexedSetter", static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { (intptr_t)static_cast<RawNativeFunction>(jsTestIndexedSetterWithIdentifierPrototypeFunctionIndexedSetter), (intptr_t) (2) } }, }; const ClassInfo JSTestIndexedSetterWithIdentifierPrototype::s_info = { "TestIndexedSetterWithIdentifier", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestIndexedSetterWithIdentifierPrototype) }; void JSTestIndexedSetterWithIdentifierPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); reifyStaticProperties(vm, JSTestIndexedSetterWithIdentifier::info(), JSTestIndexedSetterWithIdentifierPrototypeTableValues, *this); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); } const ClassInfo JSTestIndexedSetterWithIdentifier::s_info = { "TestIndexedSetterWithIdentifier", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestIndexedSetterWithIdentifier) }; JSTestIndexedSetterWithIdentifier::JSTestIndexedSetterWithIdentifier(Structure* structure, JSDOMGlobalObject& globalObject, Ref<TestIndexedSetterWithIdentifier>&& impl) : JSDOMWrapper<TestIndexedSetterWithIdentifier>(structure, globalObject, WTFMove(impl)) { } void JSTestIndexedSetterWithIdentifier::finishCreation(VM& vm) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); static_assert(!std::is_base_of<ActiveDOMObject, TestIndexedSetterWithIdentifier>::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject."); } JSObject* JSTestIndexedSetterWithIdentifier::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) { return JSTestIndexedSetterWithIdentifierPrototype::create(vm, &globalObject, JSTestIndexedSetterWithIdentifierPrototype::createStructure(vm, &globalObject, globalObject.objectPrototype())); } JSObject* JSTestIndexedSetterWithIdentifier::prototype(VM& vm, JSDOMGlobalObject& globalObject) { return getDOMPrototype<JSTestIndexedSetterWithIdentifier>(vm, globalObject); } JSValue JSTestIndexedSetterWithIdentifier::getConstructor(VM& vm, const JSGlobalObject* globalObject) { return getDOMConstructor<JSTestIndexedSetterWithIdentifierConstructor>(vm, *jsCast<const JSDOMGlobalObject*>(globalObject)); } void JSTestIndexedSetterWithIdentifier::destroy(JSC::JSCell* cell) { JSTestIndexedSetterWithIdentifier* thisObject = static_cast<JSTestIndexedSetterWithIdentifier*>(cell); thisObject->JSTestIndexedSetterWithIdentifier::~JSTestIndexedSetterWithIdentifier(); } bool JSTestIndexedSetterWithIdentifier::getOwnPropertySlot(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyName propertyName, PropertySlot& slot) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (auto index = parseIndex(propertyName)) { if (index.value() < thisObject->wrapped().length()) { auto value = toJS<IDLDOMString>(*lexicalGlobalObject, thisObject->wrapped().item(index.value())); slot.setValue(thisObject, static_cast<unsigned>(0), value); return true; } } return JSObject::getOwnPropertySlot(object, lexicalGlobalObject, propertyName, slot); } bool JSTestIndexedSetterWithIdentifier::getOwnPropertySlotByIndex(JSObject* object, JSGlobalObject* lexicalGlobalObject, unsigned index, PropertySlot& slot) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (LIKELY(index <= MAX_ARRAY_INDEX)) { if (index < thisObject->wrapped().length()) { auto value = toJS<IDLDOMString>(*lexicalGlobalObject, thisObject->wrapped().item(index)); slot.setValue(thisObject, static_cast<unsigned>(0), value); return true; } } return JSObject::getOwnPropertySlotByIndex(object, lexicalGlobalObject, index, slot); } void JSTestIndexedSetterWithIdentifier::getOwnPropertyNames(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyNameArray& propertyNames, EnumerationMode mode) { VM& vm = JSC::getVM(lexicalGlobalObject); auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(object); ASSERT_GC_OBJECT_INHERITS(object, info()); for (unsigned i = 0, count = thisObject->wrapped().length(); i < count; ++i) propertyNames.add(Identifier::from(vm, i)); JSObject::getOwnPropertyNames(object, lexicalGlobalObject, propertyNames, mode); } bool JSTestIndexedSetterWithIdentifier::put(JSCell* cell, JSGlobalObject* lexicalGlobalObject, PropertyName propertyName, JSValue value, PutPropertySlot& putPropertySlot) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (auto index = parseIndex(propertyName)) { auto throwScope = DECLARE_THROW_SCOPE(JSC::getVM(lexicalGlobalObject)); auto nativeValue = convert<IDLDOMString>(*lexicalGlobalObject, value); RETURN_IF_EXCEPTION(throwScope, true); thisObject->wrapped().indexedSetter(index.value(), WTFMove(nativeValue)); return true; } return JSObject::put(thisObject, lexicalGlobalObject, propertyName, value, putPropertySlot); } bool JSTestIndexedSetterWithIdentifier::putByIndex(JSCell* cell, JSGlobalObject* lexicalGlobalObject, unsigned index, JSValue value, bool shouldThrow) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (LIKELY(index <= MAX_ARRAY_INDEX)) { auto throwScope = DECLARE_THROW_SCOPE(JSC::getVM(lexicalGlobalObject)); auto nativeValue = convert<IDLDOMString>(*lexicalGlobalObject, value); RETURN_IF_EXCEPTION(throwScope, true); thisObject->wrapped().indexedSetter(index, WTFMove(nativeValue)); return true; } return JSObject::putByIndex(cell, lexicalGlobalObject, index, value, shouldThrow); } bool JSTestIndexedSetterWithIdentifier::defineOwnProperty(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyName propertyName, const PropertyDescriptor& propertyDescriptor, bool shouldThrow) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (auto index = parseIndex(propertyName)) { if (!propertyDescriptor.isDataDescriptor()) return false; auto throwScope = DECLARE_THROW_SCOPE(JSC::getVM(lexicalGlobalObject)); auto nativeValue = convert<IDLDOMString>(*lexicalGlobalObject, propertyDescriptor.value()); RETURN_IF_EXCEPTION(throwScope, true); thisObject->wrapped().indexedSetter(index.value(), WTFMove(nativeValue)); return true; } PropertyDescriptor newPropertyDescriptor = propertyDescriptor; newPropertyDescriptor.setConfigurable(true); return JSObject::defineOwnProperty(object, lexicalGlobalObject, propertyName, newPropertyDescriptor, shouldThrow); } template<> inline JSTestIndexedSetterWithIdentifier* IDLOperation<JSTestIndexedSetterWithIdentifier>::cast(JSGlobalObject& lexicalGlobalObject, CallFrame& callFrame) { return jsDynamicCast<JSTestIndexedSetterWithIdentifier*>(JSC::getVM(&lexicalGlobalObject), callFrame.thisValue()); } EncodedJSValue jsTestIndexedSetterWithIdentifierConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, PropertyName) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestIndexedSetterWithIdentifierPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) return throwVMTypeError(lexicalGlobalObject, throwScope); return JSValue::encode(JSTestIndexedSetterWithIdentifier::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); } bool setJSTestIndexedSetterWithIdentifierConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestIndexedSetterWithIdentifierPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) { throwVMTypeError(lexicalGlobalObject, throwScope); return false; } // Shadowing a built-in constructor return prototype->putDirect(vm, vm.propertyNames->constructor, JSValue::decode(encodedValue)); } static inline JSC::EncodedJSValue jsTestIndexedSetterWithIdentifierPrototypeFunctionIndexedSetterBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation<JSTestIndexedSetterWithIdentifier>::ClassParameter castedThis) { auto& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); UNUSED_PARAM(throwScope); UNUSED_PARAM(callFrame); auto& impl = castedThis->wrapped(); if (UNLIKELY(callFrame->argumentCount() < 2)) return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); auto index = convert<IDLUnsignedLong>(*lexicalGlobalObject, argument0.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); EnsureStillAliveScope argument1 = callFrame->uncheckedArgument(1); auto value = convert<IDLDOMString>(*lexicalGlobalObject, argument1.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); throwScope.release(); impl.indexedSetter(WTFMove(index), WTFMove(value)); return JSValue::encode(jsUndefined()); } EncodedJSValue JSC_HOST_CALL jsTestIndexedSetterWithIdentifierPrototypeFunctionIndexedSetter(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) { return IDLOperation<JSTestIndexedSetterWithIdentifier>::call<jsTestIndexedSetterWithIdentifierPrototypeFunctionIndexedSetterBody>(*lexicalGlobalObject, *callFrame, "indexedSetter"); } JSC::IsoSubspace* JSTestIndexedSetterWithIdentifier::subspaceForImpl(JSC::VM& vm) { auto& clientData = *static_cast<JSVMClientData*>(vm.clientData); auto& spaces = clientData.subspaces(); if (auto* space = spaces.m_subspaceForTestIndexedSetterWithIdentifier.get()) return space; static_assert(std::is_base_of_v<JSC::JSDestructibleObject, JSTestIndexedSetterWithIdentifier> || !JSTestIndexedSetterWithIdentifier::needsDestruction); if constexpr (std::is_base_of_v<JSC::JSDestructibleObject, JSTestIndexedSetterWithIdentifier>) spaces.m_subspaceForTestIndexedSetterWithIdentifier = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.destructibleObjectHeapCellType.get(), JSTestIndexedSetterWithIdentifier); else spaces.m_subspaceForTestIndexedSetterWithIdentifier = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.cellHeapCellType.get(), JSTestIndexedSetterWithIdentifier); auto* space = spaces.m_subspaceForTestIndexedSetterWithIdentifier.get(); IGNORE_WARNINGS_BEGIN("unreachable-code") IGNORE_WARNINGS_BEGIN("tautological-compare") if (&JSTestIndexedSetterWithIdentifier::visitOutputConstraints != &JSC::JSCell::visitOutputConstraints) clientData.outputConstraintSpaces().append(space); IGNORE_WARNINGS_END IGNORE_WARNINGS_END return space; } void JSTestIndexedSetterWithIdentifier::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) { auto* thisObject = jsCast<JSTestIndexedSetterWithIdentifier*>(cell); analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); if (thisObject->scriptExecutionContext()) analyzer.setLabelForCell(cell, "url " + thisObject->scriptExecutionContext()->url().string()); Base::analyzeHeap(cell, analyzer); } bool JSTestIndexedSetterWithIdentifierOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor, const char** reason) { UNUSED_PARAM(handle); UNUSED_PARAM(visitor); UNUSED_PARAM(reason); return false; } void JSTestIndexedSetterWithIdentifierOwner::finalize(JSC::Handle<JSC::Unknown> handle, void* context) { auto* jsTestIndexedSetterWithIdentifier = static_cast<JSTestIndexedSetterWithIdentifier*>(handle.slot()->asCell()); auto& world = *static_cast<DOMWrapperWorld*>(context); uncacheWrapper(world, &jsTestIndexedSetterWithIdentifier->wrapped(), jsTestIndexedSetterWithIdentifier); } #if ENABLE(BINDING_INTEGRITY) #if PLATFORM(WIN) #pragma warning(disable: 4483) extern "C" { extern void (*const __identifier("??_7TestIndexedSetterWithIdentifier@WebCore@@6B@")[])(); } #else extern "C" { extern void* _ZTVN7WebCore31TestIndexedSetterWithIdentifierE[]; } #endif #endif JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref<TestIndexedSetterWithIdentifier>&& impl) { #if ENABLE(BINDING_INTEGRITY) const void* actualVTablePointer = getVTablePointer(impl.ptr()); #if PLATFORM(WIN) void* expectedVTablePointer = __identifier("??_7TestIndexedSetterWithIdentifier@WebCore@@6B@"); #else void* expectedVTablePointer = &_ZTVN7WebCore31TestIndexedSetterWithIdentifierE[2]; #endif // If this fails TestIndexedSetterWithIdentifier does not have a vtable, so you need to add the // ImplementationLacksVTable attribute to the interface definition static_assert(std::is_polymorphic<TestIndexedSetterWithIdentifier>::value, "TestIndexedSetterWithIdentifier is not polymorphic"); // If you hit this assertion you either have a use after free bug, or // TestIndexedSetterWithIdentifier has subclasses. If TestIndexedSetterWithIdentifier has subclasses that get passed // to toJS() we currently require TestIndexedSetterWithIdentifier you to opt out of binding hardening // by adding the SkipVTableValidation attribute to the interface IDL definition RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); #endif return createWrapper<TestIndexedSetterWithIdentifier>(globalObject, WTFMove(impl)); } JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, TestIndexedSetterWithIdentifier& impl) { return wrap(lexicalGlobalObject, globalObject, impl); } TestIndexedSetterWithIdentifier* JSTestIndexedSetterWithIdentifier::toWrapped(JSC::VM& vm, JSC::JSValue value) { if (auto* wrapper = jsDynamicCast<JSTestIndexedSetterWithIdentifier*>(vm, value)) return &wrapper->wrapped(); return nullptr; } }
49.701266
297
0.787133
[ "object" ]
3f635062744cd4f6d8572b4ff6b1ba80f4eff738
6,424
cpp
C++
test/test-MorphingMesh.cpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
2
2019-05-14T08:14:15.000Z
2021-01-19T13:28:38.000Z
test/test-MorphingMesh.cpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
null
null
null
test/test-MorphingMesh.cpp
vadosnaprimer/desktop-m3g
fa04787e8609cd0f4e63defc7f2c669c8cc78d1f
[ "MIT" ]
null
null
null
#include <unittest++/UnitTest++.h> #include <iostream> #include "m3g/MorphingMesh.hpp" #include "m3g/VertexArray.hpp" #include "m3g/VertexBuffer.hpp" #include "m3g/TriangleStripArray.hpp" #include "m3g/Appearance.hpp" #include "m3g/Group.hpp" using namespace std; using namespace m3g; TEST (MorphingMesh_default_value) { VertexArray* varry = new VertexArray (16, 3, 2); int indices[] = {0,1,2}; int strips[] = {3}; TriangleStripArray* tris = new TriangleStripArray (3, indices, 1, strips); Appearance* app = new Appearance; float scale = 1; float bias[] = {0,0,0}; VertexBuffer* base_vertices = new VertexBuffer; base_vertices->setPositions (varry, scale, bias); VertexBuffer* target_vertices[2] = {base_vertices->duplicate (), base_vertices->duplicate ()}; MorphingMesh* mesh = new MorphingMesh (base_vertices, 2, target_vertices, tris, app); CHECK_EQUAL (2, mesh->getMorphTargetCount()); delete base_vertices; delete target_vertices[0]; delete target_vertices[1]; delete tris; delete app; delete mesh; } TEST (MorphingMesh_set_variable) { VertexArray* varry = new VertexArray (16, 3, 2); int indices[] = {0,1,2}; int strips[] = {3}; TriangleStripArray* tris = new TriangleStripArray (3, indices, 1, strips); Appearance* app = new Appearance; float scale = 1; float bias[] = {0,0,0}; VertexBuffer* base_vertices = new VertexBuffer; base_vertices->setPositions (varry, scale, bias); VertexBuffer* target_vertices[2] = {base_vertices->duplicate (), base_vertices->duplicate ()}; MorphingMesh* mesh = new MorphingMesh (base_vertices, 2, target_vertices, tris, app); float weights[3] = {1,2,998}; mesh->setWeights(2, weights); float values[3] = {999,999,999}; mesh->getWeights(values); CHECK_EQUAL (1.f, values[0]); CHECK_EQUAL (2.f, values[1]); CHECK_EQUAL (999.f, values[2]); CHECK_EQUAL (2 , mesh->getMorphTargetCount()); CHECK_EQUAL (target_vertices[0], mesh->getMorphTarget(0)); CHECK_EQUAL (target_vertices[1], mesh->getMorphTarget(1)); delete base_vertices; delete target_vertices[0]; delete target_vertices[1]; delete tris; delete app; delete mesh; } TEST (MorphingMesh_duplicate) { VertexArray* varry = new VertexArray (16, 3, 2); int indices[] = {0,1,2}; int strips[] = {3}; TriangleStripArray* tris = new TriangleStripArray (3, indices, 1, strips); Appearance* app = new Appearance; float scale = 1; float bias[] = {0,0,0}; VertexBuffer* base_vertices = new VertexBuffer; base_vertices->setPositions (varry, scale, bias); VertexBuffer* target_vertices[2] = {base_vertices->duplicate (), base_vertices->duplicate ()}; MorphingMesh* mesh1 = new MorphingMesh (base_vertices, 2, target_vertices, tris, app); float weights[2] = {1,2}; mesh1->setWeights(2, weights); MorphingMesh* mesh2 = mesh1->duplicate(); float values[3] = {999,999}; mesh2->getWeights(values); CHECK_EQUAL (1.f, values[0]); CHECK_EQUAL (2.f, values[1]); CHECK_EQUAL (2 , mesh2->getMorphTargetCount()); CHECK_EQUAL (target_vertices[0], mesh2->getMorphTarget(0)); CHECK_EQUAL (target_vertices[1], mesh2->getMorphTarget(1)); delete base_vertices; delete target_vertices[0]; delete target_vertices[1]; delete tris; delete app; delete mesh1; delete mesh2; } TEST (MorphingMesh_getReferences) { VertexArray* varry = new VertexArray (16, 3, 2); int indices[] = {0,1,2}; int strips[] = {3}; TriangleStripArray* tris = new TriangleStripArray (3, indices, 1, strips); Appearance* app = new Appearance; float scale = 1; float bias[] = {0,0,0}; VertexBuffer* base_vertices = new VertexBuffer; base_vertices->setPositions (varry, scale, bias); VertexBuffer* target_vertices[2] = {base_vertices->duplicate (), base_vertices->duplicate ()}; MorphingMesh* mesh = new MorphingMesh (base_vertices, 2, target_vertices, tris, app); int n; Object3D* objs[5]; n = mesh->getReferences (objs); CHECK_EQUAL (5, n); CHECK_EQUAL (base_vertices , objs[0]); CHECK_EQUAL (tris , objs[1]); CHECK_EQUAL (app , objs[2]); CHECK_EQUAL (target_vertices[0], objs[3]); CHECK_EQUAL (target_vertices[1], objs[4]); delete varry; delete base_vertices; delete target_vertices[0]; delete target_vertices[1]; delete tris; delete app; delete mesh; } TEST (MorphingMesh_find) { VertexArray* varry = new VertexArray (16, 3, 2); int indices[] = {0,1,2}; int strips[] = {3}; TriangleStripArray* tris = new TriangleStripArray (3, indices, 1, strips); Appearance* app = new Appearance; float scale = 1; float bias[] = {0,0,0}; VertexBuffer* base_vertices = new VertexBuffer; base_vertices->setPositions (varry, scale, bias); VertexBuffer* target_vertices[2] = {base_vertices->duplicate (), base_vertices->duplicate ()}; MorphingMesh* mesh = new MorphingMesh (base_vertices, 2, target_vertices, tris, app); varry->setUserID (100); tris->setUserID (101); app->setUserID (102); base_vertices->setUserID (103); target_vertices[0]->setUserID (104); target_vertices[1]->setUserID (105); mesh->setUserID (106); CHECK_EQUAL (varry , mesh->find(100)); CHECK_EQUAL (tris , mesh->find(101)); CHECK_EQUAL (app , mesh->find(102)); CHECK_EQUAL (base_vertices , mesh->find(103)); CHECK_EQUAL (target_vertices[0], mesh->find(104)); CHECK_EQUAL (target_vertices[1], mesh->find(105)); CHECK_EQUAL (mesh , mesh->find(106)); delete varry; delete base_vertices; delete target_vertices[0]; delete target_vertices[1]; delete tris; delete app; delete mesh; }
31.80198
98
0.605075
[ "mesh" ]
3f6d21d6db30aa3204937fba3c58c5935e0d6a39
4,828
cpp
C++
src/main.cpp
edmBernard/rename-cpp
833e835ea60bc329beab9feffcfa6aa1090f2582
[ "Apache-2.0" ]
1
2021-02-06T15:54:34.000Z
2021-02-06T15:54:34.000Z
src/main.cpp
edmBernard/rename-cpp
833e835ea60bc329beab9feffcfa6aa1090f2582
[ "Apache-2.0" ]
null
null
null
src/main.cpp
edmBernard/rename-cpp
833e835ea60bc329beab9feffcfa6aa1090f2582
[ "Apache-2.0" ]
null
null
null
// Tool to rename files based on Regex #include <filesystem> #include <regex> #include <string> #include <vector> #include <cxxopts.hpp> #include <fmt/color.h> #include <fmt/core.h> #include <spdlog/cfg/env.h> #include <spdlog/spdlog.h> namespace fs = std::filesystem; int main(int argc, char **argv) { try { spdlog::cfg::load_env_levels(); // ================================================================================================= // CLI cxxopts::Options options(argv[0], "Tool to rename files based on Regex"); options.positional_help("regex format directory").show_positional_help(); // clang-format off options.add_options() ("h,help", "Print help") ("no-dry-run", "Actually apply the changes") ("d,directory", "The directory containing files to rename", cxxopts::value<std::string>(), "DIRECTORY") ("regex", "The regular expression that will be matched against the filename", cxxopts::value<std::string>()) ("format", "The regex replacement format string", cxxopts::value<std::string>()) ("v,verbose", "Print names of files successfully renamed") ("r,recursive", "Recursively rename file in subfolder, it don't rename folder") ("no-color", "Disable color in verbose mode") ; // clang-format on options.parse_positional({"regex", "format", "directory"}); auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help() << std::endl; return 0; } if (!result.count("directory")) { spdlog::error("Directory argument required"); return 1; } fs::path directory(result["directory"].as<std::string>()); if (!fs::exists(directory)) { spdlog::error("Specified directory does not exist"); return 1; } if (!fs::is_directory(directory)) { spdlog::error("Specified directory is not a directory"); return 1; } if (!result.count("regex")) { spdlog::error("Missing input regex"); return 1; } if (!result.count("format")) { spdlog::error("Missing format regex, if you tried to pass empty string use --format=\"\" instead."); return 1; } spdlog::debug("CommandLine Argument passed: "); spdlog::debug(" directory : {}", result["directory"].as<std::string>()); spdlog::debug(" regex : {}", result["regex"].as<std::string>()); spdlog::debug(" format : {}", result["format"].as<std::string>()); spdlog::debug(" recursive : {}", result["recursive"].count()); spdlog::debug(" no-dry-run : {}", result["no-dry-run"].count()); spdlog::debug(" no-color : {}", result["no-color"].count()); const std::regex rule(result["regex"].as<std::string>()); const std::string format(result["format"].as<std::string>()); bool noRenamingDone = true; // we store filename before changing them to avoid multiple change on the same file std::vector<fs::path> filelist; if (result.count("recursive")) { for (auto& p : fs::recursive_directory_iterator(directory)) { filelist.push_back(p); } } else { for (auto& p : fs::directory_iterator(directory)) { filelist.push_back(p); } } auto getRelativePath = [=](auto path) { return fs::relative(path, fs::absolute(directory)); }; for (auto &p : filelist) { fs::path pathAbsolute = fs::absolute(p); if (!fs::is_regular_file(pathAbsolute)) { continue; } const std::string newFilename = std::regex_replace(pathAbsolute.filename().string(), rule, format); const fs::path newPath = pathAbsolute.parent_path() / newFilename; if (pathAbsolute != newPath) { if (result.count("verbose")) { if (result.count("no-color")) { fmt::print("{:40} will be renamed in {}\n", getRelativePath(pathAbsolute).string(), getRelativePath(newPath).string()); } else { fmt::print(fg(fmt::color::steel_blue), "{:40}", getRelativePath(pathAbsolute).string()); fmt::print(" will be renamed in "); fmt::print(fg(fmt::color::aqua), "{}\n", getRelativePath(newPath).string()); } } noRenamingDone = false; if (result.count("no-dry-run")) { fs::rename(pathAbsolute, newPath); } } } if (noRenamingDone) { spdlog::info("No renaming to do with current parameters."); } if (!result.count("no-dry-run")) { spdlog::info("If you are sure you want to apply the changes, run this command with the --no-dry-run option."); } } catch (const cxxopts::OptionException &e) { spdlog::error("Parsing options : {}", e.what()); return 1; } catch (const std::exception &e) { spdlog::error("{}", e.what()); return 1; } return 0; }
34
132
0.592792
[ "vector" ]
3f714fefbb152b2176763d936568dda76b79d50f
8,956
cpp
C++
extract_maximum_clique/src/calculate_km.cpp
SotaTsuji/extraction_maximum_clique
e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1
[ "MIT" ]
1
2021-09-22T08:18:49.000Z
2021-09-22T08:18:49.000Z
extract_maximum_clique/src/calculate_km.cpp
SotaTsuji/extract_maximum_clique
e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1
[ "MIT" ]
null
null
null
extract_maximum_clique/src/calculate_km.cpp
SotaTsuji/extract_maximum_clique
e9a00f15fdccd5a36f6a9bcdf618e5f01fefded1
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Sota Tsuji // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php #include "../include/calculate_km.hpp" #include <numeric> #include "../include/graph.hpp" namespace extraction_of_maximum_clique { Polynomial operator-(Polynomial pol) { for (auto& p : pol) { p = -p; } return pol; } Polynomial operator/(const Polynomial& pol1, const Polynomial& pol2) { return get<0>(polynomial_division(pol1, pol2)); } Polynomial operator/(Polynomial pol, const Bint x) { for (auto& p : pol) { p /= x; } return pol; } // Algorithm 8 Bint get_maximum_coefficient(const int n) { const int r = (n + 1) / 2; const int lambda_max = 2 * (n - 1); Bint c_n = 1; Bint c_d = 1; Bint s = 1; for (auto i = 1; i <= r; ++i) { c_n *= (n - i + 1); c_d *= i; s *= lambda_max; } return s * c_n / c_d; } // Algorithm 9 vector<int> get_prime_list(const int n, const Bint c) { const auto primes = sieve_of_Eratosthenes(4 * n * n - 1); Bint s = 1; vector<int> prime_list; for (auto i = primes.size() - 1; i >= 0; --i) { int p_i = primes[i]; s *= p_i; prime_list.push_back(p_i); if (s > 2 * c) { break; } } return prime_list; } // Algorithm 11 tuple<Polynomial, Polynomial, Bint> polynomial_division(Polynomial f, const Polynomial& g) { const int n = f.size() - 1, m = g.size() - 1; Polynomial q(n - m + 1); Bint c = 1; for (auto i = n; i >= m; --i) { const Bint c_ = g[m] / gcd(f[i], g[m]); for (auto j = n; j > i; --j) { q[j - m] *= c_; } for (auto j = 0; j <= i; ++j) { f[j] *= c_; } c *= c_; q[i - m] = f[i] / g[m]; f[i] = 0; for (auto j = 1; j <= m; ++j) { f[i - j] -= q[i - m] * g[m - j]; } } while (!f.empty() && f.back() == 0) { f.pop_back(); } return {q, f, c}; } // Algorithm 12 int get_number_of_roots(Polynomial f) { int km = 0; while (true) { const auto f_ = differential(f); const auto r = gcd(f, f_); if (r.size() <= 1) { km += get_number_of_roots_by_strum(f); return km; } km += get_number_of_roots_by_strum(f / r); f = r; } } // Algorithm 13 int get_km(const WeightedGraph& S) { const auto f = get_coefficient(S); const int km = get_number_of_roots(f); return km; } vector<int> sieve_of_Eratosthenes(const int k) { vector<int> primes(k - 1); iota(primes.begin(), primes.end(), 2); for (auto i = 0;; ++i) { auto itr = primes.cbegin() + i; const int divisor = *itr; if (divisor * divisor > k) { break; } ++itr; while (itr != primes.cend()) { if ((*itr) % divisor == 0) { itr = primes.erase(itr); } else { ++itr; } } } return primes; } Matrix get_double_adjacent_matrix(const WeightedGraph& S) { const auto n = S.v.size(); Matrix A(n, vector<int>(n)); for (auto i = 0; i < n - 1; ++i) { for (auto j = i + 1; j < n; ++j) { if (S.e.contains({S.v[i], S.v[j]})) { A[i][j] = A[j][i] = 2 / S.rw.at({S.v[i], S.v[j]}); } } } return A; } Polynomial differential(const Polynomial& f) { Polynomial f_; for (auto i = 1; i < f.size(); ++i) { f_.push_back(f[i] * i); } return f_; } Polynomial simplify_coefficient(const Polynomial& f) { if (f.size() == 1) { return Polynomial(1, 1); } else { Bint _gcd = gcd(f[0], f[1]); for (auto i = 2; i < f.size(); ++i) { _gcd = gcd(_gcd, f[i]); } return f / ((f.back() > 0 ? 1 : -1) * _gcd); } } Polynomial gcd(Polynomial f, Polynomial g) { if (f.size() < g.size()) { tie(f, g) = {g, f}; } while (true) { auto [_q, r, _c] = polynomial_division(f, g); if (r.empty()) { return simplify_coefficient(g); } tie(f, g) = {g, r}; } } Polynomial rem(const Polynomial& f, const Polynomial& g) { return get<1>(polynomial_division(f, g)); } Bint substitute_into_polynomial(const Polynomial& f, const int x) { Bint power = 1; Bint n = 0; for (auto i = 0; i < f.size(); ++i) { n += f[i] * power; power *= x; } return n; } int sigma(const vector<Polynomial>& fs, const int alpha) { int count_of_sign_changes = 0; int prev_sign = 0; int i; for (i = 0; i < fs.size() && prev_sign == 0; ++i) { const Bint sigma_alpha = substitute_into_polynomial(fs[i], alpha); prev_sign = sigma_alpha == 0 ? 0 : (sigma_alpha > 0 ? 1 : -1); } for (auto j = i; j < fs.size(); ++j) { const Bint sigma_alpha = substitute_into_polynomial(fs[j], alpha); const int current_sign = sigma_alpha == 0 ? 0 : (sigma_alpha > 0 ? 1 : -1); if (current_sign == -prev_sign) { ++count_of_sign_changes; prev_sign = current_sign; } } return count_of_sign_changes; } int sigma(const vector<Polynomial>& fs, const Infinity inf) { bool is_positive = inf == Infinity::Positive; int count_of_sign_changes = 0; int prev_sign = fs[0].back() * ((is_positive || fs[0].size() % 2 == 1) ? 1 : -1) > 0 ? 1 : -1; for (auto i = 1; i < fs.size(); ++i) { const int current_sign = fs[i].back() * ((is_positive || fs[i].size() % 2 == 1) ? 1 : -1) > 0 ? 1 : -1; if (current_sign == -prev_sign) { ++count_of_sign_changes; prev_sign = current_sign; } } return count_of_sign_changes; } int get_number_of_roots_by_strum(const Polynomial& f) { vector<Polynomial> ps; ps.push_back(f); if (f.size() > 1) { ps.push_back(differential(f)); for (auto j = 2; ps.back().size() > 1; ++j) { ps.push_back(-rem(ps[j - 2], ps[j - 1])); } } return sigma(ps, Infinity::Negative) - sigma(ps, -2); } /* The following functions are tentative. Currently, "get_coefficient" is NOT a polynomial-time algorithm. Later, we are going to replace it with a polynomial-time algorithm. */ Polynomial get_coefficient(const WeightedGraph& S) { const Matrix A = get_double_adjacent_matrix(S); PolynomialMatrix B; for (auto i = 0; i < A.size(); ++i) { vector<Polynomial> Bi(A[0].size()); for (auto j = 0; j < A[0].size(); ++j) { Bi[j].push_back(-A[i][j]); if (i == j) { Bi[j].push_back(1); } } B.push_back(Bi); } return simplify_coefficient(calculate_determinant(B)); } Polynomial calculate_determinant(const PolynomialMatrix& A) { if (A.size() == 1) { return A[0][0]; } int sign = 1; Polynomial characteristic_polynomial; for (auto k = 0; k < A.size(); ++k) { PolynomialMatrix B(A.size() - 1); for (auto i = 1; i < A.size(); ++i) { for (auto j = 0; j < A.size(); ++j) { if (k != j) { B[i - 1].push_back(A[i][j]); } } } characteristic_polynomial += sign * (A[0][k] * calculate_determinant(B)); sign *= -1; } return characteristic_polynomial; } Polynomial operator*(const int x, const Polynomial& pol) { Polynomial pol1; for (auto& p : pol) { pol1.push_back(p * x); } while (!pol1.empty() && pol1.back() == 0) { pol1.pop_back(); } return pol1; } Polynomial operator*(const Polynomial& pol1, const Polynomial& pol2) { if (pol1.empty() || pol2.empty()) { return Polynomial{}; } Polynomial pol3(pol1.size() + pol2.size() - 1); for (auto i = 0; i < pol1.size(); ++i) { for (auto j = 0; j < pol2.size(); ++j) { pol3[i + j] += pol1[i] * pol2[j]; } } return pol3; } Polynomial& operator+=(Polynomial& self, const Polynomial& other) { for (auto i = 0; i < other.size(); ++i) { if (i < self.size()) { self[i] += other[i]; } else { self.push_back(other[i]); } } while (!self.empty() && self.back() == 0) { self.pop_back(); } return self; } } // namespace extraction_of_maximum_clique
27.641975
81
0.484145
[ "vector" ]
3f762a11c27112e1ac779247a5f498bb77d043fe
20,065
cpp
C++
vstgui/tests/unittest/lib/cviewcontainer_test.cpp
etheory/vstgui
df5d1836440e743600397d33e1612d4605ea0b37
[ "BSD-3-Clause" ]
608
2015-12-18T10:21:27.000Z
2022-03-29T01:00:52.000Z
vstgui/tests/unittest/lib/cviewcontainer_test.cpp
etheory/vstgui
df5d1836440e743600397d33e1612d4605ea0b37
[ "BSD-3-Clause" ]
111
2016-01-27T09:07:33.000Z
2022-02-28T06:47:32.000Z
vstgui/tests/unittest/lib/cviewcontainer_test.cpp
etheory/vstgui
df5d1836440e743600397d33e1612d4605ea0b37
[ "BSD-3-Clause" ]
123
2015-12-18T08:30:36.000Z
2022-03-05T17:26:38.000Z
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #include "../../../lib/cframe.h" #include "../../../lib/iviewlistener.h" #include "../../../lib/ccolor.h" #include "../../../lib/dragging.h" #include "../../../lib/events.h" #include "../unittests.h" #include "eventhelpers.h" #include <vector> namespace VSTGUI { namespace { class TestViewContainerListener : public IViewContainerListener { public: void viewContainerViewAdded (CViewContainer* container, CView* view) override { viewAddedCalled = true; } void viewContainerViewRemoved (CViewContainer* container, CView* view) override { viewRemovedCalled = true; } void viewContainerViewZOrderChanged (CViewContainer* container, CView* view) override { viewZOrderChangedCalled = true; } void viewContainerTransformChanged (CViewContainer* container) override { transformChangedCalled = true; } bool viewAddedCalled {false}; bool viewRemovedCalled {false}; bool viewZOrderChangedCalled {false}; bool transformChangedCalled {false}; }; class TestView1 : public CView { public: TestView1 () : CView (CRect (0, 0, 10, 10)) {} }; class TestView2 : public CView { public: TestView2 () : CView (CRect (10, 10, 20, 20)) {} }; class MouseEventCheckView : public CView, public DropTargetAdapter { public: MouseEventCheckView () : CView (CRect ()) {} bool mouseDownCalled {false}; bool mouseMovedCalled {false}; bool mouseUpCalled {false}; bool mouseCancelCalled {false}; bool onDragEnterCalled {false}; bool onDragLeaveCalled {false}; bool onDragMoveCalled {false}; bool onWheelCalled {false}; CMouseEventResult onMouseDown (CPoint& where, const CButtonState& buttons) override { mouseDownCalled = true; return kMouseEventHandled; } CMouseEventResult onMouseMoved (CPoint& where, const CButtonState& buttons) override { mouseMovedCalled = true; return kMouseEventHandled; } CMouseEventResult onMouseUp (CPoint& where, const CButtonState& buttons) override { mouseUpCalled = true; return kMouseEventHandled; } CMouseEventResult onMouseCancel () override { mouseCancelCalled = true; return kMouseEventHandled; } SharedPointer<IDropTarget> getDropTarget () override { return this; } DragOperation onDragEnter (DragEventData data) override { onDragEnterCalled = true; return DragOperation::None; } void onDragLeave (DragEventData data) override { onDragLeaveCalled = true; } DragOperation onDragMove (DragEventData data) override { onDragMoveCalled = true; return DragOperation::None; } void onMouseWheelEvent (MouseWheelEvent& event) override { onWheelCalled = true; event.consumed = true; } }; } // anonymous TEST_SUITE_SETUP (CViewContainerTest) { SharedPointer<CViewContainer> container = makeOwned<CViewContainer> (CRect (0, 0, 200, 200)); TEST_SUITE_SET_STORAGE (SharedPointer<CViewContainer>, container); } TEST_SUITE_TEARDOWN (CViewContainerTest) { TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>) = nullptr; } TEST_CASE (CViewContainerTest, ChangeViewZOrder) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view1 = new CView (CRect (0, 0, 10, 10)); CView* view2 = new CView (CRect (0, 0, 10, 10)); CView* view3 = new CView (CRect (0, 0, 10, 10)); container->addView (view1); container->addView (view2); container->addView (view3); EXPECT(container->changeViewZOrder (view3, 0)); EXPECT(container->getView (0) == view3); EXPECT(container->getView (1) == view1); EXPECT(container->getView (2) == view2); EXPECT(container->getView (3) == nullptr); EXPECT(container->changeViewZOrder (view3, 4) == false); EXPECT(container->changeViewZOrder (view3, 0)); EXPECT(container->changeViewZOrder (view3, 1)); EXPECT(container->getView (0) == view1); EXPECT(container->getView (1) == view3); EXPECT(container->getView (2) == view2); } TEST_CASE (CViewContainerTest, AddView) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view = new CView (CRect (0, 0, 10, 10)); CView* view2 = new CView (CRect (0, 0, 10, 10)); EXPECT(container->addView (view)); EXPECT(container->addView (view2)); EXPECT(container->isChild (view)); EXPECT(container->isChild (view2)); } TEST_CASE (CViewContainerTest, AddView2) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v = new TestView1 (); CRect r (30, 40, 50, 60); EXPECT(container->addView (v, r, false)); EXPECT(v->getMouseEnabled () == false); EXPECT(v->getMouseableArea () == r); } TEST_CASE (CViewContainerTest, AddViewTwice) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view = new CView (CRect (0, 0, 10, 10)); EXPECT (container->addView (view)); EXPECT_EXCEPTION (container->addView (view), "view is already added to a container view"); } TEST_CASE (CViewContainerTest, AddViewToTwoContainer) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view = new CView (CRect (0, 0, 10, 10)); EXPECT (container->addView (view)); auto c2 = owned (new CViewContainer (CRect ())); EXPECT_EXCEPTION (c2->addView (view), "view is already added to a container view"); } TEST_CASE (CViewContainerTest, AddViewBeforeOtherView) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view = new CView (CRect (0, 0, 10, 10)); CView* view2 = new CView (CRect (0, 0, 10, 10)); EXPECT (container->addView (view)); EXPECT (container->addView (view2, view)); EXPECT (container->getView (0) == view2) EXPECT (container->getView (1) == view) } TEST_CASE (CViewContainerTest, RemoveView) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto view = makeOwned<CView> (CRect (0, 0, 10, 10)); CView* view2 = new CView (CRect (0, 0, 10, 10)); container->addView (view); container->addView (view2); container->removeView (view, false); EXPECT (container->isChild (view) == false) EXPECT (container->isChild (view2)) } TEST_CASE (CViewContainerTest, RemoveAllViews) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto view = makeOwned<CView> (CRect (0, 0, 10, 10)); auto view2 = makeOwned<CView> (CRect (0, 0, 10, 10)); container->addView (view); container->addView (view2); container->removeAll (false); EXPECT (container->isChild (view) == false) EXPECT (container->isChild (view2) == false) EXPECT (container->hasChildren () == false) } TEST_CASE (CViewContainerTest, AdvanceNextFocusView) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CFrame* frame = new CFrame (CRect (0, 0, 10, 10), nullptr); frame->onActivate (true); CView* view1 = new CView (CRect (0, 0, 10, 10)); CView* view2 = new CView (CRect (0, 0, 10, 10)); CView* view3 = new CView (CRect (0, 0, 10, 10)); view1->setWantsFocus (true); view2->setWantsFocus (true); view3->setWantsFocus (true); container->addView (view1); container->addView (view2); container->addView (view3); frame->addView (container); container->remember (); frame->attached (frame); EXPECT (container->advanceNextFocusView (nullptr, true) == true) EXPECT (frame->getFocusView () == view3) EXPECT (container->advanceNextFocusView (view3) == false) frame->setFocusView (nullptr); EXPECT (container->advanceNextFocusView (nullptr) == true) EXPECT (frame->getFocusView () == view1) frame->close (); } TEST_CASE (CViewContainerTest, AutoSizeAll) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CView* view = new CView (container->getViewSize ()); view->setAutosizeFlags (kAutosizeAll); container->addView (view); container->setAutosizingEnabled (true); EXPECT (container->getAutosizingEnabled ()); container->setViewSize (CRect (0, 0, 500, 500)); EXPECT (view->getViewSize ().left == 0) EXPECT (view->getViewSize ().top == 0) EXPECT (view->getViewSize ().right == 500) EXPECT (view->getViewSize ().bottom == 500) container->setAutosizingEnabled (false); EXPECT (container->getAutosizingEnabled () == false); } TEST_CASE (CViewContainerTest, SizeToFit) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CRect r (10, 10, 20, 20); CView* view = new CView (r); container->addView (view); container->sizeToFit (); EXPECT (container->getViewSize ().right == 30) EXPECT (container->getViewSize ().bottom == 30) } TEST_CASE (CViewContainerTest, GetViewAt) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CRect r (10, 10, 20, 20); CView* view = new CView (r); container->addView (view); EXPECT (view == container->getViewAt (r.getTopLeft ())); EXPECT (nullptr == container->getViewAt (CPoint (0, 0))); } TEST_CASE (CViewContainerTest, GetViewAtDeep) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CRect r (10, 10, 20, 20); CViewContainer* container2 = new CViewContainer (r); container->addView (container2); CRect r2 (2, 2, 4, 4); CView* view = new CView (r2); container2->addView (view); EXPECT (container->getViewAt (CPoint (12, 12)) == nullptr); EXPECT (container->getViewAt (CPoint (12, 12), GetViewOptions (GetViewOptions::kDeep)) == view); EXPECT (container->getViewAt (CPoint (11, 11), GetViewOptions (GetViewOptions::kDeep)) == nullptr); EXPECT (container->getViewAt ( CPoint (11, 11), GetViewOptions (GetViewOptions::kDeep | GetViewOptions::kIncludeViewContainer)) == container2); } TEST_CASE (CViewContainerTest, Listener) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); TestViewContainerListener listener; container->registerViewContainerListener (&listener); auto view = new CView (CRect (0, 0, 0, 0)); container->addView (view); EXPECT (listener.viewAddedCalled == true); container->removeView (view, false); EXPECT (listener.viewRemovedCalled == true); auto view2 = new CView (CRect (0, 0, 0, 0)); container->addView (view); container->addView (view2); container->changeViewZOrder (view2, 0); EXPECT (listener.viewZOrderChangedCalled == true); container->setTransform (CGraphicsTransform ().translate (1., 1.)); EXPECT (listener.transformChangedCalled == true); container->unregisterViewContainerListener (&listener); } TEST_CASE (CViewContainerTest, BackgroundColor) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); container->setBackgroundColor (kGreenCColor); EXPECT (container->getBackgroundColor () == kGreenCColor); container->setBackgroundColorDrawStyle (kDrawFilledAndStroked); EXPECT (container->getBackgroundColorDrawStyle () == kDrawFilledAndStroked); container->setBackgroundColorDrawStyle (kDrawFilled); EXPECT (container->getBackgroundColorDrawStyle () == kDrawFilled); container->setBackgroundColorDrawStyle (kDrawStroked); EXPECT (container->getBackgroundColorDrawStyle () == kDrawStroked); } TEST_CASE (CViewContainerTest, BackgroundOffset) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); container->setBackgroundOffset (CPoint (10, 10)); EXPECT (container->getBackgroundOffset () == CPoint (10, 10)); } TEST_CASE (CViewContainerTest, GetChildViewsOfType) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); container->addView (new TestView1 ()); container->addView (new TestView2 ()); std::vector<TestView1*> r; container->getChildViewsOfType<TestView1> (r); EXPECT (r.size () == 1); EXPECT (r[0] == container->getView (0)); std::vector<TestView2*> r2; container->getChildViewsOfType<TestView2> (r2); EXPECT (r2.size () == 1); EXPECT (r2[0] == container->getView (1)); auto c2 = owned (new CViewContainer (CRect (0, 0, 100, 100))); c2->addView (container); r.clear (); c2->getChildViewsOfType<TestView1> (r); EXPECT (r.size () == 0); c2->getChildViewsOfType<TestView1> (r, true); EXPECT (r.size () == 1); c2->removeView (container, false); } TEST_CASE (CViewContainerTest, Iterator) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new TestView1 (); auto v2 = new TestView2 (); container->addView (v1); container->addView (v2); ViewIterator it (container); EXPECT (*it == v1); ++it; EXPECT (*it == v2); --it; EXPECT (*it == v1); auto it2 = it++; EXPECT (*it2 == v1); EXPECT (*it == v2); } TEST_CASE (CViewContainerTest, ReverseIterator) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new TestView1 (); auto v2 = new TestView2 (); container->addView (v1); container->addView (v2); ReverseViewIterator it (container); EXPECT (*it == v2); ++it; EXPECT (*it == v1); --it; EXPECT (*it == v2); auto it2 = it++; EXPECT (*it2 == v2); EXPECT (*it == v1); ++it; EXPECT (*it == nullptr); } TEST_CASE (CViewContainerTest, MouseEventsInEmptyContainer) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); EXPECT_EQ (dispatchMouseEvent<MouseDownEvent> (container, {}), EventConsumeState::NotHandled); EXPECT_EQ (dispatchMouseEvent<MouseMoveEvent> (container, {}), EventConsumeState::NotHandled); EXPECT_EQ (dispatchMouseEvent<MouseUpEvent> (container, {}), EventConsumeState::NotHandled); EXPECT_EQ (dispatchMouseCancelEvent (container), EventConsumeState::NotHandled); EXPECT_EQ (dispatchMouseWheelEvent (container, {}, 1., 0.), EventConsumeState::NotHandled); } TEST_CASE (CViewContainerTest, MouseEvents) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new MouseEventCheckView (); auto v2 = new MouseEventCheckView (); CRect r1 (0, 0, 50, 50); CRect r2 (50, 0, 100, 50); v1->setViewSize (r1); v1->setMouseableArea (r1); v2->setViewSize (r2); v2->setMouseableArea (r2); container->addView (v1); container->addView (v2); EXPECT_EQ (dispatchMouseEvent<MouseDownEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::Handled); EXPECT_TRUE (v1->mouseDownCalled); EXPECT_FALSE (v2->mouseDownCalled); EXPECT_EQ (dispatchMouseEvent<MouseMoveEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::Handled); EXPECT_TRUE (v1->mouseMovedCalled); EXPECT_FALSE (v2->mouseMovedCalled); EXPECT_EQ (dispatchMouseEvent<MouseUpEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::Handled); EXPECT_TRUE (v1->mouseUpCalled); EXPECT_FALSE (v2->mouseUpCalled); EXPECT_EQ (dispatchMouseWheelEvent (container, {60., 10.}, 0.5, 0.), EventConsumeState::Handled); EXPECT_FALSE (v1->onWheelCalled); EXPECT_TRUE (v2->onWheelCalled); } TEST_CASE (CViewContainerTest, MouseCancel) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new MouseEventCheckView (); CRect r1 (0, 0, 50, 50); v1->setViewSize (r1); v1->setMouseableArea (r1); container->addView (v1); EXPECT_EQ (dispatchMouseEvent<MouseDownEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::Handled); EXPECT_TRUE (v1->mouseDownCalled); EXPECT_EQ (dispatchMouseCancelEvent (container), EventConsumeState::Handled); EXPECT_TRUE (v1->mouseCancelCalled); } TEST_CASE (CViewContainerTest, DragEvents) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new MouseEventCheckView (); auto v2 = new MouseEventCheckView (); CRect r1 (0, 0, 50, 50); CRect r2 (50, 0, 100, 50); v1->setViewSize (r1); v1->setMouseableArea (r1); v2->setViewSize (r2); v2->setMouseableArea (r2); container->addView (v1); container->addView (v2); DragEventData data; data.drag = nullptr; data.pos = CPoint (10, 10); data.modifiers.clear (); auto dropTarget = container->getDropTarget (); dropTarget->onDragEnter (data); EXPECT (v1->onDragEnterCalled); EXPECT (v2->onDragEnterCalled == false); dropTarget->onDragMove (data); EXPECT (v1->onDragMoveCalled); EXPECT (v2->onDragMoveCalled == false); dropTarget->onDragLeave (data); EXPECT (v1->onDragLeaveCalled); EXPECT (v2->onDragLeaveCalled == false); } TEST_CASE (CViewContainerTest, DragMoveBetweenTwoViews) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new MouseEventCheckView (); auto v2 = new MouseEventCheckView (); CRect r1 (0, 0, 50, 50); CRect r2 (50, 0, 100, 50); v1->setViewSize (r1); v1->setMouseableArea (r1); v2->setViewSize (r2); v2->setMouseableArea (r2); container->addView (v1); container->addView (v2); DragEventData data; data.drag = nullptr; data.pos = CPoint (10, 10); data.modifiers.clear (); auto dropTarget = container->getDropTarget (); dropTarget->onDragEnter (data); EXPECT (v1->onDragEnterCalled); EXPECT (v2->onDragEnterCalled == false); data.pos (60, 10); dropTarget->onDragMove (data); EXPECT (v1->onDragLeaveCalled); EXPECT (v2->onDragEnterCalled); } TEST_CASE (CViewContainerTest, MouseDownOnTransparentViewWithoutMouseSupportHidingSubviewWithMouseSupport) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); CRect r1 (0, 0, 50, 50); auto v1 = new MouseEventCheckView (); auto v2 = new CView (r1); v2->setTransparency (false); v1->setViewSize (r1); v1->setMouseableArea (r1); container->addView (v1); container->addView (v2); EXPECT_EQ (dispatchMouseEvent<MouseDownEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::NotHandled); EXPECT_FALSE (v1->mouseDownCalled); EXPECT_EQ (dispatchMouseEvent<MouseMoveEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::NotHandled); EXPECT_FALSE (v1->mouseMovedCalled); EXPECT_EQ (dispatchMouseEvent<MouseUpEvent> (container, {10., 10.}, MouseButton::Left), EventConsumeState::NotHandled); EXPECT_FALSE (v1->mouseUpCalled); } TEST_CASE (CViewContainerTest, GetViewsAt) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto v1 = new TestView1 (); auto v2 = new TestView1 (); auto c1 = new CViewContainer (CRect (0, 0, 10, 10)); auto v1c1 = new TestView1 (); v1c1->setVisible (false); auto v2c1 = new TestView1 (); c1->addView (v1c1); c1->addView (v2c1); v2->setMouseEnabled (false); container->addView (v1); container->addView (v2); container->addView (c1); CViewContainer::ViewList views; container->getViewsAt (CPoint (0, 0), views, GetViewOptions (GetViewOptions::kNone)); EXPECT (views.size () == 2); views.clear (); container->getViewsAt (CPoint (0, 0), views, GetViewOptions (GetViewOptions::kMouseEnabled)); EXPECT (views.size () == 1); views.clear (); container->getViewsAt (CPoint (0, 0), views, GetViewOptions (GetViewOptions::kIncludeViewContainer)); EXPECT (views.size () == 3); views.clear (); container->getViewsAt (CPoint (0, 0), views, GetViewOptions (GetViewOptions::kDeep)); EXPECT (views.size () == 3); views.clear (); container->getViewsAt ( CPoint (0, 0), views, GetViewOptions (GetViewOptions::kDeep | GetViewOptions::kIncludeInvisible)); EXPECT (views.size () == 4); } TEST_CASE (CViewContainerTest, GetContainerAt) { auto& container = TEST_SUITE_GET_STORAGE (SharedPointer<CViewContainer>); auto c1 = new CViewContainer (CRect (0, 0, 10, 10)); auto c2 = new CViewContainer (CRect (0, 0, 10, 10)); auto c3 = new CViewContainer (CRect (0, 0, 10, 10)); c2->setMouseEnabled (false); c3->setVisible (false); c2->addView (c3); container->addView (c1); container->addView (c2); auto res = container->getContainerAt (CPoint (0, 0), GetViewOptions (GetViewOptions::kNone)); EXPECT (res == container); res = container->getContainerAt (CPoint (0, 0), GetViewOptions (GetViewOptions::kDeep)); EXPECT (res == c2); res = container->getContainerAt ( CPoint (0, 0), GetViewOptions (GetViewOptions::kDeep | GetViewOptions::kIncludeInvisible)); EXPECT (res == c3); res = container->getContainerAt ( CPoint (0, 0), GetViewOptions (GetViewOptions::kDeep | GetViewOptions::kMouseEnabled)); EXPECT (res == c1); } } // namespaces
31.253894
97
0.721854
[ "vector" ]
3f7fb9f3c8e276d726b5b4daf47a93d82979307e
1,960
cpp
C++
problemsets/UVA/10480.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10480.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10480.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <map> using namespace std; const int MAXV = 55; int N, M; int cap[MAXV][MAXV]; int adj[MAXV][MAXV], deg[MAXV]; int prev[MAXV]; int dinic(int N, int S, int T) { int flow = 0; for (int i = 0; i < N; i++) deg[i] = 0; for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) if (cap[i][j] || cap[j][i]) adj[i][deg[i]++] = j, adj[j][deg[j]++] = i; while(1) { for (int i = 0; i < N; i++) prev[i] = -1; queue<int> q; q.push(S); prev[S] = -2; while(!q.empty() && prev[T]==-1) { int u = q.front(), v; q.pop(); for (int i = 0; i < deg[u]; i++) if (prev[v=adj[u][i]]==-1 && cap[u][v]) q.push(v), prev[v] = u; } if (prev[T] == -1) break; for (int z = 0; z < N; z++) if (cap[z][T] && prev[z]!=-1) { int bot = cap[z][T]; for (int v = z, u = prev[v]; u >= 0; v = u, u = prev[v]) bot = min(bot,cap[u][v]); if (!bot) continue; cap[z][T]-=bot; cap[T][z]+=bot; for (int v = z, u = prev[v]; u >= 0; v = u, u = prev[v]) cap[u][v]-=bot, cap[v][u]+=bot; flow+=bot; } } return flow; } int main() { while (scanf("%d %d", &N, &M) && (N|M)) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) cap[i][j] = cap[j][i] = 0; while (M--) { int u, v, c; scanf("%d %d %d", &u, &v, &c); cap[u-1][v-1] = cap[v-1][u-1] = c; } dinic(N,0,1); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) if (i != j) { if ((cap[i][j]||cap[j][i]) && prev[i]!=-1 && prev[j]==-1) printf("%d %d\n", i+1, j+1); } } puts(""); } return 0; }
27.605634
102
0.391327
[ "vector" ]
3f80736f2b2cb6301ce10968dba0b3ccb0022038
4,930
cpp
C++
src/tcp_client_mgr_thread.cpp
winer632/wacc
08a304120cce40137b84ba6c200cccb414af41e0
[ "MIT" ]
null
null
null
src/tcp_client_mgr_thread.cpp
winer632/wacc
08a304120cce40137b84ba6c200cccb414af41e0
[ "MIT" ]
null
null
null
src/tcp_client_mgr_thread.cpp
winer632/wacc
08a304120cce40137b84ba6c200cccb414af41e0
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: tcp_client_mgr_thread.cpp * * Description: * * Version: 1.0 * Created: 2015/3/12 13:06:12 * Revision: none * Compiler: gcc * * Author: wangxx * Organization: lj * * ===================================================================================== * ============================== CHANGE REPORT HISTORY ================================ * | VERSION | UPDATE DATE | UPDATED BY | DESCRIPTION OF CHANGE |* * =========================== END OF CHANGE REPORT HISTORY ============================ */ #include "tcp_client_mgr_thread.h" #include <arpa/inet.h> #include "usracc_common.h" #include "usracc_config.h" #include <string.h> #include "common_logger.h" #include "tools.h" /* *-------------------------------------------------------------------------------------- * Class: TcpClientMgrThread * Method: TcpClientMgrThread * Description: constructor *-------------------------------------------------------------------------------------- */ TcpClientMgrThread::TcpClientMgrThread() { } /* ----- end of method TcpClientMgrThread::TcpClientMgrThread(constructor) ----- */ TcpClientMgrThread::~TcpClientMgrThread() { } int TcpClientMgrThread::open(void *args) { all_stopped_ = false; if (start() == -1) { return -1; } return 0; } /* ----- end of method TcpClientMgrThread::open ----- */ int TcpClientMgrThread::svc() { for(;;) { if (test_cancel_thread() == 1) { all_stopped_ = true; break; } else { loop_process(); sleep(2); } } return 0; } /* ----- end of method TcpClientMgrThread::svc ----- */ int TcpClientMgrThread::stop() { cancel_thread(); while (!all_stopped_) { usleep(1); } return 0; } /* ----- end of method TcpClientMgrThread::stop ----- */ int TcpClientMgrThread::init(vector<TcpClient> *pclients) { pclient_list_ = pclients; conn_data_len_ = 0; memset(conn_data_, 0, sizeof(conn_data_)); conn_data_len_ = build_conndata((char*)conn_data_); return 0; } /* ----- end of method TcpClientMgrThread::init ----- */ int TcpClientMgrThread::loop_process() { int num = pclient_list_->size(); for (int i = 0; i < num; ++i) { if ((*pclient_list_)[i].connected() == false) { if ((*pclient_list_)[i].connect_to_server() == 0) { /* wangxx add 2017-05-12 */ NIF_MSG_UNIT* pointer=(NIF_MSG_UNIT*)conn_data_; CommonLogger::instance().log_info("TcpClientMgrThread::loop_process head =0x%08x", ntohl(pointer->head)); CommonLogger::instance().log_info("TcpClientMgrThread::loop_process invoke =0x%08x", ntohl(pointer->invoke)); CommonLogger::instance().log_info("TcpClientMgrThread::loop_process dialog =0x%08x", ntohl(pointer->dialog)); CommonLogger::instance().log_info("TcpClientMgrThread::loop_process send to serviceLogic msg content:"); tools::print_hex(conn_data_,sizeof(conn_data_)); /* end of wangxx add */ /*everytime acc module set up connecttion with serviceLogic module, acc send SERVLOGIC_CONNECTION_REQ msg to serviceLogic. if acc receive SERVLOGIC_CONNECTION_REQ ack from serviceLogic and result=0, acc begin to syndata with serviceLogic*/ (*pclient_list_)[i].send_data((char*)conn_data_, conn_data_len_); } } } return 0; } /* ----- end of method TcpClientMgrThread::loop_process ----- */ int TcpClientMgrThread::reconnect_to_server(TcpClient *client) { client->disconnect_to_server(); return client->connect_to_server(); } /* ----- end of method TcpClientMgrThread::reconnect_to_server ----- */ int TcpClientMgrThread::build_conndata(char *buf) { NIF_MSG_UNIT *unit = (NIF_MSG_UNIT*)(buf); unit->head = htonl(NIF_MSG_HEAD); unit->invoke = htonl(SERVLOGIC_CONNECTION_REQ); unit->dialog = htonl(BEGIN); unsigned int len = 0; vector<TidParam> tid_list = UsrAccConfig::instance().tid_num_seg_list(); unsigned int list_num = tid_list.size(); CommonLogger::instance().log_info(" list_num is %u", list_num); for (unsigned int i = 0; i < list_num; ++i) { ConnData *conn = (ConnData*)(buf + sizeof(NIF_MSG_UNIT) - sizeof(unsigned char*) + i * sizeof(ConnData)); //ConnData *conn = (ConnData *)unit->pData; conn->min_tid = htonl(tid_list[i].min_tid); conn->max_tid = htonl(tid_list[i].max_tid); conn->mod_id = UsrAccConfig::instance().module_id(); CommonLogger::instance().log_info(" min_tid is %u", tid_list[i].min_tid); CommonLogger::instance().log_info(" max_tid is %u", tid_list[i].max_tid); CommonLogger::instance().log_info(" mod_id is %u", conn->mod_id); len += sizeof(ConnData); CommonLogger::instance().log_info(" len is %u", len); } unit->length = htonl(len); return (len + sizeof(NIF_MSG_UNIT) - sizeof(unsigned char*)); } /* ----- end of method TcpClientMgrThread::build_conndata ----- */
28.830409
126
0.604665
[ "vector" ]
3f8ca7cb223105dec7d6904f7bbe4102eb827063
17,177
cpp
C++
PopcornTime_Desktop-src/gui/ChromeCast.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/gui/ChromeCast.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/gui/ChromeCast.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
#include "ChromeCast.h" #include "NjsProcess.h" #include "GlyphButton.h" #include <QDebug> #include <QPushButton> #include <QMovie> #include <QFrame> #include <QBoxLayout> #include <QLabel> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QWidget> #include <QNetworkProxy> #include <QThread> #include <QEventLoop> const char CHROMECAST_SCRIPT_DISCOVERY[] = "device-discovery.js"; const char CHROMECAST_SCRIPT_SERVER[] = "server.js"; const char CHROMECAST_DEVICE_TEXT_LOCAL[] = "Popcorn Time"; //const int CHROMECAST_DISCOVERY_RESTARTS = 3; const int CHROMECAST_REFRESH_TIMER_INTERVAL = 500; const int CHROMECAST_REFRESH_INTERVAL_CC = 1000; const int CHROMECAST_REFRESH_INTERVAL_OTHER = 30000; CastDevice::CastDevice() : type( CAST_DEVICETYPE_INVALID ) { } CastDevice::CastDevice( const QJsonObject& jObj ) : type( CAST_DEVICETYPE_INVALID ) { QString typeStr = jObj.value( "deviceType" ).toString(); if ( typeStr == "googlecast" ) type = CAST_DEVICETYPE_CHROMECAST; else if ( typeStr == "airplay" ) type = CAST_DEVICETYPE_AIRPLAY; else if ( typeStr == "dlna" ) type = CAST_DEVICETYPE_DLNA; else return; name = jObj.value( "name" ).toString().toLatin1(); ip = jObj.value( "ip" ).toArray().at( 0 ).toString().toLatin1(); url = jObj.value( "url" ).toString().toLatin1(); } ChromeCast::ChromeCast( QWidget *parent, GlyphButton *castBtn ) : QObject( parent ), netMan( parent ), discoveryProc( new NjsProcess( this ) ), // discoveryRestartCounter( CHROMECAST_DISCOVERY_RESTARTS ), castProc( new NjsProcess( this ) ), popup( new Frame( parent ) ), //Qt::Dialog | devicesView( new ListWidget ), m_castBtn( castBtn ), btnMovie( new QMovie( ":/chromecast_search" ) ), isCasting( false ), m_state( Idle ), fontSize( 0 ), startTime( 0 ) { if ( castBtn ) setButton( castBtn ); netMan.setProxy( QNetworkProxy( QNetworkProxy::NoProxy ) ); volumeTimer.setSingleShot( true ); connect( &volumeTimer, SIGNAL( timeout() ), this, SLOT( onVolumeTimer() ) ); discoveryRestartTimer.setSingleShot( true ); discoveryRestartTimer.setInterval( 45000 ); connect( &discoveryRestartTimer, SIGNAL( timeout() ), discoveryProc, SLOT( kill() ) ); connect( discoveryProc, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( discoveryStopped( int, QProcess::ExitStatus ) ) ); connect( discoveryProc, SIGNAL( haveToken( QByteArray, QByteArray ) ), this, SLOT( parseNjsData( QByteArray, QByteArray ) ) ); discoveryProc->setArguments( QStringList( CHROMECAST_SCRIPT_DISCOVERY ) ); discoveryProc->start(); discoveryRestartTimer.start(); connect( castProc, SIGNAL( finished( int, QProcess::ExitStatus ) ), this, SLOT( serverStopped( int, QProcess::ExitStatus ) ) ); connect( castProc, SIGNAL( haveToken( QByteArray, QByteArray ) ), this, SLOT( parseNjsData( QByteArray, QByteArray ) ) ); castProc->setArguments( QStringList( CHROMECAST_SCRIPT_SERVER ) ); QVBoxLayout *vl = new QVBoxLayout( popup ); QLabel *lbl = new QLabel( "Play on:" ); vl->addWidget( lbl, 0 ); lbl->setStyleSheet( "" ); vl->addWidget( devicesView ); // vl->setSizeConstraint( QLayout::SetFixedSize ); devicesView->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); devicesView->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); devicesView->addItem( CHROMECAST_DEVICE_TEXT_LOCAL ); devicesView->setSelectionMode( QAbstractItemView::SingleSelection ); devicesView->item( 0 )->setSelected( true ); devicesView->setStyleSheet( "QListView { border:0px; font:10pt; } " ); connect( devicesView, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onListItemClicked(QListWidgetItem*)) ); popup->setStyleSheet( "QFrame {background-color:black; color:#cacaca; border:1px solid #666666; padding:0px; margin:0px; font:10pt;} " "QLabel {font:13pt; border:0px} " ); connect( btnMovie, SIGNAL( frameChanged( int ) ), this, SLOT( frameChange( int ) ) ); if ( btnMovie->loopCount() != -1 ) connect( btnMovie, SIGNAL( finished() ), btnMovie, SLOT( start() ) ); btnMovie->setCacheMode( QMovie::CacheAll ); } void ChromeCast::frameChange( int frame ) { (void) frame; // static QPixmap pixmap; // qDebug() << "frame" << frame << btnMovie->isValid() << ( btnMovie->currentPixmap().toImage() == pixmap.toImage()); // pixmap = btnMovie->currentPixmap(); if ( m_castBtn ) m_castBtn->setIcon( QIcon( btnMovie->currentPixmap() ) ); } void ChromeCast::discoveryStopped( int exitCode, QProcess::ExitStatus exitStatus ) { (void) exitCode; (void) exitStatus; qDebug() << "discovery finished, exit code" << exitCode << ( exitStatus == QProcess::NormalExit ? "" : "crashed" ); if ( exitStatus != QProcess::NormalExit ) { QProcess *proc = qobject_cast<QProcess *>( sender() ); if ( proc ) CC_DEBUG << "CC discovery STDERR" << proc->readAllStandardError(); } startDiscovery( exitStatus == QProcess::NormalExit ); } void ChromeCast::serverStopped( int exitCode, QProcess::ExitStatus exitStatus ) { (void) exitCode; (void) exitStatus; qDebug() << "server finished, exit code" << exitCode << ( exitStatus == QProcess::NormalExit ? "" : "crashed" ); QProcess *proc = qobject_cast<QProcess *>( sender() ); handleCastingSwitch( false ); } void ChromeCast::setButton( GlyphButton *btn ) { m_castBtn = btn; QObject::connect( m_castBtn, SIGNAL( clicked() ), this, SLOT( buttonClicked() ) ); m_castBtn->setCheckable( false ); } void ChromeCast::buttonClicked() { if ( m_castBtn->isCheckable() ) { stop(); return; } devicesView->setFixedSize( devicesView->sizeHintForColumn( 0 ) + 2 * devicesView->frameWidth(), devicesView->sizeHintForRow( 0 ) * devicesView->count() + 2 * devicesView->frameWidth() ); popup->adjustSize(); QWidget *src = qobject_cast<QWidget *>( sender() ); if ( src ) { const QPoint srcCenter = src->parentWidget()->mapToGlobal( src->geometry().center() ); const QSize pSize = popup->size(); const QPoint newPos = QPoint( srcCenter.x() - pSize.width(), srcCenter.y() - pSize.height() ); popup->move( newPos ); } popup->show(); } void ChromeCast::stop() { if ( isCasting ) { QTimer timer; timer.setSingleShot( true ); QEventLoop loop; QObject::connect( &timer, SIGNAL( timeout() ), &loop, SLOT( quit() ) ); QNetworkReply *reply = issueCommand( "command/stop" ); if ( reply ) { QObject::connect( reply, SIGNAL( finished() ), &loop, SLOT( quit() ) ); timer.start( 500 ); qDebug() << "stopping"; loop.exec(); qDebug() << "stopped, reply finished" << reply->isFinished() << "timer active" << timer.isActive(); } } castProc->kill(); startTime = 0; } void ChromeCast::pause() { if ( state() != Paused ) issueCommand( "command/pause" ); } void ChromeCast::setTime( int time ) { if ( state() == Opening || state() == Idle ) startTime = time; else issueCommand( "command/seek", "seek=" + QByteArray::number( double( time ) / 1000 ) ); } void ChromeCast::setStartTime( int time ) { startTime = time; CC_DEBUG << "CC start time =" << time; } void ChromeCast::setMute( bool muted ) { issueCommand( "command/mute", muted ? "muted=1" : "muted=0" ); } void ChromeCast::onVolumeTimer() { issueCommand( "command/volume", QByteArray( "volume=" ) + QByteArray::number( double( lastVolume ) / 200 ) ); } void ChromeCast::setPause( bool setPause ) { if ( setPause && state() == Paused ) return; if ( !setPause && isPlaying() ) return; issueCommand( setPause ? "command/pause" : "command/play" ); } void ChromeCast::setVolume( int volume ) { static QTime blockUntil = QTime::currentTime(); if ( lastVolume == volume ) return; lastVolume = volume; if ( QTime::currentTime() < blockUntil ) volumeTimer.start( 250 ); else { issueCommand( "command/volume", QByteArray( "volume=" ) + QByteArray::number( double( volume ) / 200 ) ); blockUntil = QTime::currentTime().addMSecs( 500 ); } } void ChromeCast::setSubtitleFileV( QString fileName ) { subtitleFile = fileName; static QStringList supportedList = getSupportedSubsList(); foreach( QString ext, supportedList ) { if ( fileName.toLower().endsWith( ext ) ) { issueCommand( "command/subtitles", QString( "subtitles=%1" ).arg( subtitleFile ).toLocal8Bit() ); return; } } issueCommand( "command/subtitles", "subtitles=" ); } void ChromeCast::setFontSize( int fontSize ) { if ( fontSize > 2 ) fontSize = 2; if ( fontSize < -2 ) fontSize = -2; this->fontSize = fontSize; issueCommand( "command/fontSize", QByteArray( "fontSize=" ) + QByteArray::number( fontSize ) ); } void ChromeCast::parseDiscovery( QByteArray data ) { QJsonParseError err; QJsonObject jObj = QJsonDocument::fromJson( data, &err ).object(); if ( jObj.isEmpty() ) { qDebug() << "JSON error" << err.errorString() << data; return; } addDevice( CastDevice( jObj ) ); } bool ChromeCast::addDevice( const CastDevice& device ) { if ( !device.isValid() || devs.contains( device ) ) return false; devs += device; devicesView->addItem( device.name ); devicesView->adjustSize(); popup->adjustSize(); qDebug() << "discovered" << item.type << item.name << item.ip << item.url; return true; } void ChromeCast::parseMStat( QByteArray data ) { QJsonParseError err; QJsonObject jObj = QJsonDocument::fromJson( data, &err ).object(); if ( jObj.isEmpty() ) { qDebug() << "JSON error" << err.errorString() << data; return; } QString theState = jObj.value( "playerState" ).toString( "INVALID_VALUE" ); if ( theState == "BUFFERING" ) { theState = "Buffering"; if ( m_state == Opening ) { const int time = jObj.value( "media" ).toObject().value( "duration" ).toDouble( -1 ) * 1000; if ( time >= 0 ) emit lengthChanged( time ); } else setState( Buffering ); } else if ( theState == "PLAYING" ) { theState = "Playing"; setState( Playing ); } else if ( theState == "PAUSED" ) { theState = "Paused"; setState( Paused ); } else if ( theState == "INVALID_VALUE" ) theState = ""; if ( theState.size() ) { theState.prepend( QString( CAST_DEVICETYPE_USER_STRING[currentDevice.type] ) + " " ); emit stateText( theState ); } switch ( currentDevice.type ) { case CAST_DEVICETYPE_AIRPLAY: emit stateImage( ":/airplay_icon" ); break; case CAST_DEVICETYPE_CHROMECAST: emit stateImage( ":/chromecast_icon" ); break; case CAST_DEVICETYPE_DLNA: emit stateImage( ":/dlna_icon" ); break; default: emit stateImage( "" ); break; } const int time = jObj.value( "currentTime" ).toDouble( -1 ) * 1000; if ( time >= 0 ) { emit timeChanged( time ); currentTime = time; } } void ChromeCast::startDiscovery( bool crashed ) { qDebug() << "startDiscovery" << crashed; if ( discoveryProc->state() != QProcess::NotRunning ) return; if ( crashed ) { QTimer::singleShot( 1000, discoveryProc, SLOT( start() ) ); discoveryRestartTimer.start(); return; // if ( discoveryRestartCounter <= 0 ) return; // --discoveryRestartCounter; } // else discoveryRestartCounter = CHROMECAST_DISCOVERY_RESTARTS; // devs.clear(); // while ( devicesView->count() > 1 ) devicesView->takeItem( devicesView->count() - 1 ); discoveryProc->start(); discoveryRestartTimer.start(); } void ChromeCast::handleCastingSwitch( bool switchedToEnable ) { if ( switchedToEnable == isCasting ) return; if ( switchedToEnable ) { if ( state() == Idle ) setState( Opening ); } else { if ( state() != Idle ) setState( Idle ); } emit castingSwitched( isCasting = switchedToEnable ); qDebug() << "Casting is now" << ( isCasting ? "connected" : "disconnected" ); emit stateText( "Starting Casting..." ); totalLength = 1; lastVolume = 100; isCasting ? stateRefreshtimer.start( CHROMECAST_REFRESH_TIMER_INTERVAL, this ) : stateRefreshtimer.stop(); btnMovie->stop(); currentTime = 0; m_castBtn->setCheckable( isCasting ); m_castBtn->setChecked( isCasting ); m_castBtn->changedState( m_castBtn->isChecked() ); if ( !switchedToEnable ) { devicesView->item( 0 )->setSelected( true ); currentDevice = CastDevice(); } } void ChromeCast::timerEvent( QTimerEvent * ) { static int counter = 0; static const int CC_INTERVAL = CHROMECAST_REFRESH_INTERVAL_CC / CHROMECAST_REFRESH_TIMER_INTERVAL; static const int OTHER_INTERVAL = CHROMECAST_REFRESH_INTERVAL_OTHER / CHROMECAST_REFRESH_TIMER_INTERVAL; const int period = currentDevice.type == CAST_DEVICETYPE_CHROMECAST ? CC_INTERVAL : OTHER_INTERVAL; currentTime += CHROMECAST_REFRESH_TIMER_INTERVAL; emit timeChanged( currentTime ); if ( counter++ >= period ) { issueCommand( "command/mediaState" ); counter = 0; } } void ChromeCast::parseNjsData( QByteArray key, QByteArray value ) { if ( key == "DEVICE_FOUND" ) parseDiscovery( value ); else if ( key == "LISTEN_URL" ) { serverUrl = value; // netMan.get( QNetworkRequest( serverUrl.toString() + "command/deviceState" ) ); // qDebug() << serverUrl << "stat req"; QString req = serverUrl.toString(); static QString loadCmd = "command/load?deviceType=%1&deviceIP=%2&torrentFile=%3&fontSize=%4"; req += loadCmd.arg( CAST_DEVICETYPE_STRING[currentDevice.type], currentDevice.ip.toString(), QString( QUrl::toPercentEncoding( mediaFile ) ), QString::number( fontSize ) ); QNetworkReply *reply = netMan.get( QNetworkRequest( req ) ); connect( reply, SIGNAL( finished() ), this, SLOT( onReqestFinish() ) ); qDebug() << req << "stat req"; } else if ( key == "DSTAT" ) handleCastingSwitch( value == "CONNECTED" ); else if ( key == "MSTAT" ) parseMStat( value ); else if ( key == "ERR" ) { qDebug() << "parseCast: ERR" << value; stop(); stateText( "Casting error" ); } } void ChromeCast::onListItemClicked( QListWidgetItem *item ) { popup->hide(); if ( item->text() == currentDevice.name ) return; stop(); currentDevice = CastDevice(); if ( item->text() == CHROMECAST_DEVICE_TEXT_LOCAL ) return; foreach( CastDevice dev, devs ) { if ( item->text() != dev.name ) continue; currentDevice = dev; btnMovie->start(); castProc->restart(); // qDebug() << "selected" << dev.name << "at" << dev.ip; emit deviceSelected(); return; } } QNetworkReply* ChromeCast::issueCommand( QByteArray command, QByteArray args ) { if ( m_state != Paused && m_state != Playing ) return 0; static QString reqArgs = "?deviceType=%1&deviceIP=%2"; command += reqArgs.arg( CAST_DEVICETYPE_STRING[currentDevice.type], currentDevice.ip.toString() ); if ( args.size() && args.left( 1 ) != "&" ) args.prepend( "&" ); // currentDevice.ip.toString() ); command += args; QNetworkReply *reply = netMan.get( QNetworkRequest( serverUrl.toString() + command ) ); if ( !command.contains( "command/mediaState" ) ) CC_DEBUG << "CC command" << reply->request().url(); connect( reply, SIGNAL( finished() ), this, SLOT( onReqestFinish() ) ); QThread::msleep( 50 ); return reply; } void ChromeCast::onReqestFinish() { QNetworkReply *reply = qobject_cast<QNetworkReply *>( sender() ); // if ( reply ) qDebug() << "reply to" << reply->request().url().path() << ":" << reply->readAll(); reply->deleteLater(); } void ChromeCast::setState( State newState ) { if ( state() == newState ) return; qDebug() << "setState" << newState << "from" << m_state; State oldState = state(); m_state = newState; if ( oldState == Opening && ( newState == Paused || newState == Playing ) ) { setSubtitleFileV( subtitleFile ); if ( startTime ) QTimer::singleShot( 5000, [=]() {CC_DEBUG << "CC first buffering - seeking startTime" << startTime; issueCommand( "command/seek", "seek=" + QByteArray::number( double( startTime ) / 1000 ) ); startTime = 0;} ); } if ( newState == Idle ) { startTime = 0; emit stopped(); } else if ( newState == Opening ) emit opening(); else if ( newState == Playing && oldState != Buffering ) emit playing(); else if ( newState == Paused ) emit paused(); emit stateChanged(); } const QStringList& ChromeCast::getSupportedSubsList() { static const QStringList data = QStringList() << "srt"; return data; }
33.879684
235
0.633522
[ "geometry", "object", "solid" ]
3f923de4544131765a512c2648ac120d252f86d5
1,245
hpp
C++
include/Delivery.hpp
victoragcosta/ConcurrentProgramming-FastFoodKitchen
3d01bc1343cebab93b73ce144f2fa279e5a110f6
[ "MIT" ]
null
null
null
include/Delivery.hpp
victoragcosta/ConcurrentProgramming-FastFoodKitchen
3d01bc1343cebab93b73ce144f2fa279e5a110f6
[ "MIT" ]
14
2021-04-29T13:39:36.000Z
2021-05-11T00:06:09.000Z
include/Delivery.hpp
victoragcosta/ConcurrentProgramming-FastFoodKitchen
3d01bc1343cebab93b73ce144f2fa279e5a110f6
[ "MIT" ]
null
null
null
#ifndef DELIVERY_HPP_ #define DELIVERY_HPP_ #include <vector> #include <pthread.h> namespace Delivery { extern const int assemblingTime; extern pthread_cond_t waitForOrderDelivered; // Initializes Customer threads preparing for the simulation and set some parameters. // Returns a vector with all threads created. std::vector<pthread_t> initDelivery(int nDelivery, int nCustomers); // Stores an order of fries and burgers. typedef struct { int fries; int burgers; } order_t; // Attempts to deliver an order. If possible, subtracts all resources needed, // waits assemblingTime and then returns true. If not possible, return false. // Wakes up a Customer thread. bool deliverOrder(); // Places an order in the queue. void placeOrder(order_t order); // Thread that will think of an order, place the order, wait for the delivery // and then repeat. void *Customer(void *args); // Enumerates tasks that the Worker threads can prioritize. typedef enum { FRIES, BURGERS, DELIVERY, } priority_type_t; // Returns a vector with all the tasks that the Worker should try to do by // order of priority. std::vector<priority_type_t> getPriority(); } #endif /* DELIVERY_HPP_ */
24.9
87
0.723695
[ "vector" ]
3f927c2ab29d9f274442799d204a3d7df0ac86a4
18,924
cpp
C++
archsim/src/abi/memory/system/txln/FunctionGenSystemMemoryTranslationModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-14T22:09:30.000Z
2022-01-11T09:57:52.000Z
archsim/src/abi/memory/system/txln/FunctionGenSystemMemoryTranslationModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
6
2020-07-09T12:01:57.000Z
2021-04-27T10:23:58.000Z
archsim/src/abi/memory/system/txln/FunctionGenSystemMemoryTranslationModel.cpp
Linestro/Gensim_Y
031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8
[ "MIT" ]
10
2020-07-29T17:05:26.000Z
2021-12-04T14:57:15.000Z
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ /* * FunctionGenSystemMemoryTranslationModel.cpp * * Created on: 9 Sep 2014 * Author: harry */ #include "abi/memory/MemoryEventHandlerTranslator.h" #include "abi/memory/system/FunctionBasedSystemMemoryModel.h" #include "abi/devices/DeviceManager.h" #include "abi/devices/MMU.h" #include "gensim/gensim_processor.h" #include "translate/TranslationWorkUnit.h" #include "ij/arch/x86/macros.h" using namespace archsim::abi::memory; UseLogContext(LogSystemMemoryModel); UseLogContext(LogFunctionSystemMemoryModel); FunctionGenSystemMemoryTranslationModel::FunctionGenSystemMemoryTranslationModel() : dirty(true),Complete(0),mem_model(NULL),subscriber(NULL),write_cache(NULL),read_cache(NULL), write_cache_size(0), read_cache_size(0), write_user_cache(NULL), write_user_cache_size(0), read_user_cache(NULL), read_user_cache_size(0) { } static bool HandleSegFaultRead(void *ctx, const System::segfault_data& data) { uint64_t *page_base = (uint64_t *)(data.addr & ~4095ULL); mprotect(page_base, 4096, PROT_READ | PROT_WRITE); for (int i = 0; i < 512; i++) page_base[i] = (uint64_t)DefaultReadHandlerShunt; return true; } static bool HandleSegFaultWrite(void *ctx, const System::segfault_data& data) { uint64_t *page_base = (uint64_t *)(data.addr & ~4095ULL); mprotect(page_base, 4096, PROT_READ | PROT_WRITE); for (int i = 0; i < 512; i++) page_base[i] = (uint64_t)DefaultWriteHandlerSave; return true; } static void TlbCallback(PubSubType::PubSubType type, void *ctx, const void *data) { auto fgen = (FunctionGenSystemMemoryTranslationModel*)ctx; switch(type) { case PubSubType::ITlbEntryFlush: case PubSubType::DTlbEntryFlush: case PubSubType::RegionDispatchedForTranslationVirtual: { virt_addr_t addr = (virt_addr_t) (uint64_t)data; fgen->Evict(addr); break; } case PubSubType::ITlbFullFlush: case PubSubType::DTlbFullFlush: // case PubSubType::RegionDispatchedForTranslationPhysical: fgen->Flush(); break; default: assert(false); } } static void TimerCallback(PubSubType::PubSubType type, void *ctx, const void *data) { FunctionGenSystemMemoryTranslationModel *model = (FunctionGenSystemMemoryTranslationModel*)ctx; switch(type) { case PubSubType::UserEvent1: //clear histogram model->fn_histogram.clear(); return; case PubSubType::UserEvent2: //print histogram std::cerr << "XXX Function histogram start" << std::endl; std::cerr << model->fn_histogram.to_string(); std::cerr << "XXX Function histogram end" << std::endl; return; default: assert(false); } } bool FunctionGenSystemMemoryTranslationModel::Initialise(SystemMemoryModel &smem_model) { Complete = true; this->mem_model = (FunctionBasedSystemMemoryModel*)&smem_model; int mmap_prot = PROT_READ | PROT_WRITE; if (archsim::options::LazyMemoryModelInvalidation) { mmap_prot = PROT_NONE; } read_cache_size = sizeof(read_handler_t) * archsim::translate::profile::RegionArch::PageCount; read_cache = (read_handler_t*)mmap(NULL, read_cache_size, mmap_prot, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); write_cache_size = sizeof(write_handler_t) * archsim::translate::profile::RegionArch::PageCount; write_cache = (write_handler_t*)mmap(NULL, write_cache_size, mmap_prot, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); read_user_cache_size = sizeof(read_handler_t) * archsim::translate::profile::RegionArch::PageCount; read_user_cache = (read_handler_t*)mmap(NULL, read_cache_size, mmap_prot, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); write_user_cache_size = sizeof(write_handler_t) * archsim::translate::profile::RegionArch::PageCount; write_user_cache = (write_handler_t*)mmap(NULL, write_cache_size, mmap_prot, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (archsim::options::LazyMemoryModelInvalidation) { assert(false); mem_model->GetCPU()->GetEmulationModel().GetSystem().RegisterSegFaultHandler((uint64_t)read_cache, read_cache_size, this, HandleSegFaultRead); mem_model->GetCPU()->GetEmulationModel().GetSystem().RegisterSegFaultHandler((uint64_t)write_cache, write_cache_size, this, HandleSegFaultWrite); } else { for (uint32_t i = 0; i < archsim::translate::profile::RegionArch::PageCount; i++) { read_cache[i] = DefaultReadHandlerShunt; write_cache[i] = DefaultWriteHandlerSave; read_user_cache[i] = DefaultReadUserHandler; write_user_cache[i] = DefaultWriteUserHandler; } } auto &pubsub = mem_model->GetCPU()->GetEmulationModel().GetSystem().GetPubSub(); subscriber = new util::PubSubscriber(&pubsub); subscriber->Subscribe(PubSubType::ITlbFullFlush, TlbCallback, this); subscriber->Subscribe(PubSubType::ITlbEntryFlush, TlbCallback, this); subscriber->Subscribe(PubSubType::DTlbFullFlush, TlbCallback, this); subscriber->Subscribe(PubSubType::DTlbEntryFlush, TlbCallback, this); subscriber->Subscribe(PubSubType::RegionDispatchedForTranslationVirtual, TlbCallback, this); subscriber->Subscribe(PubSubType::UserEvent1, TimerCallback, this); subscriber->Subscribe(PubSubType::UserEvent2, TimerCallback, this); Flush(); mem_model->GetCPU()->state.smm_read_cache = (void*)read_cache; mem_model->GetCPU()->state.smm_write_cache = (void*)write_cache; mem_model->GetCPU()->state.smm_read_user_cache = (void*)read_user_cache; mem_model->GetCPU()->state.smm_write_user_cache = (void*)write_user_cache; mem_model->GetCPU()->state.mem_generation = 0; return true; } bool FunctionGenSystemMemoryTranslationModel::EmitMemoryRead(archsim::translate::llvm::LLVMInstructionTranslationContext& insn_ctx, int width, bool sx, llvm::Value*& fault, llvm::Value* address, llvm::Type* destinationType, llvm::Value* destination) { for (auto handler : insn_ctx.block.region.txln.twu.GetProcessor().GetMemoryModel().GetEventHandlers()) { handler->GetTranslator().EmitEventHandler(insn_ctx, *handler, archsim::abi::memory::MemoryModel::MemEventRead, address, (uint8_t)width); } auto &types = insn_ctx.block.region.txln.types; llvm::Type *load_ty = NULL; switch(width) { case 1: load_ty = types.pi8; break; case 2: load_ty = types.pi16; break; case 4: load_ty = types.pi32; break; default: assert(false); } llvm::Value *fn_table = GetReadFunctionTable(insn_ctx.block.region); llvm::Value *this_fun = GetFunFor(insn_ctx.block.region, fn_table, address); llvm::Value *rval = CallFn(insn_ctx.block.region, this_fun, address); fault = GetFault(insn_ctx.block.region, rval); llvm::Value *host_ptr = GetHostPtr(insn_ctx.block.region, rval); llvm::IRBuilder<> &builder = insn_ctx.block.region.builder; llvm::Value *faulty = builder.CreateICmpNE(fault, llvm::ConstantInt::get(types.i32, 0, false)); llvm::BasicBlock *success_block = llvm::BasicBlock::Create(builder.getContext(), "", builder.GetInsertBlock()->getParent()); insn_ctx.block.region.EmitLeaveInstruction(archsim::translate::llvm::LLVMRegionTranslationContext::RequireInterpret, insn_ctx.tiu.GetOffset(), faulty, success_block); builder.SetInsertPoint(success_block); host_ptr = builder.CreatePointerCast(host_ptr, load_ty); llvm::Value *data = builder.CreateLoad(host_ptr); insn_ctx.AddAliasAnalysisNode((llvm::Instruction*)host_ptr, archsim::translate::llvm::TAG_MEM_ACCESS); data = builder.CreateZExt(data, destinationType); builder.CreateStore(data, destination); return true; } bool FunctionGenSystemMemoryTranslationModel::EmitMemoryWrite(archsim::translate::llvm::LLVMInstructionTranslationContext& insn_ctx, int width, llvm::Value*& fault, llvm::Value* address, llvm::Value* value) { for (auto handler : insn_ctx.block.region.txln.twu.GetProcessor().GetMemoryModel().GetEventHandlers()) { handler->GetTranslator().EmitEventHandler(insn_ctx, *handler, archsim::abi::memory::MemoryModel::MemEventWrite, address, (uint8_t)width); } auto &types = insn_ctx.block.region.txln.types; llvm::Type *load_ty = NULL; switch(width) { case 1: load_ty = types.pi8; break; case 2: load_ty = types.pi16; break; case 4: load_ty = types.pi32; break; default: assert(false); } llvm::Value *fn_table = GetWriteFunctionTable(insn_ctx.block.region); llvm::Value *this_fun = GetFunFor(insn_ctx.block.region, fn_table, address); llvm::Value *rval = CallFn(insn_ctx.block.region, this_fun, address); fault = GetFault(insn_ctx.block.region, rval); llvm::Value *host_ptr = GetHostPtr(insn_ctx.block.region, rval); llvm::IRBuilder<> &builder = insn_ctx.block.region.builder; llvm::Value *faulty = builder.CreateICmpNE(fault, llvm::ConstantInt::get(types.i32, 0, false)); llvm::BasicBlock *success_block = llvm::BasicBlock::Create(builder.getContext(), "", builder.GetInsertBlock()->getParent()); insn_ctx.block.region.EmitLeaveInstruction(archsim::translate::llvm::LLVMRegionTranslationContext::RequireInterpret, insn_ctx.tiu.GetOffset(), faulty, success_block); builder.SetInsertPoint(success_block); host_ptr = builder.CreatePointerCast(host_ptr, load_ty); insn_ctx.AddAliasAnalysisNode((llvm::Instruction*)host_ptr, archsim::translate::llvm::TAG_MEM_ACCESS); builder.CreateStore(value, host_ptr); return true; } bool FunctionGenSystemMemoryTranslationModel::EmitNonPrivilegedRead(archsim::translate::llvm::LLVMInstructionTranslationContext& insn_ctx, int width, bool sx, llvm::Value*& fault, llvm::Value* address, llvm::Type* destinationType, llvm::Value* destination) { for (auto handler : insn_ctx.block.region.txln.twu.GetProcessor().GetMemoryModel().GetEventHandlers()) { handler->GetTranslator().EmitEventHandler(insn_ctx, *handler, archsim::abi::memory::MemoryModel::MemEventRead, address, (uint8_t)width); } auto &types = insn_ctx.block.region.txln.types; llvm::Type *load_ty = NULL; switch(width) { case 1: load_ty = types.pi8; break; case 2: load_ty = types.pi16; break; case 4: load_ty = types.pi32; break; default: assert(false); } llvm::Value *fn_table = GetReadUserFunctionTable(insn_ctx.block.region); llvm::Value *this_fun = GetFunFor(insn_ctx.block.region, fn_table, address); llvm::Value *rval = CallFn(insn_ctx.block.region, this_fun, address); fault = GetFault(insn_ctx.block.region, rval); llvm::Value *host_ptr = GetHostPtr(insn_ctx.block.region, rval); llvm::IRBuilder<> &builder = insn_ctx.block.region.builder; llvm::Value *faulty = builder.CreateICmpNE(fault, llvm::ConstantInt::get(types.i32, 0, false)); llvm::BasicBlock *success_block = llvm::BasicBlock::Create(builder.getContext(), "", builder.GetInsertBlock()->getParent()); insn_ctx.block.region.EmitLeaveInstruction(archsim::translate::llvm::LLVMRegionTranslationContext::RequireInterpret, insn_ctx.tiu.GetOffset(), faulty, success_block); builder.SetInsertPoint(success_block); host_ptr = builder.CreatePointerCast(host_ptr, load_ty); llvm::Value *data = builder.CreateLoad(host_ptr); insn_ctx.AddAliasAnalysisNode((llvm::Instruction*)host_ptr, archsim::translate::llvm::TAG_MEM_ACCESS); data = builder.CreateZExt(data, destinationType); builder.CreateStore(data, destination); return true; } bool FunctionGenSystemMemoryTranslationModel::EmitNonPrivilegedWrite(archsim::translate::llvm::LLVMInstructionTranslationContext& insn_ctx, int width, llvm::Value*& fault, llvm::Value* address, llvm::Value* value) { for (auto handler : insn_ctx.block.region.txln.twu.GetProcessor().GetMemoryModel().GetEventHandlers()) { handler->GetTranslator().EmitEventHandler(insn_ctx, *handler, archsim::abi::memory::MemoryModel::MemEventWrite, address, (uint8_t)width); } auto &types = insn_ctx.block.region.txln.types; llvm::Type *load_ty = NULL; switch(width) { case 1: load_ty = types.pi8; break; case 2: load_ty = types.pi16; break; case 4: load_ty = types.pi32; break; default: assert(false); } llvm::Value *fn_table = GetWriteUserFunctionTable(insn_ctx.block.region); llvm::Value *this_fun = GetFunFor(insn_ctx.block.region, fn_table, address); llvm::Value *rval = CallFn(insn_ctx.block.region, this_fun, address); fault = GetFault(insn_ctx.block.region, rval); llvm::Value *host_ptr = GetHostPtr(insn_ctx.block.region, rval); llvm::IRBuilder<> &builder = insn_ctx.block.region.builder; llvm::Value *faulty = builder.CreateICmpNE(fault, llvm::ConstantInt::get(types.i32, 0, false)); llvm::BasicBlock *success_block = llvm::BasicBlock::Create(builder.getContext(), "", builder.GetInsertBlock()->getParent()); insn_ctx.block.region.EmitLeaveInstruction(archsim::translate::llvm::LLVMRegionTranslationContext::RequireInterpret, insn_ctx.tiu.GetOffset(), faulty, success_block); builder.SetInsertPoint(success_block); host_ptr = builder.CreatePointerCast(host_ptr, load_ty); insn_ctx.AddAliasAnalysisNode((llvm::Instruction*)host_ptr, archsim::translate::llvm::TAG_MEM_ACCESS); builder.CreateStore(value, host_ptr); return true; } bool FunctionGenSystemMemoryTranslationModel::EmitPerformTranslation(archsim::translate::llvm::LLVMRegionTranslationContext &region, llvm::Value *virt_addr, llvm::Value *&phys_addr, llvm::Value *&fault) { llvm::Value *fn_table = GetReadFunctionTable(region); llvm::Value *this_fun = GetFunFor(region, fn_table, virt_addr); llvm::StructType *ret_type = llvm::StructType::get(region.txln.types.i32, region.txln.types.pi8, NULL); llvm::Type *paramtypes[] { region.txln.types.state_ptr, region.txln.types.i32, region.txln.types.i64 }; llvm::FunctionType *fun_type = llvm::FunctionType::get(ret_type, paramtypes, false); this_fun = region.builder.CreatePtrToInt(this_fun, region.txln.types.i64); this_fun = region.builder.CreateAdd(this_fun, llvm::ConstantInt::get(region.txln.types.i64, 10)); this_fun = region.builder.CreateIntToPtr(this_fun, fun_type->getPointerTo(0)); llvm::Value *rval = region.builder.CreateCall3(this_fun, region.values.state_val, virt_addr, llvm::ConstantInt::get(region.txln.types.i64, 0)); fault = GetFault(region, rval); phys_addr = GetHostPtr(region, rval); phys_addr = region.builder.CreatePtrToInt(phys_addr, region.txln.types.i64); phys_addr = region.builder.CreateTrunc(phys_addr, region.txln.types.i32); return true; } archsim::util::Counter64 fn_flush; void FunctionGenSystemMemoryTranslationModel::Flush() { mem_model->FlushCaches(); } void FunctionGenSystemMemoryTranslationModel::Evict(virt_addr_t virt_addr) { if(!dirty) return; uint32_t i = archsim::translate::profile::RegionArch::PageIndexOf(virt_addr); read_cache[i] = DefaultReadHandlerShunt; write_cache[i] = DefaultWriteHandlerSave; read_user_cache[i] = DefaultReadUserHandler; write_user_cache[i] = DefaultWriteUserHandler; } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetReadFunctionTable(archsim::translate::llvm::LLVMRegionTranslationContext& region) { llvm::IRBuilder<> &builder = region.builder; auto &types = region.txln.types; llvm::StructType *ret_type = llvm::StructType::get(types.i32, types.pi8, NULL); llvm::Type *paramtypes[] { types.state_ptr, types.i32 }; llvm::FunctionType *fun_type = llvm::FunctionType::get(ret_type, paramtypes, false); llvm::PointerType *fn_ptr = fun_type->getPointerTo(0)->getPointerTo(0); llvm::Value *table = builder.CreateStructGEP(region.values.state_val, gensim::CpuStateEntries::CpuState_smm_read_cache); table = builder.CreateLoad(table); table = builder.CreatePointerCast(table, fn_ptr); return table; } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetReadUserFunctionTable(archsim::translate::llvm::LLVMRegionTranslationContext& region) { llvm::IRBuilder<> &builder = region.builder; auto &types = region.txln.types; llvm::StructType *ret_type = llvm::StructType::get(types.i32, types.pi8, NULL); llvm::Type *paramtypes[] { types.state_ptr, types.i32 }; llvm::FunctionType *fun_type = llvm::FunctionType::get(ret_type, paramtypes, false); llvm::PointerType *fn_ptr = fun_type->getPointerTo(0)->getPointerTo(0); llvm::Value *table = builder.CreateStructGEP(region.values.state_val, gensim::CpuStateEntries::CpuState_smm_read_user_cache); table = builder.CreateLoad(table); table = builder.CreatePointerCast(table, fn_ptr); return table; } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetWriteFunctionTable(archsim::translate::llvm::LLVMRegionTranslationContext& region) { llvm::IRBuilder<> &builder = region.builder; auto &types = region.txln.types; llvm::StructType *ret_type = llvm::StructType::get(types.i32, types.pi8, NULL); llvm::Type *paramtypes[] { types.state_ptr, types.i32 }; llvm::FunctionType *fun_type = llvm::FunctionType::get(ret_type, paramtypes, false); llvm::PointerType *fn_ptr = fun_type->getPointerTo(0)->getPointerTo(0); llvm::Value *table = builder.CreateStructGEP(region.values.state_val, gensim::CpuStateEntries::CpuState_smm_write_cache); table = builder.CreateLoad(table); table = builder.CreatePointerCast(table, fn_ptr); return table; } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetWriteUserFunctionTable(archsim::translate::llvm::LLVMRegionTranslationContext& region) { llvm::IRBuilder<> &builder = region.builder; auto &types = region.txln.types; llvm::StructType *ret_type = llvm::StructType::get(types.i32, types.pi8, NULL); llvm::Type *paramtypes[] { types.state_ptr, types.i32 }; llvm::FunctionType *fun_type = llvm::FunctionType::get(ret_type, paramtypes, false); llvm::PointerType *fn_ptr = fun_type->getPointerTo(0)->getPointerTo(0); llvm::Value *table = builder.CreateStructGEP(region.values.state_val, gensim::CpuStateEntries::CpuState_smm_write_user_cache); table = builder.CreateLoad(table); table = builder.CreatePointerCast(table, fn_ptr); return table; } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetFunFor(archsim::translate::llvm::LLVMRegionTranslationContext& region, llvm::Value *fn_table, llvm::Value *address) { assert(Complete); llvm::IRBuilder<> &builder = region.builder; address = builder.CreateLShr(address, archsim::translate::profile::RegionArch::PageBits); llvm::Value *fn = builder.CreateGEP(fn_table, address); fn = builder.CreateLoad(fn); return fn; } llvm::Value *FunctionGenSystemMemoryTranslationModel::CallFn(archsim::translate::llvm::LLVMRegionTranslationContext& region, llvm::Value *fn, llvm::Value *address) { llvm::IRBuilder<> &builder = region.builder; return builder.CreateCall2(fn, region.values.state_val, address); } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetFault(archsim::translate::llvm::LLVMRegionTranslationContext& region, llvm::Value *rval) { llvm::IRBuilder<> &builder = region.builder; unsigned int indices[] = {0}; return builder.CreateExtractValue(rval, indices); } llvm::Value *FunctionGenSystemMemoryTranslationModel::GetHostPtr(archsim::translate::llvm::LLVMRegionTranslationContext& region, llvm::Value *rval) { llvm::IRBuilder<> &builder = region.builder; unsigned int indices[] = {1}; return builder.CreateExtractValue(rval, indices); }
38.307692
315
0.765536
[ "model" ]
3f9449e5c233256a5fbff4c6e346c7bcb28bb9ee
20,501
cpp
C++
SpaceDSL/source/SpMission.cpp
XiaoGongWei/SpaceDSL
340a297c417b6eaac6ba92f528a1451bd4283ad7
[ "MIT" ]
3
2019-01-02T15:36:44.000Z
2019-01-06T05:45:20.000Z
SpaceDSL/source/SpMission.cpp
XiaoGongWei/SpaceDSL
340a297c417b6eaac6ba92f528a1451bd4283ad7
[ "MIT" ]
null
null
null
SpaceDSL/source/SpMission.cpp
XiaoGongWei/SpaceDSL
340a297c417b6eaac6ba92f528a1451bd4283ad7
[ "MIT" ]
1
2020-05-23T07:12:19.000Z
2020-05-23T07:12:19.000Z
/************************************************************************ * Copyright (C) 2018 Niu ZhiYong * * 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. * * Author: Niu ZhiYong * Date:2018-07-27 * Description: * SpMission.cpp * * Purpose: * * Mission Management Class * * * Last modified: * * 2018-07-27 Niu Zhiyong (1st edition) * *************************************************************************/ #include "SpaceDSL/SpMission.h" #include "SpaceDSL/SpOrbitPredict.h" #include "SpaceDSL/SpUtils.h" #include "SpaceDSL/SpConst.h" namespace SpaceDSL { /************************************************* * Class type: The class of SpaceDSL Mission * Author: Niu ZhiYong * Date:2018-07-27 * Description: **************************************************/ Mission::Mission() { m_bIsEnvironmentInitialized = false; m_bIsPropagatorInitialized = false; m_bIsOptimizeInitialized = false; m_bIsMissionSequenceInitialized = false; m_bIsMultThread = false; m_SpaceVehicleNumber = 0; m_SpaceVehicleList.clear(); m_MissionThreadList.clear(); m_pEnvironment = nullptr; m_pPropagator = nullptr; m_pMissionThreadPool = new SpThreadPool(); m_DurationSec = 0; } Mission::~Mission() { for (auto pVehicle:m_SpaceVehicleList) { if (pVehicle != nullptr) delete pVehicle; } m_SpaceVehicleList.clear(); for (auto thread:m_MissionThreadList) { if (thread != nullptr) delete thread; } m_MissionThreadList.clear(); map<string, vector<double *> *>::iterator iter; for (iter = m_ProcessDataMap.begin(); iter != m_ProcessDataMap.end(); ++iter) { for(auto pData:(*(iter->second))) { delete pData; } delete iter->second; } m_ProcessDataMap.clear(); if (m_pEnvironment != nullptr) delete m_pEnvironment; if (m_pPropagator != nullptr) delete m_pPropagator; if (m_pMissionThreadPool != nullptr) delete m_pMissionThreadPool; } void Mission::InsertSpaceVehicle(const string &name, const CalendarTime& initialEpoch, const CartState& initialState, const double initialMass, const double dragCoef, const double dragArea, const double SRPCoef, const double SRPArea) { if (m_SpaceVehicleNumber != int(m_SpaceVehicleList.size())) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::InsertSpaceVehicle (SpaceVehicleNumber) != (SpaceVehicleList.Size)! "); } SpaceVehicle *pVehicle = new SpaceVehicle( name, initialEpoch, initialState, initialMass, dragCoef, dragArea, SRPCoef, SRPArea); ++m_SpaceVehicleNumber; m_SpaceVehicleList.push_back(pVehicle); vector<double *> *pOneVehicleData = new vector<double *>; m_ProcessDataMap.insert(pair<string, vector<double *> *>(name ,pOneVehicleData)); } void Mission::SetEnvironment(const SolarSysStarType centerStarType, const GravityModel::GravModelType gravModelType , const int maxDegree , const int maxOrder , const ThirdBodyGravitySign thirdBodyGravSign, const GeodeticCoordSystem::GeodeticCoordType geodeticType , const AtmosphereModel::AtmosphereModelType atmModelType , const double f107A , const double f107, double ap[], bool isUseDrag, bool isUseSRP) { if (m_pEnvironment == nullptr) { m_pEnvironment = new Environment( centerStarType, gravModelType, maxDegree, maxOrder, thirdBodyGravSign, geodeticType,atmModelType, f107A, f107, ap, isUseDrag, isUseSRP); } else { m_pEnvironment->SetCenterStarType(centerStarType); m_pEnvironment->SetGravModelType(gravModelType); m_pEnvironment->SetGravMaxDegree(maxDegree); m_pEnvironment->SetGravMaxOrder(maxOrder); m_pEnvironment->SetThirdBodySign(thirdBodyGravSign); m_pEnvironment->SetGeodeticCoordType(geodeticType); m_pEnvironment->SetAtmosphereModelType(atmModelType); m_pEnvironment->SetAverageF107(f107A); m_pEnvironment->SetDailyF107(f107); m_pEnvironment->SetGeomagneticIndex(ap); m_pEnvironment->SetIsUseDrag(isUseDrag); m_pEnvironment->SetIsUseSRP(isUseSRP); } m_bIsEnvironmentInitialized = true; } void Mission::SetPropagator(const IntegMethodType integMethodType, const double initialStep, const double accuracy, const double minStep, const double maxStep, const double maxStepAttempts, const bool bStopIfAccuracyIsViolated, const bool isUseNormalize) { if (m_pPropagator == nullptr) { m_pPropagator = new Propagator( integMethodType, initialStep, accuracy, minStep, maxStep, maxStepAttempts, bStopIfAccuracyIsViolated, isUseNormalize ); } else { m_pPropagator->SetIntegMethodType(integMethodType); m_pPropagator->SetInitialStep(initialStep); m_pPropagator->SetAccuracy(accuracy); m_pPropagator->SetMinStep(minStep); m_pPropagator->SetMaxStep(maxStep) ; m_pPropagator->SetMaxStepAttempts(maxStepAttempts) ; m_pPropagator->SetStopIfAccuracyIsViolated(bStopIfAccuracyIsViolated); m_pPropagator->SetIsUseNormalize(isUseNormalize) ; } m_bIsPropagatorInitialized = true; } void Mission::SetMissionSequence(const CalendarTime& initialEpoch, const CalendarTime& terminationEpoch) { m_InitialEpoch = initialEpoch; m_TerminationEpoch = terminationEpoch; m_DurationSec = (m_TerminationEpoch - m_InitialEpoch); m_bIsMissionSequenceInitialized = true; } const vector<SpaceVehicle *> &Mission::GetSpaceVehicleList() const { if (m_SpaceVehicleNumber != int(m_SpaceVehicleList.size()) || m_SpaceVehicleNumber <= 0) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Space Vehicle Initialise Error)! "); } return m_SpaceVehicleList; } int Mission::GetSpaceVehicleNumber() const { if (m_SpaceVehicleNumber != int(m_SpaceVehicleList.size()) || m_SpaceVehicleNumber <= 0) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Space Vehicle Initialise Error)! "); } return m_SpaceVehicleNumber; } Environment *Mission::GetEnvironment() const { if (m_bIsEnvironmentInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Environment Uninitialised)! "); } return m_pEnvironment; } Propagator *SpaceDSL::Mission::GetPropagator() const { if (m_bIsPropagatorInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Propagator Uninitialised)! "); } return m_pPropagator; } const CalendarTime &Mission::GetInitialEpoch() const { if (m_bIsMissionSequenceInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Mission Sequence Uninitialised)! "); } return m_InitialEpoch; } const CalendarTime &Mission::GetTerminationEpoch() const { if (m_bIsMissionSequenceInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Mission Sequence Uninitialised)! "); } return m_TerminationEpoch; } double Mission::GetDurationTime() const { if (m_bIsMissionSequenceInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Mission Sequence Uninitialised)! "); } return m_DurationSec; } const map<string, vector<double *> *> *Mission::GetProcessDataMap() const { return &m_ProcessDataMap; } void Mission::Start(bool bIsMultThread) { m_bIsMultThread = bIsMultThread; if (m_SpaceVehicleNumber != int(m_SpaceVehicleList.size()) || m_SpaceVehicleNumber <= 0) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Space Vehicle Initialise Error)! "); } if (m_bIsEnvironmentInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Environment Uninitialised)! "); } if (m_bIsPropagatorInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Propagator Uninitialised)! "); } if (m_bIsMissionSequenceInitialized == false) { throw SPException(__FILE__, __FUNCTION__, __LINE__, "Mission::Start (Mission Sequence Uninitialised)! "); } if (m_bIsMultThread == false) { auto pMissionThread = new MissionThread(); pMissionThread->Initializer(this, &m_SpaceVehicleList, m_pEnvironment, m_pPropagator, &m_ProcessDataMap); pMissionThread->Start(); pMissionThread->Wait(); } else { m_pMissionThreadPool->SetMaxThreadCount(int(GetHardwareConcurrency())); for (int id = 0; id < int(m_SpaceVehicleList.size()); ++id) { auto pMissionThread = new MissionThread(); pMissionThread->Initializer(this, &m_SpaceVehicleList, m_pEnvironment, m_pPropagator, &m_ProcessDataMap, id); m_MissionThreadList.push_back(pMissionThread); m_pMissionThreadPool->Start(pMissionThread); } m_pMissionThreadPool->WaitForDone(); } } void Mission::Reset() { m_bIsEnvironmentInitialized = false; m_bIsPropagatorInitialized = false; m_bIsOptimizeInitialized = false; m_bIsMultThread = false; m_SpaceVehicleNumber = 0; m_DurationSec = 0; for (auto pVehicle:m_SpaceVehicleList) { if (pVehicle != nullptr) delete pVehicle; } m_SpaceVehicleList.clear(); for (auto thread:m_MissionThreadList) { if (thread != nullptr) delete thread; } m_MissionThreadList.clear(); map<string, vector<double *> *>::iterator iter; for (iter = m_ProcessDataMap.begin(); iter != m_ProcessDataMap.end(); ++iter) { for(auto pData:(*(iter->second))) { delete pData; } delete iter->second; } m_ProcessDataMap.clear(); if (m_pEnvironment != nullptr) { delete m_pEnvironment; m_pEnvironment = nullptr; } if (m_pPropagator != nullptr) { delete m_pPropagator; m_pPropagator = nullptr; } } /************************************************* * Class type: Mission Thread Run in Mission Class * Author: Niu ZhiYong * Date:2018-07-27 * Description: **************************************************/ MissionThread::MissionThread() { m_SpaceVehicleID = -1; m_pMission = nullptr; m_pSpaceVehicleList = nullptr; m_pEnvironment = nullptr; m_pPropagator = nullptr; m_pProcessDataMap = nullptr; } MissionThread::~MissionThread() { } void SpaceDSL::MissionThread::Initializer(Mission *pMission, vector<SpaceVehicle *> *spaceVehicleList, Environment *pEnvironment, Propagator *pPropagator, map<string, vector<double *> *> *pProcessDataMap, int spaceVehicleID) { m_pMission = pMission; m_pSpaceVehicleList = spaceVehicleList; m_pEnvironment = pEnvironment; m_pPropagator = pPropagator; m_pProcessDataMap = pProcessDataMap; m_SpaceVehicleID = spaceVehicleID; } void MissionThread::SaveProcessDataLine(SpaceVehicle *pVehicle, const double Mjd, const Vector3d &pos, const Vector3d &vel, const GeodeticCoord &LLA, const double mass) { double *processData = new double[11]; auto processDataList = m_pProcessDataMap->find(pVehicle->GetName())->second; CartState currentState(pos, vel); pVehicle->SetTime(Mjd); pVehicle->SetCartState(currentState); pVehicle->SetMass(mass); processData[0] = Mjd; processData[1] = pos(0); processData[2] = pos(1); processData[3] = pos(2); processData[4] = vel(0); processData[5] = vel(1); processData[6] = vel(2); processData[7] = LLA.Latitude(); processData[8] = LLA.Longitude(); processData[9] = LLA.Altitude(); processData[10] = mass; processDataList->push_back(processData); } void MissionThread::Run() { GeodeticCoordSystem GEO(GeodeticCoordSystem::GeodeticCoordType::E_WGS84System); GeodeticCoord LLA; OrbitPredictConfig predictConfig; double Mjd_UTC0 ; double Mjd_UTC; Vector3d pos,vel; double mass; OrbitPredict orbit; if (m_SpaceVehicleID == -1) { for (auto pVehicle:(*m_pSpaceVehicleList)) { Mjd_UTC0 = pVehicle->GetEpoch(); Mjd_UTC = Mjd_UTC0; pos = pVehicle->GetCartState().Pos(); vel = pVehicle->GetCartState().Vel(); mass = pVehicle->GetMass(); predictConfig.Initializer(Mjd_UTC0, m_pEnvironment->GetCenterStarType(), m_pPropagator->GetIsUseNormalize(), m_pEnvironment->GetGravModelType(), m_pEnvironment->GetGravMaxDegree() , m_pEnvironment->GetGravMaxOrder(), m_pEnvironment->GetThirdBodySign(), m_pEnvironment->GetGeodeticCoordType(), m_pEnvironment->GetAtmosphereModelType(), pVehicle->GetDragCoef(), pVehicle->GetDragArea(), m_pEnvironment->GetAverageF107(), m_pEnvironment->GetDailyF107(), m_pEnvironment->GetGeomagneticIndex(), pVehicle->GetSRPCoef(), pVehicle->GetSRPArea(), m_pEnvironment->GetIsUseDrag(), m_pEnvironment->GetIsUseSRP()); LLA = GEO.GetGeodeticCoord(pos, Mjd_UTC); this->SaveProcessDataLine(pVehicle, Mjd_UTC, pos, vel, LLA, mass); double step = m_pPropagator->GetInitialStep(); for (int i = 0; i < m_pMission->m_DurationSec/step; ++i) { predictConfig.Update(Mjd_UTC); orbit.OrbitStep(predictConfig,step, E_RungeKutta4, mass, pos, vel); Mjd_UTC = Mjd_UTC0 + (i+1) * step/DayToSec; LLA = GEO.GetGeodeticCoord(pos, Mjd_UTC); this->SaveProcessDataLine(pVehicle, Mjd_UTC, pos, vel, LLA, mass); } } } else { if (m_SpaceVehicleID >= int(m_pSpaceVehicleList->size())) throw SPException(__FILE__, __FUNCTION__, __LINE__, "MissionThread::Run (m_SpaceVehicleID >= m_pSpaceVehicleList->size())"); auto pVehicle = (*m_pSpaceVehicleList)[m_SpaceVehicleID]; Mjd_UTC0 = pVehicle->GetEpoch(); Mjd_UTC = Mjd_UTC0; pos = pVehicle->GetCartState().Pos(); vel = pVehicle->GetCartState().Vel(); mass = pVehicle->GetMass(); predictConfig.Initializer(Mjd_UTC0, m_pEnvironment->GetCenterStarType(), m_pPropagator->GetIsUseNormalize(), m_pEnvironment->GetGravModelType(), m_pEnvironment->GetGravMaxDegree() , m_pEnvironment->GetGravMaxOrder(), m_pEnvironment->GetThirdBodySign(), m_pEnvironment->GetGeodeticCoordType(), m_pEnvironment->GetAtmosphereModelType(), pVehicle->GetDragCoef(), pVehicle->GetDragArea(), m_pEnvironment->GetAverageF107(), m_pEnvironment->GetDailyF107(), m_pEnvironment->GetGeomagneticIndex(), pVehicle->GetSRPCoef(), pVehicle->GetSRPArea(), m_pEnvironment->GetIsUseDrag(), m_pEnvironment->GetIsUseSRP()); LLA = GEO.GetGeodeticCoord(pos,Mjd_UTC); this->SaveProcessDataLine(pVehicle, Mjd_UTC, pos, vel, LLA, mass); double step = m_pPropagator->GetInitialStep(); for (int i = 0; i < m_pMission->m_DurationSec/step; ++i) { predictConfig.Update(Mjd_UTC); orbit.OrbitStep(predictConfig,step, E_RungeKutta4, mass, pos, vel); Mjd_UTC = Mjd_UTC0 + (i+1) * step/DayToSec; LLA = GEO.GetGeodeticCoord(pos,Mjd_UTC); this->SaveProcessDataLine(pVehicle, Mjd_UTC, pos, vel, LLA, mass); } } } }
38.608286
121
0.545925
[ "vector" ]
3f9ca20935c3b6ce5ca7f957e7249801aec7df3b
2,194
hpp
C++
code/szen/inc/szen/Game/Components/ParticleComponent.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
code/szen/inc/szen/Game/Components/ParticleComponent.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
code/szen/inc/szen/Game/Components/ParticleComponent.hpp
Sonaza/scyori
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
[ "BSD-3-Clause" ]
null
null
null
#ifndef SZEN_PARTICLECOMPONENT_HPP #define SZEN_PARTICLECOMPONENT_HPP #include <string> #include <vector> #include <memory> #include <SFML/Graphics.hpp> #include <szen/Game/Component.hpp> #include <Thor/Animation.hpp> #include <Thor/Particles.hpp> #include <Thor/Math.hpp> #include <Thor/Graphics.hpp> namespace sz { typedef std::unique_ptr<thor::ParticleSystem> ParticleSystemPtr; typedef thor::UniversalEmitter::Ptr ParticleEmitterPtr; class ShaderAsset; class ParticleComponent : public Component { friend class ParticleEntity; public: ParticleComponent(); ParticleComponent(const std::string &asset); virtual ~ParticleComponent(); void attached(); void update(); void parsePrefab(json::Value&); void createEmitter(); void setShader(const std::string &assetID); void setBlendMode(sf::BlendMode); void draw(sf::RenderTarget& target); void emit(const size_t amount); //protected: void prewarm(); void setColor(const sf::Color&); sf::Color getColor(); void setEmissionRate(float rate); void setLifetime(float time); void setLifetime(float start, float end); void setVelocity(sf::Vector2f vel); void setVelocityCone(float force, float direction_radians, float variance); void setRotation(float rot); void setRotation(float start, float end); void setRotationSpeed(float speed); void setRotationSpeed(float start, float end); void setScale(float scale); void setScale(float start, float end); // Fade in at "in * lifetime" seconds // Fade out at "out * lifetime" seconds void addFadeAffector(float in, float out); void addScaleAffector(float x, float y); void addForceAffector(float x, float y); void updatePosition(); private: sf::Color m_color; ShaderAsset* m_shaderAsset; sf::Time m_lifetime; sf::RenderStates m_renderStates; ParticleSystemPtr m_particleSystem; ParticleEmitterPtr m_emitter; std::shared_ptr<sf::Texture> m_particleTexture; struct Affectors { thor::Affector::Ptr fade; thor::Affector::Ptr force; thor::Affector::Ptr scale; } m_affectors; PausableClock m_particleClock; }; } #endif // SZEN_PARTICLECOMPONENT_HPP
20.12844
77
0.730173
[ "vector" ]
3fa4c77317aeb17ad75d4cda3de32e58912898c5
1,894
hpp
C++
include/scp/Scene.hpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
1
2022-01-31T22:20:01.000Z
2022-01-31T22:20:01.000Z
include/scp/Scene.hpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
null
null
null
include/scp/Scene.hpp
scp-studios/scp-game-framework
17ffb68a50d834e490d387028f05add9f5391ea5
[ "MIT" ]
null
null
null
#ifndef E1807A30_2BAB_4F2B_812D_33D2F4822F2F #define E1807A30_2BAB_4F2B_812D_33D2F4822F2F // Note: This not supposed to represent a Scene class that you would see in a // game engine. It is supposed to be simply a container for a state in the // game and to handle stuff like events and stuff. #include <scp/core-pch.hpp> #include <scp/events.hpp> #include <scp/scp.hpp> namespace scp { class SCPGFFUNC Scene { public: // The window has to be a friend class in order for it to pass events friend class Window; // Default Constructor. It will serve as the "onCreate" function Scene() = default; // Templated version template<typename SceneType, typename... ArgTypes> static void setActive(ArgTypes... args) { if (activeScene != nullptr) { delete activeScene; } activeScene = new SceneType(args...); } // Update the active scene static void updateActive(double deltaTime); // Render the active scene static void renderActive(); // Destructor. It will serve as the "onDestroy" function. virtual ~Scene() = default; private: // Called every iteration of the update thread virtual void onUpdate(double deltaTime); // Rendering virtual void render(); // Events virtual void onKeyPress(events::KeyPressEvent& event); virtual void onMouseClick(events::MouseButtonEvent& event); virtual void onMouseMove(events::MouseMoveEvent& event); virtual void onMouseScroll(events::MouseScrollEvent& event); // The currently active scene static Scene* activeScene; }; } #endif /* E1807A30_2BAB_4F2B_812D_33D2F4822F2F */
29.138462
77
0.613516
[ "render" ]
3fa94c4b69b4f5797c1c2dcf348f0a6759c96b11
8,095
cpp
C++
src/proclib.cpp
mentebinaria/maProc
75f7877b21ed01df5541cc83ccdc2f03739fda0f
[ "BSD-2-Clause" ]
10
2022-03-07T20:46:44.000Z
2022-03-22T22:29:55.000Z
src/proclib.cpp
mentebinaria/maProc
75f7877b21ed01df5541cc83ccdc2f03739fda0f
[ "BSD-2-Clause" ]
1
2022-03-22T15:16:54.000Z
2022-03-25T23:09:28.000Z
src/proclib.cpp
mentebinaria/maProc
75f7877b21ed01df5541cc83ccdc2f03739fda0f
[ "BSD-2-Clause" ]
2
2022-03-07T20:46:57.000Z
2022-03-08T01:26:00.000Z
#include "include/proclib.hpp" #include "include/filedescriptor.hpp" #include <unordered_map> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> /** * @brief routine to analyze memory, * with the appropriate p_types char, int, int16, int64,'string'I * * @param p_buffer memory for analysis * @param p_find what to look for * @param p_offsets where to p_start for counting * @param p_type p_type char, int64 ... * @return int */ void RemoteProcess::Analyse(char *p_buffer, std::string p_find, off_t p_offsets, uint8_t p_type, uint64_t p_lenght, std::vector<off_t> &p_save) { switch (p_type) { case sizeof(char): p_save.clear(); if (!isdigit(p_find[0]) && p_find.size() == 1) { for (uint64_t i = 0; i < p_lenght; i++) { if (p_buffer[i] == p_find[0]) p_save.push_back(p_offsets); p_offsets++; } } else throw std::runtime_error("Error, caracter '" + p_find + "' not valid"); break; case sizeof(int): p_save.clear(); { try { int p_findP = std::stoi(p_find); if (p_findP < INT_MAX && p_findP > 0) { for (uint64_t i = 0; i < p_lenght; i++) { if ((int)p_buffer[i] == p_findP) p_save.push_back(p_offsets); p_offsets++; } } } catch (std::exception &error) { throw std::runtime_error("Error, caracter '" + p_find + "' not valid"); } } break; case sizeof(uint16_t): p_save.clear(); { try { int16_t p_findP = (uint16_t)std::stoi(p_find); if (p_findP <= UINT16_MAX && p_findP > 0) { for (uint64_t i = 0; i < p_lenght; i++) { if ((uint16_t)p_buffer[i] == p_findP) p_save.push_back(p_offsets); p_offsets++; } } } catch (std::exception &error) { throw std::runtime_error("Error, caracter '" + p_find + "' not valid"); } } break; case sizeof(uint64_t): p_save.clear(); { try { int64_t p_findP = (uint64_t)std::stoi(p_find); if (p_findP < UINT64_MAX && p_findP > 0) { for (uint64_t i = 0; i < p_lenght; i++) { if ((int64_t)p_buffer[i] == p_findP) p_save.push_back(p_offsets); p_offsets++; } } } catch (std::exception &error) { throw std::runtime_error("Error, caracter '" + p_find + "' not valid"); } } break; case sizeof(std::string): p_save.clear(); { std::string str; for (uint64_t it = 0; it < p_lenght; it++) { if (p_buffer[it] == p_find[0]) { for (std::size_t i = 0; i < p_find.size(); i++) str += p_buffer[it + i]; if (str == p_find) p_save.push_back(p_offsets); } p_offsets++; } } break; default: break; } } RemoteProcess::RemoteProcess() { m_status = 0; } /** * @brief Attach to a remote process * @param pid_t p_pid to be attached inside the system * @return int * */ int RemoteProcess::openProcess(pid_t p_pid) { m_proc.pid = p_pid; m_status = OPEN_SUCCESS; struct stat st; m_proc.dirmem = PROC + std::to_string(m_proc.pid) + "/mem"; if (stat("/proc/self/mem", &st) == 0) { m_proc.fd = open(m_proc.dirmem.data(), O_RDWR); if (m_proc.fd == -1) m_status = OPEN_FAIL; } else m_status = OPEN_FAIL; return m_status; } /** * @brief Destroy the Remote Process:: Remote Process object * */ RemoteProcess::~RemoteProcess() { close(m_proc.fd); } /** * @brief read memory using pread * * @param p_start start offset for read mem * @param p_stop offset for stop read start + size * @param p_data where will the reading be stored in memory * @return int if read sucess return READ_SUCCESS else READ_FAIL */ int RemoteProcess::readMem(off_t p_start, off_t p_stop, Data *p_data) { if (m_status == OPEN_FAIL) return READ_FAIL; size_t bsize = p_stop - p_start; pread(m_proc.fd, p_data->m_buff, bsize, p_start); return READ_SUCCESS; } /** * @brief Write into a remote process memory * * @param p_start p_offsets to be written into * @param p_data class with the target data to be write * @return int * * If the remote memory cannot be written, it will returns WRITE_FAIL, otherwise WRITE_SUCESS. The error cause can be found at the * errno variable, which is set by ptrace. */ int RemoteProcess::writeMem(off_t p_start, Data *p_data) { if (m_status == OPEN_FAIL) return WRITE_FAIL; ssize_t write = pwrite(m_proc.fd, reinterpret_cast<const void *>(p_data->m_buff), p_data->m_size, p_start); if (write == -1) return WRITE_FAIL; return WRITE_SUCCESS; } /** * @brief find values ​​in memory * * @param p_start offset for start * @param p_length size for stop read * @param p_type type for search value * @param p_find what find * @param p_offsets store the offsets * @return int */ int RemoteProcess::findMem(off_t p_start, uint64_t p_length, uint8_t p_type, std::string p_find, std::vector<off_t> &p_offsets) { if (m_status == OPEN_FAIL) { throw std::runtime_error("Error not open file " + m_proc.dirmem); return OPEN_FAIL; } else if (!m_hasProcMem) { char *p_buffer; try { p_buffer = new char[p_length]; memset(p_buffer, 0, p_length); // clear memory for use memory if (pread(m_proc.fd, p_buffer, p_length, p_start) == -1) return READ_FAIL; else Analyse(p_buffer, p_find, p_start, p_type, p_length, p_offsets); } catch (std::exception &error) { delete[] p_buffer; throw std::runtime_error(error.what()); return READ_FAIL; } delete[] p_buffer; } else { throw std::runtime_error("Not supported p_find memory, directory 'proc/" + std::to_string(m_proc.pid) + "/mem' not found, \n maProc not support for read mem with ptrace"); return READ_FAIL; } return READ_SUCCESS; } /** * @brief stop process * * @param p_enable if stopped is return cont set true parameter */ void RemoteProcess::stopPid(bool p_enable) { if (p_enable == true && m_proc.pid != 0) kill(m_proc.pid, SIGSTOP); else kill(m_proc.pid, SIGCONT); } /** * @brief kill process * */ void RemoteProcess::killPid() { kill(m_proc.pid, SIGKILL); } // // part of the code in which we are going // to move the p_buffer for writing to memory and reading // Data::Data(uint p_size) { m_size = p_size; m_buff = new uint8_t[m_size]; externalRef = false; m_curr = 0; } Data::Data(uint8_t *p_buff, uint p_size) { externalRef = true; m_buff = p_buff; m_size = p_size; m_curr = 0; } Data::~Data() { if (!externalRef) delete[] m_buff; } void Data::write(uint8_t p_b) { if (m_curr++ == m_size) return; m_buff[m_curr] = p_b; } uint8_t *Data::read() { return (uint8_t *)m_buff; } void Data::clear() { memset(m_buff, 0, m_size); }
24.984568
179
0.529216
[ "object", "vector" ]
3fac7745aaaa5fadba35dd279a574aeac3f76ccc
2,139
cpp
C++
datasets/github_cpp_10/1/85.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/1/85.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/1/85.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
/* * BFS Algorithm. * Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. * It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key') * and explores the neighbor nodes first, before moving to the next level neighbors. * BFS was invented in the late 1950s by E. F. Moore, who used it to find the shortest path out of a maze, * and discovered independently by C. Y. Lee as a wire routing algorithm (published 1961). */ #include "BFS.h" using namespace std; /* * BFS constructor. */ BFS::BFS(string filePath):Graph(filePath) { for(unsigned long i=0; i<this->vertexsNum; i++) { this->visited.push_back(false); } } /* * Clean visit record. */ void BFS::cleanVisitRecord(void) { for(vector<bool>::iterator iter=this->visited.begin(); iter!=this->visited.end(); ++iter) { (*iter)=false; } } /* * Breadth-First-Search. * Fake code: * A non-recursive implementation of BFS: 1 Breadth-First-Search(Graph, root): 2 3 for each node n in Graph: 4 n.distance = INFINITY 5 n.parent = NIL 6 7 create empty queue Q 8 9 root.distance = 0 10 Q.enqueue(root) 11 12 while Q is not empty: 13 14 current = Q.dequeue() 15 16 for each node n that is adjacent to current: 17 if n.distance == INFINITY: 18 n.distance = current.distance + 1 19 n.parent = current 20 Q.enqueue(n) */ void BFS::goBFS(unsigned long startVertex) { this->cleanVisitRecord(); queue<unsigned long> Q; Q.push(startVertex); this->visited[startVertex]=true; cout<<"Visit:"<<startVertex<<endl; while(!Q.empty()) { unsigned long rowIndex=0; unsigned long columnIndex=0; rowIndex=Q.front(); Q.pop(); for(columnIndex=0; columnIndex<this->vertexsNum; columnIndex++) { if(this->adjacentMatrix[rowIndex][columnIndex]!=0 && this->visited[columnIndex]==false) { cout<<"Visit:"<<columnIndex<<endl; this->visited[columnIndex]=true; Q.push(columnIndex); } } } }
25.771084
105
0.640019
[ "vector" ]
3fad9bc865e9cd491d767fac1866de94f7a877b5
6,617
cpp
C++
src/sMQTTClient.cpp
terrorsl/sMQTTBroker
643d6328c16c7fcc4a9f3958749fb98dcad94527
[ "MIT" ]
10
2021-10-10T23:25:47.000Z
2022-03-16T15:55:39.000Z
src/sMQTTClient.cpp
terrorsl/sMQTTBroker
643d6328c16c7fcc4a9f3958749fb98dcad94527
[ "MIT" ]
17
2021-10-09T13:40:26.000Z
2022-03-16T10:35:49.000Z
src/sMQTTClient.cpp
terrorsl/sMQTTBroker
643d6328c16c7fcc4a9f3958749fb98dcad94527
[ "MIT" ]
null
null
null
#include<sMQTTBroker.h> sMQTTClient::sMQTTClient(sMQTTBroker *parent, TCPClient &client):mqtt_connected(false), _parent(parent) { _client = client; keepAlive = 25; updateLiveStatus(); }; sMQTTClient::~sMQTTClient() { //SMQTT_LOGD("free _client"); //delete _client; }; void sMQTTClient::update() { while (_client.available()>0) { message.incoming(_client.read()); if (message.type()) { processMessage(); message.reset(); break; } } unsigned long currentMillis; #if defined(ESP8266) || defined(ESP32) currentMillis = millis(); #endif if (keepAlive != 0 && aliveMillis < currentMillis) { SMQTT_LOGD("aliveMillis(%d) < currentMillis(%d)", aliveMillis, currentMillis); _client.stop(); } //else // SMQTT_LOGD("time %d", aliveMillis - currentMillis); }; bool sMQTTClient::isConnected() { return _client.connected(); }; void sMQTTClient::write(const char* buf, size_t length) { _client.write(buf, length); } void sMQTTClient::processMessage() { if (message.type() <= sMQTTMessage::Type::Disconnect) { SMQTT_LOGD("message type:%s(0x%x)", debugMessageType[message.type() / 0x10], message.type()); } const char *header = message.getVHeader(); switch (message.type()) { case sMQTTMessage::Type::Connect: { if (mqtt_connected) { _client.stop(); break; } unsigned char status = 0; if (strncmp("MQTT", header + 2, 4)) { //TODO: close connection } if (header[6] != 0x04) { status = sMQTTConnReturnUnacceptableProtocolVersion; // Level 3.1.1 } else { unsigned short len; mqtt_flags = header[7]; keepAlive = (header[8] << 8) | header[9]; const char *payload = &header[10]; message.getString(payload, len); clientId = std::string(payload,len); payload += len; SMQTT_LOGD("message clientId:%s", clientId.c_str()); SMQTT_LOGD("message keepTime:%d", keepAlive); if (mqtt_flags&sMQTTWillFlag) { //topic message.getString(payload, len); //willTopic = std::string(payload, len); payload += len; //message message.getString(payload, len); //willMessage = std::string(payload, len); payload += len; } std::string username; if (mqtt_flags&sMQTTUserNameFlag) { message.getString(payload, len); username = std::string(payload, len); SMQTT_LOGD("message user:%s", username.c_str()); payload += len; } std::string password; if (mqtt_flags&sMQTTPasswordFlag) { message.getString(payload, len); password = std::string(payload, len); SMQTT_LOGD("message password:%s", password.c_str()); payload += len; } if (_parent->isClientConnected(this) == false) { sMQTTNewClientEvent event(this, username, password); if(_parent->onEvent(&event)==false || _parent->onConnect(this, username, password) == false) status = sMQTTConnReturnBadUsernameOrPassword; } else status = sMQTTConnReturnIdentifierRejected; } sMQTTMessage msg(sMQTTMessage::Type::ConnAck); msg.add(0); // Session present (not implemented) msg.add(status); // Connection accepted msg.sendTo(this); if (status) _client.stop(); else mqtt_connected = true; } break; case sMQTTMessage::Type::Publish: { unsigned char qos = message.QoS(); unsigned short len; const char *payload = header; message.getString(payload, len); const char *topicName = payload; std::string _topicName(topicName, len); payload += len; char packeteIdent[2]={0}; if (qos) { packeteIdent[0] = payload[0]; packeteIdent[1] = payload[1]; payload += 2; } len = message.end() - payload; std::string _payload(payload, len); sMQTTTopic topic(_topicName,_payload, qos); if (message.isRetained()) _parent->updateRetainedTopic(&topic); switch (qos) { case 1: { sMQTTMessage msg(sMQTTMessage::Type::PubAck); msg.add(packeteIdent[0]); msg.add(packeteIdent[1]); msg.sendTo(this); } break; case 2: { sMQTTMessage msg(sMQTTMessage::Type::PubRec); msg.add(packeteIdent[0]); msg.add(packeteIdent[1]); msg.sendTo(this); } break; } _parent->publish(this,&topic, &message); } break; case sMQTTMessage::Type::PubAck: { } break; case sMQTTMessage::Type::PubRel: { const char *payload = header; sMQTTMessage msg(sMQTTMessage::Type::PubComp); msg.add(payload[0]); msg.add(payload[1]); msg.sendTo(this); } break; case sMQTTMessage::Type::Subscribe: { #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG unsigned short msg_id = (header[0] << 8) | header[1]; SMQTT_LOGD("message id:%d", msg_id); #endif const char *payload = header + 2; std::vector<char> qoss; while (payload < message.end()) { unsigned short len; message.getString(payload, len); // Topic std::string topic(payload, len); SMQTT_LOGD("message topic:%s", topic.c_str()); payload += len; unsigned char qos = *payload++; if (_parent->subscribe(this, topic.c_str()) == false) { SMQTT_LOGD("subscribe failed"); qos = 0x80; } qoss.push_back(qos); } sMQTTMessage msg(sMQTTMessage::Type::SubAck); msg.add(header[0]); msg.add(header[1]); for (int i = 0; i<qoss.size(); i++) msg.add(qoss[i]); msg.sendTo(this); } break; case sMQTTMessage::Type::UnSubscribe: { //unsigned short msg_id = (header[0] << 8) | header[1]; //SMQTT_LOGD("message id:%d", msg_id); const char *payload = header + 2; while (payload < message.end()) { unsigned short len; message.getString(payload, len); // Topic //SMQTT_LOGD("message topic:%s", std::string(payload, len).c_str()); _parent->unsubscribe(this, std::string(payload, len).c_str()); payload += len; //unsigned char qos = *payload++; } sMQTTMessage msg(sMQTTMessage::Type::UnSuback); msg.add(header[0]); msg.add(header[1]); msg.sendTo(this); } break; case sMQTTMessage::Type::Disconnect: { mqtt_connected = false; _client.stop(); } break; case sMQTTMessage::Type::PingReq: { sMQTTMessage msg(sMQTTMessage::Type::PingResp); msg.sendTo(this); } break; default: { SMQTT_LOGD("unknown message", message.type()); mqtt_connected = false; _client.stop(); } break; } updateLiveStatus(); }; void sMQTTClient::updateLiveStatus() { if (keepAlive) #if defined(ESP8266) || defined(ESP32) //aliveMillis = (keepAlive*1.5) * 1000 + millis(); aliveMillis = keepAlive*1500 + millis(); #else aliveMillis = 0; #endif else aliveMillis = 0; };
22.896194
103
0.637902
[ "vector" ]