hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
000ab09754544ba8048451e7f2e38a34770463de
4,020
hpp
C++
src/lib/DriverFramework/framework/include/DFList.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
24
2019-08-13T02:39:01.000Z
2022-03-03T15:44:54.000Z
src/lib/DriverFramework/framework/include/DFList.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
4
2020-11-16T02:03:09.000Z
2021-08-19T08:16:48.000Z
src/lib/DriverFramework/framework/include/DFList.hpp
shening/PX4-1.34-Vision-Fix
1e696bc1c2dae71ba7b277d40106a5b6c0a1a050
[ "BSD-3-Clause" ]
11
2019-07-28T09:11:40.000Z
2022-03-17T08:08:27.000Z
/********************************************************************** * Copyright (c) 2015 Mark Charlebois * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) 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 Dronecode Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #pragma once #include "DisableCopy.hpp" #include "SyncObj.hpp" namespace DriverFramework { class DFPointerList : public DisableCopy { public: class DFListNode; typedef DFListNode *Index; class DFListNode { public: DFListNode(void *item); ~DFListNode(); Index m_next; void *m_item; }; DFPointerList(); virtual ~DFPointerList(); unsigned int size(); bool pushBack(void *item); bool pushFront(void *item); virtual Index erase(Index idx); virtual void clear(); bool empty(); Index next(Index &idx); void *get(Index idx); // Caller must lock before using list SyncObj m_sync; private: Index m_head; Index m_end; unsigned int m_size; }; template <class T> class DFManagedList : public DFPointerList { public: DFManagedList() : DFPointerList() {} virtual ~DFManagedList() { Index idx = nullptr; idx = next(idx); while (idx != nullptr) { T *tmp = get(idx); delete tmp; idx = next(idx); } } T *get(Index idx) { return static_cast<T *>(DFPointerList::get(idx)); } virtual Index erase(Index idx) { if (idx != nullptr) { T *tmp = get(idx); delete tmp; return DFPointerList::erase(idx); } return idx; } virtual void clear() { Index idx = nullptr; idx = next(idx); while (idx != nullptr) { T *tmp = get(idx); delete tmp; idx = next(idx); } DFPointerList::clear(); } bool pushBack(T *item) { return DFPointerList::pushBack((void *)item); } bool pushFront(T *item) { return DFPointerList::pushFront((void *)item); } }; class DFUIntList : public DisableCopy { public: class DFUIntListNode; typedef DFUIntListNode *Index; class DFUIntListNode { public: DFUIntListNode(unsigned int item); ~DFUIntListNode(); Index m_next; unsigned int m_item; }; DFUIntList(); ~DFUIntList(); unsigned int size(); bool pushBack(unsigned int item); bool pushFront(unsigned int item); Index erase(Index idx); void clear(); bool empty(); Index next(Index &idx); bool get(Index idx, unsigned int &val); // Caller must lock before using list SyncObj m_sync; private: Index m_head; Index m_end; unsigned int m_size; }; };
20.201005
74
0.687065
shening
000d264537608ffb9769272cd044e08410cec520
6,507
cpp
C++
Source.cpp
kenjinote/GetTwitterBearerToken
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
[ "MIT" ]
null
null
null
Source.cpp
kenjinote/GetTwitterBearerToken
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
[ "MIT" ]
null
null
null
Source.cpp
kenjinote/GetTwitterBearerToken
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
[ "MIT" ]
null
null
null
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #pragma comment(lib, "wininet") #pragma comment(lib, "crypt32") #include <windows.h> #include <commctrl.h> #include <wininet.h> #include "json11.hpp" TCHAR szClassName[] = TEXT("Window"); BOOL GetStringFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPSTR lpszValue, int nSizeValue) { std::string src(lpszJson); std::string err; json11::Json v = json11::Json::parse(src, err); if (err.size()) return FALSE; lpszValue[0] = 0; strcpy_s(lpszValue, nSizeValue, v[lpszKey].string_value().c_str()); return strlen(lpszValue) > 0; } BOOL String2Base64(LPWSTR lpszBase64String, DWORD dwSize) { BOOL bReturn = FALSE; DWORD dwLength = WideCharToMultiByte(CP_ACP, 0, lpszBase64String, -1, 0, 0, 0, 0); LPSTR lpszStringA = (LPSTR)GlobalAlloc(GPTR, dwLength * sizeof(char)); WideCharToMultiByte(CP_ACP, 0, lpszBase64String, -1, lpszStringA, dwLength, 0, 0); DWORD dwResult = 0; if (CryptBinaryToStringW((LPBYTE)lpszStringA, dwLength - 1, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, 0, &dwResult)) { if (dwResult <= dwSize && CryptBinaryToStringW((LPBYTE)lpszStringA, dwLength - 1, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, lpszBase64String, &dwResult)) { bReturn = TRUE; } } GlobalFree(lpszStringA); return bReturn; } BOOL GetTwitterBearerToken(IN LPCWSTR lpszConsumerKey, IN LPCWSTR lpszConsumerSecret, OUT LPWSTR lpszBearerToken, IN DWORD dwSize) { HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hInternet == NULL) { return FALSE; } HINTERNET hSession = InternetConnectW(hInternet, L"api.twitter.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (hSession == NULL) { InternetCloseHandle(hInternet); return FALSE; } HINTERNET hRequest = HttpOpenRequestW(hSession, L"POST", L"/oauth2/token", NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE, 0); if (hRequest == NULL) { InternetCloseHandle(hSession); InternetCloseHandle(hInternet); return FALSE; } WCHAR credential[1024]; wsprintfW(credential, L"%s:%s", lpszConsumerKey, lpszConsumerSecret); String2Base64(credential, sizeof(credential)); WCHAR header[1024]; wsprintfW(header, L"Authorization: Basic %s\r\nContent-Type: application/x-www-form-urlencoded;charset=UTF-8", credential); CHAR param[] = "grant_type=client_credentials"; if (!HttpSendRequestW(hRequest, header, (DWORD)wcslen(header), param, (DWORD)strlen(param))) { InternetCloseHandle(hRequest); InternetCloseHandle(hSession); InternetCloseHandle(hInternet); return FALSE; } BOOL bResult = FALSE; WCHAR szBuffer[256] = { 0 }; DWORD dwBufferSize = _countof(szBuffer); HttpQueryInfoW(hRequest, HTTP_QUERY_CONTENT_LENGTH, szBuffer, &dwBufferSize, NULL); DWORD dwContentLength = _wtol(szBuffer); LPBYTE lpByte = (LPBYTE)GlobalAlloc(0, dwContentLength + 1); DWORD dwReadSize; InternetReadFile(hRequest, lpByte, dwContentLength, &dwReadSize); lpByte[dwReadSize] = 0; CHAR szAccessToken[256]; if (GetStringFromJSON((LPCSTR)lpByte, "access_token", szAccessToken, _countof(szAccessToken))) { DWORD nLength = MultiByteToWideChar(CP_THREAD_ACP, 0, szAccessToken, -1, 0, 0); if (nLength <= dwSize) { MultiByteToWideChar(CP_THREAD_ACP, 0, szAccessToken, -1, lpszBearerToken, nLength); bResult = TRUE; } } GlobalFree(lpByte); InternetCloseHandle(hRequest); InternetCloseHandle(hSession); InternetCloseHandle(hInternet); return bResult; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static HWND hButton; static HWND hEdit1; static HWND hEdit2; static HWND hEdit3; switch (msg) { case WM_CREATE: hEdit1 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessage(hEdit1, EM_SETCUEBANNER, TRUE, (LPARAM)TEXT("Consumer key")); hEdit2 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessage(hEdit2, EM_SETCUEBANNER, TRUE, (LPARAM)TEXT("Consumer secret")); hButton = CreateWindow(TEXT("BUTTON"), TEXT("取得"), WS_VISIBLE | WS_CHILD | WS_TABSTOP, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0); hEdit3 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), 0, WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL | ES_READONLY, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); break; case WM_SIZE: MoveWindow(hEdit1, 10, 10, LOWORD(lParam) - 20, 32, TRUE); MoveWindow(hEdit2, 10, 50, LOWORD(lParam) - 20, 32, TRUE); MoveWindow(hButton, 10, 90, 256, 32, TRUE); MoveWindow(hEdit3, 10, 130, LOWORD(lParam) - 20, 32, TRUE); break; case WM_COMMAND: if (LOWORD(wParam) == IDOK) { WCHAR szConsumerKey[128]; WCHAR szConsumerSecret[128]; WCHAR szBearerToken[128]; GetWindowTextW(hEdit1, szConsumerKey, _countof(szConsumerKey)); GetWindowTextW(hEdit2, szConsumerSecret, _countof(szConsumerSecret)); if (GetTwitterBearerToken(szConsumerKey, szConsumerSecret, szBearerToken, _countof(szBearerToken))) { SetWindowTextW(hEdit3, szBearerToken); SendMessage(hEdit3, EM_SETSEL, 0, -1); SetFocus(hEdit3); } } break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefDlgProc(hWnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreInst, LPSTR pCmdLine, int nCmdShow) { MSG msg; WNDCLASS wndclass = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, DLGWINDOWEXTRA, hInstance, 0, LoadCursor(0,IDC_ARROW), 0, 0, szClassName }; RegisterClass(&wndclass); HWND hWnd = CreateWindow( szClassName, TEXT("Get Twitter Bearer Token"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0 ); ShowWindow(hWnd, SW_SHOWDEFAULT); UpdateWindow(hWnd); while (GetMessage(&msg, 0, 0, 0)) { if (!IsDialogMessage(hWnd, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; }
33.890625
196
0.709851
kenjinote
000d80e15ffca2391a4b3fed007730c7e12c8a52
3,412
cc
C++
client/base/vlog_is_on_test.cc
zamorajavi/google-input-tools
fc9f11d80d957560f7accf85a5fc27dd23625f70
[ "Apache-2.0" ]
175
2015-01-01T12:40:33.000Z
2019-05-24T22:33:59.000Z
client/base/vlog_is_on_test.cc
DalavanCloud/google-input-tools
fc9f11d80d957560f7accf85a5fc27dd23625f70
[ "Apache-2.0" ]
11
2015-01-19T16:30:56.000Z
2018-04-25T01:06:52.000Z
client/base/vlog_is_on_test.cc
DalavanCloud/google-input-tools
fc9f11d80d957560f7accf85a5fc27dd23625f70
[ "Apache-2.0" ]
97
2015-01-19T15:35:29.000Z
2019-05-15T05:48:02.000Z
/* Copyright 2014 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "base/vlog_is_on.h" #include "base/commandlineflags.h" #include "i18n/input/engine/lib/public/win/string_utils.h" #include "testing/base/public/gunit.h" DECLARE_int32(v); DECLARE_string(vmodule); namespace ime_shared { static const wchar_t kTestFile1[] = L"TestFile1"; static const wchar_t kTestFile2[] = L"TestFile2"; static const wchar_t kTestFile3[] = L"TestFile3"; static const wchar_t kAllModule[] = L"TestFile1,TestFile2"; static const wchar_t kPartModule[] = L"Test"; static const wchar_t kComplexModule[] = L"TestFile1=2,TestFile2"; static const wchar_t kEnvModule[] = L"IME_TEST_VMODULE"; static const wchar_t kEnvLevel[] = L"IME_TEST_VLEVEL"; TEST(VLog, SetModule) { VLog::SetLevel(0); // All levels are off. VLog::SetModule(L""); EXPECT_EQ(0, VLog::GetVerboseLevel(kTestFile1)); EXPECT_FALSE(VLog::IsOn(kTestFile1, 1)); EXPECT_EQ(0, VLog::GetVerboseLevel(kTestFile2)); EXPECT_FALSE(VLog::IsOn(kTestFile2, 1)); // 1 module. VLog::SetModule(kTestFile1); EXPECT_TRUE(VLog::IsOn(kTestFile1, 1)); EXPECT_FALSE(VLog::IsOn(kTestFile2, 1)); // 2 modules. VLog::SetModule(kAllModule); EXPECT_TRUE(VLog::IsOn(kTestFile1, 1)); EXPECT_TRUE(VLog::IsOn(kTestFile2, 1)); // Partial match. VLog::SetModule(kPartModule); EXPECT_TRUE(VLog::IsOn(kTestFile1, 1)); EXPECT_TRUE(VLog::IsOn(kTestFile2, 1)); // Complex module. VLog::SetModule(kComplexModule); EXPECT_EQ(2, VLog::GetVerboseLevel(kTestFile1)); EXPECT_EQ(1, VLog::GetVerboseLevel(kTestFile2)); EXPECT_EQ(0, VLog::GetVerboseLevel(kTestFile3)); } TEST(VLog, SetLevel) { VLog::SetModule(L""); // All levels are off. VLog::SetLevel(0); EXPECT_FALSE(VLog::IsOn(kTestFile1, 1)); EXPECT_FALSE(VLog::IsOn(kTestFile1, 2)); // Level 2. VLog::SetLevel(2); EXPECT_TRUE(VLog::IsOn(kTestFile1, 1)); EXPECT_TRUE(VLog::IsOn(kTestFile1, 2)); EXPECT_FALSE(VLog::IsOn(kTestFile1, 3)); } TEST(VLog, SetFromEnvironment) { VLog::SetModule(kTestFile1); VLog::SetLevel(2); // Environment variable not existed, level not changed. SetEnvironmentVariable(kEnvModule, NULL); SetEnvironmentVariable(kEnvLevel, NULL); VLog::SetFromEnvironment(kEnvModule, kEnvLevel); EXPECT_STREQ(kTestFile1, i18n_input::engine::Utf8ToWide(FLAGS_vmodule).c_str()); EXPECT_EQ(2, FLAGS_v); // Changed. SetEnvironmentVariable(kEnvModule, kTestFile2); SetEnvironmentVariable(kEnvLevel, L"1"); VLog::SetFromEnvironment(kEnvModule, kEnvLevel); EXPECT_STREQ(kTestFile2, i18n_input::engine::Utf8ToWide(FLAGS_vmodule).c_str()); EXPECT_EQ(1, FLAGS_v); // Clean up. SetEnvironmentVariable(kEnvModule, NULL); SetEnvironmentVariable(kEnvLevel, NULL); } } // namespace ime_shared int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.19469
74
0.730363
zamorajavi
000f36e0dff70ffa9eea1662beb5752d0582927c
4,060
hh
C++
include/hdf5/helper_functions_test_client_hdf5.hh
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
5
2018-11-28T19:38:23.000Z
2021-03-15T20:44:07.000Z
include/hdf5/helper_functions_test_client_hdf5.hh
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
null
null
null
include/hdf5/helper_functions_test_client_hdf5.hh
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
1
2018-07-18T15:22:36.000Z
2018-07-18T15:22:36.000Z
/* * Copyright 2018 National Technology & Engineering Solutions of * Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, * the U.S. Government retains certain rights in this software. * * The MIT License (MIT) * * Copyright (c) 2018 Sandia 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. */ #ifndef HELPERFUNCTIONSTESTCLIENTHDF5_HH #define HELPERFUNCTIONSTESTCLIENTHDF5_HH #include <my_metadata_client_hdf5.hh> #include <hdf5.h> #include <hdf5_hl.h> #include <vector> void create_timestep(std::string run_name, std::string job_id, uint64_t timestep_id, hid_t run_file_id, std::string TYPENAME_0, std::string TYPENAME_1, std::string VARNAME_0, std::string VARNAME_1); void catalog_all_var_attributes ( hid_t var_attr_table_id, uint64_t timestep_id, md_dim_bounds query_dims ); void catalog_all_var_attributes_with_type ( hid_t var_attr_table_id, uint64_t timestep_id, std::string type_name, md_dim_bounds query_dims ); void catalog_all_var_attributes_with_var ( hid_t var_attr_table_id, uint64_t timestep_id, std::string var_name, md_dim_bounds query_dims ); void catalog_all_var_attributes_with_type_var ( hid_t var_attr_table_id, uint64_t timestep_id, std::string type_name, std::string var_name, md_dim_bounds query_dims ); void catalog_all_var_attributes_with_var_substr ( hid_t file_id, hid_t var_attr_table_id, uint64_t timestep_id, md_dim_bounds query_dims ); void catalog_all_var_attributes_with_type_var_substr ( hid_t var_attr_table_id, uint64_t timestep_id, std::string type_name, md_dim_bounds query_dims ); void catalog_all_types_substr ( hid_t var_attr_table_id, uint64_t timestep_id, md_dim_bounds query_dims ); // int delete_var_substr (hid_t file_id, hid_t var_attr_table_id, uint64_t timestep_id); void create_timestep_attrs(hid_t timestep_attr_table0, hid_t timestep_attr_table1, std::string type0_name, std::string type1_name ); void catalog_all_timestep_attributes ( hid_t timestep_attr_table_id, uint64_t timestep_id, std::string type_name); void catalog_all_timesteps_substr ( hid_t run_file_id, std::string type_name, md_dim_bounds query_dims ); void create_new_timesteps(std::string run_name, std::string job_id, uint64_t timestep_id, hid_t run_file_id, std::string type0_name, std::string type1_name, std::string var0_name, std::string var1_name, hid_t timestep20_var_attr_table_id); void catalog_all_timesteps ( hid_t run_file_id, std::string type_name, std::string var_name, md_dim_bounds query_dims ); void create_run_attrs(hid_t run_attr_table_id, std::string type0_name, std::string type1_name ); void catalog_all_run_attributes ( hid_t run_attr_table_id, std::string type_name ); void catalog_all_types ( hid_t var_attr_table_id, uint64_t timestep_id, std::string var_name, md_dim_bounds query_dims ); void create_new_types(md_timestep_entry timestep0, md_timestep_entry timestep1, std::string var0_name, std::string var1_name); #endif //HELPERFUNCTIONSTESTCLIENTHDF5_HH
48.333333
141
0.796552
mlawsonca
001054b5d4744c0808c4ff162e152d7dad69a1d6
1,971
cc
C++
oos/src/model/GetSecretParameterRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
oos/src/model/GetSecretParameterRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
oos/src/model/GetSecretParameterRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/oos/model/GetSecretParameterRequest.h> using AlibabaCloud::Oos::Model::GetSecretParameterRequest; GetSecretParameterRequest::GetSecretParameterRequest() : RpcServiceRequest("oos", "2019-06-01", "GetSecretParameter") { setMethod(HttpRequest::Method::Post); } GetSecretParameterRequest::~GetSecretParameterRequest() {} bool GetSecretParameterRequest::getWithDecryption()const { return withDecryption_; } void GetSecretParameterRequest::setWithDecryption(bool withDecryption) { withDecryption_ = withDecryption; setParameter("WithDecryption", withDecryption ? "true" : "false"); } int GetSecretParameterRequest::getParameterVersion()const { return parameterVersion_; } void GetSecretParameterRequest::setParameterVersion(int parameterVersion) { parameterVersion_ = parameterVersion; setParameter("ParameterVersion", std::to_string(parameterVersion)); } std::string GetSecretParameterRequest::getRegionId()const { return regionId_; } void GetSecretParameterRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } std::string GetSecretParameterRequest::getName()const { return name_; } void GetSecretParameterRequest::setName(const std::string& name) { name_ = name; setParameter("Name", name); }
26.635135
75
0.76002
iamzken
00121787f81db3a3224e3c7c8b80fd7ff1bbb873
2,207
hpp
C++
include/ight/common/pointer.hpp
alessandro40/libight
de434be18791844076603b50167c436a768e830e
[ "BSD-2-Clause" ]
null
null
null
include/ight/common/pointer.hpp
alessandro40/libight
de434be18791844076603b50167c436a768e830e
[ "BSD-2-Clause" ]
null
null
null
include/ight/common/pointer.hpp
alessandro40/libight
de434be18791844076603b50167c436a768e830e
[ "BSD-2-Clause" ]
null
null
null
/*- * This file is part of Libight <https://libight.github.io/>. * * Libight is free software. See AUTHORS and LICENSE for more * information on the copying conditions. */ #ifndef IGHT_COMMON_POINTER_HPP # define IGHT_COMMON_POINTER_HPP #include <memory> #include <stdexcept> namespace ight { namespace common { namespace pointer { /*! * \brief Improved std::shared_ptr<T> with null pointer checks. * * This template class is a drop-in replacemente for the standard library's * shared_ptr<>. It extends shared_ptr<>'s ->() and *() operators to check * whether the pointee is a nullptr. In such case, unlike shared_ptr<>, the * pointee is not accessed and a runtime exception is raised. * * Use this class as follows: * * using namespace ight::common::pointer; * ... * SharedPointer<Foo> ptr; * ... * ptr = std::make_shared<Foo>(...); * * That is, declare ptr as SharedPointer<Foo> and the behave like ptr was * a shared_ptr<> variable instead. * * It is safe to assign the return value of std::make_shared<Foo> to * SharedPointer<Foo> because SharedPointer have exactly the same fields * as std::shared_pointer and because it inherits the copy and move * constructors from std::shared_pointer. */ template<typename T> class SharedPointer : public std::shared_ptr<T> { using std::shared_ptr<T>::shared_ptr; public: /*! * \brief Access the pointee to get one of its fields. * \returns A pointer to the pointee that allows one to access * the requested pointee field. * \throws std::runtime_error if the pointee is nullptr. */ T *operator->() const { if (this->get() == nullptr) { throw std::runtime_error("null pointer"); } return std::shared_ptr<T>::operator->(); } /*! * \brief Get the value of the pointee. * \returns The value of the pointee. * \throws std::runtime_error if the pointee is nullptr. */ typename std::add_lvalue_reference<T>::type operator*() const { if (this->get() == nullptr) { throw std::runtime_error("null pointer"); } return std::shared_ptr<T>::operator*(); } }; }}} #endif
29.824324
75
0.656547
alessandro40
0016f8dcd21a36f8299cb3bf17f56a6fda1f20b1
9,030
hpp
C++
symbol-tables/cpp/BinarySearchTree/BinarySearchTree.hpp
goldsborough/algs4
5f711f06ebc1da598cfbaeee16db0531f79e3fee
[ "MIT" ]
17
2017-03-06T10:11:41.000Z
2021-04-28T11:21:36.000Z
symbol-tables/cpp/BinarySearchTree/BinarySearchTree.hpp
goldsborough/algs4
5f711f06ebc1da598cfbaeee16db0531f79e3fee
[ "MIT" ]
null
null
null
symbol-tables/cpp/BinarySearchTree/BinarySearchTree.hpp
goldsborough/algs4
5f711f06ebc1da598cfbaeee16db0531f79e3fee
[ "MIT" ]
6
2016-11-23T07:31:46.000Z
2021-03-10T09:58:12.000Z
#ifndef BINARY_SEARCH_TREE_HPP #define BINARY_SEARCH_TREE_HPP #include <stdexcept> template<typename Key, typename Value> class BinarySearchTree { public: typedef unsigned long size_t; struct Pair { const Key& key; Value& value; }; private: struct Node { Node(const Key& k = Key(), const Value& v = Value()) : key(k) , value(v) , pair{key, value} , parent(nullptr) , left(nullptr) , right(nullptr) , size(1) { } void resize() { size = 1; if (left) size += left->size; if (right) size += right->size; } Key key; Value value; Pair pair; Node* left; Node* right; Node* parent; size_t size; }; void _insert(Node*& node, const Key& key, const Value& value) { if (! node) node = new Node(key, value); else if (node == _end) { node = new Node(key, value); node->right = _end; _end->parent = node; } else if (key < node->key) { _insert(node->left, key, value); node->left->parent = node; if (node == _begin) _begin = node->left; node->resize(); } else if (key > node->key) { _insert(node->right, key, value); node->right->parent = node; node->resize(); } } Node* _insert(Node*& node, Node* parent, const Key& key) { if (node) { if (node == _end) { node = new Node(key); node->right = _end; node->parent = parent; _end->parent = node; } if (key < node->key) { Node* child = _insert(node->left, node, key); if (node == _begin) _begin = child; node->resize(); return child; } else if (key > node->key) { Node* child = _insert(node->left, node, key); node->resize(); return child; } } else { node = new Node(key); node->parent = parent; } return node; } Node* _erase(Node* node, const Key& key) { if (node) { if (key < node->key) { node->left = _erase(node->left, key); node->resize(); } else if (key > node->key) { node->right = _erase(node->right, key); node->resize(); } else return _erase(node); } return node; } Node* _erase(Node* node) { if (node == _begin) { if (node->right) _begin = node->right; else _begin = _begin->parent; } if (! node->left) return node->right; if (! node->right || node->right == _end) return node->left; Node* successor = node->right; while(successor->left) { successor->size--; successor = successor->left; } successor->parent->left = successor->right; successor->right = node->right; successor->left = node->left; node->right->parent = successor; node->left->parent = successor; delete node; return successor; } Node*& _find(Node*& node, const Key& key) const { if (! node || node == _end || key == node->key) return node; else if (key < node->key) return _find(node->left, key); else return _find(node->right, key); } Node* _smallest() const { if (! _root) return _end; Node* node = _root; while (node->left) node = node->left; return node; } Node* _largest() const { if (! _root) return _end; Node* node = _root; while (node->right) node = node->right; return node; } Node* _floor(Node* node, const Key& key) const { if (! node || node == _end) return nullptr; else if (key > node->key) { Node* result = _floor(node->right, key); return result ? result : node; } else return _floor(node->left, key); } Node* _ceiling(Node* node, const Key& key) const { if (! node || node == _end) return nullptr; else if (key < node->key) { Node* result = _ceiling(node->left, key); return result ? result : node; } else return _ceiling(node->right, key); } size_t _rank(Node* node, const Key& key) const { if (! node || node == _end) return 0; if (key < node->key) return _rank(node->left, key); size_t size = 1; if (node->left) size += node->left->size; if (key > node->key) size += _rank(node->right, key); return size; } Node* _select(Node* node, size_t rank) const { if (! node || node == _end) return nullptr; size_t size = node->left ? node->left->size : 0; if (size > rank) return _select(node->left, rank); else if (size < rank) return _select(node->right, rank - size - 1); else return node; } void _clear(Node* node) { if (node) { if (node->left) _clear(node->left); if (node->right) _clear(node->right); delete node; } } Node* _begin; Node* _end; Node* _root; public: class Iterator { public: Iterator(Node* node, const BinarySearchTree* bst) : _node(node) , _bst(bst) { } Pair& operator*() const { return _node->pair; } Pair* operator->() const { return &_node->pair; } bool operator==(Iterator other) const { return _node == other._node; } bool operator!=(Iterator other) const { return _node != other._node; } bool operator<(Iterator other) const { if (! _node) return false; if (! other._node) return true; return _node->key < other._node->key; } bool operator<=(Iterator other) const { if (! _node) return false; if (! other._node) return true; return _node->key <= other._node->key; } bool operator>(Iterator other) const { if (! other._node) return false; if (! _node) return true; return _node->key > other._node->key; } bool operator>=(Iterator other) const { if (! other._node) return false; if (! _node) return true; return _node->key >= other._node->key; } Iterator& operator++() { if (_node != _bst->_end) { if (_node->right) { _node = _node->right; while (_node->left) _node = _node->left; } else _node = _node->parent; } return *this; } Iterator operator++(int) { Iterator previous = *this; ++(*this); return previous; } Iterator& operator--() { if (_node != _bst->_begin) { if (_node->left) { _node = _node->left; while (_node->right) _node = _node->right; } else _node = _node->parent; } return *this; } Iterator operator--(int) { Iterator previous = *this; --(*this); return previous; } private: friend class BinarySearchTree; Node* _node; const BinarySearchTree* _bst; }; BinarySearchTree() : _begin(nullptr) , _end(new Node) , _root(_end) { } ~BinarySearchTree() { clear(); } Iterator begin() const { return {_begin, &*this}; } Iterator end() const { return {_end, &*this}; } Value& operator[](const Key& key) { Node* node = _insert(_root, nullptr, key); if (! _begin) _begin = node; return node->value; } void insert(const Key& key, const Value& value) { _insert(_root, key, value); if (! _begin) _begin = _root; } Value& at(const Key& key) { Node* node = _find(_root, key); if (! node) throw std::invalid_argument("Invalid key!"); return node->value; } const Value& at(const Key& key) const { Node* node = _find(_root, key); if (! node) throw std::invalid_argument("Invalid key!"); return node->value; } void clear() { _clear(_root); _root = nullptr; } void erase(const Key& key) { _erase(_root, key); } Iterator erase(Iterator itr) { Node* node = (itr++).node; Node* successor; if (! node->right) successor = node->left; else if (! node->left) successor = node->right; else { successor = node->right; while(successor->left) { successor->size--; successor = successor->left; } successor->parent->left = successor->right; successor->right = node->right; successor->left = node->left; } if (node == node->parent->right) { node->parent->right = successor; } else node->parent->left = successor; delete node; return itr; } bool contains(const Key& key) const { return _find(_root, key); } Iterator find(const Key& key) const { Node* node = _find(_root, key); return {node, *this}; } size_t size() const { return _root ? _root->size : 0; } size_t size(const Key& lower, const Key& upper) const { size_t first = rank(lower); size_t second = rank(upper); return second - first + 1; } bool is_empty() const { return size() == 0; } Iterator smallest() const { return begin(); } Iterator largest() const { return --end(); } Iterator floor(const Key& key) const { return _floor(_root, key); } Iterator ceiling(const Key& key) const { return _ceiling(_root, key); } size_t rank(const Key& key) const { return _rank(_root, key); } Iterator select(size_t rank) const { return _select(_root, rank); } }; #endif /* BINARY_SEARCH_TREE_HPP */
15.253378
69
0.570653
goldsborough
001766550d49a60f20f6c9bb98be1cf0e5e86d3e
1,004
cpp
C++
engine/Engine.UI/src/ui/Color.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
engine/Engine.UI/src/ui/Color.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
10
2018-03-20T21:32:16.000Z
2018-04-23T19:42:59.000Z
engine/Engine.UI/src/ui/Color.cpp
Kartikeyapan598/Ghurund
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
[ "MIT" ]
null
null
null
#include "ghuipch.h" #include "Color.h" #include <regex> namespace Ghurund::UI { Color Ghurund::UI::Color::parse(const AString& color) { uint32_t value = 0; AString str = color.toLowerCase(); std::regex regex(" *\\#((?:[a-f0-9]{2})?[a-f0-9]{6}) *"); std::smatch m; std::string s = str.Data; if (std::regex_match(s, m, regex)) { for (char c : m[0].str()) { if (c >= '0' && c <= '9') { value = value * 16 + (c - '0'); } else if (c >= 'a' && c <= 'f') { value = value * 16 + (c - 'a' + 10); } } } else { throw std::invalid_argument("invalid color string"); } return Color(value); } } namespace Ghurund::Core { template<> const Type& getType<Ghurund::UI::Color>() { static Type TYPE = Type(Ghurund::UI::NAMESPACE_NAME, "Color", sizeof(Ghurund::UI::Color)); return TYPE; } }
29.529412
98
0.465139
Kartikeyapan598
0021a96bced212c6e0f9187e795de7923b722581
653
hpp
C++
gibson/core/channels/common/MTLplyloader.hpp
rainprob/GibsonEnv
e0d0bc614713c676cb303bf9f11ca6a98713e0e0
[ "MIT" ]
731
2018-02-26T18:35:05.000Z
2022-03-23T04:00:09.000Z
gibson/core/channels/common/MTLplyloader.hpp
Shubodh/GibsonEnv
38274874d7c2c2a87efdb6ee529f2b366c5219de
[ "MIT" ]
111
2018-04-19T01:00:22.000Z
2022-03-18T17:43:50.000Z
gibson/core/channels/common/MTLplyloader.hpp
Shubodh/GibsonEnv
38274874d7c2c2a87efdb6ee529f2b366c5219de
[ "MIT" ]
153
2018-02-27T04:38:40.000Z
2022-03-28T08:10:39.000Z
#ifndef MTLPLYLOADER_H #define MTLPLYLOADER_H #include "MTLtexture.hpp" bool loadPLY_MTL( const char * path, std::vector<std::vector<glm::vec3>> & out_vertices, std::vector<std::vector<glm::vec2>> & out_uvs, std::vector<std::vector<glm::vec3>> & out_normals, std::vector<glm::vec3> & out_centers, //std::vector<int> & out_material_name, std::vector<int> & out_material_id, std::string & out_mtllib, int & num_vertices ); bool loadJSONtextures ( std::string jsonpath, std::vector<int> & out_label_id, std::vector<int> & out_segment_id, std::vector<std::vector<int>> & out_face_indices ); #endif
24.185185
55
0.672282
rainprob
0021b9dc56ef5c790cd45b1040be2e56e509b356
839
cc
C++
third_party/blink/renderer/extensions/chromeos/chromeos.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/extensions/chromeos/chromeos.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/extensions/chromeos/chromeos.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 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 "third_party/blink/renderer/extensions/chromeos/chromeos.h" #include "third_party/blink/renderer/extensions/chromeos/system_extensions/window_management/cros_window_management.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" namespace blink { ChromeOS::ChromeOS(ExecutionContext* execution_context) : window_management_( MakeGarbageCollected<CrosWindowManagement>(execution_context)) {} CrosWindowManagement* ChromeOS::windowManagement() { return window_management_; } void ChromeOS::Trace(Visitor* visitor) const { ScriptWrappable::Trace(visitor); visitor->Trace(window_management_); } } // namespace blink
32.269231
118
0.793802
chromium
002bf6c50769fe81aa30eabdf4222b6d9a59c003
1,118
cpp
C++
CPP/szuOJ/W12PC-creditCard.cpp
ParrySMS/Exp
78459e141308827b3e9a4ceb227808517d476a53
[ "Apache-2.0" ]
2
2019-05-09T16:35:21.000Z
2019-08-19T11:57:53.000Z
CPP/szuOJ/W12PC-creditCard.cpp
ParrySMS/Exp
78459e141308827b3e9a4ceb227808517d476a53
[ "Apache-2.0" ]
null
null
null
CPP/szuOJ/W12PC-creditCard.cpp
ParrySMS/Exp
78459e141308827b3e9a4ceb227808517d476a53
[ "Apache-2.0" ]
2
2019-03-29T05:31:55.000Z
2019-12-03T07:35:42.000Z
#include <iostream> #include <math.h> #include <cstring> #include <iomanip> using namespace std; class CVIP { protected: int card_id; int point; public: CCard() {} CCard(int c,int p) { card_id = c; point = p; } void init(int c,int p) { card_id = c; point = p; } }; class CCredit { protected: int credit_id; string name; int max; double bill; int cpoint; public: CCredit() { } CCredit(int cid,string _name,int _max,double _bill,int _cpoint) { credit_id = cid; name = _name; max = _max; bill = _bill; cpoint = _cpoint; } }; class CCreditVIP: public CCredit,public CVIP { public: CCreditVIP() {} CCreditVIP(int n) { seat_num = n; } }; int main() { int card_id; int point; int credit_id; string name; int max; double bill; int cpoint; cin>>max_speed>>speed>>weight; CVehicle cv(max_speed,speed,weight); cv.display(); cin>>height; CBicycle cb(cv,height); cb.showBYC(); cin>>seat_num; CMotocar cm(cv,seat_num); cm.showMOT(); CMotocycle cmoc(max_speed,speed,weight,height,seat_num); cmoc.showMC(); return 0 ; }
12.704545
67
0.635957
ParrySMS
002d927385e6b8518269dd5cb130c407f293b87a
316
cc
C++
Ejercicio1/primes.cc
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
[ "MIT" ]
null
null
null
Ejercicio1/primes.cc
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
[ "MIT" ]
null
null
null
Ejercicio1/primes.cc
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include "primefunciones.h" int main (int argc, char * argv[]) { std::string convert = argv[1]; int primeposition = stoi(convert); std::cout << "El primo #" << primeposition << " es: " << PrimePosition(primeposition) << std::endl; return 0; }
17.555556
87
0.642405
Jdorta62
002edff6b151af92ca0b0f991610936b6470f751
674
cpp
C++
Game/messageboxlogger.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
1
2021-04-14T15:06:55.000Z
2021-04-14T15:06:55.000Z
Game/messageboxlogger.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
7
2020-05-14T02:14:26.000Z
2020-05-22T04:57:47.000Z
Game/messageboxlogger.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
null
null
null
#include <vcclr.h> #include "messageboxlogger.h" MessageBoxLogger::MessageBoxLogger(HWND hWnd) { { if(!hWnd) { throw gcnew ArgumentNullException("hWnd is NULL."); } else { this->hWnd = hWnd; } } } void MessageBoxLogger::Write(String ^message) { pin_ptr<const wchar_t> unmanagedString = PtrToStringChars(message); MessageBox(this->hWnd, unmanagedString, L"Unholy Error", MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST); } // no idea why you'd use this function but it's here for completeness. void MessageBoxLogger::WriteLine(String ^message) { Write(message += Environment::NewLine); }
23.241379
102
0.649852
sethballantyne
002fd3ab99e86c06a4f8bdeab7a989ef10073872
43,933
cpp
C++
src/plugProjectHikinoU/PSSe.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/plugProjectHikinoU/PSSe.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/plugProjectHikinoU/PSSe.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_80490038 lbl_80490038: .4byte 0x8373834C .4byte 0x53458AD4 .4byte 0x88F882AB .4byte 0x90DD92E8 .4byte 0x00000000 .4byte 0x8373834C .4byte 0x95A8895E .4byte 0x82D189B9 .4byte 0x00000000 .4byte 0x8373834C .4byte 0x8E648E96 .4byte 0x924082AB .4byte 0x89B90000 .4byte 0x8373834C .4byte 0x93DB82DD .4byte 0x8D9E82DC .4byte 0x82EA82E0 .4byte 0x82AA82AB .4byte 0x90BA0000 .4byte 0x83608383 .4byte 0x838C8393 .4byte 0x83578382 .4byte 0x815B8368 .4byte 0x82CC8367 .4byte 0x83628376 .4byte 0x89E696CA .4byte 0x97700000 .4byte 0x8373834C .4byte 0x92859085 .4byte 0x89B99770 .4byte 0x00000000 .4byte 0x8373834C .4byte 0x8370836A .4byte 0x8362834E .4byte 0x83898393 .4byte 0x97700000 .global lbl_804900C8 lbl_804900C8: .4byte 0x50535365 .4byte 0x2E637070 .4byte 0x00000000 .global lbl_804900D4 lbl_804900D4: .asciz "P2Assert" .skip 3 .4byte 0x5053436F .4byte 0x6D6D6F6E .4byte 0x2E680000 .4byte 0x838A8393 .4byte 0x834E82AA .4byte 0x82A082E8 .4byte 0x82DC82B9 .4byte 0x82F10000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global __vt__Q26PSGame25Builder_EvnSe_Perspective __vt__Q26PSGame25Builder_EvnSe_Perspective: .4byte 0 .4byte 0 .4byte __dt__Q26PSGame25Builder_EvnSe_PerspectiveFv .4byte onBuild__Q26PSGame25Builder_EvnSe_PerspectiveFPQ28PSSystem9EnvSeBase .4byte newSeObj__Q26PSGame25Builder_EvnSe_PerspectiveFUlf3Vec .global __vt__Q26PSGame13EnvSe_AutoPan __vt__Q26PSGame13EnvSe_AutoPan: .4byte 0 .4byte 0 .4byte exec__Q28PSSystem9EnvSeBaseFv .4byte play__Q28PSSystem9EnvSeBaseFv .4byte getCastType__Q28PSSystem9EnvSeBaseFv .4byte setPanAndDolby__Q26PSGame13EnvSe_AutoPanFP8JAISound .global __vt__Q26PSGame17EnvSe_Perspective __vt__Q26PSGame17EnvSe_Perspective: .4byte 0 .4byte 0 .4byte exec__Q28PSSystem9EnvSeBaseFv .4byte play__Q26PSGame17EnvSe_PerspectiveFv .4byte getCastType__Q28PSSystem9EnvSeBaseFv .4byte setPanAndDolby__Q28PSSystem9EnvSeBaseFP8JAISound .global __vt__Q26PSGame9EnvSe_Pan __vt__Q26PSGame9EnvSe_Pan: .4byte 0 .4byte 0 .4byte exec__Q28PSSystem9EnvSeBaseFv .4byte play__Q28PSSystem9EnvSeBaseFv .4byte getCastType__Q28PSSystem9EnvSeBaseFv .4byte setPanAndDolby__Q26PSGame9EnvSe_PanFP8JAISound .global __vt__Q26PSGame5Rappa __vt__Q26PSGame5Rappa: .4byte 0 .4byte 0 .4byte __dt__Q26PSGame5RappaFv .global __vt__Q26PSGame5SeMgr __vt__Q26PSGame5SeMgr: .4byte 0 .4byte 0 .4byte __dt__Q26PSGame5SeMgrFv .global "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>" "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>": .4byte 0 .4byte 0 .4byte "__dt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>Fv" .section .sdata, "wa" # 0x80514680 - 0x80514D80 .global cRatio__Q26PSGame5Rappa cRatio__Q26PSGame5Rappa: .float 15.0 .global cBaseWaitTime__Q26PSGame5Rappa cBaseWaitTime__Q26PSGame5Rappa: .4byte 0x00030000 .global sRappa__Q26PSGame5Rappa sRappa__Q26PSGame5Rappa: .4byte 0x00000000 .4byte 0x00000000 .global cNotUsingMasterIdRatio__Q26PSGame6RandId cNotUsingMasterIdRatio__Q26PSGame6RandId: .float -1.0 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_8051E188 lbl_8051E188: .4byte 0x934794C4 .4byte 0x97700000 .global lbl_8051E190 lbl_8051E190: .float 1.0 .global lbl_8051E194 lbl_8051E194: .float 0.5 .global lbl_8051E198 lbl_8051E198: .4byte 0x00000000 .global lbl_8051E19C lbl_8051E19C: .float 0.1 .global lbl_8051E1A0 lbl_8051E1A0: .4byte 0xBF800000 .4byte 0x00000000 .global lbl_8051E1A8 lbl_8051E1A8: .4byte 0x43300000 .4byte 0x80000000 .global lbl_8051E1B0 lbl_8051E1B0: .4byte 0x43300000 .4byte 0x00000000 .global lbl_8051E1B8 lbl_8051E1B8: .4byte 0x40000000 .global lbl_8051E1BC lbl_8051E1BC: .4byte 0x447A0000 */ namespace PSGame { /* * --INFO-- * Address: 8033F158 * Size: 000210 */ SeMgr::SeMgr() { /* stwu r1, -0x20(r1) mflr r0 lis r4, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha stw r0, 0x24(r1) addi r0, r4, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l lis r4, lbl_80490038@ha stw r31, 0x1c(r1) addi r31, r4, lbl_80490038@l stw r30, 0x18(r1) mr r30, r3 lis r3, __vt__Q26PSGame5SeMgr@ha stw r29, 0x14(r1) stw r0, 0(r30) addi r0, r3, __vt__Q26PSGame5SeMgr@l addi r3, r30, 0x24 stw r30, "sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) stw r0, 0(r30) bl __ct__Q26PSGame6RandIdFv li r0, 0 li r3, 0x18 stw r0, 0x2c(r30) stw r0, 4(r30) stw r0, 8(r30) stw r0, 0xc(r30) stw r0, 0x10(r30) stw r0, 0x14(r30) stw r0, 0x18(r30) stw r0, 0x1c(r30) stw r0, 0x20(r30) bl __nw__FUl or. r0, r3, r3 beq lbl_8033F1EC addi r4, r31, 0 li r5, 0 li r6, 3 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F1EC: stw r0, 4(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F214 addi r4, r31, 0x14 li r5, 9 li r6, 9 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F214: stw r0, 8(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F23C addi r4, r31, 0x24 li r5, 0 li r6, 5 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F23C: stw r0, 0xc(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F264 addi r4, r31, 0x34 li r5, 0x14 li r6, 0x14 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F264: stw r0, 0x14(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F28C addi r4, r31, 0x4c li r5, 0 li r6, 2 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F28C: stw r0, 0x18(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F2B4 addi r4, r31, 0x6c li r5, 2 li r6, 5 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F2B4: stw r0, 0x1c(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F2DC addi r4, r31, 0x7c li r5, 4 li r6, 0xa bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F2DC: stw r0, 0x20(r30) li r3, 0x18 bl __nw__FUl or. r0, r3, r3 beq lbl_8033F304 addi r4, r2, lbl_8051E188@sda21 li r5, 0x14 li r6, 9 bl __ct__Q26PSGame5SetSeFPCcss mr r0, r3 lbl_8033F304: stw r0, 0x10(r30) li r29, 0 b lbl_8033F33C lbl_8033F310: rlwinm r3, r29, 2, 0x16, 0x1d addi r0, r3, 4 lwzx r0, r30, r0 cmplwi r0, 0 bne lbl_8033F338 addi r3, r31, 0x90 addi r5, r31, 0x9c li r4, 0x2c crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F338: addi r29, r29, 1 lbl_8033F33C: clrlwi r0, r29, 0x18 cmplwi r0, 8 blt lbl_8033F310 lwz r0, 0x24(r1) mr r3, r30 lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 8033F368 * Size: 000120 */ void SeMgr::playMessageVoice(unsigned long, bool) { /* stwu r1, -0x40(r1) mflr r0 stw r0, 0x44(r1) stfd f31, 0x30(r1) psq_st f31, 56(r1), 0, qr0 stfd f30, 0x20(r1) psq_st f30, 40(r1), 0, qr0 stw r31, 0x1c(r1) stw r30, 0x18(r1) stw r29, 0x14(r1) mr r30, r4 lfs f31, lbl_8051E190@sda21(r2) cmpwi r30, 0x1850 lfs f30, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13) mr r29, r3 beq lbl_8033F3CC bge lbl_8033F3B8 cmpwi r30, 0x1846 beq lbl_8033F3C4 b lbl_8033F45C lbl_8033F3B8: cmpwi r30, 0x185f beq lbl_8033F3E4 b lbl_8033F45C lbl_8033F3C4: li r31, 0xa b lbl_8033F3F0 lbl_8033F3CC: clrlwi. r0, r5, 0x18 bne lbl_8033F3D8 lfs f31, lbl_8051E194@sda21(r2) lbl_8033F3D8: lfs f30, lbl_8051E198@sda21(r2) li r31, 0xf b lbl_8033F3F0 lbl_8033F3E4: li r31, 0xf b lbl_8033F3F0 b lbl_8033F45C lbl_8033F3F0: addis r0, r31, 1 cmplwi r0, 0xffff bne lbl_8033F418 lis r3, lbl_804900C8@ha lis r5, lbl_804900D4@ha addi r3, r3, lbl_804900C8@l li r4, 0x5a addi r5, r5, lbl_804900D4@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F418: bl getRandom_0_1__7JALCalcFv fcmpo cr0, f1, f31 bge lbl_8033F42C li r0, 1 b lbl_8033F430 lbl_8033F42C: li r0, 0 lbl_8033F430: clrlwi. r0, r0, 0x18 beq lbl_8033F45C stfs f30, 0x24(r29) mr r4, r30 mr r6, r31 addi r3, r29, 0x24 addi r5, r29, 0x2c li r7, 0 bl playSystemSe__Q26PSGame6RandIdFUlPP8JAISoundUlUl lfs f0, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13) stfs f0, 0x24(r29) lbl_8033F45C: psq_l f31, 56(r1), 0, qr0 lfd f31, 0x30(r1) psq_l f30, 40(r1), 0, qr0 lfd f30, 0x20(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r0, 0x44(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 8033F488 * Size: 00003C */ void SeMgr::stopMessageVoice() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) lwz r3, 0x2c(r3) cmplwi r3, 0 beq lbl_8033F4B4 lwz r12, 0x10(r3) li r4, 0 lwz r12, 0x14(r12) mtctr r12 bctrl lbl_8033F4B4: lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F4C4 * Size: 000050 */ Rappa::Rappa() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 bl __ct__11JKRDisposerFv lis r3, __vt__Q26PSGame5Rappa@ha li r4, -1 addi r3, r3, __vt__Q26PSGame5Rappa@l li r0, 0 stw r3, 0(r31) mr r3, r31 stw r4, 0x18(r31) sth r0, 0x1c(r31) sth r0, 0x1e(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F514 * Size: 0000A0 */ void Rappa::init(unsigned short) { /* stwu r1, -0x10(r1) mflr r0 li r5, 1 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 stw r30, 8(r1) mr r30, r4 clrlwi r4, r4, 0x10 subfic r0, r4, 1 orc r3, r5, r4 srwi r0, r0, 1 subf r0, r0, r3 rlwinm. r0, r0, 1, 0x1f, 0x1f bne lbl_8033F554 li r5, 0 lbl_8033F554: clrlwi. r0, r5, 0x18 bne lbl_8033F578 lis r3, lbl_804900C8@ha lis r5, lbl_804900D4@ha addi r3, r3, lbl_804900C8@l li r4, 0xb4 addi r5, r5, lbl_804900D4@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F578: clrlwi r3, r30, 0x10 rlwinm r0, r30, 2, 0xe, 0x1d cntlzw r4, r3 addi r3, r13, sRappa__Q26PSGame5Rappa@sda21 rlwinm r4, r4, 0x1b, 0x1f, 0x1f neg r4, r4 addi r4, r4, 0xe stw r4, 0x18(r31) stwx r31, r3, r0 lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F5B4 * Size: 000008 */ void Rappa::setId(unsigned long a1) { // Generated from stw r4, 0x18(r3) _18 = a1; } /* * --INFO-- * Address: 8033F5BC * Size: 000098 */ Rappa::~Rappa() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) or. r30, r3, r3 beq lbl_8033F638 lis r3, __vt__Q26PSGame5Rappa@ha li r6, 0 addi r0, r3, __vt__Q26PSGame5Rappa@l addi r5, r13, sRappa__Q26PSGame5Rappa@sda21 stw r0, 0(r30) li r3, 0 b lbl_8033F610 lbl_8033F5F8: rlwinm r4, r6, 2, 0x16, 0x1d lwzx r0, r5, r4 cmplw r0, r30 bne lbl_8033F60C stwx r3, r5, r4 lbl_8033F60C: addi r6, r6, 1 lbl_8033F610: clrlwi r0, r6, 0x18 cmplwi r0, 2 blt lbl_8033F5F8 mr r3, r30 li r4, 0 bl __dt__11JKRDisposerFv extsh. r0, r31 ble lbl_8033F638 mr r3, r30 bl __dl__FPv lbl_8033F638: lwz r0, 0x14(r1) mr r3, r30 lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F654 * Size: 000170 */ void Rappa::playRappa(bool, float, float, JAInter::Object*) { /* stwu r1, -0x40(r1) mflr r0 stw r0, 0x44(r1) stfd f31, 0x30(r1) psq_st f31, 56(r1), 0, qr0 stfd f30, 0x20(r1) psq_st f30, 40(r1), 0, qr0 stw r31, 0x1c(r1) stw r30, 0x18(r1) stw r29, 0x14(r1) mr r29, r3 fmr f30, f1 lwz r3, 0x18(r3) fmr f31, f2 mr r30, r4 mr r31, r5 addis r0, r3, 1 cmplwi r0, 0xffff bne lbl_8033F6BC lis r3, lbl_804900C8@ha lis r5, lbl_804900D4@ha addi r3, r3, lbl_804900C8@l li r4, 0xcc addi r5, r5, lbl_804900D4@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F6BC: clrlwi r0, r30, 0x18 li r3, 0 cmplwi r0, 1 bne lbl_8033F798 lfs f0, lbl_8051E198@sda21(r2) fcmpo cr0, f31, f0 cror 2, 1, 2 bne lbl_8033F6E4 fmr f1, f31 b lbl_8033F6E8 lbl_8033F6E4: fneg f1, f31 lbl_8033F6E8: lfs f0, lbl_8051E198@sda21(r2) fcmpo cr0, f30, f0 cror 2, 1, 2 bne lbl_8033F700 fmr f31, f30 b lbl_8033F704 lbl_8033F700: fneg f31, f30 lbl_8033F704: fcmpo cr0, f31, f1 ble lbl_8033F710 b lbl_8033F714 lbl_8033F710: fmr f31, f1 lbl_8033F714: lfs f0, lbl_8051E19C@sda21(r2) fcmpo cr0, f31, f0 bge lbl_8033F728 li r3, 0 b lbl_8033F798 lbl_8033F728: mr r3, r31 lwz r4, 0x18(r29) lwz r12, 0(r31) li r5, 0 lwz r12, 0xc(r12) mtctr r12 bctrl lfs f1, lbl_8051E190@sda21(r2) lfs f0, lbl_8051E1A0@sda21(r2) fsubs f3, f31, f1 lfs f2, lbl_8051E198@sda21(r2) fmuls f3, f3, f0 fcmpo cr0, f3, f2 bge lbl_8033F764 b lbl_8033F778 lbl_8033F764: fcmpo cr0, f3, f1 ble lbl_8033F774 fmr f2, f1 b lbl_8033F778 lbl_8033F774: fmr f2, f3 lbl_8033F778: lfs f0, cRatio__Q26PSGame5Rappa@sda21(r13) lhz r0, cBaseWaitTime__Q26PSGame5Rappa@sda21(r13) fmuls f2, f2, f0 fctiwz f0, f2 stfd f0, 8(r1) lwz r4, 0xc(r1) add r0, r4, r0 sth r0, 0x1c(r29) lbl_8033F798: psq_l f31, 56(r1), 0, qr0 lfd f31, 0x30(r1) psq_l f30, 40(r1), 0, qr0 lfd f30, 0x20(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r0, 0x44(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 8033F7C4 * Size: 00003C */ void Rappa::syncCpu_WaitChk(JASTrack*) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 mr r3, r4 li r4, 0xb addi r5, r31, 0x1e bl readPortAppDirect__8JASTrackFUlPUs lwz r0, 0x14(r1) lhz r3, 0x1c(r31) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F800 * Size: 000008 */ void Rappa::syncCpu_TblNo(JASTrack*) { /* lhz r3, 0x1e(r3) blr */ } /* * --INFO-- * Address: 8033F808 * Size: 000078 */ SetSe::SetSe(const char*, short, short) { /* stwu r1, -0x10(r1) mflr r0 li r4, 0 stw r0, 0x14(r1) extsh. r0, r6 stw r31, 0xc(r1) mr r31, r3 sth r4, 0(r3) li r3, -1 sth r5, 2(r31) sth r6, 4(r31) sth r5, 6(r31) stw r3, 8(r31) stb r4, 0x14(r31) stw r4, 0xc(r31) stw r4, 0x10(r31) bge lbl_8033F868 lis r3, lbl_804900C8@ha lis r5, lbl_804900D4@ha addi r3, r3, lbl_804900C8@l li r4, 0x13f addi r5, r5, lbl_804900D4@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F868: lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033F880 * Size: 000038 */ void SetSe::exec() { /* lhz r4, 0(r3) lha r0, 6(r3) cmpw r4, r0 ble lbl_8033F898 li r0, -1 stw r0, 8(r3) lbl_8033F898: lwz r4, 8(r3) addis r0, r4, 1 cmplwi r0, 0xffff beqlr lhz r4, 0(r3) addi r0, r4, 1 sth r0, 0(r3) blr */ } /* * --INFO-- * Address: 8033F8B8 * Size: 0000B8 */ void SetSe::startSound(JAInter::Object*, unsigned long, unsigned long) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r6 stw r30, 0x18(r1) mr r30, r5 stw r29, 0x14(r1) or. r29, r4, r4 stw r28, 0x10(r1) mr r28, r3 bne lbl_8033F904 lis r3, lbl_804900C8@ha lis r5, lbl_804900D4@ha addi r3, r3, lbl_804900C8@l li r4, 0x150 addi r5, r5, lbl_804900D4@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8033F904: lwz r3, 8(r28) addis r0, r3, 1 cmplwi r0, 0xffff bne lbl_8033F94C mr r3, r29 mr r4, r30 lwz r12, 0(r29) mr r5, r31 lwz r12, 0xc(r12) mtctr r12 bctrl mr r0, r3 mr r3, r28 mr r31, r0 mr r4, r30 bl startCounter__Q26PSGame5SetSeFUl mr r3, r31 b lbl_8033F950 lbl_8033F94C: li r3, 0 lbl_8033F950: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 8033F970 * Size: 0000A0 */ void SetSe::playSystemSe(unsigned long, unsigned long) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) mr r30, r3 lwz r3, 8(r3) addis r0, r3, 1 cmplwi r0, 0xffff bne lbl_8033F9F4 lbz r0, 0x14(r30) mr r6, r5 lwz r3, spSysIF__8PSSystem@sda21(r13) slwi r5, r0, 2 addi r5, r5, 0xc add r5, r30, r5 bl playSystemSe__Q28PSSystem5SysIFFUlPP8JAISoundUl mr r3, r30 mr r4, r31 bl startCounter__Q26PSGame5SetSeFUl lbz r4, 0x14(r30) slwi r3, r4, 2 addi r0, r4, 1 add r3, r30, r3 lwz r3, 0xc(r3) stb r0, 0x14(r30) lbz r0, 0x14(r30) cmplwi r0, 2 bne lbl_8033F9F8 li r0, 0 stb r0, 0x14(r30) b lbl_8033F9F8 lbl_8033F9F4: li r3, 0 lbl_8033F9F8: lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033FA10 * Size: 000084 */ void SetSe::startCounter(unsigned long) { /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) li r0, 0 stw r31, 0x2c(r1) mr r31, r3 sth r0, 0(r3) stw r4, 8(r3) bl getRandom_0_1__7JALCalcFv lha r4, 4(r31) lis r3, 0x43300000@ha lha r0, 2(r31) xoris r4, r4, 0x8000 stw r3, 8(r1) xoris r0, r0, 0x8000 lfd f3, lbl_8051E1A8@sda21(r2) stw r4, 0xc(r1) lfd f0, 8(r1) stw r0, 0x14(r1) fsubs f2, f0, f3 stw r3, 0x10(r1) lfd f0, 0x10(r1) fsubs f0, f0, f3 fmadds f0, f2, f1, f0 fctiwz f0, f0 stfd f0, 0x18(r1) lwz r0, 0x1c(r1) sth r0, 6(r31) lwz r31, 0x2c(r1) lwz r0, 0x34(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 8033FA94 * Size: 00000C */ RandId::RandId() { /* lfs f0, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13) stfs f0, 0x43300000@l(r3) blr */ } /* * --INFO-- * Address: 8033FAA0 * Size: 0001E8 */ void RandId::startSound(JAInter::Object*, unsigned long, unsigned long, unsigned long) { /* .loc_0x0: stwu r1, -0x30(r1) mflr r0 lfs f0, -0x1C0(r2) stw r0, 0x34(r1) stmw r27, 0x1C(r1) mr r27, r3 mr r28, r4 mr r29, r5 mr r30, r6 mr r31, r7 lfs f1, 0x0(r3) fcmpu cr0, f0, f1 bne- .loc_0xAC cmplwi r30, 0x1 bgt- .loc_0x58 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1AA addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x3154B4 .loc_0x58: bl -0x285604 lis r0, 0x4330 stw r30, 0xC(r1) lfd f2, -0x1B0(r2) stw r0, 0x8(r1) lfd f0, 0x8(r1) fsubs f0, f0, f2 fmuls f1, f0, f1 bl -0x27DFCC mr r27, r3 cmplw r27, r30 blt- .loc_0xA4 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1AD addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x315500 .loc_0xA4: add r27, r29, r27 b .loc_0x194 .loc_0xAC: lfs f0, -0x1C8(r2) fcmpo cr0, f1, f0 cror 2, 0x1, 0x2 beq- .loc_0xD8 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1B0 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x315534 .loc_0xD8: cmplwi r30, 0x1 bgt- .loc_0xFC lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1B1 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x315558 .loc_0xFC: bl -0x2856A8 lfs f0, 0x0(r27) lfs f4, -0x1C8(r2) fsubs f5, f1, f0 fcmpo cr0, f5, f4 bge- .loc_0x11C mr r27, r29 b .loc_0x194 .loc_0x11C: lis r3, 0x4330 lfs f3, -0x1D0(r2) stw r30, 0xC(r1) subi r0, r30, 0x1 lfd f1, -0x1B0(r2) fsubs f2, f3, f0 stw r3, 0x8(r1) li r3, 0x1 lfd f0, 0x8(r1) fsubs f0, f0, f1 fsubs f0, f0, f3 fdivs f0, f2, f0 mtctr r0 cmplwi r30, 0x1 ble- .loc_0x174 .loc_0x158: fsubs f5, f5, f0 fcmpo cr0, f5, f4 bge- .loc_0x16C add r27, r29, r3 b .loc_0x194 .loc_0x16C: addi r3, r3, 0x1 bdnz+ .loc_0x158 .loc_0x174: lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1C3 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x3155EC mr r27, r29 .loc_0x194: cmplwi r28, 0 bne- .loc_0x1B8 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1CC addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x315614 .loc_0x1B8: mr r3, r28 mr r4, r27 lwz r12, 0x0(r28) mr r5, r31 lwz r12, 0xC(r12) mtctr r12 bctrl lmw r27, 0x1C(r1) lwz r0, 0x34(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 8033FC88 * Size: 0001B8 */ void RandId::playSystemSe(unsigned long, JAISound**, unsigned long, unsigned long) { /* .loc_0x0: stwu r1, -0x30(r1) mflr r0 lfs f0, -0x1C0(r2) stw r0, 0x34(r1) stmw r27, 0x1C(r1) mr r27, r3 mr r28, r4 mr r29, r5 mr r30, r6 mr r31, r7 lfs f1, 0x0(r3) fcmpu cr0, f0, f1 bne- .loc_0xAC cmplwi r30, 0x1 bgt- .loc_0x58 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1AA addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x31569C .loc_0x58: bl -0x2857EC lis r0, 0x4330 stw r30, 0xC(r1) lfd f2, -0x1B0(r2) stw r0, 0x8(r1) lfd f0, 0x8(r1) fsubs f0, f0, f2 fmuls f1, f0, f1 bl -0x27E1B4 mr r27, r3 cmplw r27, r30 blt- .loc_0xA4 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1AD addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x3156E8 .loc_0xA4: add r4, r28, r27 b .loc_0x194 .loc_0xAC: lfs f0, -0x1C8(r2) fcmpo cr0, f1, f0 cror 2, 0x1, 0x2 beq- .loc_0xD8 lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1B0 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x31571C .loc_0xD8: cmplwi r30, 0x1 bgt- .loc_0xFC lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1B1 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x315740 .loc_0xFC: bl -0x285890 lfs f0, 0x0(r27) lfs f4, -0x1C8(r2) fsubs f5, f1, f0 fcmpo cr0, f5, f4 bge- .loc_0x11C mr r4, r28 b .loc_0x194 .loc_0x11C: lis r3, 0x4330 lfs f3, -0x1D0(r2) stw r30, 0xC(r1) subi r0, r30, 0x1 lfd f1, -0x1B0(r2) fsubs f2, f3, f0 stw r3, 0x8(r1) li r3, 0x1 lfd f0, 0x8(r1) fsubs f0, f0, f1 fsubs f0, f0, f3 fdivs f0, f2, f0 mtctr r0 cmplwi r30, 0x1 ble- .loc_0x174 .loc_0x158: fsubs f5, f5, f0 fcmpo cr0, f5, f4 bge- .loc_0x16C add r4, r28, r3 b .loc_0x194 .loc_0x16C: addi r3, r3, 0x1 bdnz+ .loc_0x158 .loc_0x174: lis r3, 0x8049 lis r5, 0x8049 addi r3, r3, 0xC8 li r4, 0x1C3 addi r5, r5, 0xD4 crclr 6, 0x6 bl -0x3157D4 mr r4, r28 .loc_0x194: lwz r3, -0x67A8(r13) mr r5, r29 mr r6, r31 bl -0x77B8 lmw r27, 0x1C(r1) lwz r0, 0x34(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 8033FE40 * Size: 000074 */ void EnvSe_Pan::setPanAndDolby(JAISound*) { /* stwu r1, -0x10(r1) mflr r0 li r5, 0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 li r4, 0 stw r30, 8(r1) mr r30, r3 mr r3, r31 lwz r12, 0x10(r31) lfs f1, 0x3c(r30) lwz r12, 0x24(r12) mtctr r12 bctrl mr r3, r31 lfs f1, 0x40(r30) lwz r12, 0x10(r31) li r4, 0 li r5, 0 lwz r12, 0x3c(r12) mtctr r12 bctrl lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033FEB4 * Size: 000060 */ EnvSe_Perspective::EnvSe_Perspective(unsigned long, float, Vec) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r5 stw r30, 8(r1) mr r30, r3 bl __ct__Q28PSSystem9EnvSeBaseFUlf lis r3, __vt__Q26PSGame17EnvSe_Perspective@ha lfs f2, 0(r31) addi r0, r3, __vt__Q26PSGame17EnvSe_Perspective@l lfs f1, 4(r31) stw r0, 0x10(r30) mr r3, r30 lfs f0, 8(r31) stfs f2, 0x3c(r30) stfs f1, 0x40(r30) stfs f0, 0x44(r30) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033FF14 * Size: 00004C */ void EnvSe_Perspective::play() { /* stwu r1, -0x10(r1) mflr r0 li r7, 0 li r8, 0 stw r0, 0x14(r1) li r9, 4 stw r31, 0xc(r1) mr r31, r3 addi r5, r31, 0x34 lwz r3, spSysIF__8PSSystem@sda21(r13) addi r6, r31, 0x3c lwz r4, 0x24(r31) bl "startSoundVecT<8JAISound>__8JAIBasicFUlPP8JAISoundP3VecUlUlUc" lwz r0, 0x14(r1) lwz r3, 0x34(r31) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 8033FF60 * Size: 000088 */ EnvSe_AutoPan::EnvSe_AutoPan(unsigned long, float, float, float, float, float) { /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) addi r11, r1, 0x30 bl _savefpr_28 stw r31, 0xc(r1) fmr f28, f1 mr r31, r3 fmr f29, f2 fmr f30, f4 fmr f31, f5 fmr f1, f3 bl __ct__Q28PSSystem9EnvSeBaseFUlf lis r4, __vt__Q26PSGame9EnvSe_Pan@ha lis r3, __vt__Q26PSGame13EnvSe_AutoPan@ha addi r4, r4, __vt__Q26PSGame9EnvSe_Pan@l li r0, 1 stw r4, 0x10(r31) addi r4, r3, __vt__Q26PSGame13EnvSe_AutoPan@l mr r3, r31 stfs f28, 0x3c(r31) stfs f29, 0x40(r31) stw r4, 0x10(r31) stfs f30, 0x44(r31) stfs f31, 0x48(r31) stb r0, 0x4c(r31) stb r0, 0x4d(r31) addi r11, r1, 0x30 bl _restfpr_28 lwz r0, 0x34(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 8033FFE8 * Size: 00000C */ void EnvSe_AutoPan::setDirection(bool, bool) { /* stb r4, 0x4c(r3) stb r5, 0x4d(r3) blr */ } /* * --INFO-- * Address: 8033FFF4 * Size: 00011C */ void EnvSe_AutoPan::setPanAndDolby(JAISound*) { /* stwu r1, -0x10(r1) mflr r0 li r5, 0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 stw r30, 8(r1) mr r30, r3 b lbl_803400AC lbl_80340018: clrlwi r3, r5, 0x18 addi r4, r3, 0x4c lbzx r0, r30, r4 cmplwi r0, 0 beq lbl_8034006C slwi r0, r3, 2 lfs f0, lbl_8051E190@sda21(r2) add r3, r30, r0 lfs f2, 0x3c(r3) lfs f1, 0x44(r3) fadds f1, f2, f1 stfs f1, 0x3c(r3) lfs f1, 0x3c(r3) fcmpo cr0, f1, f0 ble lbl_803400A8 lfs f0, lbl_8051E1B8@sda21(r2) li r0, 0 fsubs f0, f0, f1 stfs f0, 0x3c(r3) stbx r0, r30, r4 b lbl_803400A8 lbl_8034006C: slwi r0, r3, 2 lfs f0, lbl_8051E198@sda21(r2) add r3, r30, r0 lfs f2, 0x3c(r3) lfs f1, 0x44(r3) fsubs f1, f2, f1 stfs f1, 0x3c(r3) lfs f1, 0x3c(r3) fcmpo cr0, f1, f0 bge lbl_803400A8 lfs f0, lbl_8051E1A0@sda21(r2) li r0, 1 fmuls f0, f1, f0 stfs f0, 0x3c(r3) stbx r0, r30, r4 lbl_803400A8: addi r5, r5, 1 lbl_803400AC: clrlwi r0, r5, 0x18 cmplwi r0, 2 blt lbl_80340018 mr r3, r31 lfs f1, 0x3c(r30) lwz r12, 0x10(r31) li r4, 0 li r5, 0 lwz r12, 0x24(r12) mtctr r12 bctrl mr r3, r31 lfs f1, 0x40(r30) lwz r12, 0x10(r31) li r4, 0 li r5, 0 lwz r12, 0x3c(r12) mtctr r12 bctrl lwz r0, 0x14(r1) lwz r31, 0xc(r1) lwz r30, 8(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 80340110 * Size: 00021C */ Builder_EvnSe_Perspective::Builder_EvnSe_Perspective(JGeometry::TBox3<float>) { /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stw r31, 0x2c(r1) mr r31, r4 stw r30, 0x28(r1) mr r30, r3 bl __ct__11JKRDisposerFv lis r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@ha li r0, 0 addi r3, r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@l lfs f1, 0(r31) stw r3, 0(r30) addi r3, r30, 0x40 lfs f0, 4(r31) stb r0, 0x18(r30) lfs f4, 8(r31) stw r0, 0x1c(r30) lfs f3, 0xc(r31) stw r0, 0x20(r30) lfs f2, 0x10(r31) stfs f1, 0x24(r30) lfs f1, 0x14(r31) stfs f0, 0x28(r30) lfs f0, lbl_8051E198@sda21(r2) stfs f4, 0x2c(r30) stfs f3, 0x30(r30) stfs f2, 0x34(r30) stfs f1, 0x38(r30) stfs f0, 0x3c(r30) bl initiate__10JSUPtrListFv lfs f0, 0x30(r30) li r0, 0 lfs f2, 0x24(r30) fcmpo cr0, f0, f2 cror 2, 1, 2 bne lbl_803401D0 lfs f1, 0x34(r30) lfs f0, 0x28(r30) fcmpo cr0, f1, f0 cror 2, 1, 2 bne lbl_803401D0 lfs f1, 0x38(r30) lfs f0, 0x2c(r30) fcmpo cr0, f1, f0 cror 2, 1, 2 bne lbl_803401D0 li r0, 1 lbl_803401D0: clrlwi. r0, r0, 0x18 bne lbl_80340310 lwz r0, 0x24(r30) lwz r6, 0x28(r30) stw r0, 8(r1) lwz r5, 0x2c(r30) lfs f0, 8(r1) lwz r4, 0x30(r30) lwz r3, 0x34(r30) fcmpo cr0, f2, f0 lwz r0, 0x38(r30) stw r6, 0xc(r1) stw r5, 0x10(r1) stw r4, 0x14(r1) stw r3, 0x18(r1) stw r0, 0x1c(r1) cror 2, 1, 2 bne lbl_8034021C stfs f0, 0x24(r30) lbl_8034021C: lfs f0, 0x28(r30) lfs f1, 0xc(r1) fcmpo cr0, f0, f1 cror 2, 1, 2 bne lbl_80340234 stfs f1, 0x28(r30) lbl_80340234: lfs f0, 0x2c(r30) lfs f2, 0x10(r1) fcmpo cr0, f0, f2 cror 2, 1, 2 bne lbl_8034024C stfs f2, 0x2c(r30) lbl_8034024C: lfs f0, 0x24(r30) lfs f3, 0x14(r1) fcmpo cr0, f0, f3 cror 2, 1, 2 bne lbl_80340264 stfs f3, 0x24(r30) lbl_80340264: lfs f0, 0x28(r30) lfs f4, 0x18(r1) fcmpo cr0, f0, f4 cror 2, 1, 2 bne lbl_8034027C stfs f4, 0x28(r30) lbl_8034027C: lfs f0, 0x2c(r30) lfs f5, 0x1c(r1) fcmpo cr0, f0, f5 cror 2, 1, 2 bne lbl_80340294 stfs f5, 0x2c(r30) lbl_80340294: lfs f0, 0x30(r30) lfs f6, 8(r1) fcmpo cr0, f0, f6 cror 2, 0, 2 bne lbl_803402AC stfs f6, 0x30(r30) lbl_803402AC: lfs f0, 0x34(r30) fcmpo cr0, f0, f1 cror 2, 0, 2 bne lbl_803402C0 stfs f1, 0x34(r30) lbl_803402C0: lfs f0, 0x38(r30) fcmpo cr0, f0, f2 cror 2, 0, 2 bne lbl_803402D4 stfs f2, 0x38(r30) lbl_803402D4: lfs f0, 0x30(r30) fcmpo cr0, f0, f3 cror 2, 0, 2 bne lbl_803402E8 stfs f3, 0x30(r30) lbl_803402E8: lfs f0, 0x34(r30) fcmpo cr0, f0, f4 cror 2, 0, 2 bne lbl_803402FC stfs f4, 0x34(r30) lbl_803402FC: lfs f0, 0x38(r30) fcmpo cr0, f0, f5 cror 2, 0, 2 bne lbl_80340310 stfs f5, 0x38(r30) lbl_80340310: lwz r0, 0x34(r1) mr r3, r30 lwz r31, 0x2c(r1) lwz r30, 0x28(r1) mtlr r0 addi r1, r1, 0x30 blr */ } /* * --INFO-- * Address: 8034032C * Size: 0002D0 */ void Builder_EvnSe_Perspective::build(float, PSSystem::EnvSeMgr*) { /* stwu r1, -0xc0(r1) mflr r0 stw r0, 0xc4(r1) stfd f31, 0xb0(r1) psq_st f31, 184(r1), 0, qr0 stfd f30, 0xa0(r1) psq_st f30, 168(r1), 0, qr0 stfd f29, 0x90(r1) psq_st f29, 152(r1), 0, qr0 stfd f28, 0x80(r1) psq_st f28, 136(r1), 0, qr0 stfd f27, 0x70(r1) psq_st f27, 120(r1), 0, qr0 stfd f26, 0x60(r1) psq_st f26, 104(r1), 0, qr0 stmw r25, 0x44(r1) or. r27, r4, r4 fmr f31, f1 lis r4, lbl_80490038@ha mr r26, r3 addi r30, r4, lbl_80490038@l bne lbl_80340398 addi r3, r30, 0x90 addi r5, r30, 0x9c li r4, 0x254 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80340398: lfs f3, 0x30(r26) lfs f2, 0x24(r26) lfs f1, 0x38(r26) lfs f0, 0x2c(r26) fsubs f29, f3, f2 fsubs f28, f1, f0 stfs f29, 0xc(r1) stfs f28, 8(r1) lbz r0, 0x18(r26) cmplwi r0, 0 bne lbl_80340400 lfs f1, lbl_8051E1BC@sda21(r2) addi r4, r26, 0x1c addi r3, r1, 0xc addi r0, r26, 0x20 lbl_803403D4: lfs f0, 0(r3) cmplw r4, r0 fdivs f0, f0, f1 fctiwz f0, f0 stfd f0, 0x28(r1) lwz r3, 0x2c(r1) stw r3, 0(r4) beq lbl_8034043C mr r4, r0 addi r3, r1, 8 b lbl_803403D4 lbl_80340400: lwz r0, 0x1c(r26) li r3, 0 cmpwi r0, 0 ble lbl_80340420 lwz r0, 0x20(r26) cmpwi r0, 0 ble lbl_80340420 li r3, 1 lbl_80340420: clrlwi. r0, r3, 0x18 bne lbl_8034043C addi r3, r30, 0x90 addi r5, r30, 0x9c li r4, 0x27f crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_8034043C: lwz r3, 0x1c(r26) lis r31, 0x4330 lwz r0, 0x20(r26) li r29, 0 xoris r3, r3, 0x8000 lfs f5, 0x3c(r26) xoris r0, r0, 0x8000 stw r3, 0x2c(r1) lfd f30, lbl_8051E1A8@sda21(r2) stw r31, 0x28(r1) lfs f2, lbl_8051E194@sda21(r2) lfd f0, 0x28(r1) stw r0, 0x34(r1) fsubs f4, f0, f30 lfs f1, 0x24(r26) stw r31, 0x30(r1) lfs f0, 0x2c(r26) lfd f3, 0x30(r1) fdivs f29, f29, f4 stfs f5, 0x20(r1) fsubs f3, f3, f30 fmadds f27, f29, f2, f1 fdivs f28, f28, f3 fmadds f26, f28, f2, f0 b lbl_803405AC lbl_803404A0: xoris r0, r29, 0x8000 stw r31, 0x30(r1) li r28, 0 stw r0, 0x34(r1) lfd f0, 0x30(r1) fsubs f0, f0, f30 fmadds f0, f29, f0, f27 stfs f0, 0x1c(r1) b lbl_8034059C lbl_803404C4: xoris r3, r28, 0x8000 lwz r0, 0x4c(r26) stw r3, 0x34(r1) cmplwi r0, 0 stw r31, 0x30(r1) lfd f0, 0x30(r1) fsubs f0, f0, f30 fmadds f0, f28, f0, f26 stfs f0, 0x24(r1) bne lbl_80340500 addi r3, r30, 0xa8 addi r5, r30, 0xb4 li r4, 0xd2 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80340500: lwz r3, 0x4c(r26) lwz r0, 0xc(r3) stw r0, 0x4c(r26) lwz r0, 0x4c(r26) cmplwi r0, 0 bne lbl_80340520 lwz r0, 0x40(r26) stw r0, 0x4c(r26) lbl_80340520: lwz r4, 0x10(r3) fmr f1, f31 lwz r7, 0x1c(r1) mr r3, r26 lwz r6, 0x20(r1) addi r5, r1, 0x10 lwz r0, 0x24(r1) stw r7, 0x10(r1) stw r6, 0x14(r1) stw r0, 0x18(r1) lwz r12, 0(r26) lwz r12, 0x10(r12) mtctr r12 bctrl or. r25, r3, r3 bne lbl_80340574 addi r3, r30, 0x90 addi r5, r30, 0x9c li r4, 0x296 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80340574: mr r3, r26 mr r4, r25 lwz r12, 0(r26) lwz r12, 0xc(r12) mtctr r12 bctrl mr r3, r27 mr r4, r25 bl append__10JSUPtrListFP10JSUPtrLink addi r28, r28, 1 lbl_8034059C: lwz r0, 0x20(r26) cmpw r28, r0 blt lbl_803404C4 addi r29, r29, 1 lbl_803405AC: lwz r0, 0x1c(r26) cmpw r29, r0 blt lbl_803404A0 psq_l f31, 184(r1), 0, qr0 lfd f31, 0xb0(r1) psq_l f30, 168(r1), 0, qr0 lfd f30, 0xa0(r1) psq_l f29, 152(r1), 0, qr0 lfd f29, 0x90(r1) psq_l f28, 136(r1), 0, qr0 lfd f28, 0x80(r1) psq_l f27, 120(r1), 0, qr0 lfd f27, 0x70(r1) psq_l f26, 104(r1), 0, qr0 lfd f26, 0x60(r1) lmw r25, 0x44(r1) lwz r0, 0xc4(r1) mtlr r0 addi r1, r1, 0xc0 blr */ } /* * --INFO-- * Address: 803405FC * Size: 0000AC */ void Builder_EvnSe_Perspective::newSeObj(unsigned long, float, Vec) { /* stwu r1, -0x40(r1) mflr r0 stw r0, 0x44(r1) stfd f31, 0x30(r1) psq_st f31, 56(r1), 0, qr0 stw r31, 0x2c(r1) stw r30, 0x28(r1) stw r29, 0x24(r1) fmr f31, f1 mr r29, r4 mr r30, r5 li r3, 0x48 bl __nw__FUl or. r31, r3, r3 beq lbl_80340680 lwz r6, 0(r30) fmr f1, f31 lwz r5, 4(r30) mr r4, r29 lwz r0, 8(r30) stw r6, 8(r1) stw r5, 0xc(r1) stw r0, 0x10(r1) bl __ct__Q28PSSystem9EnvSeBaseFUlf lis r3, __vt__Q26PSGame17EnvSe_Perspective@ha lfs f2, 8(r1) addi r0, r3, __vt__Q26PSGame17EnvSe_Perspective@l lfs f1, 0xc(r1) stw r0, 0x10(r31) lfs f0, 0x10(r1) stfs f2, 0x3c(r31) stfs f1, 0x40(r31) stfs f0, 0x44(r31) lbl_80340680: mr r3, r31 psq_l f31, 56(r1), 0, qr0 lwz r0, 0x44(r1) lfd f31, 0x30(r1) lwz r31, 0x2c(r1) lwz r30, 0x28(r1) lwz r29, 0x24(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 803406A8 * Size: 0000C8 */ Builder_EvnSe_Perspective::~Builder_EvnSe_Perspective() { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) mr r30, r4 stw r29, 0x14(r1) or. r29, r3, r3 beq lbl_80340750 lis r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@ha addic. r0, r29, 0x40 addi r0, r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@l stw r0, 0(r29) beq lbl_80340734 b lbl_80340714 lbl_803406E4: mr r4, r31 addi r3, r29, 0x40 bl remove__10JSUPtrListFP10JSUPtrLink lwz r31, 0(r31) cmplwi r31, 0 beq lbl_80340714 beq lbl_8034070C mr r3, r31 li r4, 0 bl __dt__10JSUPtrLinkFv lbl_8034070C: mr r3, r31 bl __dl__FPv lbl_80340714: lwz r31, 0x40(r29) cmplwi r31, 0 bne lbl_803406E4 addic. r0, r29, 0x40 beq lbl_80340734 addi r3, r29, 0x40 li r4, 0 bl __dt__10JSUPtrListFv lbl_80340734: mr r3, r29 li r4, 0 bl __dt__11JKRDisposerFv extsh. r0, r30 ble lbl_80340750 mr r3, r29 bl __dl__FPv lbl_80340750: lwz r0, 0x24(r1) mr r3, r29 lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } } // namespace PSGame namespace PSSystem { /* * --INFO-- * Address: 80340770 * Size: 000050 */ void SingletonBase<PSGame::SeMgr>::~SingletonBase() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) or. r31, r3, r3 beq lbl_803407A8 lis r5, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha extsh. r0, r4 addi r4, r5, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l li r0, 0 stw r4, 0(r31) stw r0, "sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) ble lbl_803407A8 bl __dl__FPv lbl_803407A8: lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } namespace PSGame { } // namespace PSGame /* * --INFO-- * Address: 803407C0 * Size: 000004 */ void Builder_EvnSe_Perspective::onBuild(PSSystem::EnvSeBase*) { } } // namespace PSSystem namespace PSSystem { /* * --INFO-- * Address: 803407C4 * Size: 00000C */ void EnvSeBase::getCastType() { /* lis r3, 0x62617365@ha addi r3, r3, 0x62617365@l blr */ } /* * --INFO-- * Address: 803407D0 * Size: 000004 */ void EnvSeBase::setPanAndDolby(JAISound*) { } namespace PSGame { } // namespace PSGame /* * --INFO-- * Address: 803407D4 * Size: 000064 */ SeMgr::~SeMgr() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) or. r31, r3, r3 beq lbl_80340820 lis r3, __vt__Q26PSGame5SeMgr@ha addi r0, r3, __vt__Q26PSGame5SeMgr@l stw r0, 0(r31) beq lbl_80340810 lis r3, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha li r0, 0 addi r3, r3, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l stw r3, 0(r31) stw r0, "sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) lbl_80340810: extsh. r0, r4 ble lbl_80340820 mr r3, r31 bl __dl__FPv lbl_80340820: lwz r0, 0x14(r1) mr r3, r31 lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } } // namespace PSSystem
19.987716
86
0.556939
projectPiki
00349196d94850f17f334ed09b7811c8a9995fba
997
cpp
C++
src/examples/04_module/01_bank/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
19a44954ebef1b621b851fb0089e1c72c6d7f935
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
19a44954ebef1b621b851fb0089e1c72c6d7f935
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
19a44954ebef1b621b851fb0089e1c72c6d7f935
[ "MIT" ]
null
null
null
#include "bank_account.h" #include "savings_account.h" #include "customer.h" #include<iostream> #include<vector> #include<string> using std::cout; using std::cin; int main() { SavingsAccount* s = new SavingsAccount(500); SavingsAccount s{ 90 }; SavingsAccount s{ 90 }; CheckingAccount checking{ 100 }; CheckingAccount checking1{ 90 }; std::vector<BankAccount> accounts{ s,c }; /*std::vector<BankAccount> accounts{ BankAccount(100), BankAccount(200) }; for (auto act : accounts) { cout << act.get_balance() << "\n"; }*/ BankAccount account(500); Customer cust; cust.add_account(account); /*cin >> account; cout << account; display_balance(account); auto balance = account.get_balance(); cout << "Balance is: \n" << balance; auto amount{ 0 }; cout << "\nEnter deposit amount: \n"; cin >> amount;*/ try { account.deposit(amount); cout << "Balance is: " << account.get_balance(); } catch (Invalid e) { cout << e.get_error() << "\n"; } return 0; }
18.127273
55
0.656971
acc-cosc-1337-spring-2020
0034e67156b17c063d97497084d8497ba9f12601
1,138
cpp
C++
src/operators/gradient.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
src/operators/gradient.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
2
2022-02-18T22:43:06.000Z
2022-02-18T22:43:19.000Z
src/operators/gradient.cpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
#include "gradient.hpp" #include "io/logging.hpp" namespace ccs { gradient::gradient(const mesh& m, const stencil& st, const bcs::Grid& grid_bcs, const bcs::Object& obj_bcs, bool enable_logging) { logs logger{enable_logging, "gradient", "gradient.csv"}; logger.set_pattern("%v"); auto st_info = st.query_max(); logger(spdlog::level::info, "timestamp,deriv,interp_dir,ic,y,psi,{}", fmt::join(vs::repeat_n("wall,psi", st_info.t - 1), ",")); logger.set_pattern("%Y-%m-%d %H:%M:%S.%f,%v"); dx = derivative{0, m, st, grid_bcs, obj_bcs, logger}; dy = derivative{1, m, st, grid_bcs, obj_bcs, logger}; dz = derivative{2, m, st, grid_bcs, obj_bcs, logger}; ex = m.extents(); } std::function<void(vector_span)> gradient::operator()(scalar_view u) const { return std::function<void(vector_span)>{[this, u](vector_span du) { du = 0; if (ex[0] > 1) dx(u, get<vi::X>(du)); if (ex[1] > 1) dy(u, get<vi::Y>(du)); if (ex[2] > 1) dz(u, get<vi::Z>(du)); }}; } } // namespace ccs
30.756757
74
0.558875
lanl
003b19cff897ccba73dd90d6c03796dd068c6f63
2,889
cc
C++
projects/SimpleApplication/code/main.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
projects/SimpleApplication/code/main.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
projects/SimpleApplication/code/main.cc
Destinum/S0008E
25344cc26c92ee022d7d7eac7428a113aa0be3a2
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include<cmath> #include <unistd.h> #include <sys/utsname.h> #include <thread> #include <vector> using namespace std; unsigned long int Calculation() { unsigned long int Result = 0; for (int i = 1; i <= 50000; i++) { for (int j = 1; j <= i; j++) { Result += sqrt(i * j); } } return Result; } void ThreadFunction() { cout << "Thread " << this_thread::get_id() << " created. Calculating..." << endl; unsigned long int Result = Calculation(); cout << "Thread " << this_thread::get_id() << " finished calculation. Result: " << Result << endl; } int main() { string Command; int Value; struct utsname SystemInfo; cout << "List of Commands: " << endl << "'-i' to show system information." << endl << "'-f' and an integer to run X calculations using forks." << endl << "'-t' and an integer to run X calculations using threads." << endl << endl; while(true) { cout << "Enter Command: "; cin >> Command; if (!cin.good()) { cout << "Invalid Command." << endl; } else if (Command == "-i") { char Hostname[1024]; gethostname(Hostname, 1024); uname(&SystemInfo); cout << "Number of Processors: " << std::thread::hardware_concurrency() << endl; cout << "Hostname: " << Hostname << endl; cout << "Hardware Platform: " << SystemInfo.machine << endl; cout << "Total RAM: " << sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE) / pow(10, 9) << " GB" << endl; } else if (Command == "-f") { cin >> Value; while (!cin.good() || Value < 1) { cout << "Invalid Value. Enter an integer of 1 or more: "; cin.clear(); cin.ignore(123, '\n'); cin >> Value; } pid_t Parent = getpid(); pid_t Forks[Value]; cout << "Parent Process ID: " << Parent << endl; for (int i = 0; i < Value; i++) { Forks[i] = fork(); if (Parent != getpid()) break; cout << "PID of child #" << i + 1 << ": " << Forks[i] << endl; } cout << "Process " << getpid() << " finished calculation. Result: " << Calculation() << endl; if (Parent != getpid()) { return 0; } sleep(4); } else if (Command == "-t") { cin >> Value; while (!cin.good() || Value < 1) { cout << "Invalid Value. Enter an integer of 1 or more: "; cin.clear(); cin.ignore(123, '\n'); cin >> Value; } //cout << "Command is " << Command << " with value " << Value << "."<< endl; vector<thread> ListOfThreads; for (int i = 0; i < Value; i++) { //thread thread(ThreadFunction); //thread.detach(); //thread(ThreadFunction).detach(); ListOfThreads.emplace_back(thread(ThreadFunction)); } sleep(1); cout << endl; for (auto& th : ListOfThreads) th.join(); } else { cout << "Invalid Command." << endl; } cout << endl; cin.clear(); cin.ignore(123, '\n'); } }
19.787671
107
0.555556
Destinum
004012c9a61c056eb72c5768bb66577917fb131c
2,807
cpp
C++
src/ProjectionLibrary/src/HeightMapAnalysis.cpp
psteinb/premosa
5796bacbaea9abe404c3e04024e97bb0e0b542c2
[ "BSD-3-Clause" ]
6
2017-10-25T01:15:13.000Z
2021-03-02T23:06:06.000Z
src/ProjectionLibrary/src/HeightMapAnalysis.cpp
psteinb/premosa
5796bacbaea9abe404c3e04024e97bb0e0b542c2
[ "BSD-3-Clause" ]
1
2018-07-12T11:53:54.000Z
2018-10-19T21:37:25.000Z
src/ProjectionLibrary/src/HeightMapAnalysis.cpp
psteinb/premosa
5796bacbaea9abe404c3e04024e97bb0e0b542c2
[ "BSD-3-Clause" ]
2
2018-03-20T10:49:58.000Z
2019-07-10T13:32:39.000Z
// // HeightMapAnalysis.cpp // // Created by Corinna Blasse on 30/08/12. // #include "HeightMapAnalysis.h" #include <cmath> #include <iostream> extern "C" { #include "draw.h" #include "histogram.h" #include "image.h" } #include "MylibValues.h" #include "Develop.h" using namespace MylibValues; namespace ProjectionResults { //////////////////////////////////////////////////////////////////////////////// /* Computation of the range (minimal and maximal z-section) of the height map @param heightMap: height map */ HeightMapRange GetLevelRange(Array * heightMap){ uint32 * hmVals = AUINT32(heightMap); HeightMapRange range; // set inital values, which will be definitely replaced range.maxLayer = 0; range.minLayer = 1000000; for (int i=0; i<heightMap->size; i++) { if (hmVals[i] > range.maxLayer) { range.maxLayer = hmVals[i]; } else if (hmVals[i] < range.minLayer){ range.minLayer = hmVals[i]; } } return range; } //////////////////////////////////////////////////////////////////////////////// /* Computation of the overall smoothness of the height map (The smoothness is defined as the pixel-wise difference between the height map value and the median value of its neighbors) @param heightMap: height map */ double ComputeSmoothness(Array * heightMap) { Array * distances = Make_Array_With_Shape(PLAIN_KIND,UINT32_TYPE,Coord2(heightMap->dims[1], heightMap->dims[0])); uint32 * distVals = AUINT32(distances); uint32 * hmVals = AUINT32(heightMap); Use_Reflective_Boundary(); HeightMapRange range = GetLevelRange(heightMap); // frame defines the local neighborhood Frame * f = Make_Frame(heightMap,Coord2(3,3),Coord2(1,1)); Histogram * h = Make_Histogram(UVAL,range.maxLayer,ValU(1),ValU(0)); Place_Frame(f,0); for (Indx_Type i=0; i< heightMap->size; i++) { Empty_Histogram(h); Histagain_Array(h, f, 0); int middleBin = Value2Bin(h, ValU(hmVals[i])); // To determine the median value of the pixel's neighborhood, we exlude the current pixel i from the histogram h->counts[middleBin]--; distVals[i] = std::abs(static_cast<double>(hmVals[i]) - static_cast<double>(Percentile2Bin(h, 0.5))); } #ifdef DEVELOP Write_Image("HeightMapSmoothness", distances, DONT_PRESS); #endif Empty_Histogram(h); Histagain_Array(h, distances, 0); double meanDistance = Histogram_Mean(h); std::cout << "Smoothness:\n Mean distance: " << meanDistance << "\n Sd: " << Histogram_Sigma(h) << std::endl; Free_Histogram(h); Free_Frame(f); Free_Array(distances); return meanDistance; } }
25.990741
166
0.608835
psteinb
00441f3298b17a8640d117909d59f37f59af3b46
2,196
cc
C++
src/libs/common/plugin/plugin_request.cc
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
24
2021-08-22T12:17:50.000Z
2022-03-03T06:39:00.000Z
src/libs/common/plugin/plugin_request.cc
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
2
2021-09-06T08:16:40.000Z
2021-11-04T06:06:57.000Z
src/libs/common/plugin/plugin_request.cc
warm-byte/DTC
ff98a585c07712000e486cfd2d71515e6538435f
[ "Apache-2.0" ]
15
2021-08-22T14:44:22.000Z
2022-01-30T02:03:22.000Z
/* * Copyright [2021] JD.com, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "plugin_request.h" #include "plugin_sync.h" #include "plugin_dgram.h" #include "../log/log.h" #include "plugin_mgr.h" int PluginStream::handle_process(void) { if (0 != _dll->handle_process(_recv_buf, _real_len, &_send_buf, &_send_len, &_skinfo)) { mark_handle_fail(); log4cplus_error("invoke handle_process failed, worker[%d]", _gettid_()); } else { mark_handle_succ(); } if (_incoming_notifier->Push(this) != 0) { log4cplus_error( "push plugin request to incoming failed, worker[%d]", _gettid_()); delete this; return -1; } return 0; } int PluginDatagram::handle_process(void) { if (0 != _dll->handle_process(_recv_buf, _real_len, &_send_buf, &_send_len, &_skinfo)) { mark_handle_fail(); log4cplus_error("invoke handle_process failed, worker[%d]", _gettid_()); } else { mark_handle_succ(); } if (_incoming_notifier->Push(this) != 0) { log4cplus_error( "push plugin request to incoming failed, worker[%d]", _gettid_()); delete this; return -1; } return 0; } int PluginStream::job_ask_procedure(void) { if (disconnect()) { DELETE(_plugin_sync); delete this; return -1; } if (!handle_succ()) { DELETE(_plugin_sync); delete this; return -1; } if (NULL == _plugin_sync) { delete this; return -1; } _plugin_sync->set_stage(PLUGIN_SEND); _plugin_sync->send_response(); return 0; } int PluginDatagram::job_ask_procedure(void) { if (!handle_succ()) { delete this; return -1; } if (NULL == _plugin_dgram) { delete this; return -1; } _plugin_dgram->send_response(this); return 0; }
20.333333
74
0.68898
warm-byte
004560ab9d5f31501e930cbfac1e2c839180e91c
862
cpp
C++
geonlp_ma_makedic/MakedicCsvFileIO.cpp
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2019-09-15T07:47:41.000Z
2019-09-15T07:47:41.000Z
geonlp_ma_makedic/MakedicCsvFileIO.cpp
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2019-09-13T08:27:35.000Z
2019-09-14T00:43:07.000Z
geonlp_ma_makedic/MakedicCsvFileIO.cpp
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2018-10-03T10:56:23.000Z
2018-10-03T10:56:23.000Z
#include "MakedicCsvFileIO.h" #include <fstream> void MakedicCsvFileIO::write(const std::string& path, const std::vector<MakedicItem>& contents) { std::ofstream stream(path.c_str()); for (std::vector<MakedicItem>::const_iterator it = contents.begin(); it != contents.end(); it++) { MakedicItem item = *it; stream << item.get_surface() << "," << item.get_leftContextId() << "," << item.get_rightContextId() << "," << item.get_cost() << "," << item.get_partOfSpeech() << "," << item.get_subclassification1() << "," << item.get_subclassification2() << "," << item.get_subclassification3() << "," << item.get_conjugatedForm() << "," << item.get_conjugationType() << "," << item.get_originalForm() << "," << item.get_yomi() << "," << item.get_pronunciation() << std::endl; } stream.close(); return; }
28.733333
99
0.603248
t-sagara
00492316f94c180b2d7ea6f3ec5006fec9d844c2
10,356
inl
C++
headers/Impl/GState.inl
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
1
2019-04-25T01:24:43.000Z
2019-04-25T01:24:43.000Z
headers/Impl/GState.inl
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
null
null
null
headers/Impl/GState.inl
NityaNandPandey/AndroidPDF
7a61d488c718dcb1246ed168502a6a3e6921fc87
[ "Apache-2.0" ]
null
null
null
inline GState::GState() : mp_state(0) { } inline GState::GState(const GState& c) { mp_state=c.mp_state; } inline GState& GState::operator=(const GState& c) { mp_state=c.mp_state; return *this; } inline Common::Matrix2D GState::GetTransform() { RetMtx(TRN_GStateGetTransform(mp_state,&result)); } inline ColorSpace GState::GetStrokeColorSpace() { TRN_ColorSpace result; REX(TRN_GStateGetStrokeColorSpace(mp_state,&result)); return ColorSpace(result); } inline ColorSpace GState::GetFillColorSpace() { TRN_ColorSpace result; REX(TRN_GStateGetFillColorSpace(mp_state,&result)); return result; } inline ColorPt GState::GetStrokeColor() { RetCPT(TRN_GStateGetStrokeColor(mp_state,&result)); } inline PatternColor GState::GetStrokePattern() { RetPC(TRN_GStateGetStrokePattern(mp_state,&result)); } inline ColorPt GState::GetFillColor() { RetCPT(TRN_GStateGetFillColor(mp_state,&result)); } inline PatternColor GState::GetFillPattern() { RetPC(TRN_GStateGetFillPattern(mp_state,&result)); } inline double GState::GetFlatness() const { RetDbl(TRN_GStateGetFlatness(mp_state,&result)); } inline GState::LineCap GState::GetLineCap() const { enum TRN_GStateLineCap result; REX(TRN_GStateGetLineCap(mp_state,&result)); return (GState::LineCap)result; } inline GState::LineJoin GState::GetLineJoin() const { enum TRN_GStateLineJoin result; REX(TRN_GStateGetLineJoin(mp_state,&result)); return (GState::LineJoin)result; } inline double GState::GetLineWidth() const { RetDbl(TRN_GStateGetLineWidth(mp_state, &result)); } inline double GState::GetMiterLimit() const { RetDbl(TRN_GStateGetMiterLimit(mp_state, &result)); } inline std::vector<double> GState::GetDashes() const { int dashes_sz; std::vector<double> dashes; REX(TRN_GStateGetDashes(mp_state,0,&dashes_sz)); dashes.resize(dashes_sz); if (dashes_sz < 1) { return dashes; } REX(TRN_GStateGetDashes(mp_state,&(dashes[0]),&dashes_sz)); return dashes; } #ifndef SWIG inline void GState::GetDashes(std::vector<double>& dashes) const { int dashes_sz; REX(TRN_GStateGetDashes(mp_state,0,&dashes_sz)); dashes.resize(dashes_sz); if (dashes_sz < 1) return; REX(TRN_GStateGetDashes(mp_state,&(dashes[0]),&dashes_sz)); } #endif inline double GState::GetPhase() const { RetDbl(TRN_GStateGetPhase(mp_state,&result)); } inline double GState::GetCharSpacing() const { RetDbl(TRN_GStateGetCharSpacing(mp_state, &result)); } inline double GState::GetWordSpacing() const { RetDbl(TRN_GStateGetWordSpacing(mp_state, &result)); } inline double GState::GetHorizontalScale() const { RetDbl(TRN_GStateGetHorizontalScale(mp_state, &result)); } inline double GState::GetLeading() const { RetDbl(TRN_GStateGetLeading(mp_state, &result)); } inline Font GState::GetFont() const { TRN_Font result; REX(TRN_GStateGetFont(mp_state, &result)); return Font(result); } inline double GState::GetFontSize() const { RetDbl(TRN_GStateGetFontSize(mp_state, &result)); } inline GState::TextRenderingMode GState::GetTextRenderMode() const { enum TRN_GStateTextRenderingMode result; REX(TRN_GStateGetTextRenderMode(mp_state,&result)); return (TextRenderingMode)result; } inline double GState::GetTextRise() const { RetDbl(TRN_GStateGetTextRise(mp_state,&result)); } inline bool GState::IsTextKnockout() const { RetBool(TRN_GStateIsTextKnockout(mp_state,&result)); } inline GState::RenderingIntent GState::GetRenderingIntent() const { enum TRN_GStateRenderingIntent result; REX(TRN_GStateGetRenderingIntent(mp_state,&result)); return (GState::RenderingIntent)result; } inline GState::RenderingIntent GState::GetRenderingIntentType(const char* name) { enum TRN_GStateRenderingIntent result; REX(TRN_GStateGetRenderingIntentType(name,&result)); return (GState::RenderingIntent)result; } inline GState::BlendMode GState::GetBlendMode() { enum TRN_GStateBlendMode result; REX(TRN_GStateGetBlendMode(mp_state,&result)); return (BlendMode)result; } inline double GState::GetFillOpacity() const { RetDbl(TRN_GStateGetFillOpacity(mp_state,&result)); } inline double GState::GetStrokeOpacity() const { RetDbl(TRN_GStateGetStrokeOpacity(mp_state,&result)); } inline bool GState::GetAISFlag() const { RetBool(TRN_GStateGetAISFlag(mp_state,&result)); } inline SDF::Obj GState::GetSoftMask() { RetObj(TRN_GStateGetSoftMask(mp_state,&result)); } inline Common::Matrix2D GState::GetSoftMaskTransform() { RetMtx(TRN_GStateGetSoftMaskTransform(mp_state,&result)); } inline bool GState::GetStrokeOverprint() const { RetBool(TRN_GStateGetStrokeOverprint(mp_state,&result)); } inline bool GState::GetFillOverprint() const { RetBool(TRN_GStateGetFillOverprint(mp_state,&result)); } inline int GState::GetOverprintMode() const { RetInt(TRN_GStateGetOverprintMode(mp_state,&result)); } inline bool GState::GetAutoStrokeAdjust() const { RetBool(TRN_GStateGetAutoStrokeAdjust(mp_state,&result)); } inline double GState::GetSmoothnessTolerance() const { RetDbl(TRN_GStateGetSmoothnessTolerance(mp_state,&result)); } inline SDF::Obj GState::GetTransferFunct() { RetObj(TRN_GStateGetTransferFunct(mp_state,&result)); } inline SDF::Obj GState::GetBlackGenFunct() { RetObj(TRN_GStateGetBlackGenFunct(mp_state,&result)); } inline SDF::Obj GState::GetUCRFunct() { RetObj(TRN_GStateGetUCRFunct(mp_state,&result)); } inline SDF::Obj GState::GetHalftone() { RetObj(TRN_GStateGetHalftone(mp_state,&result)); } inline void GState::SetTransform(const Common::Matrix2D& mtx) { REX(TRN_GStateSetTransformMatrix(mp_state,(const TRN_Matrix2D*)&mtx)); } inline void GState::SetTransform(double a, double b, double c, double d, double h, double v) { REX(TRN_GStateSetTransform(mp_state,a,b,c,d,h,v)); } inline void GState::Concat(const Common::Matrix2D& mtx) { REX(TRN_GStateConcatMatrix(mp_state,(const TRN_Matrix2D*)&mtx)); } inline void GState::Concat(double a, double b, double c, double d, double h, double v) { REX(TRN_GStateConcat(mp_state,a,b,c,d,h,v)); } inline void GState::SetStrokeColorSpace(ColorSpace cs) { REX(TRN_GStateSetStrokeColorSpace(mp_state,cs.mp_cs)); } inline void GState::SetFillColorSpace(ColorSpace cs) { REX(TRN_GStateSetFillColorSpace(mp_state,cs.mp_cs)); } inline void GState::SetStrokeColor(const ColorPt& c) { REX(TRN_GStateSetStrokeColorWithColorPt(mp_state,(TRN_ColorPt*)&c)); } inline void GState::SetStrokeColor(PatternColor pattern) { REX(TRN_GStateSetStrokeColorWithPattern(mp_state,pattern.mp_pc)); } inline void GState::SetStrokeColor(PatternColor pattern, const ColorPt& c) { REX(TRN_GStateSetStrokeColor(mp_state,pattern.mp_pc,(TRN_ColorPt*)&c)); } inline void GState::SetFillColor(const ColorPt& c) { REX(TRN_GStateSetFillColorWithColorPt(mp_state,(TRN_ColorPt*)&c)); } inline void GState::SetFillColor(PatternColor pattern) { REX(TRN_GStateSetFillColorWithPattern(mp_state,pattern.mp_pc)); } inline void GState::SetFillColor(PatternColor pattern, const ColorPt& c) { REX(TRN_GStateSetFillColor(mp_state, pattern.mp_pc,(const TRN_ColorPt*)&c)); } inline void GState::SetFlatness(double flatness) { REX(TRN_GStateSetFlatness(mp_state, flatness)); } inline void GState::SetLineCap(LineCap cap) { REX(TRN_GStateSetLineCap(mp_state, (enum TRN_GStateLineCap)cap)); } inline void GState::SetLineJoin(LineJoin join) { REX(TRN_GStateSetLineJoin(mp_state, (enum TRN_GStateLineJoin)join)); } inline void GState::SetLineWidth(double width) { REX(TRN_GStateSetLineWidth(mp_state,width)); } inline void GState::SetMiterLimit(double miter_limit) { REX(TRN_GStateSetMiterLimit(mp_state,miter_limit)); } inline void GState::SetDashPattern(const std::vector<double>& dash_array, double phase) { size_t sz = dash_array.size(); REX(TRN_GStateSetDashPattern(mp_state, (sz<1 ? 0 : &dash_array[0]), int(sz), phase)); } inline void GState::SetCharSpacing(double char_spacing) { REX(TRN_GStateSetCharSpacing(mp_state,char_spacing)); } inline void GState::SetWordSpacing(double word_spacing) { REX(TRN_GStateSetWordSpacing(mp_state,word_spacing)); } inline void GState::SetHorizontalScale(double hscale) { REX(TRN_GStateSetHorizontalScale(mp_state,hscale)); } inline void GState::SetLeading(double leading) { REX(TRN_GStateSetLeading(mp_state,leading)); } inline void GState::SetFont(Font font, double font_sz) { REX(TRN_GStateSetFont(mp_state,font.mp_font,font_sz)); } inline void GState::SetTextRenderMode(TextRenderingMode rmode) { REX(TRN_GStateSetTextRenderMode(mp_state,(enum TRN_GStateTextRenderingMode)rmode)); } inline void GState::SetTextRise(double rise) { REX(TRN_GStateSetTextRise(mp_state,rise)); } inline void GState::SetTextKnockout(bool knockout) { REX(TRN_GStateSetTextKnockout(mp_state,BToTB(knockout))); } inline void GState::SetRenderingIntent(RenderingIntent intent) { REX(TRN_GStateSetRenderingIntent(mp_state,(enum TRN_GStateRenderingIntent)intent)); } inline void GState::SetBlendMode(BlendMode BM) { REX(TRN_GStateSetBlendMode(mp_state, (enum TRN_GStateBlendMode)BM)); } inline void GState::SetFillOpacity(double ca) { REX(TRN_GStateSetFillOpacity(mp_state,ca)); } inline void GState::SetStrokeOpacity(double CA) { REX(TRN_GStateSetStrokeOpacity(mp_state, CA)); } inline void GState::SetAISFlag(bool AIS) { REX(TRN_GStateSetAISFlag(mp_state,BToTB(AIS))); } inline void GState::SetSoftMask(SDF::Obj SM) { REX(TRN_GStateSetSoftMask(mp_state,SM.mp_obj)); } inline void GState::SetStrokeOverprint(bool OP) { REX(TRN_GStateSetStrokeOverprint(mp_state,BToTB(OP))); } inline void GState::SetFillOverprint(bool op) { REX(TRN_GStateSetFillOverprint(mp_state,BToTB(op))); } inline void GState::SetOverprintMode(int OPM) { REX(TRN_GStateSetOverprintMode(mp_state,OPM)); } inline void GState::SetAutoStrokeAdjust(bool SA) { REX(TRN_GStateSetAutoStrokeAdjust(mp_state,BToTB(SA))); } inline void GState::SetSmoothnessTolerance(double SM) { REX(TRN_GStateSetSmoothnessTolerance(mp_state,SM)); } inline void GState::SetBlackGenFunct(SDF::Obj BG) { REX(TRN_GStateSetBlackGenFunct(mp_state,BG.mp_obj)); } inline void GState::SetUCRFunct(SDF::Obj UCR) { REX(TRN_GStateSetUCRFunct(mp_state,UCR.mp_obj)); } inline void GState::SetTransferFunct(SDF::Obj TR) { REX(TRN_GStateSetTransferFunct(mp_state,TR.mp_obj)); } inline void GState::SetHalftone(SDF::Obj HT) { REX(TRN_GStateSetHalftone(mp_state,HT.mp_obj)); } inline GState::GState(TRN_GState impl) : mp_state(impl) { }
22.270968
92
0.781672
NityaNandPandey
00496c1a78cefa3402280a38f591de341fa1f608
14,602
cpp
C++
Bonsai/graphics/D3D.cpp
Resoona/Bonsai-Engine
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
[ "MIT" ]
null
null
null
Bonsai/graphics/D3D.cpp
Resoona/Bonsai-Engine
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
[ "MIT" ]
null
null
null
Bonsai/graphics/D3D.cpp
Resoona/Bonsai-Engine
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
[ "MIT" ]
null
null
null
#include "D3D.h" namespace bonsai { namespace graphics { Direct3D::Direct3D() { m_SwapChain = nullptr; m_Device = nullptr; m_DeviceContext = nullptr; m_RenderTargetView = nullptr; m_DepthStencilBuffer = nullptr; m_DepthStencilState = nullptr; m_DepthDisabledStencilState = nullptr; m_DepthStencilView = nullptr; m_RasterState = nullptr; m_AlphaDisableBlendingState = nullptr; m_AlphaEnableBlendingState = nullptr; } Direct3D::Direct3D(const Direct3D&) { } Direct3D::~Direct3D() { } bool Direct3D::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth, float screenNear) { HRESULT result; IDXGIFactory* factory; IDXGIAdapter* adapter; IDXGIOutput* adapterOutput; UINT numModes, i, numerator, denominator; ULONGLONG stringLength; DXGI_MODE_DESC* displayModeList; DXGI_ADAPTER_DESC adapterDesc; INT error; DXGI_SWAP_CHAIN_DESC swapChainDesc; D3D_FEATURE_LEVEL featureLevel; ID3D11Texture2D* backBufferPtr; D3D11_TEXTURE2D_DESC depthBufferDesc; D3D11_DEPTH_STENCIL_DESC depthStencilDesc; D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; D3D11_RASTERIZER_DESC rasterDesc; D3D11_VIEWPORT viewport; D3D11_BLEND_DESC blendStateDesc; m_vsync_enabled = vsync; //Create a DirectX graphics interface factory result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory); if (FAILED(result)) return false; // Use the factory to create an adapter for the primary graphics interface (video card). result = factory->EnumAdapters(0, &adapter); if (FAILED(result)) return false; // Enumerate the primary adapter output (monitor). result = adapter->EnumOutputs(0, &adapterOutput); if (FAILED(result)) return false; // Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL); if (FAILED(result)) return false; // Create a list to hold all the possible display modes for this monitor/video card combination. displayModeList = new DXGI_MODE_DESC[numModes]; if (!displayModeList) return false; // Now fill the display mode list structures. result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList); if (FAILED(result)) return false; // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the numerator and denominator of the refresh rate for that monitor. for(i=0; i<numModes; i++) { if ((displayModeList[i].Width == (UINT)screenWidth) && displayModeList[i].Height == (UINT)screenHeight) { numerator = displayModeList[i].RefreshRate.Numerator; denominator = displayModeList[i].RefreshRate.Denominator; } } //Get the video card description result = adapter->GetDesc(&adapterDesc); if (FAILED(result)) return false; //store in MB m_VideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024); //Convert the name of the video card to a character array and store it. error = wcstombs_s(&stringLength, m_VideoCardDescription, 128, adapterDesc.Description, 128); if (error != 0) return false; //Release ptrs delete[] displayModeList; displayModeList = nullptr; adapterOutput->Release(); adapterOutput = nullptr; adapter->Release(); adapter = nullptr; factory->Release(); factory = nullptr; //Init swap chain (back and front buffers) //Self note ZeroMemory == memset(dest,0,size) ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); //Set to a single back buffer swapChainDesc.BufferCount = 1; //Set the widths and height of the back buffer swapChainDesc.BufferDesc.Width = screenWidth; swapChainDesc.BufferDesc.Height = screenHeight; //Set regular 32-bit surface for the back buffer swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //refresh rate if(m_vsync_enabled) { swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator; swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator; } else { swapChainDesc.BufferDesc.RefreshRate.Numerator = 0; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; } //Set usage of back buffer swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //Set the handle for the window to render to swapChainDesc.OutputWindow = hwnd; //Turn multisampling off swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; //Set to fullscreen or windowed mode if (fullscreen) swapChainDesc.Windowed = false; else swapChainDesc.Windowed = true; //Set the scan line ordering and scaling to unspecified swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //Discard the back buffer after presenting swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //Dont set the advanced flags swapChainDesc.Flags = 0; //Set feature level (can swap to lower versions to support lower end hardware) featureLevel = D3D_FEATURE_LEVEL_11_0; //Create swap chain, D3D device and D3d device context - if no dx11 support swap driver type hardward to reference for cpu rendering result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_Device, NULL, &m_DeviceContext); if (FAILED(result)) return false; //Get the pointer to the backbuffer result = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr); if (FAILED(result)) return false; //Create render target view with the back buffer pointer result = m_Device->CreateRenderTargetView(backBufferPtr, NULL, &m_RenderTargetView); if (FAILED(result)) return false; //Release pointer to the back buffer as we no longer need it backBufferPtr->Release(); backBufferPtr = nullptr; //Initalize the description and the depth buffer ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc)); //Setup the description of the depth buffer (with attached stencil for blur, vol shadows, etc) depthBufferDesc.Width = screenWidth; depthBufferDesc.Height = screenHeight; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthBufferDesc.SampleDesc.Count = 1; depthBufferDesc.SampleDesc.Quality = 0; depthBufferDesc.Usage = D3D11_USAGE_DEFAULT; depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthBufferDesc.CPUAccessFlags = 0; depthBufferDesc.MiscFlags = 0; //Create the texture for the depth buffer using the filled out desc result = m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer); if (FAILED(result)) return false; //setup the depth stensil desc //init the description ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; //if the pixel is front facing depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //if the pixel is back-facing depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; result = m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState); if (FAILED(result)) return false; //Set the depth stencil state m_DeviceContext->OMSetDepthStencilState(m_DepthStencilState, 1); //FOR 2D ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc)); depthDisabledStencilDesc.DepthEnable = false; depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthDisabledStencilDesc.StencilEnable = true; depthDisabledStencilDesc.StencilReadMask = 0xFF; depthDisabledStencilDesc.StencilWriteMask = 0xFF; //if the pixel is front facing depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //if the pixel is back-facing depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; result = m_Device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_DepthDisabledStencilState); if (FAILED(result)) return false; //initalize the depth stencil view ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); //setup the depth stencil view desc depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilViewDesc.Texture2D.MipSlice = 0; //create the depth stencil view result = m_Device->CreateDepthStencilView(m_DepthStencilBuffer, &depthStencilViewDesc, &m_DepthStencilView); if (FAILED(result)) return false; //bind the render target view and depth stencil buffer to the output render pipeline m_DeviceContext->OMSetRenderTargets(1, &m_RenderTargetView, m_DepthStencilView); //setup the raster description which will determine h ow and what polygons will be drawn rasterDesc.AntialiasedLineEnable = false; rasterDesc.CullMode = D3D11_CULL_BACK; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = 0.0f; rasterDesc.DepthClipEnable = true; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.MultisampleEnable = false; rasterDesc.ScissorEnable = false; rasterDesc.SlopeScaledDepthBias = 0.0f; //Create the rasterizer state from the desc result = m_Device->CreateRasterizerState(&rasterDesc, &m_RasterState); if (FAILED(result)) return false; //Now set the rasterizer state m_DeviceContext->RSSetState(m_RasterState); //Setup the viewport for rendering viewport.Width = (float)screenWidth; viewport.Height = (float)screenHeight; viewport.MaxDepth = 1.0f; viewport.MinDepth = 0.0f; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; //Create the viewport m_DeviceContext->RSSetViewports(1, &viewport); //Init blend state desc ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC)); //For when we want blending blendStateDesc.RenderTarget[0].BlendEnable = true; blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_ALPHA; blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f; result = m_Device->CreateBlendState(&blendStateDesc, &m_AlphaEnableBlendingState); if (FAILED(result)) return false; //For when we dont want blending blendStateDesc.RenderTarget[0].BlendEnable = false; result = m_Device->CreateBlendState(&blendStateDesc, &m_AlphaDisableBlendingState); if (FAILED(result)) return false; //World Matrix m_WorldMatrix = XMMatrixIdentity(); return true; } void Direct3D::Shutdown() { //before shutdown set to windowed to avoid throwing exceptions if(m_SwapChain) { m_SwapChain->SetFullscreenState(false, NULL); } if (m_RasterState) { m_RasterState->Release(); m_RasterState = nullptr; } if (m_DepthStencilView) { m_DepthStencilView->Release(); m_DepthStencilView = nullptr; } if (m_DepthStencilState) { m_DepthStencilState->Release(); m_DepthStencilState = nullptr; } if (m_DepthDisabledStencilState) { m_DepthDisabledStencilState->Release(); m_DepthDisabledStencilState = nullptr; } if (m_DepthStencilBuffer) { m_DepthStencilBuffer->Release(); m_DepthStencilBuffer = nullptr; } if (m_RenderTargetView) { m_RenderTargetView->Release(); m_RenderTargetView = nullptr; } if (m_DeviceContext) { m_DeviceContext->Release(); m_DeviceContext = nullptr; } if (m_Device) { m_Device->Release(); m_Device = nullptr; } if (m_SwapChain) { m_SwapChain->Release(); m_SwapChain = nullptr; } if (m_AlphaDisableBlendingState) { m_AlphaDisableBlendingState->Release(); m_AlphaDisableBlendingState = nullptr; } if (m_AlphaEnableBlendingState) { m_AlphaEnableBlendingState->Release(); m_AlphaEnableBlendingState = nullptr; } } void Direct3D::BeginScene(float red, float green, float blue, float alpha) { float color[4]; color[0] = red; color[1] = green; color[2] = blue; color[3] = alpha; //clear the back buffer m_DeviceContext->ClearRenderTargetView(m_RenderTargetView, color); //clear the depth buffer m_DeviceContext->ClearDepthStencilView(m_DepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0.0f); } void Direct3D::EndScene() { if (m_vsync_enabled) { //lock refresh rate m_SwapChain->Present(1, 0); } else { m_SwapChain->Present(0, 0); } } void Direct3D::GetVideoCardInfo(char* cardName, int& memory) { strcpy_s(cardName, 128, m_VideoCardDescription); memory = m_VideoCardMemory; } } }
32.73991
185
0.751472
Resoona
004a36e80a95872435312482183c0ab60c68c30e
1,071
cc
C++
test/class/class-impl.cc
gabrielschulhof/webidl-napi
88a9f9aa6975351b52b4a787468185c8a5024685
[ "MIT" ]
3
2020-10-20T17:58:24.000Z
2020-11-10T21:04:56.000Z
test/class/class-impl.cc
gabrielschulhof/webidl-napi
88a9f9aa6975351b52b4a787468185c8a5024685
[ "MIT" ]
18
2020-10-20T17:05:23.000Z
2020-11-16T07:04:28.000Z
test/class/class-impl.cc
gabrielschulhof/webidl-napi
88a9f9aa6975351b52b4a787468185c8a5024685
[ "MIT" ]
9
2020-10-20T14:40:31.000Z
2021-03-04T07:33:38.000Z
#include "class-impl.h" struct value__ { value__(unsigned long initial): val(initial) {} unsigned long val = 0; size_t refcount = 1; inline void Ref() { refcount++; } inline void Unref() { if (refcount == 0) abort(); if (--refcount == 0) delete this; } }; void Decrementor::operator=(const Decrementor& other) { val = other.val; val->Ref(); } Decrementor::Decrementor() {} Decrementor::Decrementor(const Incrementor& inc) { val = inc.val; val->Ref(); } Decrementor::~Decrementor() { val->Unref(); } unsigned long Decrementor::decrement() { return --(val->val); } Incrementor::Incrementor(): Incrementor(0) {} Incrementor::Incrementor(DOMString initial_value) : Incrementor(std::stoul(initial_value)) {} Incrementor::Incrementor(unsigned long initial_value): props{"blah", 42} { val = new value__(initial_value); val->val = initial_value; } unsigned long Incrementor::increment() { return ++(val->val); } Decrementor Incrementor::getDecrementor() { return Decrementor(*this); } Incrementor::~Incrementor() { val->Unref(); }
23.8
74
0.678805
gabrielschulhof
004bac6cdf5d212c65c44505d14ab2ee73bc0985
1,618
cpp
C++
tests/Cases/Allocators/TestStackAllocator.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
86
2018-04-20T04:40:20.000Z
2022-02-09T08:36:28.000Z
tests/Cases/Allocators/TestStackAllocator.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
16
2018-04-25T09:34:40.000Z
2020-10-16T03:55:05.000Z
tests/Cases/Allocators/TestStackAllocator.cpp
cpv-project/cpv-framework
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
[ "MIT" ]
10
2019-10-07T08:06:15.000Z
2021-07-26T18:46:11.000Z
#include <functional> #include <CPVFramework/Allocators/StackAllocator.hpp> #include <CPVFramework/Testing/GTestUtils.hpp> TEST(StackAllocator, allocate) { static constexpr const std::size_t Size = sizeof(int)*4; cpv::StackAllocatorStorage<Size> storage; cpv::StackAllocator<int, Size> allocator(storage); using ptr_type = std::unique_ptr<int, std::function<void(int*)>>; ptr_type first(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); }); ptr_type second(allocator.allocate(2), [&allocator] (int* p) { allocator.deallocate(p, 2); }); ptr_type forth(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); }); ptr_type fifth(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); }); ptr_type sixth(allocator.allocate(2), [&allocator] (int* p) { allocator.deallocate(p, 2); }); void* begin = static_cast<void*>(&storage); void* end = static_cast<void*>(&storage + 1); ASSERT_GE(static_cast<void*>(first.get()), begin); ASSERT_LT(static_cast<void*>(first.get()), end); ASSERT_GE(static_cast<void*>(second.get()), begin); ASSERT_LT(static_cast<void*>(second.get()), end); ASSERT_GE(static_cast<void*>(forth.get()), begin); ASSERT_LT(static_cast<void*>(forth.get()), end); ASSERT_EQ(static_cast<void*>(first.get() + 1), static_cast<void*>(second.get())); ASSERT_EQ(static_cast<void*>(second.get() + 2), static_cast<void*>(forth.get())); ASSERT_TRUE(static_cast<void*>(fifth.get()) < begin || static_cast<void*>(fifth.get()) > end); ASSERT_TRUE(static_cast<void*>(sixth.get()) < begin || static_cast<void*>(sixth.get()) > end); }
52.193548
95
0.70581
cpv-project
004cf962302aeb78432151a5e6daf4280d21a93f
2,955
cpp
C++
modules/crypto/src/ExternTemplates.cpp
TankerHQ/sdk-native
5d9eb7c2048fdefae230590a3110e583f08c2c49
[ "Apache-2.0" ]
19
2018-12-05T12:18:02.000Z
2021-07-13T07:33:22.000Z
modules/crypto/src/ExternTemplates.cpp
TankerHQ/sdk-native
5d9eb7c2048fdefae230590a3110e583f08c2c49
[ "Apache-2.0" ]
3
2020-03-16T15:52:06.000Z
2020-08-01T11:14:30.000Z
modules/crypto/src/ExternTemplates.cpp
TankerHQ/sdk-native
5d9eb7c2048fdefae230590a3110e583f08c2c49
[ "Apache-2.0" ]
3
2020-01-07T09:55:32.000Z
2020-08-01T01:29:28.000Z
#include <Tanker/Crypto/AeadIv.hpp> #include <Tanker/Crypto/BasicHash.hpp> #include <Tanker/Crypto/EncryptedSymmetricKey.hpp> #include <Tanker/Crypto/Mac.hpp> #include <Tanker/Crypto/PrivateEncryptionKey.hpp> #include <Tanker/Crypto/PrivateSignatureKey.hpp> #include <Tanker/Crypto/PublicEncryptionKey.hpp> #include <Tanker/Crypto/PublicSignatureKey.hpp> #include <Tanker/Crypto/SealedPrivateEncryptionKey.hpp> #include <Tanker/Crypto/SealedPrivateSignatureKey.hpp> #include <Tanker/Crypto/SealedSymmetricKey.hpp> #include <Tanker/Crypto/Signature.hpp> #include <Tanker/Crypto/SymmetricKey.hpp> #include <Tanker/Crypto/TwoTimesSealedPrivateEncryptionKey.hpp> #include <Tanker/Crypto/TwoTimesSealedSymmetricKey.hpp> namespace Tanker { namespace Crypto { template class BasicCryptographicType<AeadIv, AeadIv::arraySize>; template class BasicCryptographicType<BasicHash<void>, BasicHash<void>::arraySize>; template class BasicHash<void>; template class BasicCryptographicType<EncryptedSymmetricKey, EncryptedSymmetricKey::arraySize>; template class BasicCryptographicType<Mac, Mac::arraySize>; template class BasicCryptographicType< AsymmetricKey<KeyType::Private, KeyUsage::Encryption>, AsymmetricKey<KeyType::Private, KeyUsage::Encryption>::arraySize>; template class AsymmetricKey<KeyType::Private, KeyUsage::Encryption>; template class BasicCryptographicType< AsymmetricKey<KeyType::Private, KeyUsage::Signature>, AsymmetricKey<KeyType::Private, KeyUsage::Signature>::arraySize>; template class AsymmetricKey<KeyType::Private, KeyUsage::Signature>; template class BasicCryptographicType< AsymmetricKey<KeyType::Public, KeyUsage::Encryption>, AsymmetricKey<KeyType::Public, KeyUsage::Encryption>::arraySize>; template class AsymmetricKey<KeyType::Public, KeyUsage::Encryption>; template class BasicCryptographicType< AsymmetricKey<KeyType::Public, KeyUsage::Signature>, AsymmetricKey<KeyType::Public, KeyUsage::Signature>::arraySize>; template class AsymmetricKey<KeyType::Public, KeyUsage::Signature>; template class BasicCryptographicType<SealedPrivateEncryptionKey, SealedPrivateEncryptionKey::arraySize>; template class BasicCryptographicType<SealedPrivateSignatureKey, SealedPrivateSignatureKey::arraySize>; template class BasicCryptographicType<SealedSymmetricKey, SealedSymmetricKey::arraySize>; template class BasicCryptographicType<TwoTimesSealedSymmetricKey, TwoTimesSealedSymmetricKey::arraySize>; template class BasicCryptographicType< TwoTimesSealedPrivateEncryptionKey, TwoTimesSealedPrivateEncryptionKey::arraySize>; template class BasicCryptographicType<Signature, Signature::arraySize>; template class BasicCryptographicType<SymmetricKey, SymmetricKey::arraySize>; } }
50.084746
77
0.770558
TankerHQ
005a90986635ba22239690be245bb249f0927d70
2,420
cpp
C++
engine/calculators/source/SoakCalculator.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/calculators/source/SoakCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/calculators/source/SoakCalculator.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "SoakCalculator.hpp" #include "Wearable.hpp" using namespace std; SoakCalculator::SoakCalculator() { } SoakCalculator::~SoakCalculator() { } // A creature gets 1 point of Soak for every 4 Health over 10, // plus any bonuses or penalties from equipment. int SoakCalculator::calculate_soak(const CreaturePtr& c) { int soak = 0; if (c) { soak = c->get_base_soak().get_current(); soak += get_equipment_bonus(c); soak += get_modifier_bonus(c); soak += get_health_bonus(c); soak += get_rage_bonus(c); } return soak; } int SoakCalculator::get_equipment_bonus(const CreaturePtr& c) { int equipment_soak_bonus = 0; Equipment& eq = c->get_equipment(); EquipmentMap equipment = eq.get_equipment(); for (const EquipmentMap::value_type& item : equipment) { WearablePtr equipped = dynamic_pointer_cast<Wearable>(item.second); if (equipped) { // The player can equip a lot of things in the ammunition slot. // Prevent the use of anything but ammunition when calculating // soak. if (item.first == EquipmentWornLocation::EQUIPMENT_WORN_AMMUNITION) { if (equipped->get_type() == ItemType::ITEM_TYPE_AMMUNITION) { equipment_soak_bonus += equipped->get_evade(); } } else { equipment_soak_bonus += equipped->get_soak(); } } } return equipment_soak_bonus; } int SoakCalculator::get_modifier_bonus(const CreaturePtr& c) { int mod_bonus = 0; if (c) { const map<double, vector<pair<string, Modifier>>> modifiers = c->get_active_modifiers(); for (const auto& mod_pair : modifiers) { for (const auto& current_mod_pair : mod_pair.second) { mod_bonus += current_mod_pair.second.get_soak_modifier(); } } } return mod_bonus; } int SoakCalculator::get_health_bonus(const CreaturePtr& c) { int health_bonus = 0; if (c != nullptr) { int health = c->get_health().get_current(); if (health > 10) { health_bonus = (health - 10) / 4; } } return health_bonus; } int SoakCalculator::get_rage_bonus(const CreaturePtr& c) { int rage_bonus = 0; if (c != nullptr) { if (c->has_status(StatusIdentifiers::STATUS_ID_RAGE)) { rage_bonus = c->get_level().get_current(); } } return rage_bonus; } #ifdef UNIT_TESTS #include "unit_tests/SoakCalculator_test.cpp" #endif
19.836066
92
0.656612
sidav
005c03dd374a0553105b5f618a997b48d8d309d4
7,908
cpp
C++
main.cpp
Daria602/AdventureIn10
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
[ "MIT" ]
1
2021-05-03T12:29:52.000Z
2021-05-03T12:29:52.000Z
main.cpp
Daria602/AdventureIn10
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
[ "MIT" ]
null
null
null
main.cpp
Daria602/AdventureIn10
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
[ "MIT" ]
null
null
null
#include "Game.h" void addSpaces() { std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; } void mainMenu(Character& boss) { std::cout << "You meet " << boss << std::endl; std::cout << "What will you do?" << std::endl; std::cout << "1 - > attack him" << std::endl; std::cout << "2 - > try to run away (if failed, you will have to fight)" << std::endl; std::cout << "3 - > open inventory" << std::endl; } void menuFight() { std::cout << "What will you do?" << std::endl; std::cout << "1 - > attack him again" << std::endl; std::cout << "2 - > open inventory" << std::endl; } void eatFromInventory(Player& player, Inventory& inventory) { std::cout << "What would you like to eat?\n"; for (size_t i = 0; i < inventory.getInventory().size(); i++) { std::cout << i + 1 << " - >" << inventory.getInventory()[i]; } std::cout << "0 - > go back" << std::endl; int index = 0; std::cin >> index; if (index == 0) { return; } while (index != 0 && inventory.getInventory().size() != 0) { Edible e = inventory.getInventory()[index - 1]; player.increaseStamina(e.getReplenishStamina()); player.increaseHealth(e.getReplenishHealth()); inventory.eraseFromInventory(index - 1); std::cout << "What would you like to eat?\n"; for (size_t i = 0; i < inventory.getInventory().size(); i++) { std::cout << i + 1 << " - >" << inventory.getInventory()[i]; } std::cout << "0 - > go back" << std::endl; int index; std::cin >> index; } } void inBossFight(Character &boss, Player &player, Inventory &inventory,Pet &pet) { Character* c; Character* p; p = &pet; c = &player; if (boss.getHP() > 0 && player.getStamina() < 2 && inventory.getInventory().size() == 0) { std::cout << "You are exhausted and have nothing to eat. Game over for you."; return; } boss.wasAttacked(c->attack()); if (boss.getHP() > 0) { c->wasAttacked(boss.attack()); } while (boss.getHP() > 0) { player.seeStats(); menuFight(); if (pet.getIsPresent() == true) { std::cout << "3 - > ask " << pet.getName() << " to attack" << std::endl; } int answer; std::cin >> answer; if (answer == 1 && player.getStamina() >= 2) { boss.wasAttacked(c->attack()); if (boss.getHP() > 0) { c->wasAttacked(boss.attack()); } } else if (answer == 1 && player.getStamina() < 2) { std::cout << "You are too tired to fight "; if (inventory.getInventory().size() == 0 && boss.getHP() > 0) { std::cout << "and you have nothing to eat... GAME OVER"; return; } else { std::cout << ".\nDo you want to eat something?\n1 - > yes\n2 - > no" << std::endl; int answer1; std::cin >> answer1; if (answer1 == 1) { eatFromInventory(player, inventory); } else { if (boss.getHP() > 0) { std::cout << "GAME OVER"; return; } } } } if (answer == 2) { eatFromInventory(player, inventory); } if (answer == 3) { int damage; damage = p->attack(); if (damage != 0) { boss.wasAttacked(damage); if (boss.getHP() > 0) { c->wasAttacked(boss.attack()); } } pet.setIsPresent(false); } } } std::vector<Character> getAllMonsters() { std::vector<Character> monsters; Character mutant("Mutant", 3, 3, 0, 2), goblin("Goblin", 4, 4, 0, 2), businessman("Businessman", 5, 5, 0, 1), evilMagician("Evil Magician", 6, 6, 0, 3); monsters.push_back(mutant); monsters.push_back(goblin); monsters.push_back(businessman); monsters.push_back(evilMagician); return monsters; } std::vector<Edible> getAllEdible() { std::vector<Edible> edibles; Edible apple("Apple", 3, 3), caveCarrot("Cave carrot", 2, 2), pizza("Pizza", 4, 4); edibles.push_back(apple); edibles.push_back(caveCarrot); edibles.push_back(pizza); return edibles; } bool inRoom = true; int main() { srand((unsigned int)time(NULL)); Game game; std::vector<Character> all_monsters = getAllMonsters(); std::vector<Edible> all_edible = getAllEdible(); std::vector<Room> all_rooms; for (int i = 1; i <= 10; i++) { RoomBuilder rb; int indexMonster = rand() % (all_monsters.size() - 1); int indexEdible = rand() % (all_edible.size() - 2); Room r = rb.indexRoom(i).monsterInRoom(all_monsters[indexMonster]).edibleInRoom(all_edible[indexEdible]).build(); all_rooms.push_back(r); } Inventory inventory; Pet pet("Barsik", 5, 5, 1, 4); std::cout << "Welcome to the ADVENTURE IN 10!" << std::endl; std::cout << "What is your name?" << std::endl; std::string name; std::cin >> name; Player player(name, 10, 10, 1, 2, 10, 10); std::cout << "Hello, " << player.getName() << "!" << std::endl; std::cout << "The goal is to get to the treasure room in 10 days. \nEvery action you take will drain your stamina. \nAfter you rest, your stamina will be back to max, but the day count will increase.\n"; int i = 0; while (i < all_rooms.size() && game.getDayCount() <= 10 && player.getHP() > 0) { Room room = all_rooms[i]; std::cout << "You enter the room number " << room.getRoomIndex() << "." << std::endl; if (i == 3) { std::cout << "You see a cat. It seems to like you. You pet him and it decides to stick around." << std::endl; pet.setIsPresent(true); } if (room.getRoomIndex() == 10) { std::cout << "IT'S A TREASURE ROOM!\nCongratulations!!! You won!" << std::endl; return 0; } Character boss = room.getMonster(); mainMenu(boss); inRoom = true; while (inRoom == true) { int answer; std::cin >> answer; switch (answer) { case 1: { if (room.getRoomIndex() > 3) { pet.setIsPresent(true); } inBossFight(boss, player, inventory, pet); if (boss.getHP() > 0) { return 0; } int answer2; std::cout << "Press 1 to continue to the next room.\nPress 2 to scope the room." << std::endl; std::cin >> answer2; if (answer2 == 1) { inRoom = false; } else { Edible eat = room.getEdible(); std::cout << "You found " << eat << "\nWould you like to add it to the inventory?\n1 - > yes\n2 - > no" << std::endl; std::cin >> answer2; if (answer2 == 1) { inventory.addToInventory(eat); std::cout << "The " << eat.getName() << " has been added to your inventory." << std::endl; } inRoom = false; } }break; case 2: { int chance; chance = player.run(); if (chance == 1) { //Character* c; std::cout << "The " << boss.getName() << " is approaching. You raise your weapon." << std::endl; inBossFight(boss, player, inventory, pet); if (boss.getHP() > 0) { return 0; } } else { inRoom = false; } }break; case 3: { eatFromInventory(player, inventory); std::cout << boss.getName() << " is patiently waiting for you. But everybody has their limits..." << std::endl; std::cout << "What will you do?" << std::endl; std::cout << "1 - > attack him" << std::endl; std::cout << "2 - > try to run away (if failed, you will have to fight)" << std::endl; std::cout << "3 - > open inventory" << std::endl; } break; } } std::cout << "Would you like to rest?\n1 - > yes\n2 - > no" << std::endl; int answer; std::cin >> answer; if (answer == 1) { player.rest(); game.incrementDayCount(); } i++; } }
25.758958
205
0.552226
Daria602
005c7dd846eae5eb9e39de2162ec96740911b3c7
580
hpp
C++
peek-mill-utils.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
1
2016-08-22T13:46:32.000Z
2016-08-22T13:46:32.000Z
peek-mill-utils.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
null
null
null
peek-mill-utils.hpp
andybarry/peekmill
d990877ef943a791f66d19ed897f1421b8e6e0ea
[ "BSD-3-Clause" ]
null
null
null
/* * Utility functions for opencv-stereo * * Copyright 2013, Andrew Barry <abarry@csail.mit.edu> * */ #ifndef PEEK_MILL_UTIL #define PEEK_MILL_UTIL #include "opencv2/legacy/legacy.hpp" #include "opencv2/opencv.hpp" #include <stdio.h> using namespace std; using namespace cv; struct OpenCvCalibration { Mat M1; Mat D1; }; bool LoadCalibration(OpenCvCalibration *calibration); //void Draw3DPointsOnImage(Mat camera_image, vector<Point3f> *points_list_in, Mat cam_mat_m, Mat cam_mat_d, Mat cam_mat_r, int color = 128, float x=0, float y=0, float z=0); #endif
18.125
173
0.737931
andybarry
005d101e3205b261677a7a2160e17d31325af760
19,044
cc
C++
code/addons/locale/localeserver.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/addons/locale/localeserver.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/addons/locale/localeserver.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // locale/localeserver_main.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "locale/localeserver.h" #include "locale/localeattributes.h" #include "db/reader.h" #include "db/sqlite3/sqlite3database.h" #include "db/sqlite3/sqlite3factory.h" #include "io/filestream.h" #include "io/ioserver.h" #include "io/textreader.h" #include "io/textwriter.h" namespace Locale { __ImplementClass(Locale::LocaleServer, 'LOCA', Core::RefCounted); __ImplementSingleton(Locale::LocaleServer); using namespace Db; using namespace IO; using namespace Util; //------------------------------------------------------------------------------ /** */ LocaleServer::LocaleServer() : isOpen(false) { __ConstructSingleton; } //------------------------------------------------------------------------------ /** */ LocaleServer::~LocaleServer() { if (this->IsOpen()) { this->Close(); } __DestructSingleton; } //------------------------------------------------------------------------------ /** */ bool LocaleServer::Open() { n_assert(!this->IsOpen()); this->isOpen = true; return true; } //------------------------------------------------------------------------------ /** */ String LocaleServer::ParseText(const String& text) { // replace \n and \t String str(text); str.SubstituteString("\\t", "\t"); str.SubstituteString("\\n", "\n"); return str; } //------------------------------------------------------------------------------ /** */ void LocaleServer::Close() { n_assert(this->IsOpen()); this->dictionary.Clear(); this->isOpen = false; } //------------------------------------------------------------------------------ /** */ String LocaleServer::GetLocaleText(const String& id) { n_assert(this->IsOpen()); if(!id.IsValid()) { return ""; } String idStr(id); if (this->dictionary.Contains(idStr)) { return this->dictionary[idStr]; } else { n_printf("WARNING: Locale::LocaleServer: id string '%s' not found!!\n", id.AsCharPtr()); static String msg; msg = "LOCALIZE: '"; msg.Append(idStr); msg.Append("'"); return msg; } } //------------------------------------------------------------------------------ /** */ String LocaleServer::GetLocaleTextFemale(const String& id) { n_assert(this->IsOpen()); if(!id.IsValid()) { return ""; } String idStr = id; idStr.Append("-female"); if (this->dictionary.Contains(idStr)) { return this->dictionary[idStr]; } else { return this->GetLocaleText(id); } } //------------------------------------------------------------------------------ /** Analyzes argument statements of id which can be: "...{<ArgIdx>:s}..." for string arguments "...{<ArgIdx>:l}..." for string arguments which also will be localized "...{<ArgIdx>:i}..." for integer arguments The argument index must be of type integer ([0-9]*). Gets the locale text with id and replaces the argument statements in the locale text with the arguments. Additionally it's possible to specify a plural choice statement: "...{<ArgIdx>:p:<plural choice>}..." (see PluralChoice(...)) */ String __cdecl LocaleServer::GetLocaleTextArgs(const char* id, ...) { n_assert(this->IsOpen()); // id string String idStr(id); n_assert(idStr.IsValid()); // replaced id String text = ""; // localized text (text with replaced argument statements) String localeText = ""; // analyze argument statements if (!this->AnalyzeArgumentStatements(id)) { n_error("Locale::LocaleServer: %s", this->errMsg.AsCharPtr()); return "Localization Error:" + idStr; } // get arguments and interpret them with help of 'argTypes' va_list vArgList; va_start(vArgList, id); this->InterpretArguments(vArgList); va_end(vArgList); // get text with id text = this->GetLocaleText(idStr); // build localized text by replacing argument statements in text with arguments localeText = this->BuildLocalizedText(text); if (localeText.IsValid()) { return localeText; } else { n_error("Locale::LocaleServer: %s", this->errMsg.AsCharPtr()); return "Localization Error:" + idStr; } } //------------------------------------------------------------------------------ /** Analyzes argument statements and puts results to 'argTypes'. Will return 'false' if there are errors while analyzing process (e.g. syntax errors). Will place error message in 'errMsg'. Type 'l' for localisation will be handled as 's' (string). Type 'p' for plural choice will be handled as 'i' (integer). */ bool LocaleServer::AnalyzeArgumentStatements(const String& str) { n_assert(str.IsValid()); this->argTypes.Clear(); IndexT idxOpenBracket = 0; // index of last found open bracket IndexT idxColon = 0; // index of last found colon String argIdxStr = ""; // argument index (between open bracket and colon) IndexT argIdx = InvalidIndex; // argument index as integer char argType = '\0'; // argument type (character after colon) while (true) { // find open bracket idxOpenBracket = str.FindCharIndex('{', idxColon); // if there is no open bracket: stop if (idxOpenBracket == InvalidIndex) break; // find colon idxColon = str.FindCharIndex(':', idxOpenBracket); // if there is no colon: stop if (idxColon == InvalidIndex) { this->errMsg.Format("Syntax error in id string '%s'! Colon missing.", str); return false; } // get argument index as string argIdxStr = str.ExtractRange(idxOpenBracket + 1, idxColon - idxOpenBracket - 1); // check if argument index string is valid for converting to integer SizeT argIdxStrLength = argIdxStr.Length(); IndexT idx; for (idx = 0; idx < argIdxStrLength; idx++) { if (argIdxStr[idx] < '0' || argIdxStr[idx] > '9') { this->errMsg.Format("Syntax error in id string '%s'! Argument index at position '%d' invalid.", str, idxOpenBracket); return false; } } // convert argument index string to integer argIdx = argIdxStr.AsInt(); // get argument type argType = str[idxColon + 1]; // argument type l (localize) also is of type string if ('l' == argType) { argType = 's'; } // argument type p (plural choice) also is of type integer if ('p' == argType) { argType = 'i'; } // interpret argument type switch (argType) { case 's': // string type case 'i': // integer type // add argument index and type to argTypes dictionary if (!argTypes.Contains(argIdx)) { // argument index is not in direcory: add index and type to dictionary argTypes.Add(argIdx, argType); } else if (argType != argTypes[argIdx]) { // argument index is in direcory: generate error message if types are not equal (type of argument is ambiguous) this->errMsg.Format("Parsing error in id string '%s'! Different types for argument %d specified.", str, argIdx); return false; } break; default: this->errMsg.Format("Syntax error in id string '%s'! Type '%c' of argument %d invalid.", str, argType, argIdx); return false; } } return true; } //------------------------------------------------------------------------------ /** Gets arguments and interprets them with help of 'argTypes' storing arguments to 'argInts' and 'argStrs'. */ void LocaleServer::InterpretArguments(va_list vArgList) { IndexT argIdx = 0; // argument index char argType = '\0'; // argument type String strArg = ""; this->argStrs.Clear(); this->argInts.Clear(); while(true) { if (argTypes.Contains(argIdx)) { // get argument type argType = argTypes[argIdx]; // interpret argument type switch (argType) { case 's': // string type // get next argument, interpret as string and add to argStrs dictionary strArg = va_arg(vArgList, char*); argStrs.Add(argIdx, strArg); break; case 'i': // integer type // get next argument, interpret as integer and add to argInts dictionary argInts.Add(argIdx, va_arg(vArgList, int)); break; default: // should be impossible n_error("Locale::LocaleServer: Internal error!\nType '%c' of argument %d invalid.", argType, argIdx); break; } argIdx++; } else { // stop searching for arguments if argument index cannot be found in argTypes dictionary break; } } } //------------------------------------------------------------------------------ /** Builds the localized text by replacing argument statements with arguments. Returns "" if there are errors. */ String LocaleServer::BuildLocalizedText(const String& str) { n_assert(str.IsValid()); IndexT idxOpenBracket = 0; // index of last found open bracket IndexT idxAfterCloseBracket = 0; // index of last found close bracket + 1 IndexT idxColon = 0; // index of last found colon String argIdxStr = ""; // argument index (between open bracket and colon) IndexT argIdx = InvalidIndex; // argument index as integer char argType = '\0'; // argument type (character after colon) String localizedText; // localized text (text with replaced argument statements) while (idxAfterCloseBracket < str.Length()) { // find open bracket idxOpenBracket = str.FindCharIndex('{', idxAfterCloseBracket); // if there is no open bracket stop if (idxOpenBracket == InvalidIndex) { // add rest of text to localized text localizedText += str.ExtractToEnd(idxAfterCloseBracket); break; } // add text between close and open bracket to localized text localizedText += str.ExtractRange(idxAfterCloseBracket, idxOpenBracket - idxAfterCloseBracket); // find colon idxColon = str.FindCharIndex(':', idxOpenBracket); // if there is no colon: stop if (idxColon == InvalidIndex) { this->errMsg.Format("Syntax error in localized text string '%s'! Colon missing.", str); return ""; } // find close bracket idxAfterCloseBracket = str.FindCharIndex('}', idxColon) + 1; // get argument index as string argIdxStr = str.ExtractRange(idxOpenBracket + 1, idxColon - idxOpenBracket - 1); // check if argument index string is valid for converting to integer SizeT argIdxStrLength = argIdxStr.Length(); IndexT idx; for (idx = 0; idx < argIdxStrLength; idx++) { if (argIdxStr[idx] < '0' || argIdxStr[idx] > '9') { this->errMsg.Format("Syntax error in localized text string '%s'! Argument index at position '%d' invalid.", str, idxOpenBracket); return ""; } } // convert argument index string to integer argIdx = argIdxStr.AsInt(); // get argument type argType = str[idxColon + 1]; // interpret argument type switch (argType) { case 's': // string type // check if argument index is in string directory if (!argStrs.Contains(argIdx)) { // argument index is not in string direcory: generate error message this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type string was not available in id string.", str, argIdx); return ""; } else { // add argument to localized text localizedText += argStrs[argIdx]; } break; case 'l': // string type (argument string have be localized, too) // check if argument index is in string directory if (!argStrs.Contains(argIdx)) { // argument index is not in string direcory: generate error message this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type string was not available in id string. For localization string type is needed.", str, argIdx); return ""; } else { // add argument to localized text localizedText += this->GetLocaleText(argStrs[argIdx]); } break; case 'i': // integer type // check if argument index is in integer directory if (!argInts.Contains(argIdx)) { // argument index is not in integer direcory: generate error message this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type integer was not available in id string.", str, argIdx); return ""; } else { // add argument to localized text localizedText += String::FromInt(argInts[argIdx]); } break; case 'p': // plural choice // check if argument index is in integer directory if (!argInts.Contains(argIdx)) { // argument index is not in integer direcory: generate error message this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type integer was not available in id string. For plural choice integer type is needed.", str, argIdx); return ""; } else { // add plural choice to localized text localizedText += this->PluralChoice(argInts[argIdx], str.ExtractRange(idxColon + 3, idxAfterCloseBracket - idxColon - 4)); } break; default: this->errMsg.Format("Argument error in localized text string '%s'! Type '%c' of argument %d invalid.", str, argType, argIdx); return ""; } } return localizedText; } //------------------------------------------------------------------------------ /** Chooses the part of the plural choice string which fits best to the amount. The plural choice string must match to this pattern: [<is zero text>|]<is one text>|<else text> Example 1: PluralChoice(1, "Child|Children"); // Child PluralChoice(4, "Child|Children"); // Children Example 2: PluralChoice(0, "no Children|one Child|many Children"); // no Children PluralChoice(1, "no Children|one Child|many Children"); // one Child PluralChoice(5, "no Children|one Child|many Children"); // many Children */ String LocaleServer::PluralChoice(int amount, const String& pluralChoice) { n_assert(pluralChoice.IsValid()); Array<String> choices = pluralChoice.Tokenize("|"); switch (choices.Size()) { case 2: if ( 1 == amount) return choices[0]; // is one text else return choices[1]; // else text break; case 3: if ( 0 == amount) return choices[0]; // is zero text else if ( 1 == amount) return choices[1]; // is one text else return choices[2]; // else text break; default: n_error("Locale::LocaleServer: Syntax error in plural choice '%s'!", pluralChoice.AsCharPtr()); return pluralChoice; break; } } //------------------------------------------------------------------------------ /** Add a locale table from db */ void LocaleServer::AddLocaleDBTable(const String& tableName, const IO::URI& dbUri) { LocaPath newPath; newPath.path = dbUri.AsString(); newPath.tableName = tableName; this->fileList.Append(newPath); this->LoadLocaleDataFromDB(tableName, dbUri); } //------------------------------------------------------------------------------ /** Clears the complete locale data dictionary */ void LocaleServer::ClearLocaleData() { this->dictionary.Clear(); this->fileList.Clear(); } //------------------------------------------------------------------------------ /** reload locaDB */ void LocaleServer::ReloadLocaDB() { this->dictionary.Clear(); SizeT numFilePaths = this->fileList.Size(); IndexT idx; for(idx = 0; idx < numFilePaths; idx++) { this->LoadLocaleDataFromDB(this->fileList[idx].tableName, this->fileList[idx].path); } } //------------------------------------------------------------------------------ /** Add a locale table from db */ void LocaleServer::LoadLocaleDataFromDB(const String& tableName, const IO::URI& dbUri) { n_assert(dbUri.IsValid()); __MEMORY_CHECKPOINT("> Locale::LocaleServer::LoadLocaleDataFromDB()"); Ptr<Sqlite3Factory> dbFactory = 0; if(!Sqlite3Factory::HasInstance()) { dbFactory = Sqlite3Factory::Create(); } else { dbFactory = Sqlite3Factory::Instance(); } Ptr<Sqlite3Database> db = dbFactory->CreateDatabase().downcast<Sqlite3Database>(); db->SetURI(dbUri); db->SetAccessMode(Database::ReadOnly); db->SetExclusiveMode(true); db->SetIgnoreUnknownColumns(false); if (db->Open()) { if (db->HasTable(tableName)) { Ptr<Reader> reader = Reader::Create(); reader->SetDatabase(db.cast<Database>()); reader->SetTableName(tableName); if (reader->Open()) { SizeT numRows = reader->GetNumRows(); this->dictionary.Reserve(numRows); IndexT rowIndex; for (rowIndex = 0; rowIndex < numRows; rowIndex++) { reader->SetToRow(rowIndex); this->dictionary.Add(reader->GetString(Attr::LocaId), reader->GetString(Attr::LocaText)); } } reader->Close(); } db->Close(); } __MEMORY_CHECKPOINT("< Locale::LocaleServer::LoadLocaleDataFromDB()"); } }; // namespace Locale //----------------------------------------------------------------------------
30.421725
200
0.53765
gscept
005d99e5dc4bc70053c9030d4942372b518209db
1,412
cpp
C++
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
9
2018-10-24T15:16:47.000Z
2021-12-14T13:53:50.000Z
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
null
null
null
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
6fd64801863e883508f15d16398744405f4f9e34
[ "Unlicense" ]
7
2018-10-29T15:30:37.000Z
2021-01-18T15:15:09.000Z
/* TITLE Roman numerals Chapter10Exercise7.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Include calculations with Roman numerals. Input: - Output: - Author: Chris B. Kirov Data: 15.02.2015 */ /* Calculator Grammar: Calculation: Print Quit Statement Calculation Statement Statement: Declaration ----------------------------> Declaration: "let" name "=" Expression constant variable Declaration: "let" "const" name "=" Expression Expression Expression: Term Expression +;- Term Term: Primary Term *; / ; % Primary Primary: Floating point Numbers / Roman numerals '(' Expressions ')' sqrt-----------------------------------> sqrt: "sqrt" "(" Expression ")" pow------------------------------------> pow: "pow" "("double, integer ")" factorial------------------------------> factorial: integer"!" +; - primary name-----------------------------------> returns the value of a defined variable previously introduced by "let" command sin------------------------------------> returns the sinus of the an angle within [0,360] degrees. */ #include <iostream> #include <string> #include <vector> #include <map> #include <forward_list> #include "Chapter10Exercise7.h" int main() { std::cout << "\t\tWelcome to our calculator!" << std::endl; calculate(ts); }
28.24
122
0.568697
Ziezi
005f2774a7ee51980431db92e3eaec5ce6112e93
30,403
cpp
C++
engine/xbox/generic/xboxport.cpp
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
600
2017-04-05T07:52:07.000Z
2022-03-31T07:56:47.000Z
engine/xbox/generic/xboxport.cpp
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
166
2017-04-16T12:16:11.000Z
2022-03-02T21:42:48.000Z
engine/xbox/generic/xboxport.cpp
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
105
2017-04-05T08:18:08.000Z
2022-03-31T06:44:04.000Z
/* * OpenBOR - http://www.LavaLit.com * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in OpenBOR root for details. * * Copyright (c) 2004 - 2011 OpenBOR Team */ #include <XBApp.h> #include <XBFont.h> #include <XBHelp.h> #include <XBSound.h> #include <xgraphics.h> #include <assert.h> #include <d3d8perf.h> #include "SndXBOX.hxx" #include <stdio.h> #include <vector> #include "undocumented.h" #include "iosupport.h" #include "panel.h" #include "custom_launch_params.h" #include "keyboard_api.h" #include "gamescreen.h" DWORD g_dwSoundThreadId ; HANDLE g_hSoundThread ; #ifdef __cplusplus extern "C" { #endif #include "xboxport.h" #include "packfile.h" #define uint8 unsigned char #define uint32 unsigned int void xbox_init(void); void xbox_return(void); void _2xSaI(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void _2xSaIScanline(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void SuperEagle(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void SuperEagleScanline(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void Super2xSaI(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void Super2xSaIScanline(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void Scale2x(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void SuperScale(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void SuperScaleScanline(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void Eagle(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void EagleScanline(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode); void Simple2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */, unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanlines) ; void AdMame2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */, unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanline) ; char packfile[128] = {"d:\\Paks\\menu.pak"}; #ifdef __cplusplus } #endif #pragma warning(disable:4244) #pragma warning(disable:4018) #pragma warning(disable:4101) #define PLATFORM_SAV L"OPENBORSAV" #define PLATFORM_INI "OpenBoR.ini" #define DEFAULT_SAVE_PATH "d:\\Saves" //----------------------------------------------------------------------------- // Name: class CXBoxSample // Desc: Main class to run this application. Most functionality is inherited // from the CXBApplication base class. //----------------------------------------------------------------------------- class CXBoxSample : public CXBApplication { public: CXBoxSample(); virtual HRESULT Initialize(); virtual HRESULT InitializeWithScreen(); virtual HRESULT FrameMove(); virtual void initConsole(UINT32 idx, int isFavorite, int forceConfig); virtual int init_texture(); virtual void doScreenSize(); virtual BOOL SetRefreshRate(INT iRefreshRate); virtual int render_to_texture(int src_w, int src_h, s_screen* source); virtual void saveSettings(char *filename); virtual int loadSettings(char *filename); void setPalette(unsigned char *palette); virtual void pollXBoxControllers(void); virtual void xboxChangeFilter(); void ClearScreen(); void ResetResolution(); virtual void fillPresentationParams(); D3DCOLOR m_color_palette[256]; DWORD m_startTime ; DWORD m_joypad ; D3DCOLOR color_palette[256]; unsigned long m_xboxControllers[4] ; D3DXVECTOR2 m_gameVecScale ; D3DXVECTOR2 m_gameVecTranslate ; RECT m_gameRectSource ; int m_throttle ; int m_xboxSFilter ; unsigned int m_pitch ; D3DPRESENT_PARAMETERS m_origPP ; CPanel m_pnlBackgroundMain ; CPanel m_pnlBackgroundSelect ; CPanel m_pnlBackgroundOther ; CPanel m_pnlSplashEmu ; CPanel m_pnlSplashGame ; CPanel m_pnlPopup ; CPanel m_pnlGameScreen ; CPanel m_pnlGameScreen2 ; CIoSupport m_io ; LPDIRECT3DTEXTURE8 Texture; LPDIRECT3DTEXTURE8 Texture2; LPDIRECT3DTEXTURE8 WhiteTexture; LPD3DXSPRITE Sprite; LPD3DXSPRITE MenuSprite; byte* g_pBlitBuff ; byte* g_pDeltaBuff ; WCHAR m_strMessage[80]; UINT32 m_msgDelay ; SoundXBOX m_sound; char g_savePath[500] ; char g_saveprefix[500] ; // Indicates the width and height of the screen UINT32 theWidth; UINT32 theHeight; RECT SrcRect; RECT DestRect; int m_nScreenX, m_nScreenY, m_nScreenMaxX, m_nScreenMaxY ; }; #ifdef __cplusplus extern "C" { #endif void hq2x_16(unsigned char*, unsigned char*, DWORD, DWORD, DWORD, DWORD, DWORD); unsigned int LUT16to32[65536]; unsigned int RGBtoYUV[65536]; #ifdef __cplusplus } #endif void hq2x_16_stub(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode ) { hq2x_16( srcPtr, dstPtr, width, height, dstPitch, srcPitch - (width<<1), dstPitch - (width<<2)); } void dummy_blitter(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode ) { } struct blitters { void (*blitfunc)(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode ) ; char name[100] ; float multiplier ; } SOFTWARE_FILTERS[] = { { dummy_blitter, "None", 1 }, { _2xSaI, "2xSai", 2}, { Super2xSaI, "Super 2xSai", 2}, { hq2x_16_stub, "HQ2X", 2}, { Eagle, "Eagle2x", 2}, { SuperEagle, "Super Eagle 2x", 2}, { SuperScale, "SuperScale 2x", 2}, { AdMame2x, "AdvanceMame 2x", 2}, { Simple2x, "Simple 2x", 2}, { _2xSaIScanline, "2xSai Scanline", 2}, { Super2xSaIScanline, "Super 2xSai Scanline", 2}, { EagleScanline, "Eagle2x Scanline", 2}, { SuperEagleScanline, "Super Eagle2x Scanline", 2}, { SuperScaleScanline, "SuperScale 2x Scanline", 2}, } ; #define HQFILTERNUM 1 #define NUM_SOFTWARE_FILTERS 14 void InitLUTs(void) { int i, j, k, r, g, b, Y, u, v; for (i=0; i<65536; i++) LUT16to32[i] = ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3); for (i=0; i<32; i++) for (j=0; j<64; j++) for (k=0; k<32; k++) { r = i << 3; g = j << 2; b = k << 3; Y = (r + g + b) >> 2; u = 128 + ((r - b) >> 2); v = 128 + ((-r + 2*g -b)>>3); RGBtoYUV[ (i << 11) + (j << 5) + k ] = (Y<<16) + (u<<8) + v; } } CXBoxSample *g_app ; char global_error_message[1024] ; unsigned int m_performanceFreq[2] ; unsigned int m_performancePrev[2] ; int recreate( D3DPRESENT_PARAMETERS *pparams ) { char tmpfilename[500] ; SAFE_RELEASE( g_app->Sprite ) ; SAFE_RELEASE( g_app->MenuSprite ) ; g_app->m_pd3dDevice->Release(); //g_app->fillPresentationParams() ; if( FAILED( g_app->m_pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING, pparams, &g_app->m_pd3dDevice ) ) ) { return 0 ; } else { g_pd3dDevice = g_app->m_pd3dDevice ; g_app->m_pnlBackgroundMain.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlBackgroundSelect.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlBackgroundOther.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlSplashEmu.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlSplashGame.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlPopup.Recreate( g_app->m_pd3dDevice ); g_app->m_pnlGameScreen.Recreate( g_app->m_pd3dDevice ); return 1 ; } } void xbox_set_refreshrate( int rate ) { int nativeRate ; D3DPRESENT_PARAMETERS holdpp ; if(XGetVideoStandard() == XC_VIDEO_STANDARD_PAL_I) { //get supported video flags DWORD videoFlags = XGetVideoFlags(); //set pal60 if available. if(videoFlags & XC_VIDEO_FLAGS_PAL_60Hz) nativeRate = 60 ; else nativeRate = 50 ; } else nativeRate = 60 ; if ( rate != g_app->m_d3dpp.FullScreen_RefreshRateInHz ) { g_app->m_d3dpp.FullScreen_RefreshRateInHz = rate ; if ( nativeRate != rate ) { g_app->m_d3dpp.Flags |= D3DPRESENTFLAG_EMULATE_REFRESH_RATE ; } else { g_app->m_d3dpp.Flags &= ~D3DPRESENTFLAG_EMULATE_REFRESH_RATE ; } memcpy( &holdpp, &g_app->m_d3dpp, sizeof(D3DPRESENT_PARAMETERS) ) ; recreate( &g_app->m_d3dpp ) ; memcpy( &g_app->m_d3dpp, &holdpp, sizeof(D3DPRESENT_PARAMETERS) ) ; g_app->m_pd3dDevice->Reset(&g_app->m_d3dpp); memcpy( &g_app->m_d3dpp, &holdpp, sizeof(D3DPRESENT_PARAMETERS) ) ; } } int CXBoxSample::init_texture() { D3DCOLOR *palette ; // Release any previous texture if (Texture) { return 1 ; Texture->BlockUntilNotBusy() ; Texture->Release(); Texture = NULL; } theWidth = 320*4 ; theHeight = 240*4 ; // Create the texture if (D3DXCreateTextureFromFileInMemoryEx(m_pd3dDevice, GAMESCREEN_FILE, sizeof(GAMESCREEN_FILE), theWidth, theHeight, 1, 0, D3DFMT_LIN_R5G6B5, D3DPOOL_MANAGED, //D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED, D3DX_FILTER_NONE , D3DX_FILTER_NONE, 0, NULL, NULL, &Texture)==D3D_OK) { m_pnlGameScreen.m_pTexture = NULL ; if ( FAILED(m_pnlGameScreen.Create(m_pd3dDevice, Texture, FALSE, theWidth, theHeight)) ) { //popupMsg( "no create panel", &m_pnlBackgroundOther ) ; } } else { //popupMsg( "no load texture", &m_pnlBackgroundOther ) ; } D3DSURFACE_DESC desc; Texture->GetLevelDesc(0, &desc); if (g_pBlitBuff != NULL) { delete [] g_pBlitBuff; g_pBlitBuff = NULL; } // Allocate a buffer to blit our frames to g_pBlitBuff = new byte[ desc.Size ]; if (g_pDeltaBuff != NULL) { delete [] g_pDeltaBuff; g_pDeltaBuff = NULL; } // Allocate a buffer to blit our frames to g_pDeltaBuff = new byte[desc.Size]; if ( g_pDeltaBuff == NULL ) return 1 ; memset( g_pDeltaBuff, 0x00, desc.Size ) ; RECT rectSource; rectSource.top = 0; rectSource.left = 0; rectSource.bottom = theHeight-1 ; rectSource.right = theWidth-1 ; D3DLOCKED_RECT d3dlr; Texture->LockRect(0, &d3dlr, &rectSource, 0); m_pitch = d3dlr.Pitch ; // Unlock our texture Texture->UnlockRect(0); return 0; } void CXBoxSample::ResetResolution() { m_pd3dDevice->Reset(&m_d3dpp); m_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,0x0,1.0f,0); m_pd3dDevice->Present( NULL, NULL, NULL, NULL ); //Device->SetFlickerFilter(FlickerFilter) ; //Device->SetSoftDisplayFilter(Soften) ; } void CXBoxSample::saveSettings( char *filename ) { FILE *setfile ; setfile = fopen( filename, "wb" ) ; if ( !setfile ) return ; fwrite( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ; fwrite( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ; fwrite( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ; fwrite( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ; fwrite( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ; fclose( setfile ) ; } void CXBoxSample::setPalette( unsigned char *palette) { memset( color_palette, 0, 256*sizeof(D3DCOLOR) ) ; DWORD r, g, b; for (int i = 0; i < 256; i++) { r = palette[i*3] ; g = palette[(i*3)+1] ; b = palette[(i*3)+2] ; color_palette[i] = ( ( r >> 3 ) << 11 ) | ( ( g >> 2 ) << 5 ) | ( b >> 3 ) ; } } int CXBoxSample::loadSettings(char *filename) { FILE *setfile ; setfile = fopen( filename, "rb" ) ; if ( !setfile ) { saveSettings( filename ) ; return 1; } fread( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ; fread( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ; fread( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ; fread( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ; fread( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ; fclose( setfile ) ; if ( ( m_xboxSFilter < 0 ) || ( m_xboxSFilter >= NUM_SOFTWARE_FILTERS )) { m_xboxSFilter = 0 ; } return 0 ; } HRESULT CXBoxSample::InitializeWithScreen() { FILE *debugfile ; char initext[100] ; char szDevice[2000] ; char *fpos, *epos ; int numread ; char tmpfilename[MAX_PATH] ; XBInput_GetInput(); XMountUtilityDrive( TRUE ) ; m_io.Unmount("C:") ; m_io.Unmount("E:") ; m_io.Unmount("F:") ; m_io.Unmount("G:") ; m_io.Unmount("X:") ; m_io.Unmount("Y:") ; m_io.Unmount("Z:") ; m_io.Unmount("R:") ; m_io.Mount("C:", "Harddisk0\\Partition2"); m_io.Mount("E:", "Harddisk0\\Partition1"); m_io.Mount("F:", "Harddisk0\\Partition6"); m_io.Mount("G:", "Harddisk0\\Partition7"); m_io.Mount("X:", "Harddisk0\\Partition3"); m_io.Mount("Y:", "Harddisk0\\Partition4"); m_io.Mount("Z:", "Harddisk0\\Partition5"); m_io.Mount("R:","Cdrom0"); XFormatUtilityDrive() ; char szNewDir[MAX_PATH] ; char *s, *p ; strcpy( szNewDir, DEFAULT_SAVE_PATH ) ; s = szNewDir+3 ; while ( p = strchr( s, '\\' ) ) { *p = 0 ; CreateDirectory( szNewDir, NULL ) ; *p = '\\' ; p++ ; s = p ; } CreateDirectory( DEFAULT_SAVE_PATH, NULL ) ; m_xboxSFilter = 0 ; m_nScreenMaxX = 640 ; m_nScreenMaxY = 480 ; m_nScreenX = 0 ; m_nScreenY = 0 ; DWORD tdiff = GetTickCount() ; tdiff = GetTickCount() - tdiff ; m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL|D3DCLEAR_TARGET, 0x00000000, 0.0f, 0L ); m_pd3dDevice->Present( NULL, NULL, NULL, NULL ); QueryPerformanceFrequency((union _LARGE_INTEGER *) m_performanceFreq); InitLUTs() ; XGetCustomLaunchData() ; m_msgDelay = 0 ; wcscpy( m_strMessage, L" " ) ; g_pBlitBuff = NULL ; g_pDeltaBuff = NULL ; WhiteTexture = NULL ; Texture = NULL ; Sprite = NULL ; MenuSprite = NULL ; g_saveprefix[0] = 0 ; initConsole(0,0,0) ; return S_OK; } //----------------------------------------------------------------------------- // Name: FrameMove // Desc: Performs per-frame updates //----------------------------------------------------------------------------- HRESULT CXBoxSample::FrameMove() { InitializeWithScreen() ; return S_OK; } int CXBoxSample::render_to_texture(int src_w, int src_h, s_screen* source) { int vp_vstart ; int vp_vend ; int vp_hstart ; int vp_hend ; int w,h ; RECT src, dst; WORD *curr1 ; byte *curr2 ; DWORD pitchDiff1 ; DWORD pitchDiff2 ; D3DCOLOR *palette ; char palstr[200] ; DWORD pixel ; byte r,g,b ; // Get a description of our level 0 texture so we can figure // out the pitch of the texture D3DSURFACE_DESC desc; Texture->GetLevelDesc(0, &desc); // Allocate a buffer to blit our frames to unsigned char *bsrc = source->data; unsigned short *bdst = (unsigned short*)g_pBlitBuff; for ( int y = 0 ; y < source->height ; y++ ) { for ( int x = 0 ; x < source->width ; x++ ) { *(bdst+x) = color_palette[ *bsrc++ ] ; } bdst += m_pitch/2 ; } // Figure out how big of a rect to lock in our texture RECT rectSource; rectSource.top = 0; rectSource.left = 0; rectSource.bottom = source->height; rectSource.right = source->width; // Lock the rect in our texture D3DLOCKED_RECT d3dlr; Texture->LockRect(0, &d3dlr, &rectSource, 0); float mx, my ; if ( m_xboxSFilter ) { SOFTWARE_FILTERS[m_xboxSFilter].blitfunc(g_pBlitBuff + m_pitch,m_pitch, g_pDeltaBuff+m_pitch, ((unsigned char*)d3dlr.pBits)+m_pitch, m_pitch, src_w, src_h, 0 ) ; Texture->UnlockRect(0); g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L); g_pd3dDevice->BeginScene(); mx = (float)m_nScreenMaxX / ((float)src_w*SOFTWARE_FILTERS[m_xboxSFilter].multiplier) ; my = (float)m_nScreenMaxY / ((float)src_h*SOFTWARE_FILTERS[m_xboxSFilter].multiplier); m_gameRectSource.top = 0 ; m_gameRectSource.left = 0 ; m_gameRectSource.bottom = (src_h)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ; m_gameRectSource.right = (src_w)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ; } else { unsigned char *src = g_pBlitBuff; unsigned char *dst = (unsigned char*)d3dlr.pBits; for ( int y = 0 ; y < src_h ; y++ ) { memcpy( dst, src, src_w*2 ) ; dst += m_pitch ; src += m_pitch ; } Texture->UnlockRect(0); g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L); g_pd3dDevice->BeginScene(); mx = (float)m_nScreenMaxX / ((float)src_w) ; my = (float)m_nScreenMaxY / ((float)src_h); m_gameRectSource.top = 0; m_gameRectSource.left = 0; m_gameRectSource.bottom = src_h; m_gameRectSource.right = src_w; } m_gameVecScale.x = mx ; m_gameVecScale.y = my; m_gameVecTranslate.x = m_nScreenX ; m_gameVecTranslate.y = m_nScreenY ; D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0); m_pnlGameScreen.Render( m_gameRectSource.left, m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ; if ( global_error_message[0] ) { WCHAR msg[500] ; m_msgDelay-- ; swprintf( msg, L"%S", global_error_message ) ; if ( m_msgDelay <= 0 ) { global_error_message[0] = 0 ; } } // End the scene. g_pd3dDevice->EndScene(); g_pd3dDevice->Present(NULL, NULL, NULL, NULL); return 1; } struct vidmodes { char name[100] ; unsigned int width ; unsigned int height ; char progressive ; float multx ; float multy ; } VIDEOMODES[] = { { "Standard 480i", 640, 480, 0, 1.0f, 1.0f }, { "480p", 640, 480, 1, 1.0f, 1.0f }, { "720p", 1280, 720, 1, 2.0f, 1.5f }, { "1080i", 1920, 1080, 0, 3.0f, 2.25f }, { "720x480", 720, 480, 0, 1.125f, 1.0f }, { "720x576", 720, 576, 0, 1.125f, 1.2f }, } ; void CXBoxSample::fillPresentationParams() { IDirect3D8 *pD3D; DWORD videoFlags = XGetVideoFlags(); ZeroMemory(&m_d3dpp, sizeof(m_d3dpp)); m_d3dpp.BackBufferWidth = 640; m_d3dpp.BackBufferHeight = 480; m_d3dpp.BackBufferFormat = D3DFMT_LIN_R5G6B5; m_d3dpp.Flags = D3DPRESENTFLAG_INTERLACED; m_d3dpp.BackBufferCount = 1; m_d3dpp.EnableAutoDepthStencil = TRUE; m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; if(XGetVideoStandard() == XC_VIDEO_STANDARD_PAL_I) { // Set pal60 if available. if(videoFlags & XC_VIDEO_FLAGS_PAL_60Hz) m_d3dpp.FullScreen_RefreshRateInHz = 60; else m_d3dpp.FullScreen_RefreshRateInHz = 50; } else m_d3dpp.FullScreen_RefreshRateInHz = 60; if(XGetAVPack() == XC_AV_PACK_HDTV) { if(videoFlags & XC_VIDEO_FLAGS_HDTV_1080i) { m_d3dpp.Flags = D3DPRESENTFLAG_WIDESCREEN | D3DPRESENTFLAG_INTERLACED; m_d3dpp.BackBufferWidth = 1920; m_d3dpp.BackBufferHeight = 1080; return; } else if(videoFlags & XC_VIDEO_FLAGS_HDTV_720p) { m_d3dpp.Flags = D3DPRESENTFLAG_PROGRESSIVE | D3DPRESENTFLAG_WIDESCREEN; m_d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; m_d3dpp.BackBufferWidth = 1280; m_d3dpp.BackBufferHeight = 720; return; } else if(videoFlags & XC_VIDEO_FLAGS_HDTV_480p) { m_d3dpp.Flags = D3DPRESENTFLAG_PROGRESSIVE; m_d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; m_d3dpp.BackBufferWidth = 640; m_d3dpp.BackBufferHeight = 480; return; } } } CXBoxSample xbApp; extern "C" { void changeResolution() { xbApp.fillPresentationParams() ; xbApp.ResetResolution(); } } VOID __cdecl main() { g_app = &xbApp ; xbApp.fillPresentationParams() ; memcpy( &xbApp.m_origPP, &xbApp.m_d3dpp, sizeof(xbApp.m_origPP) ) ; if( FAILED( xbApp.Create() ) ) { return; } xbApp.Run(); } //----------------------------------------------------------------------------- // Name: CXBoxSample (constructor) // Desc: Constructor for CXBoxSample class //----------------------------------------------------------------------------- CXBoxSample::CXBoxSample() :CXBApplication() { global_error_message[0] = 0 ; } void CXBoxSample::ClearScreen() { m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL|D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L ); m_pd3dDevice->Present( NULL, NULL, NULL, NULL ); } #define XBOX_DPAD_UP 0x00000001 #define XBOX_DPAD_RIGHT 0x00000002 #define XBOX_DPAD_DOWN 0x00000004 #define XBOX_DPAD_LEFT 0x00000008 #define XBOX_A 0x00000010 #define XBOX_B 0x00000020 #define XBOX_X 0x00000040 #define XBOX_Y 0x00000080 #define XBOX_BLACK 0x00000100 #define XBOX_WHITE 0x00000200 #define XBOX_START 0x00000400 #define XBOX_BACK 0x00000800 #define XBOX_LEFT_TRIGGER 0x00001000 #define XBOX_RIGHT_TRIGGER 0x00002000 #define XBOX_LEFT_THUMB 0x00004000 #define XBOX_RIGHT_THUMB 0x00008000 #define XBOX_LTHUMB_UP 0x00010000 #define XBOX_LTHUMB_RIGHT 0x00020000 #define XBOX_LTHUMB_DOWN 0x00040000 #define XBOX_LTHUMB_LEFT 0x00080000 #define XBOX_RTHUMB_UP 0x00100000 #define XBOX_RTHUMB_RIGHT 0x00200000 #define XBOX_RTHUMB_DOWN 0x00400000 #define XBOX_RTHUMB_LEFT 0x00800000 void CXBoxSample::pollXBoxControllers(void) { int i = 0; static int didfilter = 0; XBInput_GetInput(); for(i=0; i<4; i++) { m_xboxControllers[i] = 0; if(g_Gamepads[i].hDevice) { if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_A] > 25) m_xboxControllers[i] |= XBOX_A; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_B] > 25) m_xboxControllers[i] |= XBOX_B; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_X] > 25) m_xboxControllers[i] |= XBOX_X; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_Y] > 25) m_xboxControllers[i] |= XBOX_Y; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_BLACK] > 25) m_xboxControllers[i] |= XBOX_BLACK; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_WHITE] > 25) m_xboxControllers[i] |= XBOX_WHITE; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_UP) m_xboxControllers[i] |= XBOX_DPAD_UP; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) m_xboxControllers[i] |= XBOX_DPAD_RIGHT; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_DOWN) m_xboxControllers[i] |= XBOX_DPAD_DOWN; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_LEFT) m_xboxControllers[i] |= XBOX_DPAD_LEFT; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_START) m_xboxControllers[i] |= XBOX_START; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_BACK) m_xboxControllers[i] |= XBOX_BACK; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER] > 25) m_xboxControllers[i] |= XBOX_LEFT_TRIGGER; if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] > 25) m_xboxControllers[i] |= XBOX_RIGHT_TRIGGER; if(g_Gamepads[i].fX1 > 0.40f) m_xboxControllers[i] |= XBOX_DPAD_RIGHT; if(g_Gamepads[i].fX1 < -0.40f) m_xboxControllers[i] |= XBOX_DPAD_LEFT; if(g_Gamepads[i].fY1 > 0.40f) m_xboxControllers[i] |= XBOX_DPAD_UP; if(g_Gamepads[i].fY1 < -0.40f) m_xboxControllers[i] |= XBOX_DPAD_DOWN; if(g_Gamepads[i].fX2 > 0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_RIGHT; if(g_Gamepads[i].fX2 < -0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_LEFT; if(g_Gamepads[i].fY2 > 0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_UP; if(g_Gamepads[i].fY2 < -0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_DOWN; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_LEFT_THUMB) m_xboxControllers[i] |= XBOX_LEFT_THUMB; if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) { m_xboxControllers[i] |= XBOX_RIGHT_THUMB; if(!didfilter) { xboxChangeFilter(); didfilter = 1; } } else didfilter = 0; if((g_Gamepads[i].wButtons & XINPUT_GAMEPAD_START) && (g_Gamepads[i].wButtons & XINPUT_GAMEPAD_BACK)) { PLAUNCH_DATA ldata; memset(&ldata, 0, sizeof(PLAUNCH_DATA)); XLaunchNewImage("D:\\default.xbe", ldata); } } } } BOOL CXBoxSample::SetRefreshRate(INT iRefreshRate) { char xmsg[100] ; m_d3dpp.FullScreen_RefreshRateInHz = iRefreshRate; DWORD res = m_pd3dDevice->Reset(&m_d3dpp); return TRUE; } HRESULT CXBoxSample::Initialize() { //m_logfile = fopen( "D:\\err.log", "wb" ) ; // Create DirectSound if( FAILED( DirectSoundCreate( NULL, &(m_sound.dsound), NULL ) ) ) return E_FAIL; if ( ( XCreateSaveGame( "U:\\", PLATFORM_SAV, OPEN_ALWAYS, 0, g_savePath, 500 ) ) != ERROR_SUCCESS ) { //return E_FAIL; } m_sound.dsound_init() ; m_sound.m_fps = m_d3dpp.FullScreen_RefreshRateInHz ; return S_OK ; } void CXBoxSample::xboxChangeFilter() { g_app->m_xboxSFilter = (g_app->m_xboxSFilter+1)%NUM_SOFTWARE_FILTERS ; saveSettings( "d:\\Saves\\settings.cfg" ) ; memset( g_app->g_pDeltaBuff, 0x00, 480*g_app->m_pitch ) ; sprintf( global_error_message, "%s Filtering", SOFTWARE_FILTERS[m_xboxSFilter].name ) ; debug_printf("%s Filtering", SOFTWARE_FILTERS[m_xboxSFilter].name); m_msgDelay = 120 ; } DWORD WINAPI Sound_ThreadFunc( LPVOID lpParam ) { float FPS ; unsigned int perfCurr[2] ; unsigned int perfPrev[2] ; QueryPerformanceCounter((union _LARGE_INTEGER *) perfPrev); while ( 1 ) { do { QueryPerformanceCounter((union _LARGE_INTEGER *) perfCurr); if (perfCurr[0] != perfPrev[0]) { FPS = (float) (m_performanceFreq[0]) / (float) (perfCurr[0] - perfPrev[0]); } else { FPS = 200.0f ; } Sleep(1) ; } while ( FPS > 120 ) ; perfPrev[0] = perfCurr[0]; g_app->m_sound.process( g_app->m_throttle ) ; } return 0; } void CXBoxSample::doScreenSize() { WCHAR str[200]; int x, y, maxx, maxy ; float fx, fy, fmaxx, fmaxy ; float origw, origh ; DWORD mtime ; mtime = GetTickCount() ; x = m_nScreenX ; y = m_nScreenY ; maxx = m_nScreenMaxX; maxy = m_nScreenMaxY ; fx = (float)x ; fy = (float)y ; fmaxx = (float)maxx ; fmaxy = (float)maxy ; origw = (float)m_nScreenMaxX/m_gameVecScale.x ; origh = (float)m_nScreenMaxY/m_gameVecScale.y ; while ( 1 ) { m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0x00000000, 1.0f, 0L ); x = (int)fx ; y = (int)fy ; maxx = (int)fmaxx ; maxy = (int)fmaxy ; D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0); m_gameVecScale.x = (float)maxx / ((float)origw); m_gameVecScale.y = (float)maxy / ((float)origh); m_gameVecTranslate.x = x ; m_gameVecTranslate.y = y ; m_pnlGameScreen.Render(m_gameRectSource.left,m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,x,y,maxx,maxy) ; m_pd3dDevice->Present( NULL, NULL, NULL, NULL ); XBInput_GetInput(); if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B]) { break ; } else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A]) { m_nScreenX = x ; m_nScreenY = y ; m_nScreenMaxX = maxx ; m_nScreenMaxY = maxy ; saveSettings( "d:\\Saves\\settings.cfg" ) ; break ; } else { if ( g_Gamepads[0].hDevice ) { if ( GetTickCount() - mtime > 5 ) { mtime = GetTickCount() ; fx += (g_Gamepads[0].fX1) ; fy -= (g_Gamepads[0].fY1) ; fmaxx += (g_Gamepads[0].fX2) ; fmaxy -= (g_Gamepads[0].fY2) ; } } } } } void CXBoxSample::initConsole( UINT32 idx, int isFavorite, int forceConfig ) { char filename[500]; char shortpath[100]; unsigned char *gimage; int ntsccol; FILE *infile; UINT32 fsize; char *forcebuf; int isOther; setSystemRam(); // Create necessary directories First CreateDirectory("d:\\Paks", NULL); CreateDirectory("d:\\Saves", NULL); CreateDirectory("d:\\Logs", NULL); CreateDirectory("d:\\ScreenShots", NULL); m_throttle = 0 ; global_error_message[0] = 0 ; m_sound.init() ; // Create our texture init_texture(); // Create our sprite driver if ( Sprite == NULL ) D3DXCreateSprite(m_pd3dDevice, &Sprite); m_fAppTime = 0.0f ; m_startTime = GetTickCount() ; QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev); xbox_set_refreshrate(60) ; //Then start it up m_sound.pause( FALSE ) ; loadSettings("d:\\Saves\\settings.cfg"); g_hSoundThread = CreateThread( NULL, // (this parameter is ignored) 0, // use default stack size Sound_ThreadFunc, // thread function NULL, // argument to thread function 0, // use default creation flags &g_dwSoundThreadId); // returns the thread identifier xbox_init(); packfile_mode(0); openborMain(0,NULL); } #ifdef __cplusplus extern "C" { #endif void borExit(int reset) { tracemalloc_dump(); xbox_return() ; } void xbox_resize() { g_app->doScreenSize() ; } void xbox_clear_screen() { g_app->ClearScreen() ; } void xbox_pause_audio( int state ) { g_app->m_sound.pause( state ? true : false ) ; } void xbox_check_events(void) { g_app->pollXBoxControllers(); } unsigned long xbox_get_playerinput( int playernum ) { return g_app->m_xboxControllers[playernum]; } void xbox_put_image(int src_w, int src_h, s_screen* source) { if ( g_app->m_throttle ) g_app->m_throttle-- ; if ( g_app->m_throttle == 0 ) g_app->render_to_texture(src_w, src_h, source) ; } void xbox_set_palette( char *palette ) { g_app->setPalette( (unsigned char*)palette) ; } void xbox_init() { XGetCustomLaunchData(); } void xbox_return() { XReturnToLaunchingXBE() ; } void xbox_Sleep( int d ) { Sleep( d ) ; } unsigned int xbox_get_throttle() { return g_app->m_throttle ; } int xbox_get_filter() { return g_app->m_xboxSFilter ; } #ifdef __cplusplus } #endif
23.733802
171
0.66181
christianhaitian
00606d7e6028a2844e51c26293b4d5bcc89c39fd
8,235
cpp
C++
packages/sim/merlion/applications/source_inversion/src/source_inversion/InversionSim.cpp
USEPA/Water-Security-Toolkit
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
[ "BSD-3-Clause" ]
3
2019-06-10T18:04:14.000Z
2020-12-05T18:11:40.000Z
packages/sim/merlion/applications/source_inversion/src/source_inversion/InversionSim.cpp
USEPA/Water-Security-Toolkit
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
[ "BSD-3-Clause" ]
null
null
null
packages/sim/merlion/applications/source_inversion/src/source_inversion/InversionSim.cpp
USEPA/Water-Security-Toolkit
6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb
[ "BSD-3-Clause" ]
2
2020-09-24T19:04:14.000Z
2020-12-05T18:11:43.000Z
#include <source_inversion/InversionDataWriter.hpp> #include <source_inversion/InversionSimOptions.hpp> #include <source_inversion/InversionNetworkSimulator.hpp> #include <merlionUtils/TaskTimer.hpp> #include <merlion/Merlion.hpp> #include <merlion/BlasWrapper.hpp> #include <merlion/TriSolve.hpp> #include <merlion/MerlionDefines.hpp> #include <merlion/SparseMatrix.hpp> #include <time.h> #include <set> #include <vector> int main(int argc, char** argv) { time_t start_other_time = time(NULL); // Handle the optional inputs to this executable InversionSimOptions options; options.parse_inputs(argc, argv); // Helpful interface for setting up the refuce inverse matrix InversionNetworkSimulator net(options.disable_warnings); const merlionUtils::MerlionModelContainer& model(net.Model()); if (options.logging) { net.StartLogging(options.output_prefix+"inversionsim.log"); options.print_summary(net.Log()); } if ((options.inp_filename != "") && (options.wqm_filename != "")) { std::cerr << std::endl; std::cerr << "ERROR: Both a wqm file and an inp file cannot be specified." << std::endl; std::cerr << std::endl; return 1; } if (options.inp_filename != "") { // Read an epanet input file merlionUtils::TaskTimer Run_Hydraulics; net.ReadINPFile(options.inp_filename, options.sim_duration_min, options.qual_step_min, options.epanet_output_filename, options.merlion_save_filename, -1, -1, options.ignore_merlion_warnings, options.decay_k); Run_Hydraulics.StopAndPrint(std::cout, "\n\t- Ran hydraulic model with Epanet "); } else if (options.wqm_filename != "") { if (options.decay_k != -1.0f) { std::cerr << std::endl; std::cerr << "ERROR: A decay coefficient cannot be specified when using the --wqm option." << std::endl; std::cerr << std::endl; return 1; } merlionUtils::TaskTimer Read_WQM; // read a merlion water quality model file net.ReadWQMFile(options.wqm_filename); Read_WQM.StopAndPrint(std::cout, "\n\t- Read water quality data "); } else { std::cerr << std::endl; std::cerr << "ERROR: Missing network input file." << std::endl; std::cerr << std::endl; return 1; } //Read the measurements file if(options.measurement_filename != "") { net.ReadMEASUREMENTS(options.measurement_filename); //net.FilterMeasurements(); } else { std::cerr << std::endl; std::cerr << "ERROR: Missing measurement file." << std::endl; std::cerr << std::endl; return 1; } //Build the inverse matrix std::set<int> rowIDs; const std::vector<Measure*>& measures=net.MeasureList(); //start time in seconds int start_inversion, end_inversion=0; if(options.start_time ==-1) { int last_measure_time_s=-1; for(std::vector<Measure*>::const_iterator s_pos=measures.begin(),e_pos=measures.end();s_pos!=e_pos;s_pos++) { if((*s_pos)->MeasureTimeSeconds()>last_measure_time_s){last_measure_time_s=(*s_pos)->MeasureTimeSeconds();} } start_inversion=last_measure_time_s; } else{start_inversion=options.start_time*60;} std::cout<<"last_ts: "<<merlionUtils::SecondsToNearestTimestepBoundary(start_inversion,model.qual_step_minutes)<<"\n"; //end time in seconds if((options.inversion_horizon !=-1)/*&&(start_inversion > options.inversion_horizon*60)*/) end_inversion=start_inversion-options.inversion_horizon*60; else end_inversion=0; if(end_inversion<0) end_inversion=0; // Sets the time (in seconds) to take a snap of uncertain nodes if(options.snap_time!=-1){ int snap_timestep = merlionUtils::SecondsToNearestTimestepBoundary(options.snap_time*60,model.qual_step_minutes); net.setSnapTimeStep(snap_timestep); } else{ net.setSnapTimeStep(-1); } /* if(end_inversion<0){ std::cerr << std::endl; std::cerr << "ERROR: Bad horizon specification" << std::endl; std::cerr << std::endl; return 1; }*/ std::cout<<"last_ts: "<<merlionUtils::SecondsToNearestTimestepBoundary(end_inversion,model.qual_step_minutes)<<"\n"; bool oneDeleted=false; for(std::vector<Measure*>::const_iterator s_pos=measures.begin(),e_pos=measures.end();s_pos!=e_pos;s_pos++) { if((*s_pos)->MeasureTimeSeconds()>start_inversion || (*s_pos)->MeasureTimeSeconds()<end_inversion) { oneDeleted=true; } else { rowIDs.insert(model.perm_nt_to_upper[model.NodeID((*s_pos)->nodeName())*model.n_steps + (*s_pos)->Measure_timestep(model.qual_step_minutes)]); } } if(oneDeleted) { std::cerr << std::endl; std::cerr << "WARNING: There are measuremets taken that are not being consider in the source inversion." << std::endl; std::cerr << " Consider change the horizon or the inversion start-time options." << std::endl; std::cerr << std::endl; } //Method that build the inverse matrix. net.GenerateReducedInverse(rowIDs,merlionUtils::SecondsToNearestTimestepBoundary(end_inversion,model.qual_step_minutes),1,false,options.wqm_zero_tol); // We instantiate the data writer with pointers to the following // objects so function calls can be less cluttered with arguments // The data writer will be used to write the resulting data files // for the optimization problem InversionDataWriter writer(&net, &options); if(options.probability) options.optimization = false; if(options.optimization) { options.probability = false; std::cout << "\nNetwork Stats:\n"; std::cout << "\tNumber of Junctions - " << model.junctions.size() << "\n"; std::cout << "\tNumber of Nonzero Demand Junctions - " << model.nzd_junctions.size() << "\n"; std::cout << "\tNumber of Tanks - " << model.tanks.size() << "\n"; std::cout << "\tNumber of Reservoirs - " << model.reservoirs.size() << "\n"; std::cout << "\tWater Quality Timestep (minutes) - " << model.qual_step_minutes << "\n"; std::cout << "\tNumber of measurements - " << net.MeasureList().size()<< "\n"; std::cout<<"\tInverse Matrix dimensions - " << net.reduceMatrixNrows()<<"x"<<net.reduceMatrixNcols()<<"\n"; std::cout << std::endl; //Write Data Files end_inversion=merlionUtils::SecondsToNearestTimestepBoundary(end_inversion,model.qual_step_minutes); start_inversion=merlionUtils::SecondsToNearestTimestepBoundary(start_inversion,model.qual_step_minutes); if(!options.reduceSystem) { writer.WriteReduceMAtrixGInverse(); writer.WriteMeasurments(end_inversion,start_inversion); } else { writer.WriteGMAtrixToAMPL(end_inversion,start_inversion); writer.WriteMeasurments(end_inversion,start_inversion); } } time_t total_other_time = time(NULL) - start_other_time; std::cout<<"Total other time : "<<total_other_time<<"\n"; // Probability calculations if(options.probability) { float pf = options.meas_failure; float conf = options.confidence; std::vector<std::string> most_probable_nodes; if(options.allowedNodes_filename!="") { std::cout<<"Using Allowed Nodes Cut ... " ; net.readAllowedNodes(options.allowedNodes_filename); } most_probable_nodes=net.EventProbabilities(pf, conf, options.output_prefix, options.meas_threshold, options.wqm_zero_tol, options.merlion, options.inp_filename); if(options.output_impact_nodeNames) writer.WriteImpactNodeNames(most_probable_nodes); writer.WriteUncertainNodes(); } //std::cout<<"@@@@@@@@@@@@@@@"<<options.sim_duration_min<<std::endl; net.StopLogging(); //Free all other memory being used writer.clear(); net.clear(); std::cout << "\nDONE" << std::endl; return 0; }
34.746835
153
0.647237
USEPA
006217f72f5d9786e94dbc7379d375ef41c4e270
4,020
cpp
C++
src/Overlay/Window/RoomWindow.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
48
2020-06-09T22:53:52.000Z
2022-01-02T12:44:33.000Z
src/Overlay/Window/RoomWindow.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
2
2020-05-27T21:25:49.000Z
2020-05-27T23:56:56.000Z
src/Overlay/Window/RoomWindow.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
12
2020-06-17T20:44:17.000Z
2022-01-04T18:15:27.000Z
#include "RoomWindow.h" #include "Core/interfaces.h" #include "Core/utils.h" #include "Game/gamestates.h" #include "Overlay/imgui_utils.h" #include "Overlay/WindowManager.h" #include "Overlay/Widget/ActiveGameModeWidget.h" #include "Overlay/Widget/GameModeSelectWidget.h" #include "Overlay/Widget/StageSelectWidget.h" #include "Overlay/Window/PaletteEditorWindow.h" void RoomWindow::BeforeDraw() { ImGui::SetWindowPos(m_windowTitle.c_str(), ImVec2(200, 200), ImGuiCond_FirstUseEver); //ImVec2 windowSizeConstraints; //switch (Settings::settingsIni.menusize) //{ //case 1: // windowSizeConstraints = ImVec2(250, 190); // break; //case 3: // windowSizeConstraints = ImVec2(400, 230); // break; //default: // windowSizeConstraints = ImVec2(330, 230); //} ImVec2 windowSizeConstraints = ImVec2(300, 190); ImGui::SetNextWindowSizeConstraints(windowSizeConstraints, ImVec2(1000, 1000)); } void RoomWindow::Draw() { if (!g_interfaces.pRoomManager->IsRoomFunctional()) { ImGui::TextDisabled("YOU ARE NOT IN A ROOM OR ONLINE MATCH!"); m_windowTitle = m_origWindowTitle; return; } std::string roomTypeName = g_interfaces.pRoomManager->GetRoomTypeName(); SetWindowTitleRoomType(roomTypeName); ImGui::Text("Online type: %s", roomTypeName.c_str()); ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); if (isStageSelectorEnabledInCurrentState()) { ImGui::VerticalSpacing(10); StageSelectWidget(); } if (isOnCharacterSelectionScreen() || isOnVersusScreen() || isInMatch()) { ImGui::VerticalSpacing(10); ActiveGameModeWidget(); } if (isGameModeSelectorEnabledInCurrentState()) { bool isThisPlayerSpectator = g_interfaces.pRoomManager->IsRoomFunctional() && g_interfaces.pRoomManager->IsThisPlayerSpectator(); if (!isThisPlayerSpectator) { GameModeSelectWidget(); } } if (isInMatch()) { ImGui::VerticalSpacing(10); WindowManager::GetInstance().GetWindowContainer()-> GetWindow<PaletteEditorWindow>(WindowType_PaletteEditor)->ShowAllPaletteSelections("Room"); } if (isInMenu()) { ImGui::VerticalSpacing(10); DrawRoomImPlayers(); } if (isOnCharacterSelectionScreen() || isOnVersusScreen() || isInMatch()) { ImGui::VerticalSpacing(10); DrawMatchImPlayers(); } ImGui::PopStyleVar(); } void RoomWindow::SetWindowTitleRoomType(const std::string& roomTypeName) { m_windowTitle = "Online - " + roomTypeName + "###Room"; } void RoomWindow::ShowClickableSteamUser(const char* playerName, const CSteamID& steamId) const { ImGui::TextUnformatted(playerName); ImGui::HoverTooltip("Click to open Steam profile"); if (ImGui::IsItemClicked()) { g_interfaces.pSteamFriendsWrapper->ActivateGameOverlayToUser("steamid", steamId); } } void RoomWindow::DrawRoomImPlayers() { ImGui::BeginGroup(); ImGui::TextUnformatted("Improvement Mod users in Room:"); ImGui::BeginChild("RoomImUsers", ImVec2(230, 150), true); for (const IMPlayer& imPlayer : g_interfaces.pRoomManager->GetIMPlayersInCurrentRoom()) { ShowClickableSteamUser(imPlayer.steamName.c_str(), imPlayer.steamID); ImGui::NextColumn(); } ImGui::EndChild(); ImGui::EndGroup(); } void RoomWindow::DrawMatchImPlayers() { ImGui::BeginGroup(); ImGui::TextUnformatted("Improvement Mod users in match:"); ImGui::BeginChild("MatchImUsers", ImVec2(230, 150), true); if (g_interfaces.pRoomManager->IsThisPlayerInMatch()) { ImGui::Columns(2); for (const IMPlayer& imPlayer : g_interfaces.pRoomManager->GetIMPlayersInCurrentMatch()) { uint16_t matchPlayerIndex = g_interfaces.pRoomManager->GetPlayerMatchPlayerIndexByRoomMemberIndex(imPlayer.roomMemberIndex); std::string playerType; if (matchPlayerIndex == 0) playerType = "Player 1"; else if (matchPlayerIndex == 1) playerType = "Player 2"; else playerType = "Spectator"; ShowClickableSteamUser(imPlayer.steamName.c_str(), imPlayer.steamID); ImGui::NextColumn(); ImGui::TextUnformatted(playerType.c_str()); ImGui::NextColumn(); } } ImGui::EndChild(); ImGui::EndGroup(); }
25.283019
131
0.74005
GrimFlash
006ab54d6ebae19511ea7481b2eb6e35854eb37a
15,657
hpp
C++
test/simulation_tests.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
22
2015-09-28T14:41:00.000Z
2020-07-03T00:16:19.000Z
test/simulation_tests.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
6
2017-08-10T18:35:40.000Z
2018-10-13T01:38:04.000Z
test/simulation_tests.hpp
marekpetrik/CRAAM
62cc392e876b5383faa5cb15ab1f6b70b26ff395
[ "MIT" ]
10
2016-09-19T18:31:07.000Z
2018-07-05T08:59:45.000Z
// This file is part of CRAAM, a C++ library for solving plain // and robust Markov decision processes. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #pragma once #include "craam/Simulation.hpp" #include "craam/modeltools.hpp" #include "craam/RMDP.hpp" #include "craam/algorithms/values.hpp" #include "craam/simulators/inventory_simulation.hpp" #include "craam/simulators/invasive_species_simulation.hpp" #include <iostream> #include <sstream> #include <random> #include <utility> #include <functional> #include <boost/functional/hash.hpp> using namespace std; using namespace craam; using namespace craam::msen; using namespace craam::algorithms; using namespace util::lang; struct TestState{ int index; TestState(int i) : index(i){ }; }; class TestSim { public: typedef TestState State; typedef int Action; TestState init_state() const{ return TestState(1); } pair<double,TestState> transition(TestState, int) const{ return pair<double,TestState>(1.0,TestState(1)); }; bool end_condition(TestState) const{ return false; }; long action_count(TestState) const{return 1;} int action(TestState, long) const{return 1;} }; int test_policy(TestState){ return 0; } BOOST_AUTO_TEST_CASE(basic_simulation) { TestSim sim; auto samples = simulate<TestSim>(sim,test_policy,10,5); BOOST_CHECK_EQUAL(samples.size(), 50); } /** A simple simulator class. The state represents a position in a chain and actions move it up and down. The reward is equal to the position. Representation ~~~~~~~~~~~~~~ - State: position (int) - Action: change (int) */ class Counter{ private: default_random_engine gen; bernoulli_distribution d; const vector<int> actions_list; const int initstate; public: using State = int; using Action = int; /** Define the success of each action \param success The probability that the action is actually applied */ Counter(double success, int initstate, random_device::result_type seed = random_device{}()) : gen(seed), d(success), actions_list({1,-1}), initstate(initstate) {}; int init_state() const { return initstate; } pair<double,int> transition(int pos, int action) { int nextpos = d(gen) ? pos + action : pos; return make_pair((double) pos, nextpos); } bool end_condition(const int){ return false; } int action(State , long index) const{ return actions_list[index]; } virtual vector<int> get_valid_actions(State state) const{ return actions_list; } size_t action_count(State) const{return actions_list.size();}; }; /** A counter that terminates at either end as defined by the end state */ class CounterTerminal : public Counter { public: int endstate; CounterTerminal(double success, int initstate, int endstate, random_device::result_type seed = random_device{}()) : Counter(success, initstate, seed), endstate(endstate) {}; bool end_condition(const int state){ return (abs(state) >= endstate); } }; /** A counter that has bound states */ class CounterBound : public Counter { private: int min_state; int max_state; vector<int> min_state_actions; vector<int> max_state_actions; public: CounterBound(double success, int init_state, int min_state, int max_state, random_device::result_type seed = random_device{}()) : Counter(success, init_state, seed), min_state(min_state), max_state(max_state), min_state_actions({1}), max_state_actions({-1}) {}; virtual vector<int> get_valid_actions(State state) const{ if ( state == min_state ) return min_state_actions; else if ( state == max_state ) return max_state_actions; else return Counter::get_valid_actions(state); } }; // Hash function for the Counter / CounterTerminal EState above namespace std{ template<> struct hash<pair<int,int>>{ size_t operator()(pair<int,int> const& s) const{ boost::hash<pair<int,int>> h; return h(s); }; }; } BOOST_AUTO_TEST_CASE(simulation_multiple_counter_si ) { Counter sim(0.9,0,1); RandomPolicy<Counter> random_pol(sim,1); auto samples = simulate(sim,random_pol,20,20); BOOST_CHECK_CLOSE(samples.mean_return(0.9), -3.51759102217019, 0.0001); samples = simulate(sim,random_pol,1,20); BOOST_CHECK_CLOSE(samples.mean_return(0.9), 0, 0.0001); Counter sim2(0.9,3,1); samples = simulate(sim2,random_pol,1,20); BOOST_CHECK_CLOSE(samples.mean_return(0.9), 3, 0.0001); } BOOST_AUTO_TEST_CASE(simulation_multiple_counter_si_return ) { Counter sim(0.9,0,1); RandomPolicy<Counter> random_pol(sim,1); // sets the random seed auto samples_returns = simulate_return(sim,0.9,random_pol,20,20); auto v = samples_returns.second; auto meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size()); BOOST_CHECK_CLOSE(meanreturn, -3.51759102217019, 0.0001); samples_returns = simulate_return(sim,0.9,random_pol,1,20); v = samples_returns.second; meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size()); BOOST_CHECK_CLOSE(meanreturn, 0, 0.0001); Counter sim2(0.9,3,1); samples_returns = simulate_return(sim2,0.9,random_pol,1,20); v = samples_returns.second; meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size()); BOOST_CHECK_CLOSE(meanreturn, 3, 0.0001); // test termination probability equals to discount samples_returns = simulate_return(sim,1.0,DeterministicPolicy<Counter>(sim,indvec{0,1,1}),1000,100,0.1,1); v = samples_returns.second; meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size()); BOOST_CHECK_CLOSE(meanreturn, 4.73684, 10.0); // test stochastic policies CounterBound stochastic_sim(0.9,0,0,2,1); prob_matrix_t prob_matrix; prob_list_t prob_list1; prob_list_t prob_list2; prob_list_t prob_list3; prob_list1.push_back(1); prob_list1.push_back(0); prob_list2.push_back(0.6); prob_list2.push_back(0.4); prob_list3.push_back(0); prob_list3.push_back(1); prob_matrix.push_back(prob_list1); prob_matrix.push_back(prob_list2); prob_matrix.push_back(prob_list3); samples_returns = simulate_return(stochastic_sim,1.0,StochasticPolicy<Counter>(sim,prob_matrix,1),1000,4,0.1,1); v = samples_returns.second; meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size()); BOOST_CHECK_EQUAL(meanreturn, 3); } BOOST_AUTO_TEST_CASE(cumulative_rewards){ // check that the reward is constructed correctly from samples DiscreteSamples samples; samples.add_sample(0,0,1,1.0,3.0,0,0); samples.add_sample(0,0,1,2.0,2.0,0,0); samples.add_sample(0,0,1,3.0,1.0,0,0); samples.add_sample(0,0,2,7.0,1.0,0,1); samples.add_sample(0,0,3,2.0,1.0,0,1); samples.add_sample(0,0,0,0.0,1.0,0,1); samples.add_sample(DiscreteSample(0,0,1,1,1,0,2)); samples.add_sample(DiscreteSample(0,0,1,11,1,0,2)); BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[2], 6); BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[5], 9); BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[7], 12); } BOOST_AUTO_TEST_CASE(sampled_mdp_reward){ // check that the reward is constructed correctly from samples DiscreteSamples samples; // relevant samples (transition to 1) samples.add_sample(0,0,1,1.0,3.0,0,0); samples.add_sample(0,0,1,2.0,2.0,0,0); samples.add_sample(0,0,1,3.0,1.0,0,0); // irrelevant samples (do not transition to 1) samples.add_sample(0,0,2,0.0,1.0,0,0); samples.add_sample(0,0,3,0.0,1.0,0,0); samples.add_sample(0,0,0,0.0,1.0,0,0); SampledMDP smdp; smdp.add_samples(samples); auto reward = (*smdp.get_mdp())[0][0][0].get_rewards()[1]; //cout << (*smdp.get_mdp())[0][0][0].get_rewards()[1] << endl; BOOST_CHECK_CLOSE(reward, 1.666666, 1e-4); // check that the reward is constructed correctly from samples DiscreteSamples samples2; // relevant samples (transition to 1) samples2.add_sample(0,0,1,2.0,9.0,0,0); samples2.add_sample(0,0,1,4.0,6.0,0,0); samples2.add_sample(0,0,1,6.0,3.0,0,0); // irrelevant samples (do not transition to 1) samples2.add_sample(0,0,2,0.0,1.0,0,0); samples2.add_sample(0,0,3,0.0,1.0,0,0); samples2.add_sample(0,0,0,0.0,1.0,0,0); smdp.add_samples(samples2); //cout << (*smdp.get_mdp())[0][0][0].get_rewards()[1] << endl; reward = (*smdp.get_mdp())[0][0][0].get_rewards()[1]; BOOST_CHECK_CLOSE(reward, 2.916666666666, 1e-4); } BOOST_AUTO_TEST_CASE(construct_mdp_from_samples_si_pol){ CounterTerminal sim(0.9,0,10,1); RandomPolicy<CounterTerminal> random_pol(sim,1); auto samples = make_samples<CounterTerminal>(); simulate(sim,samples,random_pol,50,50); simulate(sim,samples,[](int){return 1;},10,20); simulate(sim,samples,[](int){return -1;},10,20); SampleDiscretizerSD<typename CounterTerminal::State, typename CounterTerminal::Action> sd; sd.add_samples(samples); BOOST_CHECK_EQUAL(samples.get_initial().size(), sd.get_discrete()->get_initial().size()); BOOST_CHECK_EQUAL(samples.size(), sd.get_discrete()->size()); SampledMDP smdp; smdp.add_samples(*sd.get_discrete()); shared_ptr<const MDP> mdp = smdp.get_mdp(); // check that the number of actions is correct (2) for(size_t i = 0; i < mdp->state_count(); i++){ if(mdp->get_state(i).action_count() > 0) BOOST_CHECK_EQUAL(mdp->get_state(i).action_count(), 2); } auto&& sol = mpi_jac(*mdp,0.9); BOOST_CHECK_CLOSE(sol.total_return(smdp.get_initial()), 51.313973, 1e-3); } template<class Model> Model create_test_mdp_sim(){ Model rmdp(3); // nonrobust // action 1 is optimal, with transition matrix [[0,1,0],[0,0,1],[0,0,1]] and rewards [0,0,1.1] add_transition<Model>(rmdp,0,1,1,1.0,0.0); add_transition<Model>(rmdp,1,1,2,1.0,0.0); add_transition<Model>(rmdp,2,1,2,1.0,1.1); add_transition<Model>(rmdp,0,0,0,1.0,0.0); add_transition<Model>(rmdp,1,0,0,1.0,1.0); add_transition<Model>(rmdp,2,0,1,1.0,1.0); add_transition<Model>(rmdp,1,2,1,0.5,0.5); return rmdp; } BOOST_AUTO_TEST_CASE(simulate_mdp){ shared_ptr<MDP> m = make_shared<MDP>(); *m = create_test_mdp_sim<MDP>(); Transition initial({0},{1.0}); ModelSimulator ms(m, initial,13); ModelRandomPolicy rp(ms,10); auto samples = simulate(ms, rp, 1000, 5, -1, 0.0, 10); BOOST_CHECK_EQUAL(samples.size(), 49); //cout << "Number of samples " << samples.size() << endl; SampledMDP smdp; smdp.add_samples(samples); auto newmdp = smdp.get_mdp(); auto solution1 = mpi_jac(*m, 0.9); auto solution2 = mpi_jac(*newmdp, 0.9); BOOST_CHECK_CLOSE(solution1.total_return(initial),8.90971,1e-3); //cout << "Return in original MDP " << solution1.total_return(initial) << endl; BOOST_CHECK_CLOSE(solution2.total_return(initial),8.90971,1e-3); //cout << "Return in sampled MDP " << solution2.total_return(initial) << endl; // need to remove the terminal state from the samples indvec policy = solution2.policy; policy.pop_back(); //cout << "Computed policy " << policy << endl; indvec policytarget{1,1,1}; BOOST_CHECK_EQUAL_COLLECTIONS(policy.begin(), policy.end(), policytarget.begin(), policytarget.end()); auto solution3 = mpi_jac(*m, 0.9, numvec(0), PlainBellman(policy)); BOOST_CHECK_CLOSE(solution3.total_return(initial), 8.90916, 1e-2); //cout << "Return of sampled policy in the original MDP " << solution3.total_return(initial) << endl; ModelDeterministicPolicy dp(ms, policy); auto samples_policy = simulate(ms, dp, 1000, 5); BOOST_CHECK_CLOSE(samples_policy.mean_return(0.9), 8.91, 1e-3); //cout << "Return of sampled " << samples_policy.mean_return(0.9) << endl; ModelRandomizedPolicy rizedp(ms, {{0.5,0.5},{0.5,0.4,0.1},{0.5,0.5}},0); auto randomized_samples = simulate(ms, rizedp, 1000, 5, -1, 0.0, 10); BOOST_CHECK_CLOSE(randomized_samples.mean_return(0.9), 4.01147, 1e-3); //cout << "Return of randomized samples " << randomized_samples.mean_return(0.9) << endl; } BOOST_AUTO_TEST_CASE(inventory_simulator){ long horizon = 10; long num_runs = 5; long initial=0, max_inventory=15; int rand_seed=7; double purchase_cost=2, sale_price=3; double prior_mean = 4, prior_std=1, demand_std=1.3; InventorySimulator simulator(initial, prior_mean, prior_std, demand_std, purchase_cost, sale_price, max_inventory, rand_seed); ModelInventoryPolicy rp(simulator, max_inventory, rand_seed); auto samples = simulate(simulator, rp, horizon, num_runs, -1, 0.0, rand_seed); BOOST_CHECK_EQUAL(samples.size(), 50); //horizon*num_runs SampledMDP smdp; smdp.add_samples(samples); auto newmdp = smdp.get_mdp(); auto solution = mpi_jac(*newmdp, 0.9); Transition init({initial},{1.0}); //The actual return for the mdp is not calculated to be 49.52, it's just picked to pass the test. //Need to know what the exact return should be to make the below test meaningful. BOOST_CHECK_CLOSE(solution.total_return(init),29.5768,1e-2); } BOOST_AUTO_TEST_CASE(invasive_species_simulator){ long horizon = 10; long num_runs = 5; long initial_population=30, carrying_capacity=1000; int rand_seed=7; long n_hat = 300, threshold_control = 0; prec_t mean_lambda=1.02, sigma2_lambda=0.02, sigma2_y=20, beta_1=0.001, beta_2=-0.0000021, prob_control = 0.5; InvasiveSpeciesSimulator simulator(initial_population, carrying_capacity, mean_lambda, sigma2_lambda, sigma2_y, beta_1, beta_2, n_hat, rand_seed); ModelInvasiveSpeciesPolicy rp(simulator, threshold_control, prob_control, rand_seed); auto samples = simulate(simulator, rp, horizon, num_runs, -1, 0.0, rand_seed); BOOST_CHECK_EQUAL(samples.size(), 50); //horizon*num_runs SampledMDP smdp; smdp.add_samples(samples); auto newmdp = smdp.get_mdp(); auto solution = mpi_jac(*newmdp, 0.9); Transition init({initial_population},{1.0}); //The actual return for the mdp is not calculated to be 49.52, it's just picked to pass the test. //Need to know what the exact return should be to make the below test meaningful. //BOOST_CHECK_CLOSE(solution.total_return(init),-0.4245,1e-2); }
32.686848
141
0.685444
marekpetrik
006bef6bf26e467e6902de9faaea6727a4a86a3d
86
cpp
C++
utils/uicommon/FAudioUI_main.cpp
benoit-pierre/FAudio
e37acb75c186a365dd55bdb97b4dac84ab6a163a
[ "Zlib" ]
null
null
null
utils/uicommon/FAudioUI_main.cpp
benoit-pierre/FAudio
e37acb75c186a365dd55bdb97b4dac84ab6a163a
[ "Zlib" ]
null
null
null
utils/uicommon/FAudioUI_main.cpp
benoit-pierre/FAudio
e37acb75c186a365dd55bdb97b4dac84ab6a163a
[ "Zlib" ]
null
null
null
/* Use this if your toolchain is fussy about the C file */ #include "FAudioUI_main.c"
28.666667
58
0.732558
benoit-pierre
006f6420103afc3273e353bb3a3cb285d6dd4a18
4,673
cpp
C++
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
1
2022-03-10T11:43:24.000Z
2022-03-10T11:43:24.000Z
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <tga2d/windows/WindowsWindow.h> #include "resource.h" #include <WinUser.h> #include <tga2d/imguiinterface/ImGuiInterface.h> using namespace Tga2D; WindowsWindow::WindowsWindow(void) :myWndProcCallback(nullptr) { } WindowsWindow::~WindowsWindow(void) { } bool WindowsWindow::Init(Vector2ui aWindowSize, HWND*& aHwnd, EngineCreateParameters* aSetting, HINSTANCE& aHInstanceToFill, callback_function_wndProc aWndPrcCallback) { if (!aSetting) { return false; } myWndProcCallback = aWndPrcCallback; HINSTANCE instance = GetModuleHandle(NULL); aHInstanceToFill = instance; ZeroMemory(&myWindowClass, sizeof(WNDCLASSEX)); myWindowClass.cbSize = sizeof(WNDCLASSEX); myWindowClass.style = CS_HREDRAW | CS_VREDRAW; myWindowClass.lpfnWndProc = WindowProc; myWindowClass.hInstance = instance; myWindowClass.hCursor = LoadCursor(NULL, IDC_ARROW); myWindowClass.hbrBackground = (HBRUSH)COLOR_WINDOW; myWindowClass.lpszClassName = L"WindowClass1"; myWindowClass.hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); myWindowClass.hIconSm = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); RegisterClassEx(&myWindowClass); RECT wr = {0, 0, static_cast<long>(aWindowSize.x), static_cast<long>(aWindowSize.y)}; // set the size, but not the position //AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size DWORD windowStyle = 0; switch (aSetting->myWindowSetting) { case WindowSetting::Overlapped: windowStyle = WS_OVERLAPPEDWINDOW; break; case WindowSetting::Borderless: windowStyle = WS_VISIBLE | WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; break; default: break; } if (!aHwnd) { myWindowHandle = CreateWindowEx(WS_EX_APPWINDOW, L"WindowClass1", // name of the window class aSetting->myApplicationName.c_str(), // title of the window windowStyle, // window style CW_USEDEFAULT, // x-position of the window CW_USEDEFAULT, // y-position of the window wr.right - wr.left, // width of the window wr.bottom - wr.top, // height of the window NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL instance, // application handle NULL); // used with multiple windows, NULL ShowWindow(myWindowHandle, true); aHwnd = &myWindowHandle; } else { myWindowHandle = *aHwnd; } SetWindowLongPtr(myWindowHandle, GWLP_USERDATA, (LONG_PTR)this); // Fix to set the window to the actual resolution as the borders will mess with the resolution wanted myResolution = aWindowSize; myResolutionWithBorderDifference = myResolution; if (aSetting->myWindowSetting == WindowSetting::Overlapped) { RECT r; GetClientRect(myWindowHandle, &r); //get window rect of control relative to screen int horizontal = r.right - r.left; int vertical = r.bottom - r.top; int diffX = aWindowSize.x - horizontal; int diffY = aWindowSize.y - vertical; SetResolution(aWindowSize + Vector2ui(diffX, diffY)); myResolutionWithBorderDifference = aWindowSize + Vector2ui(diffX, diffY); } INFO_PRINT("%s %i %i", "Windows created with size ", aWindowSize.x, aWindowSize.y); return true; } #ifndef _RETAIL IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif LRESULT WindowsWindow::LocWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { #ifndef _RETAIL if (ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam)) { return S_OK; } #endif if (myWndProcCallback) { return myWndProcCallback(hWnd, message, wParam, lParam); } return S_OK; } LRESULT CALLBACK WindowsWindow::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { WindowsWindow* windowsClass = (WindowsWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (windowsClass) { LRESULT result = windowsClass->LocWindowProc(hWnd, message, wParam, lParam); if (result) { return DefWindowProc(hWnd, message, wParam, lParam); } } switch(message) { case WM_DESTROY: { PostQuitMessage(0); return 0; } break; case WM_SIZE: { if (Engine::GetInstance()) Engine::GetInstance()->SetWantToUpdateSize(); break; } } return DefWindowProc (hWnd, message, wParam, lParam); } void Tga2D::WindowsWindow::SetResolution(Vector2ui aResolution) { ::SetWindowPos(myWindowHandle, 0, 0, 0, aResolution.x, aResolution.y, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER); } void Tga2D::WindowsWindow::Close() { DestroyWindow(myWindowHandle); }
27.815476
168
0.711748
sarisman84
006fc1f49ec8f6c0970729038579eb100d4bf8d5
254
cpp
C++
sdk/src/layers/ItemAton.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
4
2021-07-07T10:42:53.000Z
2022-01-11T12:53:25.000Z
sdk/src/layers/ItemAton.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
2
2022-02-13T19:59:25.000Z
2022-03-25T01:02:17.000Z
sdk/src/layers/ItemAton.cpp
Fpepe943/fairwindplusplus
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
[ "Apache-2.0" ]
7
2021-06-07T07:12:55.000Z
2022-01-12T16:09:55.000Z
// // Created by Raffaele Montella on 03/05/21. // #include "FairWindSdk/layers/ItemAton.hpp" ItemAton::ItemAton(QString &typeUuid): ItemSignalK(typeUuid) { } QImage ItemAton::getImage() const { return QImage(":/resources/images/ais_aton.png"); }
19.538462
62
0.720472
Fpepe943
00786a1ab462b9cae550f5dfbb92685202f08563
1,603
hpp
C++
libs/gui/include/sge/gui/widget/bar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/gui/include/sge/gui/widget/bar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/gui/include/sge/gui/widget/bar.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_GUI_WIDGET_BAR_HPP_INCLUDED #define SGE_GUI_WIDGET_BAR_HPP_INCLUDED #include <sge/gui/fill_color.hpp> #include <sge/gui/fill_level.hpp> #include <sge/gui/detail/symbol.hpp> #include <sge/gui/renderer/base_fwd.hpp> #include <sge/gui/style/const_reference.hpp> #include <sge/gui/widget/bar_fwd.hpp> #include <sge/gui/widget/base.hpp> #include <sge/renderer/context/ffp_fwd.hpp> #include <sge/rucksack/axis.hpp> #include <sge/rucksack/dim_fwd.hpp> #include <sge/rucksack/widget/base_fwd.hpp> #include <sge/rucksack/widget/dummy.hpp> #include <fcppt/nonmovable.hpp> #include <fcppt/strong_typedef.hpp> namespace sge::gui::widget { class bar : public sge::gui::widget::base { FCPPT_NONMOVABLE(bar); public: SGE_GUI_DETAIL_SYMBOL bar(sge::gui::style::const_reference, sge::rucksack::dim const &, sge::rucksack::axis, sge::gui::fill_color, sge::gui::fill_level); SGE_GUI_DETAIL_SYMBOL ~bar() override; SGE_GUI_DETAIL_SYMBOL void value(sge::gui::fill_level); private: void on_draw(sge::gui::renderer::base &, sge::renderer::context::ffp &) override; [[nodiscard]] sge::rucksack::widget::base &layout() override; sge::gui::style::const_reference const style_; sge::rucksack::axis const axis_; sge::gui::fill_color const foreground_; sge::gui::fill_level value_; sge::rucksack::widget::dummy layout_; }; } #endif
25.046875
83
0.726138
cpreh
0078eaf95ade009a79cdf34c1a94c415a21100ad
1,407
cpp
C++
DWITE/DWITE_10_R5P5_Cube_World.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
null
null
null
DWITE/DWITE_10_R5P5_Cube_World.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-10-14T18:26:56.000Z
2021-10-14T18:26:56.000Z
DWITE/DWITE_10_R5P5_Cube_World.cpp
Togohogo1/pg
ee3c36acde47769c66ee13a227762ee677591375
[ "MIT" ]
1
2021-08-06T03:39:55.000Z
2021-08-06T03:39:55.000Z
#include <bits/stdc++.h> using namespace std; #define f first #define s second const int MM = 22; int N, M, ans, grid[MM][MM], vis[MM][MM], dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; priority_queue<pair<int, pair<int, int>>> pq; int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); for (int i = 0; i < 5; i++) { cin >> N >> M; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> grid[i][j]; if (i == 0 || i == N - 1 || j == 0 || j == M - 1) { vis[i][j] = true; pq.push({-grid[i][j], {i, j}}); } } } while (!pq.empty()) { int cur = -pq.top().f, cr = pq.top().s.f, cc = pq.top().s.s; pq.pop(); for (int i = 0; i < 4; i++) { int nr = cr + dir[i][0], nc = cc + dir[i][1]; if (!vis[nr][nc] && nr >= 0 && nc >= 0 && nr < N && nc < M) { if (cur - grid[nr][nc] > 0) { ans += cur-grid[nr][nc]; pq.push({-cur, {nr, nc}}); } else pq.push({-grid[nr][nc], {nr, nc}}); vis[nr][nc] = true; } } } cout << ans << '\n'; memset(vis, 0, sizeof(vis)); ans = 0; } }
25.581818
89
0.331912
Togohogo1
0078fea0aae13cf93b439c1dca7535689c1ed16e
622
cpp
C++
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int x,y,i,sum,t,k; while(cin>>t) { for(k=1; k<=t; k++) { cin>>x>>y; sum=0; if(x<=y) { for(i=x+1; i<y; i++) { if(i%2!=0) sum=sum+i; } } else { for(i=y+1; i<x; i++) { if(i%2!=0) sum=sum+i; } } printf("%d\n",sum); } } return 0; }
18.294118
36
0.233119
arifparvez14
00796dce8f7bddbc4d4a1eee2c504af59ad4372e
8,388
cpp
C++
pdfium_lib/pdfium/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp
qingqibing/vs_pdfium
6d009d478c3e761fac49b357d81532c3ed7aad9f
[ "BSD-3-Clause" ]
null
null
null
pdfium_lib/pdfium/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp
qingqibing/vs_pdfium
6d009d478c3e761fac49b357d81532c3ed7aad9f
[ "BSD-3-Clause" ]
null
null
null
pdfium_lib/pdfium/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp
qingqibing/vs_pdfium
6d009d478c3e761fac49b357d81532c3ed7aad9f
[ "BSD-3-Clause" ]
1
2020-04-04T17:23:01.000Z
2020-04-04T17:23:01.000Z
// Copyright 2016 PDFium 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 <memory> #include <string> #include "core/fxcrt/fx_system.h" #include "public/cpp/fpdf_scopers.h" #include "public/fpdf_edit.h" #include "public/fpdf_save.h" #include "public/fpdfview.h" #include "testing/embedder_test.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kAgeUTF8[] = "\xc3\xa2" "ge"; const char kAgeLatin1[] = "\xe2" "ge"; const char kHotelUTF8[] = "h" "\xc3\xb4" "tel"; const char kHotelLatin1[] = "h" "\xf4" "tel"; } // namespace class CPDFSecurityHandlerEmbedderTest : public EmbedderTest {}; TEST_F(CPDFSecurityHandlerEmbedderTest, Unencrypted) { ASSERT_TRUE(OpenDocument("about_blank.pdf")); EXPECT_EQ(0xFFFFFFFF, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UnencryptedWithPassword) { ASSERT_TRUE(OpenDocumentWithPassword("about_blank.pdf", "foobar")); EXPECT_EQ(0xFFFFFFFF, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, NoPassword) { EXPECT_FALSE(OpenDocument("encrypted.pdf")); } TEST_F(CPDFSecurityHandlerEmbedderTest, BadPassword) { EXPECT_FALSE(OpenDocumentWithPassword("encrypted.pdf", "tiger")); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPassword) { ASSERT_TRUE(OpenDocumentWithPassword("encrypted.pdf", "1234")); EXPECT_EQ(0xFFFFF2C0, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPassword) { ASSERT_TRUE(OpenDocumentWithPassword("encrypted.pdf", "5678")); EXPECT_EQ(0xFFFFFFFC, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, PasswordAfterGenerateSave) { #if _FX_PLATFORM_ == _FX_PLATFORM_LINUX_ const char md5[] = "7048dca58e2ed8f93339008b91e4eb4e"; #elif _FX_PLATFORM_ == _FX_PLATFORM_APPLE_ const char md5[] = "6951b6c9891dfe0332a5b1983e484400"; #else const char md5[] = "041c2fb541c8907cc22ce101b686c79e"; #endif // _FX_PLATFORM_ == _FX_PLATFORM_LINUX_ { ASSERT_TRUE(OpenDocumentWithOptions("encrypted.pdf", "5678", LinearizeOption::kMustLinearize, JavaScriptOption::kEnableJavaScript)); FPDF_PAGE page = LoadPage(0); ASSERT_TRUE(page); FPDF_PAGEOBJECT red_rect = FPDFPageObj_CreateNewRect(10, 10, 20, 20); ASSERT_TRUE(red_rect); EXPECT_TRUE(FPDFPath_SetFillColor(red_rect, 255, 0, 0, 255)); EXPECT_TRUE(FPDFPath_SetDrawMode(red_rect, FPDF_FILLMODE_ALTERNATE, 0)); FPDFPage_InsertObject(page, red_rect); ScopedFPDFBitmap bitmap = RenderLoadedPage(page); CompareBitmap(bitmap.get(), 612, 792, md5); EXPECT_TRUE(FPDFPage_GenerateContent(page)); SetWholeFileAvailable(); EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); UnloadPage(page); } std::string new_file = GetString(); FPDF_FILEACCESS file_access; memset(&file_access, 0, sizeof(file_access)); file_access.m_FileLen = new_file.size(); file_access.m_GetBlock = GetBlockFromString; file_access.m_Param = &new_file; EXPECT_FALSE(FPDF_LoadCustomDocument(&file_access, nullptr)); struct { const char* password; const unsigned long permissions; } tests[] = {{"1234", 0xFFFFF2C0}, {"5678", 0xFFFFFFFC}}; for (const auto& test : tests) { ASSERT_TRUE(OpenSavedDocumentWithPassword(test.password)); FPDF_PAGE page = LoadSavedPage(0); VerifySavedRendering(page, 612, 792, md5); EXPECT_EQ(test.permissions, FPDF_GetDocPermissions(saved_document_)); CloseSavedPage(page); CloseSavedDocument(); } } TEST_F(CPDFSecurityHandlerEmbedderTest, NoPasswordVersion5) { ASSERT_FALSE(OpenDocument("bug_644.pdf")); } TEST_F(CPDFSecurityHandlerEmbedderTest, BadPasswordVersion5) { ASSERT_FALSE(OpenDocumentWithPassword("bug_644.pdf", "tiger")); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion5) { ASSERT_TRUE(OpenDocumentWithPassword("bug_644.pdf", "a")); EXPECT_EQ(0xFFFFFFFC, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion5) { ASSERT_TRUE(OpenDocumentWithPassword("bug_644.pdf", "b")); EXPECT_EQ(0xFFFFFFFC, FPDF_GetDocPermissions(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion2UTF8) { // The password is "age", where the 'a' has a circumflex. Encoding the // password as UTF-8 works. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r2.pdf", kAgeUTF8)); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion2Latin1) { // The same password encoded as Latin-1 also works at revision 2. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r2.pdf", kAgeLatin1)); EXPECT_EQ(2, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion3UTF8) { // Same as OwnerPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r3.pdf", kAgeUTF8)); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion3Latin1) { // Same as OwnerPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r3.pdf", kAgeLatin1)); EXPECT_EQ(3, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion5UTF8) { // Same as OwnerPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r5.pdf", kAgeUTF8)); EXPECT_EQ(5, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion5Latin1) { // Same as OwnerPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r5.pdf", kAgeLatin1)); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion6UTF8) { // Same as OwnerPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r6.pdf", kAgeUTF8)); EXPECT_EQ(6, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, OwnerPasswordVersion6Latin1) { // Same as OwnerPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r6.pdf", kAgeLatin1)); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion2UTF8) { // The password is "hotel", where the 'o' has a circumflex. Encoding the // password as UTF-8 works. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r2.pdf", kHotelUTF8)); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion2Latin1) { // The same password encoded as Latin-1 also works at revision 2. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r2.pdf", kHotelLatin1)); EXPECT_EQ(2, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion3UTF8) { // Same as UserPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r3.pdf", kHotelUTF8)); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion3Latin1) { // Same as UserPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r3.pdf", kHotelLatin1)); EXPECT_EQ(3, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion5UTF8) { // Same as UserPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r5.pdf", kHotelUTF8)); EXPECT_EQ(5, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion5Latin1) { // Same as UserPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r5.pdf", kHotelLatin1)); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion6UTF8) { // Same as UserPasswordVersion2UTF8 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r6.pdf", kHotelUTF8)); EXPECT_EQ(6, FPDF_GetSecurityHandlerRevision(document())); } TEST_F(CPDFSecurityHandlerEmbedderTest, UserPasswordVersion6Latin1) { // Same as UserPasswordVersion2Latin1 test above. ASSERT_TRUE( OpenDocumentWithPassword("encrypted_hello_world_r6.pdf", kHotelLatin1)); }
35.096234
78
0.771817
qingqibing
007c70b8547794cca85d109520cab277ee4f94b7
3,579
cxx
C++
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
akenmorris/VTK
cf80447580ff48cbdb4a588aaafe1d3397af3791
[ "BSD-3-Clause" ]
null
null
null
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
akenmorris/VTK
cf80447580ff48cbdb4a588aaafe1d3397af3791
[ "BSD-3-Clause" ]
2
2018-05-04T02:00:02.000Z
2018-05-04T02:15:19.000Z
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
akenmorris/VTK
cf80447580ff48cbdb4a588aaafe1d3397af3791
[ "BSD-3-Clause" ]
1
2020-08-18T11:44:39.000Z
2020-08-18T11:44:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPPartitionedDataSetCollectionToMultiBlockDataSet.h" #include "vtkCommunicator.h" #include "vtkMultiBlockDataSet.h" #include "vtkMultiProcessController.h" #include "vtkObjectFactory.h" #include "vtkPartitionedDataSet.h" #include "vtkPartitionedDataSetCollection.h" #include "vtkSmartPointer.h" #include <vector> vtkObjectFactoryNewMacro(vtkPPartitionedDataSetCollectionToMultiBlockDataSet); vtkCxxSetObjectMacro( vtkPPartitionedDataSetCollectionToMultiBlockDataSet, Controller, vtkMultiProcessController); //---------------------------------------------------------------------------- vtkPPartitionedDataSetCollectionToMultiBlockDataSet:: vtkPPartitionedDataSetCollectionToMultiBlockDataSet() : Controller(nullptr) { this->SetController(vtkMultiProcessController::GetGlobalController()); } //---------------------------------------------------------------------------- vtkPPartitionedDataSetCollectionToMultiBlockDataSet:: ~vtkPPartitionedDataSetCollectionToMultiBlockDataSet() { this->SetController(nullptr); } //---------------------------------------------------------------------------- int vtkPPartitionedDataSetCollectionToMultiBlockDataSet::RequestData( vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkSmartPointer<vtkPartitionedDataSetCollection> input = vtkPartitionedDataSetCollection::GetData(inputVector[0], 0); auto output = vtkMultiBlockDataSet::GetData(outputVector, 0); if (this->Controller && this->Controller->GetNumberOfProcesses() > 1 && input->GetNumberOfPartitionedDataSets() > 0) { // ensure that we have exactly the same number of partitions on all ranks. vtkNew<vtkPartitionedDataSetCollection> clone; clone->ShallowCopy(input); const auto count = input->GetNumberOfPartitionedDataSets(); std::vector<unsigned int> piece_counts(count); for (unsigned int cc = 0; cc < count; ++cc) { piece_counts[cc] = clone->GetPartitionedDataSet(cc) ? clone->GetPartitionedDataSet(cc)->GetNumberOfPartitions() : 0; } std::vector<unsigned int> result(piece_counts.size()); this->Controller->AllReduce( &piece_counts[0], &result[0], static_cast<vtkIdType>(count), vtkCommunicator::MAX_OP); for (unsigned int cc = 0; cc < count; ++cc) { if (result[cc] > 0) { if (clone->GetPartitionedDataSet(cc) == nullptr) { clone->SetPartitionedDataSet(cc, vtkNew<vtkPartitionedDataSet>{}); } clone->GetPartitionedDataSet(cc)->SetNumberOfPartitions(result[cc]); } } input = clone; } return this->Execute(input, output) ? 1 : 0; } //---------------------------------------------------------------------------- void vtkPPartitionedDataSetCollectionToMultiBlockDataSet::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Controller: " << this->Controller << endl; }
37.673684
98
0.654652
akenmorris
007fc689f124f891c8ab4743497c17a90a6fe25d
148
cpp
C++
Ch01/Ex1_20.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
4
2015-04-20T10:04:49.000Z
2018-04-19T12:46:01.000Z
Ch01/Ex1_20.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
null
null
null
Ch01/Ex1_20.cpp
boscotsang/CppPrimerCode
65eed86652f5ec475dec593bd731b7752cb46c51
[ "MIT" ]
null
null
null
#include <iostream> #include "Sales_item.h" int main(){ Sales_item s1; while(std::cin >> s1) std::cout << s1 << std::endl; return 0; }
16.444444
55
0.594595
boscotsang
00803af5abfb8a6ab8da8a5e8de32254429127ad
3,562
hpp
C++
src/Setup.hpp
albrdev/kalk
529472931308da37391601ef47e59e03bc91b693
[ "Apache-2.0" ]
null
null
null
src/Setup.hpp
albrdev/kalk
529472931308da37391601ef47e59e03bc91b693
[ "Apache-2.0" ]
null
null
null
src/Setup.hpp
albrdev/kalk
529472931308da37391601ef47e59e03bc91b693
[ "Apache-2.0" ]
null
null
null
#ifndef __SETUP_HPP__ #define __SETUP_HPP__ #include "text/exception/SyntaxError.hpp" #include "text/expression/ExpressionParser.hpp" #include "text/parsing/CommandParser.hpp" #include <string> #include <tuple> #include <unordered_map> #include <vector> #include <mpfr.h> #include <mpreal.h> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using DefaultArithmeticType = mpfr::mpreal; using DefaultValueType = Text::Expression::ValueToken<std::nullptr_t, DefaultArithmeticType, std::string, boost::posix_time::ptime, boost::posix_time::time_duration>; using DefaultVariableType = Text::Expression::VariableToken<std::nullptr_t, DefaultArithmeticType, std::string, boost::posix_time::ptime, boost::posix_time::time_duration>; using ChemArithmeticType = mpfr::mpreal; using ChemValueType = Text::Expression::ValueToken<ChemArithmeticType>; using ChemVariableType = Text::Expression::VariableToken<ChemArithmeticType>; using Text::Expression::IValueToken; using Text::Expression::IVariableToken; using Text::Expression::IUnaryOperatorToken; using Text::Expression::IBinaryOperatorToken; using Text::Expression::IFunctionToken; using Text::Expression::UnaryOperatorToken; using Text::Expression::BinaryOperatorToken; using Text::Expression::FunctionToken; using Text::Expression::Associativity; using Text::Expression::ExpressionParser; using Text::Parsing::CommandParser; using Text::Exception::SyntaxError; inline std::unordered_map<char, std::unique_ptr<UnaryOperatorToken>> defaultUnaryOperatorCache; inline std::unordered_map<char, IUnaryOperatorToken*> defaultUnaryOperators; inline std::unordered_map<std::string, std::unique_ptr<BinaryOperatorToken>> defaultBinaryOperatorCache; inline std::unordered_map<std::string, IBinaryOperatorToken*> defaultBinaryOperators; inline std::unordered_map<std::string, std::unique_ptr<FunctionToken>> defaultFunctionCache; inline std::unordered_map<std::string, IFunctionToken*> defaultFunctions; inline std::unordered_map<std::string, std::unique_ptr<DefaultVariableType>> defaultUninitializedVariableCache; inline std::unordered_map<std::string, std::unique_ptr<DefaultVariableType>> defaultInitializedVariableCache; inline std::unordered_map<std::string, IVariableToken*> defaultVariables; inline std::vector<DefaultValueType> results; inline std::vector<std::tuple<const IUnaryOperatorToken*, std::string, std::string>> unaryOperatorInfoMap; inline std::vector<std::tuple<const IBinaryOperatorToken*, std::string, std::string>> binaryOperatorInfoMap; inline std::vector<std::tuple<const IFunctionToken*, std::string, std::string>> functionInfoMap; inline std::vector<std::tuple<const IVariableToken*, std::string, std::string>> variableInfoMap; inline bool quit = false; struct kalk_options { mpfr_prec_t precision; mpfr_rnd_t roundingMode; int digits; int output_base; int input_base; int jpo_precedence; std::string date_ofmt; unsigned int seed; bool interactive; }; const inline kalk_options defaultOptions {128, mpfr_rnd_t::MPFR_RNDN, 30, 10, 10, -1, "%Y-%m-%d %H:%M:%S", 0u, false}; inline kalk_options options {}; mpfr_rnd_t strToRmode(const std::string value); void printValue(const DefaultValueType& value); const DefaultValueType* ans(int index = -1); void list(const std::string& searchPattern = ".*"); void InitDefaultExpressionParser(ExpressionParser& instance); void InitChemicalExpressionParser(ExpressionParser& instance); void InitCommandParser(CommandParser& instance); #endif // __SETUP_HPP__
39.142857
148
0.800955
albrdev
0082d550c3bc030679b8af046c7d4d62a8be6caf
3,736
cpp
C++
playground/mainwindow.cpp
evonove/moply
96ad70612fc652e46792c101d463364a824f60ec
[ "BSD-2-Clause-FreeBSD" ]
1
2017-06-01T12:54:29.000Z
2017-06-01T12:54:29.000Z
playground/mainwindow.cpp
evonove/moply
96ad70612fc652e46792c101d463364a824f60ec
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
playground/mainwindow.cpp
evonove/moply
96ad70612fc652e46792c101d463364a824f60ec
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "moply/gldrawer.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <QFileDialog> #include <QDebug> #include <QSignalMapper> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); loadAction = new QAction(tr("&Load"), this); connect(loadAction, SIGNAL(triggered()), this, SLOT(load())); // add menu action fileMenu = ui->menuBar->addMenu(tr("&File")); fileMenu->addAction(loadAction); // set up QGLFormat QGLFormat *f = new QGLFormat(); f->setStencil(true); f->setRgba(true); f->setDepth(true); f->setDoubleBuffer(true); drawer = new GLDrawer(ui->GLPlaceholder, f); drawer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout * l = new QVBoxLayout(ui->GLPlaceholder); l->setMargin(0); l->setSpacing(0); l->addWidget(drawer); //ui->horizontalLayout->insertWidget(0, drawer, 1, 0); //connect(ui->loadFile, SIGNAL(clicked()), this, SLOT(load())); signalMapper = new QSignalMapper(this); // mapping components to commands signalMapper->setMapping(ui->meshBox, "mesh"); signalMapper->setMapping(ui->ribbonBox, "ribbon"); signalMapper->setMapping(ui->linesBox, "lines"); signalMapper->setMapping(ui->cartoonBox, "cartoon"); signalMapper->setMapping(ui->nbBox, "nonbonded"); signalMapper->setMapping(ui->surfaceBox, "surface"); signalMapper->setMapping(ui->sticksBox, "sticks"); // connecting checkboxes connect(ui->meshBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->ribbonBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->linesBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->cartoonBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->nbBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->surfaceBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(ui->sticksBox, SIGNAL(toggled(bool)), signalMapper, SLOT(map())); connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(render(QString))); // sequence selector connect(ui->showSeqBox, SIGNAL(toggled(bool)), drawer, SLOT(sequence(bool))); // quality selector QSignalMapper *qualityMapper = new QSignalMapper(this); qualityMapper->setMapping(ui->maxP, 100); qualityMapper->setMapping(ui->avgP, 66); qualityMapper->setMapping(ui->avgQ, 33); qualityMapper->setMapping(ui->maxQ, 0); connect(ui->maxP, SIGNAL(toggled(bool)), qualityMapper, SLOT(map())); connect(ui->avgP, SIGNAL(toggled(bool)), qualityMapper, SLOT(map())); connect(ui->avgQ, SIGNAL(toggled(bool)), qualityMapper, SLOT(map())); connect(ui->maxQ, SIGNAL(toggled(bool)), qualityMapper, SLOT(map())); connect(qualityMapper, SIGNAL(mapped(int)), drawer, SLOT(quality(int))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::load() { ui->linesBox->setChecked(true); ui->nbBox->setChecked(true); ui->meshBox->setChecked(false); ui->cartoonBox->setChecked(false); ui->ribbonBox->setChecked(false); ui->surfaceBox->setChecked(false); ui->sticksBox->setChecked(false); QString fname = QFileDialog::getOpenFileName(this, tr("Open file"), "", tr("Mol Files (*.pdb);;All Files (*)")); if (fname != "") { string _fname = fname.toUtf8().constData(); drawer->loadFile(&_fname); } qDebug() << "load action triggered"; ui->avgP->setChecked(true); } void MainWindow::render(QString str) { QCheckBox *qcb = (QCheckBox*) signalMapper->mapping(str); drawer->render(qcb->isChecked(), str.toUtf8().constData()); }
33.357143
116
0.671574
evonove
0083211ed313f9ef7734feba0aa047036abb9fdb
1,976
cpp
C++
src/main.cpp
grillbaer/esp32-iot-logger
e4beb8e324c00abc4de1cbe300d855ef904b0286
[ "MIT" ]
null
null
null
src/main.cpp
grillbaer/esp32-iot-logger
e4beb8e324c00abc4de1cbe300d855ef904b0286
[ "MIT" ]
null
null
null
src/main.cpp
grillbaer/esp32-iot-logger
e4beb8e324c00abc4de1cbe300d855ef904b0286
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "driver/pcnt.h" #include "driver/gpio.h" #include "driver/rtc_io.h" #include "input.h" #include "display.h" #include "ingest.h" #include "ADS1115InputChannel.h" // blinky state int blinky = 1; const uint32_t sampleIntervalMicros = 1000000L; uint32_t sampleStartMicros; const int16_t ingestIntervalSecs = 60; int16_t ingestCountdown; const int watchdogTimeoutMicros = 40000000L; hw_timer_t *watchdogTimer = NULL; uint32_t calcRemainingWait(); void IRAM_ATTR watchdogExpired(); void setup() { Serial.begin(115200); delay(500); // wait to avoid serial problems Serial.println("Starting!"); // initialize watchdog timer watchdogTimer = timerBegin(0, 80, true); timerAttachInterrupt(watchdogTimer, &watchdogExpired, true); timerAlarmWrite(watchdogTimer, watchdogTimeoutMicros, false); timerAlarmEnable(watchdogTimer); // blinky pinMode(LED_BUILTIN, OUTPUT); setupInput(); setupIngest(); setupDisplay(); ingestCountdown = ingestIntervalSecs; } void loop() { sampleStartMicros = micros(); // blinky digitalWrite(LED_BUILTIN, blinky); blinky = !blinky; // reset watchdog timerWrite(watchdogTimer, 0); Serial.print("Sample:"); for (int i = 0; i < inputChannelCount; i++) { inputChannels[i]->readValue(); Serial.print(" "); Serial.print(inputChannels[i]->getName()); Serial.print("="); Serial.printf(inputChannels[i]->getFormat(), inputChannels[i]->getValue()); delay(1); // try to fix sporadic wrong readings } Serial.println(); ingestCountdown--; if (ingestCountdown <= 0) { ingestCountdown = ingestIntervalSecs; ingest(); } updateDisplay(); int32_t remainingWait = calcRemainingWait(); delayMicroseconds(remainingWait); } uint32_t calcRemainingWait() { const uint32_t remainingMicros = sampleIntervalMicros - (micros() - sampleStartMicros); return remainingMicros > sampleIntervalMicros ? 0 : remainingMicros; // handle overflow } void IRAM_ATTR watchdogExpired() { esp_restart(); }
21.247312
88
0.739879
grillbaer
0083d8116dbf8c73d9daf185fe21ad206df3a45f
9,227
cpp
C++
src/main.cpp
lscandolo/Compressed-shadow-maps
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
[ "MIT" ]
7
2020-04-07T18:53:12.000Z
2022-01-25T15:06:30.000Z
src/main.cpp
lscandolo/Compressed-shadow-maps
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
[ "MIT" ]
null
null
null
src/main.cpp
lscandolo/Compressed-shadow-maps
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
[ "MIT" ]
1
2021-07-14T02:14:45.000Z
2021-07-14T02:14:45.000Z
#include "common.h" #include "helpers/OpenGLHelpers.h" #include "helpers/FPCamera.h" #include "helpers/CameraRecord.h" #include "helpers/MeshData.h" #include "helpers/LightData.h" #include "helpers/ScopeTimer.h" #include "helpers/Ini.h" #include "gui/MeshGUI.h" #include "gui/LightGUI.h" #include "gui/FPCameraGUI.h" #include "gui/RenderGUI.h" #include "csm/CSMTechnique.h" #include "managers/GLStateManager.h" #include "managers/TextureManager.h" #include "managers/GUIManager.h" #include "managers/GLShapeManager.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <GLFW/glfw3.h> #include <freeimage.h> #include <tiny_obj_loader.h> #include <iostream> #include <random> using namespace glm; std::vector<Technique*> techniques = { new CSMTechnique }; bool display_gui = true; bool full_screen = false; RenderStats renderstats; #define INIT_WIN_WIDTH 1280 #define INIT_WIN_HEIGHT 720 FPCamera fpcamera; glm::vec3 fpcamera_speed(0.f, 0.f, 0.f); glm::vec2 fpcamera_rotational_speed(0.f, 0.f); bool cursor_lock = false; using namespace GLHelpers; static void resize_callback(GLFWwindow* window, int width, int height) { DefaultRenderOptions().window_size = size2D(width, height); DefaultRenderOptions().output_size = size2D(width, height); DefaultRenderOptions().current_technique()->output_resize_callback(size2D(width, height)); fpcamera.aspect = DefaultRenderOptions().output_size.width / float(DefaultRenderOptions().output_size.height); fpcamera.jitter_plane = glm::ivec2(DefaultRenderOptions().output_size.width, DefaultRenderOptions().output_size.height); } static void camera_key_callback(int key, int scancode, int action, int mods) { if (action != GLFW_PRESS && action != GLFW_RELEASE) return; if (key == GLFW_KEY_W) fpcamera_speed.z = action == GLFW_PRESS ? 1.0f : 0.0f; if (key == GLFW_KEY_S) fpcamera_speed.z = action == GLFW_PRESS ? -1.0f : 0.0f; if (key == GLFW_KEY_D) fpcamera_speed.x = action == GLFW_PRESS ? 1.0f : 0.0f; if (key == GLFW_KEY_A) fpcamera_speed.x = action == GLFW_PRESS ? -1.0f : 0.0f; if (key == GLFW_KEY_E) fpcamera_speed.y = action == GLFW_PRESS ? 1.0f : 0.0f; if (key == GLFW_KEY_Q) fpcamera_speed.y = action == GLFW_PRESS ? -1.0f : 0.0f; } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { size2D& window_size = DefaultRenderOptions().window_size; if (GUIManager::instance().key_callback(key, scancode, action, mods)) return; // If GUIManager uses the input then skip passing it to the rest of the systems if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); if (key == GLFW_KEY_F) { if (action == GLFW_PRESS) cursor_lock = !cursor_lock; if (cursor_lock) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN | GLFW_CURSOR_DISABLED); glfwSetCursorPos(window, window_size.width/2.0, window_size.height/2.0); } else { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } if (key == GLFW_KEY_M && action == GLFW_PRESS) { display_gui = !display_gui; } camera_key_callback(key, scancode, action, mods); } static void char_callback(GLFWwindow* window, unsigned int c) { if (GUIManager::instance().char_callback(c)) return; } static void cursor_callback(GLFWwindow* window, double xpos, double ypos) { size2D& window_size = DefaultRenderOptions().window_size; double half_width = window_size.width / 2.0; double half_height = window_size.height / 2.0; if (!cursor_lock) return; if (xpos == half_width && ypos == half_height) return; fpcamera_rotational_speed = glm::vec2(float(xpos - half_width), float(ypos - half_height)); glfwSetCursorPos(window, half_width, half_height); return; } int main() { //dl_main(); //return 0; //////////////// FreeImage_Initialise(); //////////////// if (!glfwInit()) { std::cerr << "Error initializing GLFW." << std::endl; return -1; } std::cout << "Initialized glfw." << std::endl; glfwSetErrorCallback(errorCallbackGLFW); //////////////// //////////////// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); glfwWindowHint(GLFW_DOUBLEBUFFER, true); glfwWindowHint(GLFW_DEPTH_BITS, 0); GLFWwindow* window = glfwCreateWindow(INIT_WIN_WIDTH, INIT_WIN_HEIGHT, "Compressed shadow maps demo", NULL, NULL); if (!window) { std::cerr << "Error creating window." << std::endl; glfwTerminate(); return -1; } std::cout << "Created window." << std::endl; size2D& output_size = DefaultRenderOptions().output_size; size2D& window_size = DefaultRenderOptions().window_size; output_size = size2D(INIT_WIN_WIDTH, INIT_WIN_HEIGHT); window_size = size2D(INIT_WIN_WIDTH, INIT_WIN_HEIGHT); //////////////// glfwSetWindowSizeCallback(window, resize_callback); glfwSetKeyCallback(window, key_callback); glfwSetCharCallback(window, char_callback); glfwSetCursorPosCallback(window, cursor_callback); glfwMakeContextCurrent(window); glfwSwapInterval(0); //////////////// GLenum glewInitResult = glewInit(); if (glewInitResult != GL_NO_ERROR) { std::cerr << "Error creating window." << std::endl; glfwTerminate(); return -1; } std::cout << "Initialized glew." << std::endl; //////////////// Default render options for (auto& o : DefaultRenderOptions().debug_var) o = 0.5f; //////////////// // During init, enable debug output #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(DebugCallbackGL, 0); #endif //////////////// MeshData mesh; LightData lights; fpcamera.aspect = output_size.width / float(output_size.height); fpcamera.jitter_plane = ivec2(output_size.width, output_size.height); fpcamera.mov_speed = 0.25f; fpcamera.rot_speed = 0.001f; Ini ini; std::string tecname; ini.load("data/inis/default.ini", IniInfo(&mesh, &fpcamera, &lights, &tecname)); //////////////// GLStateManager::instance().resetState(true); for (int i = 0; i < techniques.size(); ++i) { DefaultRenderOptions().add_technique(techniques[i]); } //////////////// GUIManager::instance().initialize(window); GUIManager::instance().addGUI("1_rendergui", std::shared_ptr<BaseGUI>(new RenderGUI(&DefaultRenderOptions(), &renderstats))); GUIManager::instance().addGUI("2_camfpgui", std::shared_ptr<BaseGUI>(new FPCameraGUI(&fpcamera))); GUIManager::instance().addGUI("3_meshgui", std::shared_ptr<BaseGUI>(new MeshGUI(&mesh))); //////////////// GLShapeManager::instance().initialize(); bool first_frame = true; Camera* camera = &fpcamera; //////////////// std::cout << "Starting main loop." << std::endl; check_opengl(); while (!glfwWindowShouldClose(window)) { PROFILE_SCOPE("Main loop") glfwMakeContextCurrent(window); lights.updateGLResources(); mesh.materialdata.updateGLResources(); DefaultRenderOptions().new_frame(); if (first_frame) { DefaultRenderOptions().request_technique(techniques[0]->name()); first_frame = false; } if (DefaultRenderOptions().get_flag(RenderOptions::FLAG_DIRTY_TECHNIQUE)) { Technique::SetupData ts; ts.output_size = DefaultRenderOptions().output_size; ts.mesh = &mesh; ts.lightdata = &lights; ts.camera = camera; DefaultRenderOptions().switch_to_requested_technique(); DefaultRenderOptions().initialize_technique(ts); GUIManager::instance().setTechnique(DefaultRenderOptions().current_technique()); DefaultRenderOptions().reset_flag(RenderOptions::FLAG_DIRTY_TECHNIQUE); } //// Update vsync options glfwSwapInterval(DefaultRenderOptions().vsync ? 1 : 0); //// Swap current and previous depth tex //std::swap(depthtex, prev_depthtex); //fbo.AttachDepthTexture(depthtex); { PROFILE_SCOPE("Render") DefaultRenderOptions().current_technique()->output_resize_callback(output_size); DefaultRenderOptions().current_technique()->frame_prologue(); DefaultRenderOptions().current_technique()->frame_render(); DefaultRenderOptions().current_technique()->frame_epilogue(); } //// Draw GUI fpcamera.copied = false; if (display_gui) GUIManager::instance().draw(); //// Swap buffers glfwSwapBuffers(window); //// Update timings TimingManager::instance().endFrame(); TimingStats s = TimingManager::instance().getTimingStats("Render"); renderstats.time_cpu_ms = s.cpu_time; renderstats.time_gl_ms = s.gl_time; renderstats.time_cuda_ms = s.cuda_time; //// Get input glfwPollEvents(); //// Update camera s = TimingManager::instance().getTimingStats("Main loop"); float time = std::max(s.gl_time, std::max(s.cpu_time, s.cuda_time)); if (fpcamera_rotational_speed != vec2(0.f, 0.f) || fpcamera_speed != vec3(0.f, 0.f, 0.f)) { fpcamera.update(fpcamera_rotational_speed, fpcamera_speed * time * 0.001f); fpcamera_rotational_speed = vec2(0.f, 0.f); fpcamera.moved = true; } else { fpcamera.update(fpcamera_rotational_speed, fpcamera_speed); fpcamera.moved = false; } } for (auto t : techniques) t->destroy(); // Clear textures before leaving context TextureManager::instance().clear(); GUIManager::instance().finalize(window); glfwDestroyWindow(window); glfwTerminate(); return 0; }
28.744548
158
0.715834
lscandolo
0084908178ca0bc782ff19fd8e2cb48f57b035e7
12,523
cpp
C++
script/src/llasm_var.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
script/src/llasm_var.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
script/src/llasm_var.cpp
tweber-ill/ill_mirror-takin2-tlibs2
669fd34c306625fd306da278a5b29fb6aae16a87
[ "BSD-3-Clause-Open-MPI" ]
1
2021-09-20T19:30:13.000Z
2021-09-20T19:30:13.000Z
/** * llvm three-address code generator -- variables * @author Tobias Weber <tweber@ill.fr> * @date apr/may-2020 * @license GPLv3, see 'LICENSE' file * @desc Forked on 18/July/2020 from my privately developed "matrix_calc" project (https://github.com/t-weber/matrix_calc). * * References: * - https://llvm.org/docs/LangRef.html * - https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.html * - https://llvm.org/docs/GettingStarted.html * * ---------------------------------------------------------------------------- * tlibs * Copyright (C) 2017-2021 Tobias WEBER (Institut Laue-Langevin (ILL), * Grenoble, France). * Copyright (C) 2015-2017 Tobias WEBER (Technische Universitaet Muenchen * (TUM), Garching, Germany). * matrix_calc * Copyright (C) 2020 Tobias WEBER (privately developed). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ---------------------------------------------------------------------------- */ #include "llasm.h" #include <sstream> t_astret LLAsm::visit(const ASTVar* ast) { t_astret sym = get_sym(ast->GetIdent()); if(sym == nullptr) throw std::runtime_error("ASTVar: Symbol \"" + ast->GetIdent() + "\" not in symbol table."); std::string var = std::string{"%"} + sym->name; if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT) { t_astret retvar = get_tmp_var(sym->ty, &sym->dims); std::string ty = LLAsm::get_type_name(sym->ty); (*m_ostr) << "%" << retvar->name << " = load " << ty << ", " << ty << "* " << var << "\n"; return retvar; } else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX) { return sym; } else if(sym->ty == SymbolType::STRING) { return sym; } else { throw std::runtime_error("ASTVar: Invalid type for visited variable: \"" + sym->name + "\"."); } return nullptr; } t_astret LLAsm::visit(const ASTVarDecl* ast) { for(const auto& _var : ast->GetVariables()) { t_astret sym = get_sym(_var); std::string ty = LLAsm::get_type_name(sym->ty); if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT) { (*m_ostr) << "%" << sym->name << " = alloca " << ty << "\n"; } else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX) { std::size_t dim = get_arraydim(sym); // allocate the array's memory (*m_ostr) << "%" << sym->name << " = alloca [" << dim << " x double]\n"; } else if(sym->ty == SymbolType::STRING) { std::size_t dim = std::get<0>(sym->dims); // allocate the string's memory (*m_ostr) << "%" << sym->name << " = alloca [" << dim << " x i8]\n"; // get a pointer to the string t_astret strptr = get_tmp_var(sym->ty); (*m_ostr) << "%" << strptr->name << " = getelementptr [" << dim << " x i8], [" << dim << " x i8]* %" << sym->name << ", i64 0, i64 0\n"; // set first element to zero (*m_ostr) << "store i8 0, i8* %" << strptr->name << "\n"; } else { throw std::runtime_error("ASTVarDecl: Invalid type in declaration: \"" + sym->name + "\"."); } // optional assignment if(ast->GetAssignment()) ast->GetAssignment()->accept(this); } return nullptr; } t_astret LLAsm::visit(const ASTAssign* ast) { t_astret expr = ast->GetExpr()->accept(this); // multiple assignments if(ast->IsMultiAssign()) { if(expr->ty != SymbolType::COMP) { throw std::runtime_error("ASTAssign: Need a compound symbol for multi-assignment."); } const auto& vars = ast->GetIdents(); if(expr->elems.size() != vars.size()) { std::ostringstream ostrerr; ostrerr << "ASTAssign: Mismatch in multi-assign size, " << "expected " << vars.size() << " symbols, received " << expr->elems.size() << " symbols."; throw std::runtime_error(ostrerr.str()); } std::size_t elemidx = 0; for(std::size_t idx=0; idx<vars.size(); ++idx) { const SymbolPtr retsym = expr->elems[idx]; const std::string& var = vars[idx]; t_astret sym = get_sym(var); // get current memory block pointer t_astret varmemptr = get_tmp_var(SymbolType::STRING); (*m_ostr) << "%" << varmemptr->name << " = getelementptr i8, i8* %" << expr->name << ", i64 " << elemidx << "\n"; // directly read scalar value from memory block if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT) { std::string symty = LLAsm::get_type_name(sym->ty); std::string retty = LLAsm::get_type_name(retsym->ty); t_astret varptr = get_tmp_var(sym->ty); (*m_ostr) << "%" << varptr->name << " = bitcast i8* %" << varmemptr->name << " to " << retty << "*\n"; t_astret _varval = get_tmp_var(sym->ty); (*m_ostr) << "%" << _varval->name << " = load " << retty << ", " << retty << "* %" << varptr->name << "\n"; if(!check_sym_compat( sym->ty, std::get<0>(sym->dims), std::get<1>(sym->dims), retsym->ty, std::get<0>(retsym->dims), std::get<1>(retsym->dims))) { std::ostringstream ostrErr; ostrErr << "ASTAssign: Multi-assignment type or dimension mismatch: "; ostrErr << Symbol::get_type_name(sym->ty) << "[" << std::get<0>(sym->dims) << ", " << std::get<1>(sym->dims) << "] != " << Symbol::get_type_name(retsym->ty) << "[" << std::get<0>(retsym->dims) << ", " << std::get<1>(retsym->dims) << "]."; throw std::runtime_error(ostrErr.str()); } // cast if needed _varval = convert_sym(_varval, sym->ty); (*m_ostr) << "store " << symty << " %" << _varval->name << ", "<< symty << "* %" << var << "\n"; } // read double array from memory block else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX) { cp_mem_vec(varmemptr, sym, false); } // read char array from memory block else if(sym->ty == SymbolType::STRING) { cp_mem_str(varmemptr, sym, false); } // nested compound symbols else if(sym->ty == SymbolType::COMP) { cp_mem_comp(varmemptr, sym); } elemidx += get_bytesize(sym); } // free heap return value (TODO: check if it really is on the heap) (*m_ostr) << "call void @ext_heap_free(i8* %" << expr->name << ")\n"; } // single assignment else { std::string var = ast->GetIdent(); t_astret sym = get_sym(var); if(!check_sym_compat( sym->ty, std::get<0>(sym->dims), std::get<1>(sym->dims), expr->ty, std::get<0>(expr->dims), std::get<1>(expr->dims))) { std::ostringstream ostrErr; ostrErr << "ASTAssign: Assignment type or dimension mismatch: "; ostrErr << Symbol::get_type_name(sym->ty) << "[" << std::get<0>(sym->dims) << ", " << std::get<1>(sym->dims) << "] != " << Symbol::get_type_name(expr->ty) << "[" << std::get<0>(expr->dims) << ", " << std::get<1>(expr->dims) << "]."; throw std::runtime_error(ostrErr.str()); } // cast if needed expr = convert_sym(expr, sym->ty); if(expr->ty == SymbolType::SCALAR || expr->ty == SymbolType::INT) { std::string ty = LLAsm::get_type_name(expr->ty); (*m_ostr) << "store " << ty << " %" << expr->name << ", "<< ty << "* %" << var << "\n"; } else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX) { std::size_t dimDst = get_arraydim(sym); std::size_t dimSrc = get_arraydim(expr); // copy elements in a loop generate_loop(0, dimDst, [this, expr, sym, dimDst, dimSrc](t_astret ctrval) { // loop statements t_astret elemptr_src = get_tmp_var(SymbolType::SCALAR); (*m_ostr) << "%" << elemptr_src->name << " = getelementptr [" << dimSrc << " x double], [" << dimSrc << " x double]* %" << expr->name << ", i64 0, i64 %" << ctrval->name << "\n"; t_astret elemptr_dst = get_tmp_var(SymbolType::SCALAR); (*m_ostr) << "%" << elemptr_dst->name << " = getelementptr [" << dimDst << " x double], [" << dimDst << " x double]* %" << sym->name << ", i64 0, i64 %" << ctrval->name << "\n"; t_astret elem_src = get_tmp_var(SymbolType::SCALAR); (*m_ostr) << "%" << elem_src->name << " = load double, double* %" << elemptr_src->name << "\n"; (*m_ostr) << "store double %" << elem_src->name << ", double* %" << elemptr_dst->name << "\n"; }); } else if(sym->ty == SymbolType::STRING) { std::size_t src_dim = std::get<0>(expr->dims); std::size_t dst_dim = std::get<0>(sym->dims); //if(src_dim > dst_dim) // TODO // throw std::runtime_error("ASTAssign: Buffer of string \"" + sym->name + "\" is not large enough."); std::size_t dim = std::min(src_dim, dst_dim); // copy elements in a loop generate_loop(0, dim, [this, expr, sym, src_dim, dst_dim](t_astret ctrval) { // loop statements t_astret elemptr_src = get_tmp_var(); (*m_ostr) << "%" << elemptr_src->name << " = getelementptr [" << src_dim << " x i8], [" << src_dim << " x i8]* %" << expr->name << ", i64 0, i64 %" << ctrval->name << "\n"; t_astret elemptr_dst = get_tmp_var(); (*m_ostr) << "%" << elemptr_dst->name << " = getelementptr [" << dst_dim << " x i8], [" << dst_dim << " x i8]* %" << sym->name << ", i64 0, i64 %" << ctrval->name << "\n"; t_astret elem_src = get_tmp_var(); (*m_ostr) << "%" << elem_src->name << " = load i8, i8* %" << elemptr_src->name << "\n"; (*m_ostr) << "store i8 %" << elem_src->name << ", i8* %" << elemptr_dst->name << "\n"; }); } return expr; } return nullptr; } t_astret LLAsm::visit(const ASTNumConst<double>* ast) { double val = ast->GetVal(); t_astret retvar = get_tmp_var(SymbolType::SCALAR); t_astret retval = get_tmp_var(SymbolType::SCALAR); (*m_ostr) << "%" << retvar->name << " = alloca double\n"; (*m_ostr) << "store double " << std::scientific << val << ", double* %" << retvar->name << "\n"; (*m_ostr) << "%" << retval->name << " = load double, double* %" << retvar->name << "\n"; return retval; } t_astret LLAsm::visit(const ASTNumConst<std::int64_t>* ast) { std::int64_t val = ast->GetVal(); t_astret retvar = get_tmp_var(SymbolType::INT); t_astret retval = get_tmp_var(SymbolType::INT); (*m_ostr) << "%" << retvar->name << " = alloca i64\n"; (*m_ostr) << "store i64 " << val << ", i64* %" << retvar->name << "\n"; (*m_ostr) << "%" << retval->name << " = load i64, i64* %" << retvar->name << "\n"; return retval; } t_astret LLAsm::visit(const ASTStrConst* ast) { const std::string& str = ast->GetVal(); std::size_t dim = str.length()+1; std::array<std::size_t, 2> dims{{dim, 1}}; t_astret str_mem = get_tmp_var(SymbolType::STRING, &dims); // allocate the string's memory (*m_ostr) << "%" << str_mem->name << " = alloca [" << dim << " x i8]\n"; // set the individual chars for(std::size_t idx=0; idx<dim; ++idx) { t_astret ptr = get_tmp_var(); (*m_ostr) << "%" << ptr->name << " = getelementptr [" << dim << " x i8], [" << dim << " x i8]* %" << str_mem->name << ", i64 0, i64 " << idx << "\n"; int val = (idx<dim-1) ? str[idx] : 0; (*m_ostr) << "store i8 " << val << ", i8* %" << ptr->name << "\n"; } return str_mem; } t_astret LLAsm::visit(const ASTExprList* ast) { // only double arrays are handled here if(!ast->IsScalarArray()) { throw std::runtime_error("ASTExprList: General expression list should not be directly evaluated."); } // array values and size const auto& lst = ast->GetList(); std::size_t len = lst.size(); std::array<std::size_t, 2> dims{{len, 1}}; // allocate double array t_astret vec_mem = get_tmp_var(SymbolType::VECTOR, &dims); (*m_ostr) << "%" << vec_mem->name << " = alloca [" << len << " x double]\n"; // set the individual array elements auto iter = lst.begin(); for(std::size_t idx=0; idx<len; ++idx) { t_astret ptr = get_tmp_var(); (*m_ostr) << "%" << ptr->name << " = getelementptr [" << len << " x double], [" << len << " x double]* %" << vec_mem->name << ", i64 0, i64 " << idx << "\n"; t_astret val = (*iter)->accept(this); val = convert_sym(val, SymbolType::SCALAR); (*m_ostr) << "store double %" << val->name << ", double* %" << ptr->name << "\n"; ++iter; } return vec_mem; }
32.275773
123
0.577737
tweber-ill
0a5263a045fa4ad3ccc150da1fc9ab4aaca1471d
268
cpp
C++
production/subsystems/gui/src/status_bar.cpp
ratelware/logreader
6ca96c49a342dcaef59221dd3497563f54b63ae7
[ "MIT" ]
null
null
null
production/subsystems/gui/src/status_bar.cpp
ratelware/logreader
6ca96c49a342dcaef59221dd3497563f54b63ae7
[ "MIT" ]
3
2017-11-21T22:16:51.000Z
2017-11-21T23:34:31.000Z
production/subsystems/gui/src/status_bar.cpp
ratelware/logreader
6ca96c49a342dcaef59221dd3497563f54b63ae7
[ "MIT" ]
null
null
null
#include <gui/status_bar.hpp> #include <nana/gui/filebox.hpp> namespace gui { status_bar::status_bar(nana::form& window_form) : bar_panel(window_form) { bar_panel.bgcolor(nana::colors::red); } nana::widget& status_bar::get_widget() { return bar_panel; } }
17.866667
75
0.716418
ratelware
0a58656e35d6a41487b1e652fc8f4bd7cb8c1d9e
6,721
cpp
C++
plll/src/lattices/enumimpl-simpleenum.cpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/src/lattices/enumimpl-simpleenum.cpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
plll/src/lattices/enumimpl-simpleenum.cpp
KudrinMatvey/myfplll
99fa018201097b6c078c00721cdc409cdcd4092c
[ "MIT" ]
null
null
null
/* Copyright (c) 2011-2014 University of Zurich 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 PLLL_INCLUDE_GUARD__ENUMIMPL_SIMPLEENUM_CPP #define PLLL_INCLUDE_GUARD__ENUMIMPL_SIMPLEENUM_CPP namespace plll { template<class RealTypeContext, class IntTypeContext> class SimpleEnumerator { public: typedef boost::function<void(const linalg::math_matrix<typename IntTypeContext::Integer> & basis, int p, const linalg::math_rowvector<typename IntTypeContext::Integer> & vec)> CallbackFunction; private: Updater<RealTypeContext, IntTypeContext> d_update; Verbose & d_verbose; public: SimpleEnumerator(Verbose & v) : d_update(), d_verbose(v) { } SimpleEnumerator(Verbose & v, GaussianFactorComputer &, unsigned enumdimension) : d_update(), d_verbose(v) { } bool enumerate(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end, linalg::math_rowvector<typename IntTypeContext::Integer> & result, typename RealTypeContext::Real & bound) // Finds a shortest vector in the lattice generated by the orthogonal projections of the vectors // A.row(begin) to A.row(end) into the orthogonal complement of the vectors A.row(0) to // A.row(begin-1). Uses the Kannan-Schnorr-Euchner enumeration method. { // Initialize updater RealTypeContext & rc = lattice.rc(); IntTypeContext & ic = lattice.ic(); d_update.initialize(d_verbose, lattice, begin, end, bound); const unsigned dim = end - begin + 1; // Prepare enumeration linalg::math_rowvector<typename IntTypeContext::Integer> x(dim); linalg::math_rowvector<typename RealTypeContext::Real> x_real(dim); for (unsigned i = 0; i < dim; ++i) { x_real[i].setContext(rc); setZero(x_real[i]); } linalg::base_rowvector<long> delta(dim); linalg::base_rowvector<int> delta2(dim); linalg::base_rowvector<int> r(dim + 1); linalg::math_matrix<typename RealTypeContext::Real> sigma(dim, dim); for (unsigned i = 0; i < dim; ++i) { r[i] = dim - 1; for (unsigned j = 0; j < dim; ++j) { sigma(i, j).setContext(rc); setZero(sigma(i, j)); } } setOne(x[0]); setOne(x_real[0]); delta[0] = 1; delta2[0] = 1; for (unsigned i = 1; i < dim; ++i) delta2[i] = -1; linalg::math_rowvector<typename RealTypeContext::Real> c(dim), ell(dim + 1); for (unsigned i = 0; i < dim; ++i) { c[i].setContext(rc); setZero(c[i]); } for (unsigned i = 0; i <= dim; ++i) { ell[i].setContext(rc); setZero(ell[i]); } // Do enumeration unsigned stage = 0, last_nonzero_stage = 0; bool noSolutionYet = true; typename RealTypeContext::Real tmp(rc); while (true) { tmp = x_real[stage] - c[stage]; square(ell[stage], tmp); ell[stage] *= lattice.getNormSq(begin + stage); ell[stage] += ell[stage + 1]; if (ell[stage] <= bound) { if (stage == 0) { d_update(lattice, begin, end, result, bound, x, ell[0], noSolutionYet); } else { --stage; if (stage > 0) { if (r[stage - 1] < r[stage]) r[stage - 1] = r[stage]; } for (unsigned j = r[stage]; j > stage; --j) // this is the summation order considered in Pujol-Stehle { tmp = x_real[j] * lattice.getCoeff(begin + j, begin + stage); sigma(stage, j - 1) = sigma(stage, j) + tmp; } c[stage] = -sigma(stage, stage); bool ru; arithmetic::convert_round(x[stage], c[stage], ru, ic); arithmetic::convert(x_real[stage], x[stage], rc); delta[stage] = 0; delta2[stage] = ru ? 1 : -1; continue; } } if (++stage >= dim) break; r[stage - 1] = stage; if (stage >= last_nonzero_stage) { last_nonzero_stage = stage; ++x[stage]; } else { delta2[stage] = -delta2[stage]; delta[stage] = -delta[stage] + delta2[stage]; x[stage] += arithmetic::convert(delta[stage], ic); } arithmetic::convert(x_real[stage], x[stage], rc); } return !noSolutionYet; } static void setCallback(CallbackFunction) { } }; } #endif
39.769231
125
0.502009
KudrinMatvey
0a60ff787f117849dd7641ad0070d95f852d964e
1,383
cpp
C++
json_source/test/test_json_source.cpp
waltronix/smaep
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
[ "MIT" ]
1
2019-12-21T15:09:40.000Z
2019-12-21T15:09:40.000Z
json_source/test/test_json_source.cpp
waltronix/smaep
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
[ "MIT" ]
null
null
null
json_source/test/test_json_source.cpp
waltronix/smaep
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
[ "MIT" ]
null
null
null
#include <string> #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include "json_source.h" TEST_CASE("some_simple_jsonpath", "json_tests") { const std::string json = R"JSON( { "x": "1", "y": "2" } )JSON"; smaep::data::json_source<double> jw(json); auto rs = jw.get_value_for("$.x"); REQUIRE(1 == rs); } TEST_CASE("nested jsonpath", "json_tests") { const std::string json = R"JSON( { "A": { "x": "1", "y": "2" }, "B": { "x": "3", "y": "4" } } )JSON"; smaep::data::json_source<double> jw(json); REQUIRE(1 == jw.get_value_for("$.A.x")); REQUIRE(3 == jw.get_value_for("$.B.x")); } TEST_CASE("select temp", "json_tests") { const std::string json = R"JSON( { "A": { "temp": "25.71", "pressure": "1013", "humidity": "53" } } )JSON"; smaep::data::json_source<double> jw(json); auto temp = jw.get_value_for("$..temp"); REQUIRE(25.71 == temp); } TEST_CASE("no_result", "json_tests") { const std::string json = R"JSON( { "y": "2" } )JSON"; smaep::data::json_source<double> jw(json); REQUIRE_THROWS(jw.get_value_for("$.x")); } TEST_CASE("more_then_one_result", "json_tests") { const std::string json = R"JSON( { "A": { "x": "1" }, "B": { "x": "2" } } )JSON"; smaep::data::json_source<double> jw(json); REQUIRE_THROWS(jw.get_value_for("$.x")); }
15.896552
49
0.561099
waltronix
0a62df76d2d85e117857b03ea8f23567aa542c64
1,357
hpp
C++
examples/modem_console/main/my_module_dce.hpp
jonathandreyer/esp-modem
6311c3bd775dcdb22878dab83e703b46ee5321c1
[ "Apache-2.0" ]
2
2021-08-23T09:07:11.000Z
2021-11-06T12:12:41.000Z
examples/modem_console/main/my_module_dce.hpp
jonathandreyer/esp-modem
6311c3bd775dcdb22878dab83e703b46ee5321c1
[ "Apache-2.0" ]
null
null
null
examples/modem_console/main/my_module_dce.hpp
jonathandreyer/esp-modem
6311c3bd775dcdb22878dab83e703b46ee5321c1
[ "Apache-2.0" ]
null
null
null
/* Modem console example: Custom DCE This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #pragma once #include "cxx_include/esp_modem_dce_factory.hpp" #include "cxx_include/esp_modem_dce_module.hpp" /** * @brief Definition of a custom modem which inherits from the GenericModule, uses all its methods * and could override any of them. Here, for demonstration purposes only, we redefine just `get_module_name()` */ class MyShinyModem: public esp_modem::GenericModule { using GenericModule::GenericModule; public: esp_modem::command_result get_module_name(std::string &name) override { name = "Custom Shiny Module"; return esp_modem::command_result::OK; } }; /** * @brief Helper create method which employs the DCE factory for creating DCE objects templated by a custom module * @return unique pointer of the resultant DCE */ std::unique_ptr<esp_modem::DCE> create_shiny_dce(const esp_modem::dce_config *config, std::shared_ptr<esp_modem::DTE> dte, esp_netif_t *netif) { return esp_modem::dce_factory::Factory::build_unique<MyShinyModem>(config, std::move(dte), netif); }
33.925
114
0.741341
jonathandreyer
0a64c7e5115802a1f0bdc4b0b2ffb390c42348b2
931
hpp
C++
src/Components/PlayerInputComponent.hpp
DylanConvery/2D-Game-Engine-Prototype
55e5adbb687ccec593a3f5063ad2195e760bd3b6
[ "MIT" ]
null
null
null
src/Components/PlayerInputComponent.hpp
DylanConvery/2D-Game-Engine-Prototype
55e5adbb687ccec593a3f5063ad2195e760bd3b6
[ "MIT" ]
null
null
null
src/Components/PlayerInputComponent.hpp
DylanConvery/2D-Game-Engine-Prototype
55e5adbb687ccec593a3f5063ad2195e760bd3b6
[ "MIT" ]
null
null
null
#ifndef PLAYERINPUTCOMPONENT_H #define PLAYERINPUTCOMPONENT_H #include "../AssetManager.hpp" #include "../Component.hpp" #include "SpriteComponent.hpp" #include "TransformComponent.hpp" #include "string" class SpriteComponent; class PlayerInputComponent : public Component { public: PlayerInputComponent(); PlayerInputComponent(float speed, std::string up_key, std::string down_key, std::string left_key, std::string right_key, std::string action_key); std::string getSDLStringCode(std::string key) const; void initialize() override; void update(float delta_time) override; void render() override; std::string _up_key; std::string _down_key; std::string _left_key; std::string _right_key; std::string _action_key; TransformComponent* _transform; SpriteComponent* _sprite; float _speed; private: void boundingBoxCheck(); }; #endif // !PLAYERINPUTCOMPONENT_H
25.861111
149
0.736842
DylanConvery
0a6585ed4329612ee36bb987a8b87683f2c938bf
21,630
cpp
C++
src/mfx/uitk/pg/FxPEq.cpp
D-J-Roberts/pedalevite
157611b5ccf2bb97f0007d7d17b4c07bd6a21fba
[ "WTFPL" ]
69
2017-01-17T13:17:31.000Z
2022-03-01T14:56:32.000Z
src/mfx/uitk/pg/FxPEq.cpp
D-J-Roberts/pedalevite
157611b5ccf2bb97f0007d7d17b4c07bd6a21fba
[ "WTFPL" ]
1
2020-11-03T14:52:45.000Z
2020-12-01T20:31:15.000Z
src/mfx/uitk/pg/FxPEq.cpp
D-J-Roberts/pedalevite
157611b5ccf2bb97f0007d7d17b4c07bd6a21fba
[ "WTFPL" ]
8
2017-02-08T13:30:42.000Z
2021-12-09T08:43:09.000Z
/***************************************************************************** FxPEq.cpp Author: Laurent de Soras, 2017 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/def.h" #include "fstb/ToolsSimd.h" #include "mfx/piapi/ParamDescInterface.h" #include "mfx/piapi/PluginDescInterface.h" #include "mfx/pi/dwm/Param.h" #include "mfx/pi/peq/Param.h" #include "mfx/uitk/grap/PrimLine.h" #include "mfx/uitk/grap/RenderCtx.h" #include "mfx/uitk/pg/FxPEq.h" #include "mfx/uitk/pg/Tools.h" #include "mfx/uitk/NodeEvt.h" #include "mfx/uitk/PageMgrInterface.h" #include "mfx/uitk/PageSwitcher.h" #include "mfx/ui/Font.h" #include "mfx/Cst.h" #include "mfx/LocEdit.h" #include "mfx/Model.h" #include "mfx/View.h" #include <algorithm> #include <cassert> #include <cstring> #include <cmath> namespace mfx { namespace uitk { namespace pg { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ FxPEq::FxPEq (PageSwitcher &page_switcher, LocEdit &loc_edit) : _page_switcher (page_switcher) , _loc_edit (loc_edit) , _model_ptr (nullptr) , _view_ptr (nullptr) , _page_ptr (nullptr) , _page_size () , _fnt_t_ptr (nullptr) , _fnt_s_ptr (nullptr) , _cur_param_sptr (std::make_shared <NText > (Entry_PARAM )) , _prec_sptr ( std::make_shared <NText > (Entry_PREC )) , _content_sptr ( std::make_shared <NBitmap> (Entry_CONTENT)) , _legend_sptr_arr () , _cur_param (Param_RANGE) , _nbr_param (Param_BAND_BASE) , _nbr_bands (0) , _cur_band (-1) , _range_db_idx (1) // Default: +/-12 dB , _prec_idx (0) , _settings () { // Nothing } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void FxPEq::do_connect (Model &model, const View &view, PageMgrInterface &page, Vec2d page_size, void *usr_ptr, const FontSet &fnt) { fstb::unused (usr_ptr); _model_ptr = &model; _view_ptr = &view; _page_ptr = &page; _page_size = page_size; _fnt_t_ptr = &fnt._t; _fnt_s_ptr = &fnt._s; const int scr_w = _page_size [0]; _content_sptr->set_coord (Vec2d (0, 0)); _cur_param_sptr->set_coord (Vec2d (0 , _page_size [1] - 1)); _cur_param_sptr->set_justification (0, 1, false); _cur_param_sptr->set_font (*_fnt_s_ptr); _prec_sptr ->set_coord (Vec2d (3 * scr_w / 4, _page_size [1] - 1)); _prec_sptr ->set_justification (1, 1, false); _prec_sptr ->set_font (*_fnt_s_ptr); _prec_sptr ->set_blend_mode (ui::DisplayInterface::BlendMode_MAX); update_band_info (); update_display (); } void FxPEq::do_disconnect () { // Nothing } MsgHandlerInterface::EvtProp FxPEq::do_handle_evt (const NodeEvt &evt) { EvtProp ret_val = EvtProp_PASS; if (evt.is_button_ex ()) { const Button but = evt.get_button_ex (); switch (but) { case Button_S: _prec_idx = (_prec_idx + 1) % _nbr_steps; update_param_txt (); break; case Button_E: _page_switcher.switch_to (pg::PageType_PARAM_LIST, nullptr); ret_val = EvtProp_CATCH; break; case Button_U: move_param (-1); break; case Button_D: move_param (+1); break; case Button_L: change_param (-1); ret_val = EvtProp_CATCH; break; case Button_R: change_param (+1); ret_val = EvtProp_CATCH; break; default: // Nothing break; } } return ret_val; } void FxPEq::do_activate_preset (int index) { fstb::unused (index); _page_switcher.switch_to (PageType_PROG_EDIT, nullptr); } void FxPEq::do_set_param (int slot_id, int index, float val, PiType type) { fstb::unused (index, val, type); if (slot_id == _loc_edit._slot_id) { update_band_info (); update_display (); } } void FxPEq::do_remove_plugin (int slot_id) { if (slot_id == _loc_edit._slot_id) { _page_switcher.switch_to (PageType_PROG_EDIT, nullptr); } } /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ // Requires update_band_info() before void FxPEq::update_display () { _page_ptr->clear_all_nodes (); _page_ptr->push_back (_content_sptr); _page_ptr->push_back (_cur_param_sptr); _page_ptr->push_back (_prec_sptr); const int scr_w = _page_size [0]; const float f_beg = 20; // Hz const float f_end = 20000; // Hz const int nbr_freq = scr_w; const int height = _page_size [1]; _content_sptr->set_size (_page_size); const int stride = _content_sptr->get_stride (); uint8_t * disp_ptr = _content_sptr->use_buffer (); memset (disp_ptr, 0, _page_size [0] * _page_size [1]); // Graduations display_graduations (f_beg, f_end, nbr_freq); // Curve const int slot_id = _loc_edit._slot_id; const doc::Preset & preset = _view_ptr->use_preset_cur (); const doc::Slot & slot = preset.use_slot (slot_id); if (_nbr_bands > 0) { const piapi::PluginDescInterface & desc = _model_ptr->get_model_desc (slot._pi_model); const piapi::PluginDescInterface & desc_mix = _model_ptr->get_model_desc (Cst::_plugin_dwm); const float gain = get_param ( slot._settings_mixer, desc_mix, pi::dwm::Param_GAIN ); // Populates band parameters auto band_arr = create_bands (_settings, desc); // Retrieve the z-equations as biquads auto biq_arr = retrieve_z_eq (band_arr); // Creates a frequency map auto puls_arr = create_freq_map (nbr_freq, f_beg, f_end); #if PV_VERSION == 2 // First, draws only the current band contribution if (_cur_band >= 0) { std::vector <float> lvl_arr (nbr_freq, 1); compute_freq_resp (lvl_arr, puls_arr, biq_arr [_cur_band]); std::vector <int32_t> y_arr = compute_y_pos (lvl_arr, height); Tools::draw_curve (y_arr, disp_ptr, height, stride, 96); } #endif // Now the main curve. Starts with the main gain std::vector <float> lvl_arr (nbr_freq, gain); // Computes the response (linear gain) for each frequency for (const auto &biq : biq_arr) { compute_freq_resp (lvl_arr, puls_arr, biq); } // Transforms levels into pixel positions std::vector <int32_t> y_arr = compute_y_pos (lvl_arr, height); // Draws the curve Tools::draw_curve (y_arr, disp_ptr, height, stride, 255); } update_param_txt (); _content_sptr->invalidate_all (); } void FxPEq::display_graduations (float f_beg, float f_end, int nbr_freq) { const int h_t = _fnt_t_ptr->get_char_h (); const int stride = _content_sptr->get_stride (); uint8_t * disp_ptr = _content_sptr->use_buffer (); const int height = _content_sptr->get_bounding_box ().get_size () [1]; _legend_sptr_arr.clear (); int node_id = Entry_LEGEND_BASE; #if PV_VERSION == 2 grap::RenderCtx ctx { disp_ptr, _content_sptr->get_bounding_box ().get_size (), stride }; #endif // Hz static const std::array <const char *, 5> freq_0_list = {{ "1", "10", "100", "1k", "10k" }}; for (int p = 1; p < int (freq_0_list.size ()); ++ p) { const float f = float (pow (10, p)); for (int m = 1; m < 10; ++ m) { const int x = conv_freq_to_x (f * float (m), f_beg, f_end, nbr_freq); if (x >= 0 && x < nbr_freq) { #if PV_VERSION == 2 const uint8_t col = (m == 1) ? 64 : 40; grap::PrimLine::draw_v (ctx, x, 0, height, col, false); #else disp_ptr [ 0 * stride + x] = 255; disp_ptr [(height - 1) * stride + x] = 255; if (m == 1 || m == 5) { disp_ptr [ 1 * stride + x] = 255; disp_ptr [(height - 2) * stride + x] = 255; } #endif } } const int x = conv_freq_to_x (f, f_beg, f_end, nbr_freq); if (x >= 0 && x < nbr_freq) { #if PV_VERSION != 2 for (int y = 0; y < height; y += 4) { disp_ptr [y * stride + x] = 255; } #endif TxtSPtr txt_sptr { std::make_shared <NText> (node_id) }; txt_sptr->set_justification (0.5f, 0, false); txt_sptr->set_font (*_fnt_t_ptr); txt_sptr->set_coord (Vec2d (x, 3)); txt_sptr->set_blend_mode (ui::DisplayInterface::BlendMode_MAX); txt_sptr->set_text (freq_0_list [p]); _legend_sptr_arr.push_back (txt_sptr); _page_ptr->push_back (txt_sptr); ++ node_id; } } // dB #if PV_VERSION != 2 const int height_h = height / 2; for (int x = 0; x < nbr_freq; x += 3) { disp_ptr [height_h * stride + x] = 255; } #endif char txt_0 [127+1]; #if PV_VERSION == 2 static const std::array <float, 7> db_arr = {{ -1, -2/3.f, -1/3.f, 0, 1/3.f, 2/3.f, 1 }}; #else static const std::array <float, 4> db_arr = {{ -1, -0.5f, 0.5f, 1 }}; #endif for (int r_idx = 0; r_idx < int (db_arr.size ()); ++r_idx) { const float db = float (_range_db_arr [_range_db_idx]) * db_arr [r_idx]; const int y = fstb::limit (conv_db_to_y (db, height), 0, height - 1); #if PV_VERSION == 2 const uint8_t col = fstb::is_null (db) ? 64 : 40; grap::PrimLine::draw_h (ctx, 0, y, nbr_freq, col, false); #else disp_ptr [y * stride + 0] = 255; disp_ptr [y * stride + 1] = 255; disp_ptr [y * stride + nbr_freq - 2] = 255; disp_ptr [y * stride + nbr_freq - 1] = 255; #endif fstb::snprintf4all ( txt_0, sizeof (txt_0), "%+.0f", db ); TxtSPtr txt_sptr { std::make_shared <NText> (node_id) }; txt_sptr->set_justification (1, (y > h_t) ? 1.f : 0.f, false); txt_sptr->set_font (*_fnt_t_ptr); txt_sptr->set_coord (Vec2d (nbr_freq, y)); txt_sptr->set_blend_mode (ui::DisplayInterface::BlendMode_MAX); txt_sptr->set_text (txt_0); _legend_sptr_arr.push_back (txt_sptr); _page_ptr->push_back (txt_sptr); ++ node_id; } } // Requires update_band_info() before void FxPEq::update_param_txt () { _cur_param = fstb::limit (_cur_param, 0, _nbr_param - 1); char txt_0 [127+1]; const int slot_id = _loc_edit._slot_id; const doc::Preset & preset = _view_ptr->use_preset_cur (); const doc::Slot & slot = preset.use_slot (slot_id); // Range if (_cur_param == Param_RANGE) { fstb::snprintf4all ( txt_0, sizeof (txt_0), "R %.0f", _range_db_arr [_range_db_idx] ); _cur_param_sptr->set_text (txt_0); } // Gain else if (_cur_param == Param_GAIN) { const piapi::PluginDescInterface & desc_mix = _model_ptr->get_model_desc (Cst::_plugin_dwm); const float gain = get_param ( slot._settings_mixer, desc_mix, pi::dwm::Param_GAIN ); const float gain_db = float (20 * log10 (gain)); fstb::snprintf4all ( txt_0, sizeof (txt_0), "V %+.1f", gain_db ); _cur_param_sptr->set_text (txt_0); } // Band parameters else { const piapi::PluginDescInterface & desc = _model_ptr->get_model_desc (slot._pi_model); const int param_idx = (_cur_param - Param_BAND_BASE) % pi::peq::Param_NBR_ELT; const float nat = get_param ( _settings, desc, _cur_band * pi::peq::Param_NBR_ELT + param_idx); switch (param_idx) { case pi::peq::Param_FREQ: if (nat < 9999.5) { fstb::snprintf4all ( txt_0, sizeof (txt_0), "%dF %.0f", _cur_band + 1, nat ); } else { const int hecto = fstb::round_int (nat / 100); const int kilo = hecto / 10; const int hectr = hecto % 10; fstb::snprintf4all ( txt_0, sizeof (txt_0), "%dF %dk%d", _cur_band + 1, kilo, hectr ); } break; case pi::peq::Param_Q: fstb::snprintf4all ( txt_0, sizeof (txt_0), "%dQ %.2f", _cur_band + 1, nat ); break; case pi::peq::Param_GAIN: { const float db = float (20 * log10 (std::max (nat, 1e-9f))); fstb::snprintf4all ( txt_0, sizeof (txt_0), "%dG %+.1f", _cur_band + 1, db ); } break; case pi::peq::Param_TYPE: switch (fstb::round_int (nat)) { case pi::peq::PEqType_PEAK: fstb::snprintf4all (txt_0, sizeof (txt_0), "%dPeak", _cur_band + 1); break; case pi::peq::PEqType_SHELF_LO: fstb::snprintf4all (txt_0, sizeof (txt_0), "%dSh-L", _cur_band + 1); break; case pi::peq::PEqType_HP: fstb::snprintf4all (txt_0, sizeof (txt_0), "%dHPF" , _cur_band + 1); break; case pi::peq::PEqType_SHELF_HI: fstb::snprintf4all (txt_0, sizeof (txt_0), "%dSh-H", _cur_band + 1); break; case pi::peq::PEqType_LP: fstb::snprintf4all (txt_0, sizeof (txt_0), "%dLPF" , _cur_band + 1); break; default: assert (false); break; } break; case pi::peq::Param_BYPASS: fstb::snprintf4all ( txt_0, sizeof (txt_0), "%d%s", _cur_band + 1, (nat >= 0.5f) ? "Off" : "On" ); break; default: assert (false); break; } _cur_param_sptr->set_text (txt_0); } // Precision std::string txt_prec; for (int prec_cnt = 0; prec_cnt <= _prec_idx; ++prec_cnt) { txt_prec += "\xE2\x9A\xAB"; // MEDIUM BLACK CIRCLE U+26AB } _prec_sptr->set_text (txt_prec); } void FxPEq::update_band_info () { const int slot_id = _loc_edit._slot_id; const doc::Preset & preset = _view_ptr->use_preset_cur (); const doc::Slot & slot = preset.use_slot (slot_id); auto it_settings = slot._settings_all.find (slot._pi_model); if (it_settings == slot._settings_all.end ()) { _nbr_param = Param_BAND_BASE; _nbr_bands = 0; } else { _settings = it_settings->second; const piapi::PluginDescInterface & desc = _model_ptr->get_model_desc (slot._pi_model); const int nbr_param = desc.get_nbr_param (piapi::ParamCateg_GLOBAL); _nbr_bands = nbr_param / pi::peq::Param_NBR_ELT; _nbr_param = Param_BAND_BASE + _nbr_bands * pi::peq::Param_NBR_ELT; } _cur_param = fstb::limit (_cur_param, 0, _nbr_param - 1); if (_nbr_bands <= 0) { _cur_band = -1; } else { if (_cur_param < Param_BAND_BASE) { _cur_band = -1; } else { _cur_band = (_cur_param - Param_BAND_BASE) / pi::peq::Param_NBR_ELT; if (_cur_band >= _nbr_bands) { assert (false); _cur_band = -1; } } } } std::vector <pi::peq::BandParam> FxPEq::create_bands (const doc::PluginSettings &settings, const piapi::PluginDescInterface &desc) const { const int nbr_param = desc.get_nbr_param (piapi::ParamCateg_GLOBAL); const int nbr_bands = nbr_param / pi::peq::Param_NBR_ELT; std::vector <pi::peq::BandParam> band_arr (nbr_bands); // Populates band parameters for (int b_cnt = 0; b_cnt < nbr_bands; ++b_cnt) { const int base = b_cnt * pi::peq::Param_NBR_ELT; auto & band = band_arr [b_cnt]; const float freq = get_param (settings, desc, base + pi::peq::Param_FREQ); const float q = get_param (settings, desc, base + pi::peq::Param_Q); const float gain = get_param (settings, desc, base + pi::peq::Param_GAIN); const float type = get_param (settings, desc, base + pi::peq::Param_TYPE); const float bypass = get_param (settings, desc, base + pi::peq::Param_BYPASS); band.set_freq (freq); band.set_q (q); band.set_gain (gain); band.set_type (static_cast <pi::peq::PEqType> (fstb::round_int (type))); band.set_bypass (bypass >= 0.5f); } return band_arr; } std::vector <FxPEq::Biq> FxPEq::retrieve_z_eq (const std::vector <pi::peq::BandParam> &band_arr) const { std::vector <Biq> biq_arr; const int nbr_bands = int (band_arr.size ()); const float fs = float (_model_ptr->get_sample_freq ()); const float inv_fs = 1.0f / fs; for (int b_cnt = 0; b_cnt < nbr_bands; ++b_cnt) { Biq biq; const auto & band = band_arr [b_cnt]; if (! band.is_bypass ()) { band.create_filter (&biq._b [0], &biq._a [0], fs, inv_fs); } biq_arr.push_back (biq); } return biq_arr; } std::vector <float> FxPEq::create_freq_map (int nbr_freq, float f_beg, float f_end) const { assert (nbr_freq > 0); assert (f_beg > 0); assert (f_end > f_beg); // For each displayed pixel column, rad/s std::vector <float> puls_arr (nbr_freq); const float fs = float (_model_ptr->get_sample_freq ()); const float base = float (log2 (double (2 * fstb::PI) * f_beg / fs)); const float mul = float (log2 (f_end / f_beg) / nbr_freq); const auto v_base = fstb::Vf32 (base); const auto v_mul = fstb::Vf32 (mul); const auto v_linstep = fstb::Vf32 (0, 1, 2, 3); for (int f_idx = 0; f_idx < nbr_freq; f_idx += 4) { auto v_idx = fstb::Vf32 (float (f_idx)); v_idx += v_linstep; auto v_puls = fstb::Approx::exp2 (v_base + v_idx * v_mul); v_puls.storeu_part (&puls_arr [f_idx], nbr_freq - f_idx); } return puls_arr; } // Output positions can be located out of the rendering zone. std::vector <int32_t> FxPEq::compute_y_pos (const std::vector <float> &lvl_arr, int pix_h) const { const int nbr_freq = int (lvl_arr.size ()); std::vector <int> y_arr (nbr_freq); const float range = float (_range_db_arr [_range_db_idx]); const float hh = float (pix_h) * 0.5f; const auto mul = fstb::Vf32 (float ( -20 * fstb::LOG10_2 * hh / range )); const auto ofs = fstb::Vf32 (hh); const auto secu = fstb::Vf32 (1e-15f); for (int f_idx = 0; f_idx < nbr_freq; f_idx += 4) { const int ns = nbr_freq - f_idx; auto lvl = fstb::Vf32::loadu_part (&lvl_arr [f_idx], ns); lvl = fstb::max (lvl, secu); const auto y_flt = fstb::Approx::log2 (lvl) * mul + ofs; const auto y = fstb::ToolsSimd::conv_f32_to_s32 (y_flt); y.storeu_part (&y_arr [f_idx], ns); } return y_arr; } /* H (z) = (b0 + b1 * z^-1 + b2 * z^-2) / (1 + a1 * z^-1 + a2 * z^-2) z -> exp (j * w) c1 = cos (w) s1 = sin (w) |H (z)|^2 = H (z) * H*(z) = (((b0 + b2) * c1 + b1)^2 + ((b0 - b2) * s1)^2) / (((1 + a2) * c1 + a1)^2 + ((1 - a2) * s1)^2) */ void FxPEq::compute_freq_resp (std::vector <float> &lvl_arr, const std::vector <float> &puls_arr, const Biq &biq) const { const int nbr_freq = int (puls_arr.size ()); assert (int (lvl_arr.size ()) == nbr_freq); const auto one = fstb::Vf32 (1); const auto b0 = fstb::Vf32 (biq._b [0]); const auto b1 = fstb::Vf32 (biq._b [1]); const auto b2 = fstb::Vf32 (biq._b [2]); const auto a1 = fstb::Vf32 (biq._a [1]); const auto a2 = fstb::Vf32 (biq._a [2]); for (int f_idx = 0; f_idx < nbr_freq; f_idx += 4) { const int ns = nbr_freq - f_idx; const auto w = fstb::Vf32::loadu_part (&puls_arr [f_idx], ns); fstb::Vf32 c1; fstb::Vf32 s1; fstb::Approx::cos_sin_rbj (c1, s1, w); const auto h2_nc = (b0 + b2) * c1 + b1; const auto h2_dc = (one + a2) * c1 + a1; const auto h2_ns = (b0 - b2) * s1; const auto h2_ds = (one - a2) * s1; const auto h2_n = h2_nc * h2_nc + h2_ns * h2_ns; const auto h2_d = h2_dc * h2_dc + h2_ds * h2_ds; const auto h2 = h2_n / h2_d; const auto h_abs = fstb::sqrt (h2); auto l = fstb::Vf32::loadu_part (&lvl_arr [f_idx], ns); l *= h_abs; l.storeu_part (&lvl_arr [f_idx], ns); } } // Result can be out of the window int FxPEq::conv_freq_to_x (float f, float f_beg, float f_end, int nbr_freq) const { const float f_rel = f / f_beg; const float f_amp = f_end / f_beg; const float l_rel = log2f (f_rel); const float l_amp = log2f (f_amp); const float x_flt = l_rel * float (nbr_freq) / l_amp; const int x = fstb::round_int (x_flt); return x; } int FxPEq::conv_db_to_y (float db, int pix_h) const { const float range_db = float (_range_db_arr [_range_db_idx]); const float pos_rel = db / range_db; const float hh = float (pix_h) * 0.5f; const float y_flt = hh * (1 - pos_rel); const int y = fstb::round_int (y_flt); return y; } void FxPEq::move_param (int dir) { const int band_old = _cur_band; _cur_param = (_cur_param + _nbr_param + dir) % _nbr_param; update_band_info (); if (_cur_band != band_old) { update_display (); } else { update_param_txt (); } } void FxPEq::change_param (int dir) { if (_cur_param == Param_RANGE) { const int nbr_ranges = int (_range_db_arr.size ()); _range_db_idx = (_range_db_idx + nbr_ranges + dir) % nbr_ranges; update_display (); } else { const int step_scale = _page_ptr->get_shift (PageMgrInterface::Shift::R) ? 1 : 0; float step = float (Cst::_step_param / pow (10, _prec_idx + step_scale)); int slot_id = -1; PiType type = PiType_INVALID; int index = -1; if (_cur_param == Param_GAIN) { slot_id = _loc_edit._slot_id; index = pi::dwm::Param_GAIN; type = PiType_MIX; } else { slot_id = _loc_edit._slot_id; index = _cur_param - Param_BAND_BASE; type = PiType_MAIN; } Tools::change_param ( *_model_ptr, *_view_ptr, slot_id, type, index, step, _prec_idx, dir ); } } float FxPEq::get_param (const doc::PluginSettings &settings, const piapi::PluginDescInterface &desc_pi, int index) { return float (Tools::get_param_nat (settings, desc_pi, index)); } const std::array <double, 6> FxPEq::_range_db_arr = {{ 6, 12, 18, 24, 36, 48 }}; } // namespace pg } // namespace uitk } // namespace mfx /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
24.976905
136
0.614933
D-J-Roberts
0a68588d9ea092ab703badf7915c483c03cf27d7
194
cpp
C++
src/config.cpp
XujieSi/fse18-artifact-183
29cf14b5072fdfb1786eaaf60e9ac6e75f932d74
[ "MIT" ]
6
2018-11-01T23:15:38.000Z
2022-02-17T09:37:44.000Z
src/config.cpp
XujieSi/fse18-artifact-183
29cf14b5072fdfb1786eaaf60e9ac6e75f932d74
[ "MIT" ]
null
null
null
src/config.cpp
XujieSi/fse18-artifact-183
29cf14b5072fdfb1786eaaf60e9ac6e75f932d74
[ "MIT" ]
1
2018-11-01T23:15:41.000Z
2018-11-01T23:15:41.000Z
// // config.cpp // ALPS // // Created by Xujie Si on 11/9/17. // Copyright © 2017 Xujie Si. All rights reserved. // #include "config.hpp" Configuration* Configuration::config = nullptr;
14.923077
51
0.659794
XujieSi
0a68a7b34aad2694b2096f1fa098fe432a023e73
8,396
cpp
C++
FaceTracking/src/shape_model.cpp
johmathe/ComputerVisionStuff
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
[ "Apache-2.0" ]
null
null
null
FaceTracking/src/shape_model.cpp
johmathe/ComputerVisionStuff
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
[ "Apache-2.0" ]
null
null
null
FaceTracking/src/shape_model.cpp
johmathe/ComputerVisionStuff
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * Non-Rigid Face Tracking ****************************************************************************** * by Jason Saragih, 5th Dec 2012 * http://jsaragih.org/ ****************************************************************************** * Ch6 of the book "Mastering OpenCV with Practical Computer Vision Projects" * Copyright Packt Publishing 2012. * http://www.packtpub.com/cool-projects-with-opencv/book *****************************************************************************/ /* shape_model: A combined local-global 2D point distribution model Jason Saragih (2012) */ #include "shape_model.hpp" #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #define fl at<float> //============================================================================== void shape_model::calc_params(const vector<Point2f> &pts, const Mat weight, const float c_factor) { int n = pts.size(); assert(V.rows == 2 * n); Mat s = Mat(pts).reshape(1, 2 * n); // point set to vector format if (weight.empty()) p = V.t() * s; // simple projection else { // scaled projection if (weight.rows != n) { cout << "Invalid weighting matrix" << endl; abort(); } int K = V.cols; Mat H = Mat::zeros(K, K, CV_32F), g = Mat::zeros(K, 1, CV_32F); for (int i = 0; i < n; i++) { Mat v = V(Rect(0, 2 * i, K, 2)); float w = weight.fl(i); H += w * v.t() * v; g += w * v.t() * Mat(pts[i]); } solve(H, g, p, DECOMP_SVD); } this->clamp(c_factor); // clamp resulting parameters } //============================================================================== Mat shape_model::center_shape(const Mat &pts) { int n = pts.rows / 2; float mx = 0, my = 0; for (int i = 0; i < n; i++) { mx += pts.fl(2 * i); my += pts.fl(2 * i + 1); } Mat p(2 * n, 1, CV_32F); mx /= n; my /= n; for (int i = 0; i < n; i++) { p.fl(2 * i) = pts.fl(2 * i) - mx; p.fl(2 * i + 1) = pts.fl(2 * i + 1) - my; } return p; } //============================================================================== vector<Point2f> shape_model::calc_shape() { Mat s = V * p; int n = s.rows / 2; vector<Point2f> pts; for (int i = 0; i < n; i++) pts.push_back(Point2f(s.fl(2 * i), s.fl(2 * i + 1))); return pts; } //============================================================================== void shape_model::set_identity_params() { p = 0.0; p.fl(0) = 1.0; // 1'st parameter is scale } //============================================================================== void shape_model::train(const vector<vector<Point2f> > &points, const vector<Vec2i> &con, const float frac, const int kmax) { // vectorize points Mat X = this->pts2mat(points); int N = X.cols, n = X.rows / 2; // align shapes Mat Y = this->procrustes(X); // compute rigid transformation Mat R = this->calc_rigid_basis(Y); // compute non-rigid transformation Mat P = R.t() * Y; Mat dY = Y - R * P; SVD svd(dY * dY.t()); int m = min(min(kmax, N - 1), n - 1); float vsum = 0; for (int i = 0; i < m; i++) vsum += svd.w.fl(i); float v = 0; int k = 0; for (k = 0; k < m; k++) { v += svd.w.fl(k); if (v / vsum >= frac) { k++; break; } } if (k > m) k = m; Mat D = svd.u(Rect(0, 0, k, 2 * n)); // combine bases V.create(2 * n, 4 + k, CV_32F); Mat Vr = V(Rect(0, 0, 4, 2 * n)); R.copyTo(Vr); Mat Vd = V(Rect(4, 0, k, 2 * n)); D.copyTo(Vd); // compute variance (normalized wrt scale) Mat Q = V.t() * X; for (int i = 0; i < N; i++) { float v = Q.fl(0, i); Mat q = Q.col(i); q /= v; } e.create(4 + k, 1, CV_32F); pow(Q, 2, Q); for (int i = 0; i < 4 + k; i++) { if (i < 4) e.fl(i) = -1; else e.fl(i) = Q.row(i).dot(Mat::ones(1, N, CV_32F)) / (N - 1); } // store connectivity if (con.size() > 0) { // default connectivity int m = con.size(); C.create(m, 2, CV_32F); for (int i = 0; i < m; i++) { C.at<int>(i, 0) = con[i][0]; C.at<int>(i, 1) = con[i][1]; } } else { // user-specified connectivity C.create(n, 2, CV_32S); for (int i = 0; i < n - 1; i++) { C.at<int>(i, 0) = i; C.at<int>(i, 1) = i + 1; } C.at<int>(n - 1, 0) = n - 1; C.at<int>(n - 1, 1) = 0; } } //============================================================================== Mat shape_model::pts2mat(const vector<vector<Point2f> > &points) { int N = points.size(); assert(N > 0); int n = points[0].size(); for (int i = 1; i < N; i++) assert(int(points[i].size()) == n); Mat X(2 * n, N, CV_32F); for (int i = 0; i < N; i++) { Mat x = X.col(i), y = Mat(points[i]).reshape(1, 2 * n); y.copyTo(x); } return X; } //============================================================================== Mat shape_model::procrustes(const Mat &X, const int itol, const float ftol) { int N = X.cols, n = X.rows / 2; // remove centre of mass Mat P = X.clone(); for (int i = 0; i < N; i++) { Mat p = P.col(i); float mx = 0, my = 0; for (int j = 0; j < n; j++) { mx += p.fl(2 * j); my += p.fl(2 * j + 1); } mx /= n; my /= n; for (int j = 0; j < n; j++) { p.fl(2 * j) -= mx; p.fl(2 * j + 1) -= my; } } // optimise scale and rotation Mat C_old; for (int iter = 0; iter < itol; iter++) { Mat C = P * Mat::ones(N, 1, CV_32F) / N; normalize(C, C); if (iter > 0) { if (norm(C, C_old) < ftol) break; } C_old = C.clone(); for (int i = 0; i < N; i++) { Mat R = this->rot_scale_align(P.col(i), C); for (int j = 0; j < n; j++) { float x = P.fl(2 * j, i), y = P.fl(2 * j + 1, i); P.fl(2 * j, i) = R.fl(0, 0) * x + R.fl(0, 1) * y; P.fl(2 * j + 1, i) = R.fl(1, 0) * x + R.fl(1, 1) * y; } } } return P; } //============================================================================= Mat shape_model::rot_scale_align(const Mat &src, const Mat &dst) { // construct linear system int n = src.rows / 2; float a = 0, b = 0, d = 0; for (int i = 0; i < n; i++) { d += src.fl(2 * i) * src.fl(2 * i) + src.fl(2 * i + 1) * src.fl(2 * i + 1); a += src.fl(2 * i) * dst.fl(2 * i) + src.fl(2 * i + 1) * dst.fl(2 * i + 1); b += src.fl(2 * i) * dst.fl(2 * i + 1) - src.fl(2 * i + 1) * dst.fl(2 * i); } a /= d; b /= d; // solved linear system return (Mat_<float>(2, 2) << a, -b, b, a); } //============================================================================== Mat shape_model::calc_rigid_basis(const Mat &X) { // compute mean shape int N = X.cols, n = X.rows / 2; Mat mean = X * Mat::ones(N, 1, CV_32F) / N; // construct basis for similarity transform Mat R(2 * n, 4, CV_32F); for (int i = 0; i < n; i++) { R.fl(2 * i, 0) = mean.fl(2 * i); R.fl(2 * i + 1, 0) = mean.fl(2 * i + 1); R.fl(2 * i, 1) = -mean.fl(2 * i + 1); R.fl(2 * i + 1, 1) = mean.fl(2 * i); R.fl(2 * i, 2) = 1.0; R.fl(2 * i + 1, 2) = 0.0; R.fl(2 * i, 3) = 0.0; R.fl(2 * i + 1, 3) = 1.0; } // Gram-Schmidt orthonormalization for (int i = 0; i < 4; i++) { Mat r = R.col(i); for (int j = 0; j < i; j++) { Mat b = R.col(j); r -= b * (b.t() * r); } normalize(r, r); } return R; } //============================================================================== void shape_model::clamp(const float c) { double scale = p.fl(0); for (int i = 0; i < e.rows; i++) { if (e.fl(i) < 0) continue; float v = c * sqrt(e.fl(i)); if (fabs(p.fl(i) / scale) > v) { if (p.fl(i) > 0) p.fl(i) = v * scale; else p.fl(i) = -v * scale; } } } //============================================================================== void shape_model::write(FileStorage &fs) const { assert(fs.isOpened()); fs << "{" << "V" << V << "e" << e << "C" << C << "}"; } //============================================================================== void shape_model::read(const FileNode &node) { assert(node.type() == FileNode::MAP); node["V"] >> V; node["e"] >> e; node["C"] >> C; p = Mat::zeros(e.rows, 1, CV_32F); } //==============================================================================
30.754579
80
0.407932
johmathe
0a68fd4158f11695b65ff930a8fa9778ff613572
5,283
cpp
C++
bfcp/common/bfcp_msg.cpp
Issic47/bfcp
b0e78534f58820610df6133dc4043f902c001173
[ "BSD-3-Clause" ]
10
2015-08-05T06:07:41.000Z
2020-12-17T04:28:48.000Z
bfcp/common/bfcp_msg.cpp
Issic47/bfcp
b0e78534f58820610df6133dc4043f902c001173
[ "BSD-3-Clause" ]
null
null
null
bfcp/common/bfcp_msg.cpp
Issic47/bfcp
b0e78534f58820610df6133dc4043f902c001173
[ "BSD-3-Clause" ]
8
2015-11-27T13:22:30.000Z
2021-01-28T07:20:50.000Z
#include <bfcp/common/bfcp_msg.h> #include <algorithm> #include <muduo/base/Logging.h> using muduo::net::Buffer; using muduo::net::InetAddress; using muduo::strerror_tl; namespace bfcp { namespace detail { int printToString(const char *p, size_t size, void *arg) { string *str = static_cast<string*>(arg); str->append(p, p + size); return 0; } } // namespace detail BfcpMsg::BfcpMsg(muduo::net::Buffer *buf, const muduo::net::InetAddress &src, muduo::Timestamp receivedTime) : msg_(nullptr), receivedTime_(receivedTime) { mbuf_t mb; mbuf_init(&mb); mb.buf = reinterpret_cast<uint8_t*>(const_cast<char*>(buf->peek())); mb.size = buf->readableBytes(); mb.end = mb.size; err_ = bfcp_msg_decode(&msg_, &mb); buf->retrieveAll(); if (err_ == 0) setSrc(src); isComplete_ = !valid() || !msg_->f; if (valid() && msg_->f) { fragments_.emplace(msg_->fragoffset, msg_->fraglen, msg_->fragdata); } } std::list<BfcpAttr> BfcpMsg::getAttributes() const { std::list<BfcpAttr> attrs; struct le *le = list_head(&msg_->attrl); while (le) { bfcp_attr_t *attr = static_cast<bfcp_attr_t*>(le->data); le = le->next; attrs.push_back(BfcpAttr(*attr)); } return attrs; } std::list<BfcpAttr> BfcpMsg::findAttributes( ::bfcp_attrib attrType ) const { std::list<BfcpAttr> attrs; struct le *le = list_head(&msg_->attrl); while (le) { bfcp_attr_t *attr = static_cast<bfcp_attr_t*>(le->data); le = le->next; if (attr->type == attrType) attrs.push_back(BfcpAttr(*attr)); } return attrs; } string BfcpMsg::toString() const { char buf[256]; if (!valid()) { snprintf(buf, sizeof buf, "{errcode=%d,errstr='%s'}", err_, strerror_tl(err_)); } else { snprintf(buf, sizeof buf, "{ver=%u,cid=%u,tid=%u,uid=%u,prim=%s}", msg_->ver, msg_->confid, msg_->tid, msg_->userid, bfcp_prim_name(msg_->prim)); } return buf; } bfcp_floor_id_list BfcpMsg::getFloorIDs() const { bfcp_floor_id_list floorIDs; auto attrs = findAttributes(BFCP_FLOOR_ID); floorIDs.reserve(attrs.size()); for (auto &attr : attrs) { floorIDs.push_back(attr.getFloorID()); } return floorIDs; } string BfcpMsg::toStringInDetail() const { string str; struct re_printf printFunc; printFunc.vph = &detail::printToString; printFunc.arg = &str; bfcp_msg_print(&printFunc, msg_); return str; } void BfcpMsg::addFragment( const BfcpMsgPtr &msg ) { assert(this != &(*msg)); if (!valid() || !canMergeWith(msg)) { LOG_WARN << "Cannot merge fragment: " << msg->toString(); err_ = EBADMSG; return; } if (!isComplete_ && holes_.empty()) { holes_.emplace_back(0, getLength() - 1); doAddFragment(this); } doAddFragment(&(*msg)); if (holes_.empty()) { isComplete_ = true; mergeFragments(); } } bool BfcpMsg::canMergeWith( const BfcpMsgPtr &msg ) const { return (isFragment() && msg->isFragment()) && getEntity() == msg->getEntity() && primitive() == msg->primitive() && getLength() == msg->getLength() && isResponse() == msg->isResponse(); } void BfcpMsg::doAddFragment(const BfcpMsg *msg) { bool isInHole = false; uint16_t fragOffset = msg->msg_->fragoffset; uint16_t fragBack = fragOffset + msg->msg_->fraglen - 1; for (auto it = holes_.begin(); it != holes_.end(); ++it) { if ((*it).front <= fragOffset && fragBack <= (*it).back) { isInHole = true; if ((*it).front < fragOffset) { holes_.emplace_back((*it).front, fragOffset - 1); } if (fragBack < (*it).back) { holes_.emplace_back(fragBack + 1, (*it).back); } it = holes_.erase(it); break; } } if (!isInHole) { LOG_WARN << "Ignore fragment not in the hole: " << msg->toString(); } else { fragments_.emplace( msg->msg_->fragoffset, msg->msg_->fraglen, msg->msg_->fragdata); } } bool BfcpMsg::checkComplete() { isComplete_ = false; auto it = fragments_.begin(); if ((*it).getOffset() != 0) { return false; } auto nextIt = it; ++nextIt; size_t len = it->getLen(); for (; nextIt != fragments_.end(); ++it, ++nextIt) { size_t offsetEnd = (*it).getOffset() + (*it).getLen(); if (offsetEnd < (*nextIt).getOffset()) { return false; } else if (offsetEnd > (*nextIt).getOffset()) { LOG_WARN << "Received overlap fragments: " << toString(); err_ = EBADMSG; return false; } len += (*nextIt).getLen(); } if (len == msg_->len) { isComplete_ = true; return true; } else if (len > msg_->len) { LOG_WARN << "Received too large fragments: " << toString(); err_ = EBADMSG; return false; } return false; } void BfcpMsg::mergeFragments() { assert(valid()); uint8_t buf[65536]; mbuf_t mb; mbuf_init(&mb); mb.buf = buf; mb.pos = 0; mb.end = 0; mb.size = sizeof buf; for (auto &fragment : fragments_) { mbuf_t *fragBuf = fragment.getBuf(); err_ = mbuf_write_mem(&mb, fragBuf->buf, fragBuf->end); assert(err_ == 0); } mb.pos = 0; err_ = bfcp_attrs_decode(&msg_->attrl, &mb, 4 * msg_->len, &msg_->uma); fragments_.clear(); } } // namespace bfcp
21.388664
75
0.605338
Issic47
0a74e732b1a1b7620b37cf7c5074d79a87a6c213
3,229
hpp
C++
source/modules/distribution/multivariate/normal/normal.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
source/modules/distribution/multivariate/normal/normal.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
source/modules/distribution/multivariate/normal/normal.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
/** \namespace multivariate * @brief Namespace declaration for modules of type: multivariate. */ /** \file * @brief Header file for module: Normal. */ /** \dir distribution/multivariate/normal * @brief Contains code, documentation, and scripts for module: Normal. */ #pragma once #include "modules/distribution/multivariate/multivariate.hpp" #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> namespace korali { namespace distribution { namespace multivariate { ; /** * @brief Class declaration for module: Normal. */ class Normal : public Multivariate { private: /** * @brief Temporal storage for covariance matrix */ gsl_matrix_view _sigma_view; /** * @brief Temporal storage for variable means */ gsl_vector_view _mean_view; /** * @brief Temporal storage for work */ gsl_vector_view _work_view; public: /** * @brief Means of the variables. */ std::vector<double> _meanVector; /** * @brief Cholesky Decomposition of the covariance matrix. */ std::vector<double> _sigma; /** * @brief [Internal Use] Auxiliary work vector. */ std::vector<double> _workVector; /** * @brief Obtains the entire current state and configuration of the module. * @param js JSON object onto which to save the serialized state of the module. */ void getConfiguration(knlohmann::json& js) override; /** * @brief Sets the entire state and configuration of the module, given a JSON object. * @param js JSON object from which to deserialize the state of the module. */ void setConfiguration(knlohmann::json& js) override; /** * @brief Applies the module's default configuration upon its creation. * @param js JSON object containing user configuration. The defaults will not override any currently defined settings. */ void applyModuleDefaults(knlohmann::json& js) override; /** * @brief Applies the module's default variable configuration to each variable in the Experiment upon creation. */ void applyVariableDefaults() override; /* * @brief Updates distribution to new covariance matrix. */ void updateDistribution() override; /** * @brief Updates a specific property with a vector of values. * @param propertyName The name of the property to update * @param values double Numerical values to assign. */ void setProperty(const std::string &propertyName, const std::vector<double> &values) override; /** * @brief Gets the probability density of the distribution at points x. * @param x points to evaluate * @param result P(x) at the given points * @param n number of points */ void getDensity(double *x, double *result, const size_t n) override; /** * @brief Gets Log probability density of the distribution at points x. * @param x points to evaluate * @param result log(P(x)) at the given points * @param n number of points */ void getLogDensity(double *x, double *result, const size_t n) override; /** * @brief Draws and returns a random number vector from the distribution. * @param x Random real number vector. * @param n Vector size */ void getRandomVector(double *x, const size_t n) override; }; } //multivariate } //distribution } //korali ;
26.040323
119
0.704552
JonathanLehner
0a78be8d5b181f93ad7df01797458b5a6cd2f9f3
651
cc
C++
EDMUtils/src/TFileUtils.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
EDMUtils/src/TFileUtils.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
EDMUtils/src/TFileUtils.cc
NTUHEP-Tstar/ManagerUtils
2536174671e537f210c330fe739f4cf0615e735e
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : TFileUtils.cc * Description : Implementation of utility functions * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #include "TFile.h" #include <string> using namespace std; // Returing a clone of a object for safe use in edm plugis TObject* GetCloneFromFile( const string& filename, const string& objname ) { TFile* file = TFile::Open( filename.c_str() ); TObject* ans = file->Get( objname.c_str() )->Clone(); file->Close(); return ans; }
29.590909
80
0.509985
NTUHEP-Tstar
0a7acbda3f66137d53aa010a061042622418c971
40,426
cc
C++
ns-allinone-3.35/ns-3.35/src/wifi/test/wifi-txop-test.cc
usi-systems/cc
487aa9e322b2b01b6af3a92e38545c119e4980a3
[ "Apache-2.0" ]
null
null
null
ns-allinone-3.35/ns-3.35/src/wifi/test/wifi-txop-test.cc
usi-systems/cc
487aa9e322b2b01b6af3a92e38545c119e4980a3
[ "Apache-2.0" ]
null
null
null
ns-allinone-3.35/ns-3.35/src/wifi/test/wifi-txop-test.cc
usi-systems/cc
487aa9e322b2b01b6af3a92e38545c119e4980a3
[ "Apache-2.0" ]
null
null
null
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2020 Universita' degli Studi di Napoli Federico II * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Stefano Avallone <stavallo@unina.it> */ #include "ns3/test.h" #include "ns3/string.h" #include "ns3/qos-utils.h" #include "ns3/packet.h" #include "ns3/wifi-net-device.h" #include "ns3/wifi-mac-header.h" #include "ns3/mobility-helper.h" #include "ns3/spectrum-wifi-helper.h" #include "ns3/single-model-spectrum-channel.h" #include "ns3/packet-socket-server.h" #include "ns3/packet-socket-client.h" #include "ns3/packet-socket-helper.h" #include "ns3/config.h" #include "ns3/pointer.h" #include "ns3/rng-seed-manager.h" #include "ns3/wifi-psdu.h" #include "ns3/wifi-ppdu.h" #include "ns3/ap-wifi-mac.h" using namespace ns3; /** * \ingroup wifi-test * \ingroup tests * * \brief Test TXOP rules * * */ class WifiTxopTest : public TestCase { public: /** * Constructor * \param pifsRecovery whether PIFS recovery is used after failure of a non-initial frame */ WifiTxopTest (bool pifsRecovery); virtual ~WifiTxopTest (); /** * Function to trace packets received by the server application * \param context the context * \param p the packet * \param addr the address */ void L7Receive (std::string context, Ptr<const Packet> p, const Address &addr); /** * Callback invoked when PHY receives a PSDU to transmit * \param context the context * \param psduMap the PSDU map * \param txVector the TX vector * \param txPowerW the tx power in Watts */ void Transmit (std::string context, WifiConstPsduMap psduMap, WifiTxVector txVector, double txPowerW); /** * Check correctness of transmitted frames */ void CheckResults (void); private: void DoRun (void) override; /// Information about transmitted frames struct FrameInfo { Time txStart; ///< Frame start TX time Time txDuration; ///< Frame TX duration WifiMacHeader header; ///< Frame MAC header WifiTxVector txVector; ///< TX vector used to transmit the frame }; uint16_t m_nStations; ///< number of stations NetDeviceContainer m_staDevices; ///< container for stations' NetDevices NetDeviceContainer m_apDevices; ///< container for AP's NetDevice std::vector<FrameInfo> m_txPsdus; ///< transmitted PSDUs Time m_txopLimit; ///< TXOP limit uint8_t m_aifsn; ///< AIFSN for BE uint32_t m_cwMin; ///< CWmin for BE uint16_t m_received; ///< number of packets received by the stations bool m_pifsRecovery; ///< whether to use PIFS recovery }; WifiTxopTest::WifiTxopTest (bool pifsRecovery) : TestCase ("Check correct operation within TXOPs"), m_nStations (3), m_txopLimit (MicroSeconds (4768)), m_received (0), m_pifsRecovery (pifsRecovery) { } WifiTxopTest::~WifiTxopTest () { } void WifiTxopTest::L7Receive (std::string context, Ptr<const Packet> p, const Address &addr) { if (p->GetSize () >= 500) { m_received++; } } void WifiTxopTest::Transmit (std::string context, WifiConstPsduMap psduMap, WifiTxVector txVector, double txPowerW) { // Log all transmitted frames that are not beacon frames and have been transmitted // after 400ms (so as to skip association requests/responses) if (!psduMap.begin ()->second->GetHeader (0).IsBeacon () && Simulator::Now () > MilliSeconds (400)) { m_txPsdus.push_back ({Simulator::Now (), WifiPhy::CalculateTxDuration (psduMap, txVector, WIFI_PHY_BAND_5GHZ), psduMap[SU_STA_ID]->GetHeader (0), txVector}); } // Print all the transmitted frames if the test is executed through test-runner std::cout << Simulator::Now () << " " << psduMap.begin ()->second->GetHeader (0).GetTypeString () << " seq " << psduMap.begin ()->second->GetHeader (0).GetSequenceNumber () << " to " << psduMap.begin ()->second->GetAddr1 () << " TX duration " << WifiPhy::CalculateTxDuration (psduMap, txVector, WIFI_PHY_BAND_5GHZ) << " duration/ID " << psduMap.begin ()->second->GetHeader (0).GetDuration () << std::endl; } void WifiTxopTest::DoRun (void) { RngSeedManager::SetSeed (1); RngSeedManager::SetRun (40); int64_t streamNumber = 100; NodeContainer wifiApNode; wifiApNode.Create (1); NodeContainer wifiStaNodes; wifiStaNodes.Create (m_nStations); Ptr<SingleModelSpectrumChannel> spectrumChannel = CreateObject<SingleModelSpectrumChannel> (); Ptr<FriisPropagationLossModel> lossModel = CreateObject<FriisPropagationLossModel> (); spectrumChannel->AddPropagationLossModel (lossModel); Ptr<ConstantSpeedPropagationDelayModel> delayModel = CreateObject<ConstantSpeedPropagationDelayModel> (); spectrumChannel->SetPropagationDelayModel (delayModel); SpectrumWifiPhyHelper phy; phy.SetChannel (spectrumChannel); Config::SetDefault ("ns3::QosFrameExchangeManager::PifsRecovery", BooleanValue (m_pifsRecovery)); Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue (1900)); WifiHelper wifi; wifi.SetStandard (WIFI_STANDARD_80211a); wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("OfdmRate12Mbps"), "ControlMode", StringValue ("OfdmRate6Mbps")); WifiMacHelper mac; mac.SetType ("ns3::StaWifiMac", "QosSupported", BooleanValue (true), "Ssid", SsidValue (Ssid ("non-existent-ssid"))); m_staDevices = wifi.Install (phy, mac, wifiStaNodes); mac.SetType ("ns3::ApWifiMac", "QosSupported", BooleanValue (true), "Ssid", SsidValue (Ssid ("wifi-txop-ssid")), "BeaconInterval", TimeValue (MicroSeconds (102400)), "EnableBeaconJitter", BooleanValue (false)); m_apDevices = wifi.Install (phy, mac, wifiApNode); // schedule association requests at different times Time init = MilliSeconds (100); Ptr<WifiNetDevice> dev; for (uint16_t i = 0; i < m_nStations; i++) { dev = DynamicCast<WifiNetDevice> (m_staDevices.Get (i)); Simulator::Schedule (init + i * MicroSeconds (102400), &WifiMac::SetSsid, dev->GetMac (), Ssid ("wifi-txop-ssid")); } // Assign fixed streams to random variables in use wifi.AssignStreams (m_apDevices, streamNumber); MobilityHelper mobility; Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> (); positionAlloc->Add (Vector (0.0, 0.0, 0.0)); positionAlloc->Add (Vector (1.0, 0.0, 0.0)); positionAlloc->Add (Vector (0.0, 1.0, 0.0)); positionAlloc->Add (Vector (-1.0, 0.0, 0.0)); mobility.SetPositionAllocator (positionAlloc); mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); mobility.Install (wifiApNode); mobility.Install (wifiStaNodes); // set the TXOP limit on BE AC dev = DynamicCast<WifiNetDevice> (m_apDevices.Get (0)); PointerValue ptr; dev->GetMac ()->GetAttribute ("BE_Txop", ptr); ptr.Get<QosTxop> ()->SetTxopLimit (m_txopLimit); m_aifsn = ptr.Get<QosTxop> ()->GetAifsn (); m_cwMin = ptr.Get<QosTxop> ()->GetMinCw (); PacketSocketHelper packetSocket; packetSocket.Install (wifiApNode); packetSocket.Install (wifiStaNodes); // DL frames for (uint16_t i = 0; i < m_nStations; i++) { PacketSocketAddress socket; socket.SetSingleDevice (m_apDevices.Get (0)->GetIfIndex ()); socket.SetPhysicalAddress (m_staDevices.Get (i)->GetAddress ()); socket.SetProtocol (1); // Send one QoS data frame (not protected by RTS/CTS) to each station Ptr<PacketSocketClient> client1 = CreateObject<PacketSocketClient> (); client1->SetAttribute ("PacketSize", UintegerValue (500)); client1->SetAttribute ("MaxPackets", UintegerValue (1)); client1->SetAttribute ("Interval", TimeValue (MicroSeconds (1))); client1->SetRemote (socket); wifiApNode.Get (0)->AddApplication (client1); client1->SetStartTime (MilliSeconds (410)); client1->SetStopTime (Seconds (1.0)); // Send one QoS data frame (protected by RTS/CTS) to each station Ptr<PacketSocketClient> client2 = CreateObject<PacketSocketClient> (); client2->SetAttribute ("PacketSize", UintegerValue (2000)); client2->SetAttribute ("MaxPackets", UintegerValue (1)); client2->SetAttribute ("Interval", TimeValue (MicroSeconds (1))); client2->SetRemote (socket); wifiApNode.Get (0)->AddApplication (client2); client2->SetStartTime (MilliSeconds (520)); client2->SetStopTime (Seconds (1.0)); Ptr<PacketSocketServer> server = CreateObject<PacketSocketServer> (); server->SetLocal (socket); wifiStaNodes.Get (i)->AddApplication (server); server->SetStartTime (Seconds (0.0)); server->SetStopTime (Seconds (1.0)); } // The AP does not correctly receive the Ack sent in response to the QoS // data frame sent to the first station Ptr<ReceiveListErrorModel> apPem = CreateObject<ReceiveListErrorModel> (); apPem->SetList ({6}); dev = DynamicCast<WifiNetDevice> (m_apDevices.Get (0)); dev->GetMac ()->GetWifiPhy ()->SetPostReceptionErrorModel (apPem); // The second station does not correctly receive the first QoS // data frame sent by the AP Ptr<ReceiveListErrorModel> sta2Pem = CreateObject<ReceiveListErrorModel> (); sta2Pem->SetList ({19}); dev = DynamicCast<WifiNetDevice> (m_staDevices.Get (1)); dev->GetMac ()->GetWifiPhy ()->SetPostReceptionErrorModel (sta2Pem); // UL Traffic (the first station sends one frame to the AP) { PacketSocketAddress socket; socket.SetSingleDevice (m_staDevices.Get (0)->GetIfIndex ()); socket.SetPhysicalAddress (m_apDevices.Get (0)->GetAddress ()); socket.SetProtocol (1); Ptr<PacketSocketClient> client = CreateObject<PacketSocketClient> (); client->SetAttribute ("PacketSize", UintegerValue (1500)); client->SetAttribute ("MaxPackets", UintegerValue (1)); client->SetAttribute ("Interval", TimeValue (MicroSeconds (0))); client->SetRemote (socket); wifiStaNodes.Get (0)->AddApplication (client); client->SetStartTime (MilliSeconds (412)); client->SetStopTime (Seconds (1.0)); Ptr<PacketSocketServer> server = CreateObject<PacketSocketServer> (); server->SetLocal (socket); wifiApNode.Get (0)->AddApplication (server); server->SetStartTime (Seconds (0.0)); server->SetStopTime (Seconds (1.0)); } Config::Connect ("/NodeList/*/ApplicationList/*/$ns3::PacketSocketServer/Rx", MakeCallback (&WifiTxopTest::L7Receive, this)); // Trace PSDUs passed to the PHY on all devices Config::Connect ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/PhyTxPsduBegin", MakeCallback (&WifiTxopTest::Transmit, this)); Simulator::Stop (Seconds (1)); Simulator::Run (); CheckResults (); Simulator::Destroy (); } void WifiTxopTest::CheckResults (void) { Time tEnd, // TX end for a frame tStart, // TX start fot the next frame txopStart, // TXOP start time tolerance = NanoSeconds (50), // due to propagation delay sifs = DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetPhy ()->GetSifs (), slot = DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetPhy ()->GetSlot (), navEnd; // lambda to round Duration/ID (in microseconds) up to the next higher integer auto RoundDurationId = [] (Time t) { return MicroSeconds (ceil (static_cast<double> (t.GetNanoSeconds ()) / 1000)); }; /* * Verify the different behavior followed when an initial/non-initial frame of a TXOP * fails. Also, verify that a CF-end frame is sent if enough time remains in the TXOP. * The destination of failed frames is put in square brackets below. * * |---NAV-----till end TXOP--------->| * | |----NAV--till end TXOP---->| * | | |---------------------------NAV---------------------------------->| * | | | |--------------------------NAV---------------------------->| * | | | | |------------------------NAV----------------------->| * | | | | | |-------------NAV--------------->| * Start| | Start| | | | |----------NAV----------->| * TXOP | | TXOP | | | Ack | | |-------NAV------->| * | | | | | | | Timeout | | | |---NAV---->| * |---| |---|-backoff->|---| |---| |---| |-PIFS or->|---| |---| |---| |---| |-----| * |QoS| |Ack| |QoS| |Ack| |QoS| |-backoff->|QoS| |Ack| |QoS| |Ack| |CFend| * ---------------------------------------------------------------------------------------------------- * From: AP STA1 AP STA1 AP AP STA2 AP STA3 AP * To: STA1 [AP] STA1 AP [STA2] STA2 AP STA3 AP all */ NS_TEST_EXPECT_MSG_EQ (m_txPsdus.size (), 25, "Expected 25 transmitted frames"); // the first frame sent after 400ms is a QoS data frame sent by the AP to STA1 txopStart = m_txPsdus[0].txStart; NS_TEST_EXPECT_MSG_EQ (m_txPsdus[0].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[0].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (0))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the first station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[0].header.GetDuration (), RoundDurationId (m_txopLimit - m_txPsdus[0].txDuration), "Duration/ID of the first frame must cover the whole TXOP"); // a Normal Ack is sent by STA1 tEnd = m_txPsdus[0].txStart + m_txPsdus[0].txDuration; tStart = m_txPsdus[1].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the first frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the first frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[1].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[1].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[1].header.GetDuration (), RoundDurationId (m_txPsdus[0].header.GetDuration () - sifs - m_txPsdus[1].txDuration), "Duration/ID of the Ack must be derived from that of the first frame"); // the AP receives a corrupted Ack in response to the frame it sent, which is the initial // frame of a TXOP. Hence, the TXOP is terminated and the AP retransmits the frame after // invoking the backoff txopStart = m_txPsdus[2].txStart; tEnd = m_txPsdus[1].txStart + m_txPsdus[1].txDuration; tStart = m_txPsdus[2].txStart; NS_TEST_EXPECT_MSG_GT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot, "Less than AIFS elapsed between AckTimeout and the next TXOP start"); NS_TEST_EXPECT_MSG_LT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot + (2 * (m_cwMin + 1) - 1) * slot, "More than AIFS+BO elapsed between AckTimeout and the next TXOP start"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[2].header.IsQosData (), true, "Expected to retransmit a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[2].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (0))->GetMac ()->GetAddress (), "Expected to retransmit a frame to the first station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[2].header.GetDuration (), RoundDurationId (m_txopLimit - m_txPsdus[2].txDuration), "Duration/ID of the retransmitted frame must cover the whole TXOP"); // a Normal Ack is then sent by STA1 tEnd = m_txPsdus[2].txStart + m_txPsdus[2].txDuration; tStart = m_txPsdus[3].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the first frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the first frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[3].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[3].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[3].header.GetDuration (), RoundDurationId (m_txPsdus[2].header.GetDuration () - sifs - m_txPsdus[3].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // the AP sends a frame to STA2 tEnd = m_txPsdus[3].txStart + m_txPsdus[3].txDuration; tStart = m_txPsdus[4].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Second frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Second frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[4].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[4].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (1))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the second station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[4].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[4].txStart - txopStart) - m_txPsdus[4].txDuration), "Duration/ID of the second frame does not cover the remaining TXOP"); // STA2 receives a corrupted frame and hence it does not send the Ack. When the AckTimeout // expires, the AP performs PIFS recovery or invoke backoff, without terminating the TXOP, // because a non-initial frame of the TXOP failed tEnd = m_txPsdus[4].txStart + m_txPsdus[4].txDuration + sifs + slot + WifiPhy::CalculatePhyPreambleAndHeaderDuration (m_txPsdus[4].txVector); // AckTimeout tStart = m_txPsdus[5].txStart; if (m_pifsRecovery) { NS_TEST_EXPECT_MSG_EQ (tEnd + sifs + slot, tStart, "Second frame must have been sent after a PIFS"); } else { NS_TEST_EXPECT_MSG_GT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot, "Less than AIFS elapsed between AckTimeout and the next transmission"); NS_TEST_EXPECT_MSG_LT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot + (2 * (m_cwMin + 1) - 1) * slot, "More than AIFS+BO elapsed between AckTimeout and the next TXOP start"); } NS_TEST_EXPECT_MSG_EQ (m_txPsdus[5].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[5].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (1))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the second station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[5].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[5].txStart - txopStart) - m_txPsdus[5].txDuration), "Duration/ID of the second frame does not cover the remaining TXOP"); // a Normal Ack is then sent by STA2 tEnd = m_txPsdus[5].txStart + m_txPsdus[5].txDuration; tStart = m_txPsdus[6].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the second frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the second frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[6].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[6].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[6].header.GetDuration (), RoundDurationId (m_txPsdus[5].header.GetDuration () - sifs - m_txPsdus[6].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // the AP sends a frame to STA3 tEnd = m_txPsdus[6].txStart + m_txPsdus[6].txDuration; tStart = m_txPsdus[7].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Third frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Third frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[7].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[7].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (2))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the third station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[7].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[7].txStart - txopStart) - m_txPsdus[7].txDuration), "Duration/ID of the third frame does not cover the remaining TXOP"); // a Normal Ack is then sent by STA3 tEnd = m_txPsdus[7].txStart + m_txPsdus[7].txDuration; tStart = m_txPsdus[8].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the third frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the third frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[8].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[8].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[8].header.GetDuration (), RoundDurationId (m_txPsdus[7].header.GetDuration () - sifs - m_txPsdus[8].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // the TXOP limit is such that enough time for sending a CF-End frame remains tEnd = m_txPsdus[8].txStart + m_txPsdus[8].txDuration; tStart = m_txPsdus[9].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "CF-End sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "CF-End sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[9].header.IsCfEnd (), true, "Expected a CF-End frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[9].header.GetDuration (), Seconds (0), "Duration/ID must be set to 0 for CF-End frames"); // the CF-End frame resets the NAV on STA1, which can now transmit tEnd = m_txPsdus[9].txStart + m_txPsdus[9].txDuration; tStart = m_txPsdus[10].txStart; NS_TEST_EXPECT_MSG_GT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot, "Less than AIFS elapsed between two TXOPs"); NS_TEST_EXPECT_MSG_LT_OR_EQ (tStart - tEnd, sifs + m_aifsn * slot + m_cwMin * slot + tolerance, "More than AIFS+BO elapsed between two TXOPs"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[10].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[10].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a frame sent by the first station to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[10].header.GetDuration (), RoundDurationId (m_txopLimit - m_txPsdus[10].txDuration), "Duration/ID of the frame sent by the first station does not cover the remaining TXOP"); // a Normal Ack is then sent by the AP tEnd = m_txPsdus[10].txStart + m_txPsdus[10].txDuration; tStart = m_txPsdus[11].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[11].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[11].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the first station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[11].header.GetDuration (), RoundDurationId (m_txPsdus[10].header.GetDuration () - sifs - m_txPsdus[11].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // the TXOP limit is such that enough time for sending a CF-End frame remains tEnd = m_txPsdus[11].txStart + m_txPsdus[11].txDuration; tStart = m_txPsdus[12].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "CF-End sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "CF-End sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[12].header.IsCfEnd (), true, "Expected a CF-End frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[12].header.GetDuration (), Seconds (0), "Duration/ID must be set to 0 for CF-End frames"); /* * Verify that the Duration/ID of RTS/CTS frames is set correctly, that the TXOP holder is * kept and allows stations to ignore NAV properly and that the CF-End Frame is not sent if * not enough time remains * * |---------------------------------------------NAV---------------------------------->| * | |-----------------------------------------NAV------------------------------->| * | | |-------------------------------------NAV---------------------------->| * | | | |---------------------------------NAV------------------------->| * | | | | |-----------------------------NAV---------------------->| * | | | | | |-------------------------NAV------------------->| * | | | | | | |---------------------NAV---------------->| * | | | | | | | |-----------------NAV------------->| * | | | | | | | | |-------------NAV---------->| * | | | | | | | | | |---------NAV------->| * | | | | | | | | | | |-----NAV---->| * | | | | | | | | | | | |-NAV->| * |---| |---| |---| |---| |---| |---| |---| |---| |---| |---| |---| |---| * |RTS| |CTS| |QoS| |Ack| |RTS| |CTS| |QoS| |Ack| |RTS| |CTS| |QoS| |Ack| * ---------------------------------------------------------------------------------------------------- * From: AP STA1 AP STA1 AP STA2 AP STA2 AP STA3 AP STA3 * To: STA1 AP STA1 AP STA2 AP STA2 AP STA3 AP STA3 AP */ // the first frame is an RTS frame sent by the AP to STA1 txopStart = m_txPsdus[13].txStart; NS_TEST_EXPECT_MSG_EQ (m_txPsdus[13].header.IsRts (), true, "Expected an RTS frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[13].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (0))->GetMac ()->GetAddress (), "Expected an RTS frame sent by the AP to the first station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[13].header.GetDuration (), RoundDurationId (m_txopLimit - m_txPsdus[13].txDuration), "Duration/ID of the first RTS frame must cover the whole TXOP"); // a CTS is sent by STA1 tEnd = m_txPsdus[13].txStart + m_txPsdus[13].txDuration; tStart = m_txPsdus[14].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "CTS in response to the first RTS frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "CTS in response to the first RTS frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[14].header.IsCts (), true, "Expected a CTS"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[14].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a CTS frame sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[14].header.GetDuration (), RoundDurationId (m_txPsdus[13].header.GetDuration () - sifs - m_txPsdus[14].txDuration), "Duration/ID of the CTS frame must be derived from that of the RTS frame"); // the AP sends a frame to STA1 tEnd = m_txPsdus[14].txStart + m_txPsdus[14].txDuration; tStart = m_txPsdus[15].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "First QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "First QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[15].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[15].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (0))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the first station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[15].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[15].txStart - txopStart) - m_txPsdus[15].txDuration), "Duration/ID of the first QoS data frame does not cover the remaining TXOP"); // a Normal Ack is then sent by STA1 tEnd = m_txPsdus[15].txStart + m_txPsdus[15].txDuration; tStart = m_txPsdus[16].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the first QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the first QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[16].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[16].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[16].header.GetDuration (), RoundDurationId (m_txPsdus[15].header.GetDuration () - sifs - m_txPsdus[16].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // An RTS frame is sent by the AP to STA2 tEnd = m_txPsdus[16].txStart + m_txPsdus[16].txDuration; tStart = m_txPsdus[17].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Second RTS frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Second RTS frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[17].header.IsRts (), true, "Expected an RTS frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[17].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (1))->GetMac ()->GetAddress (), "Expected an RTS frame sent by the AP to the second station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[17].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[17].txStart - txopStart) - m_txPsdus[17].txDuration), "Duration/ID of the second RTS frame must cover the whole TXOP"); // a CTS is sent by STA2 (which ignores the NAV) tEnd = m_txPsdus[17].txStart + m_txPsdus[17].txDuration; tStart = m_txPsdus[18].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "CTS in response to the second RTS frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "CTS in response to the second RTS frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[18].header.IsCts (), true, "Expected a CTS"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[18].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a CTS frame sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[18].header.GetDuration (), RoundDurationId (m_txPsdus[17].header.GetDuration () - sifs - m_txPsdus[18].txDuration), "Duration/ID of the CTS frame must be derived from that of the RTS frame"); // the AP sends a frame to STA2 tEnd = m_txPsdus[18].txStart + m_txPsdus[18].txDuration; tStart = m_txPsdus[19].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Second QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Second QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[19].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[19].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (1))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the second station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[19].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[19].txStart - txopStart) - m_txPsdus[19].txDuration), "Duration/ID of the second QoS data frame does not cover the remaining TXOP"); // a Normal Ack is then sent by STA2 tEnd = m_txPsdus[19].txStart + m_txPsdus[19].txDuration; tStart = m_txPsdus[20].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the second QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the second QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[20].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[20].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[20].header.GetDuration (), RoundDurationId (m_txPsdus[19].header.GetDuration () - sifs - m_txPsdus[20].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // An RTS frame is sent by the AP to STA3 tEnd = m_txPsdus[20].txStart + m_txPsdus[20].txDuration; tStart = m_txPsdus[21].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Third RTS frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Third RTS frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[21].header.IsRts (), true, "Expected an RTS frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[21].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (2))->GetMac ()->GetAddress (), "Expected an RTS frame sent by the AP to the third station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[21].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[21].txStart - txopStart) - m_txPsdus[21].txDuration), "Duration/ID of the third RTS frame must cover the whole TXOP"); // a CTS is sent by STA3 (which ignores the NAV) tEnd = m_txPsdus[21].txStart + m_txPsdus[21].txDuration; tStart = m_txPsdus[22].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "CTS in response to the third RTS frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "CTS in response to the third RTS frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[22].header.IsCts (), true, "Expected a CTS"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[22].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a CTS frame sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[22].header.GetDuration (), RoundDurationId (m_txPsdus[21].header.GetDuration () - sifs - m_txPsdus[22].txDuration), "Duration/ID of the CTS frame must be derived from that of the RTS frame"); // the AP sends a frame to STA3 tEnd = m_txPsdus[22].txStart + m_txPsdus[22].txDuration; tStart = m_txPsdus[23].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Third QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Third QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[23].header.IsQosData (), true, "Expected a QoS data frame"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[23].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_staDevices.Get (2))->GetMac ()->GetAddress (), "Expected a frame sent by the AP to the third station"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[23].header.GetDuration (), RoundDurationId (m_txopLimit - (m_txPsdus[23].txStart - txopStart) - m_txPsdus[23].txDuration), "Duration/ID of the third QoS data frame does not cover the remaining TXOP"); // a Normal Ack is then sent by STA3 tEnd = m_txPsdus[23].txStart + m_txPsdus[23].txDuration; tStart = m_txPsdus[24].txStart; NS_TEST_EXPECT_MSG_LT (tEnd + sifs, tStart, "Ack in response to the third QoS data frame sent too early"); NS_TEST_EXPECT_MSG_LT (tStart, tEnd + sifs + tolerance, "Ack in response to the third QoS data frame sent too late"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[24].header.IsAck (), true, "Expected a Normal Ack"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[24].header.GetAddr1 (), DynamicCast<WifiNetDevice> (m_apDevices.Get (0))->GetMac ()->GetAddress (), "Expected a Normal Ack sent to the AP"); NS_TEST_EXPECT_MSG_EQ (m_txPsdus[24].header.GetDuration (), RoundDurationId (m_txPsdus[23].header.GetDuration () - sifs - m_txPsdus[24].txDuration), "Duration/ID of the Ack must be derived from that of the previous frame"); // there is no time remaining for sending a CF-End frame. This is verified by checking // that 25 frames are transmitted (done at the beginning of this method) // 3 DL packets (without RTS/CTS), 1 UL packet and 3 DL packets (with RTS/CTS) NS_TEST_EXPECT_MSG_EQ (m_received, 7, "Unexpected number of packets received"); } /** * \ingroup wifi-test * \ingroup tests * * \brief wifi TXOP Test Suite */ class WifiTxopTestSuite : public TestSuite { public: WifiTxopTestSuite (); }; WifiTxopTestSuite::WifiTxopTestSuite () : TestSuite ("wifi-txop", UNIT) { AddTestCase (new WifiTxopTest (true), TestCase::QUICK); AddTestCase (new WifiTxopTest (false), TestCase::QUICK); } static WifiTxopTestSuite g_wifiTxopTestSuite; ///< the test suite
51.894737
120
0.619181
usi-systems
0a7c87e7d11a71320cbe4e5104f756505a98d13e
3,446
cpp
C++
src/lib/Components/WindowSizeComponent.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Components/WindowSizeComponent.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Components/WindowSizeComponent.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #include <QSizeF> #include <QPainter> #include <QVariant> #include <QStyleOptionGraphicsItem> #include "CSI.h" #include "StandardDataTypes.h" #include "StandardComponents.h" #include "Components/BasicComponentDrawData.h" #include "Components/WindowSizeComponent.h" namespace BOI { BOI_BEGIN_RECEIVERS(WindowSizeComponent) BOI_END_RECEIVERS(WindowSizeComponent) BOI_BEGIN_EMITTERS(WindowSizeComponent) BOI_DECLARE_EMITTER("{8d001b1b-c057-44c8-a4a6-aab8e9da1916}") BOI_DECLARE_EMITTER("{24a74700-21ae-4e99-8e95-366901620655}") BOI_DECLARE_EMITTER("{64078be7-c9eb-4851-bf29-5f2484a81401}") BOI_END_EMITTERS(WindowSizeComponent) BOI_BEGIN_FUNCSETS(WindowSizeComponent) BOI_END_FUNCSETS(WindowSizeComponent) BOI_BEGIN_CALLERS(WindowSizeComponent) BOI_END_CALLERS(WindowSizeComponent) WindowSizeComponent::WindowSizeComponent(const BasicComponentDrawData* pDrawData) : Component(BOI_STD_C(WindowSize)), m_sizeRef(), m_widthRef(), m_heightRef(), m_pDrawData(pDrawData) { } bool WindowSizeComponent::Initialize() { m_sizeRef = SI()->NewData(BOI_STD_D(Size)); m_widthRef = SI()->NewData(BOI_STD_D(Float)); m_heightRef = SI()->NewData(BOI_STD_D(Float)); QVariant value; SI()->RegisterStateListener(StateId_WindowSize, this, value); SetSize(value.toSizeF()); SetBoundingRect(m_pDrawData->BoundingRect()); return true; } void WindowSizeComponent::Destroy() { SI()->UnregisterStateListener(StateId_WindowSize, this); } void WindowSizeComponent::HandleStateChanged(StateId stateId, DRef& dref) { Q_UNUSED(stateId); const QSizeF* pSize = dref.GetReadInstance<QSizeF>(); SetSize(*pSize); } void WindowSizeComponent::HandleEmitterConnected(int emitter, int componentId) { Q_UNUSED(componentId); if (EmitterHasNew(emitter)) { if (emitter == Emitter_Size) { EmitToNew(Emitter_Size, m_sizeRef); } else if (emitter == Emitter_Width) { EmitToNew(Emitter_Width, m_widthRef); } else if (emitter == Emitter_Height) { EmitToNew(Emitter_Height, m_heightRef); } } } void WindowSizeComponent::SetSize(const QSizeF& size) { qreal width = size.width(); qreal height = size.height(); QSizeF* pSize = m_sizeRef.GetWriteInstance<QSizeF>(); pSize->setWidth(width); pSize->setHeight(height); if (EmitterConnected(Emitter_Size)) { Emit(Emitter_Size, m_sizeRef); } float* pWidth = m_widthRef.GetWriteInstance<float>(); *pWidth = width; if (EmitterConnected(Emitter_Width)) { Emit(Emitter_Width, m_widthRef); } float* pHeight = m_heightRef.GetWriteInstance<float>(); *pHeight = height; if (EmitterConnected(Emitter_Height)) { Emit(Emitter_Height, m_heightRef); } } void WindowSizeComponent::Draw(QPainter* pPainter, const QStyleOptionGraphicsItem* pOption) { pPainter->drawImage(pOption->exposedRect, m_pDrawData->Image(), pOption->exposedRect); } } // namespace BOI
23.127517
81
0.680499
romoadri21
0a7f2436adc749bb8a5257f5a526be7fa5b4f3b3
9,866
cpp
C++
src/ias/test/Analysis_test.cpp
anetczuk/ImageProcessingService
d9de80b2e51c0d3ac59b7bcc7cfd7e62393cfbd4
[ "MIT" ]
null
null
null
src/ias/test/Analysis_test.cpp
anetczuk/ImageProcessingService
d9de80b2e51c0d3ac59b7bcc7cfd7e62393cfbd4
[ "MIT" ]
null
null
null
src/ias/test/Analysis_test.cpp
anetczuk/ImageProcessingService
d9de80b2e51c0d3ac59b7bcc7cfd7e62393cfbd4
[ "MIT" ]
null
null
null
/// MIT License /// /// Copyright (c) 2017 Arkadiusz Netczuk <dev.arnet@gmail.com> /// /// 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 "ias/Analysis.h" #include <boost/test/unit_test.hpp> using namespace ias; BOOST_AUTO_TEST_SUITE( AnalysisSuite ) BOOST_AUTO_TEST_CASE( loadImage_not_found ) { Analysis object; const bool loaded = object.loadImage("not_found.png"); BOOST_CHECK_EQUAL( loaded, false ); } BOOST_AUTO_TEST_CASE( loadImage_valid ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_CHECK_EQUAL( loaded, true ); } BOOST_AUTO_TEST_CASE( loadImage_corrupt ) { Analysis object; const bool loaded = object.loadImage("data/corrupt.png"); BOOST_CHECK_EQUAL( loaded, false ); } BOOST_AUTO_TEST_CASE( color_invalid ) { Analysis object; const cv::Vec3b color = object.color( 0, 0 ); BOOST_CHECK_EQUAL( color, cv::Vec3b(0, 0, 0) ); } BOOST_AUTO_TEST_CASE( color_valid ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Vec3b color1 = object.color( 45, 0 ); BOOST_CHECK_EQUAL( color1, cv::Vec3b(0, 0, 255) ); /// red const cv::Vec3b color2 = object.color( 0, 45 ); BOOST_CHECK_EQUAL( color2, cv::Vec3b(255, 255, 255) ); /// white } BOOST_AUTO_TEST_CASE( color_valid2 ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Vec3b color1 = object.color( cv::Point(0, 45) ); BOOST_CHECK_EQUAL( color1, cv::Vec3b(0, 0, 255) ); /// red const cv::Vec3b color2 = object.color( cv::Point(45, 0) ); BOOST_CHECK_EQUAL( color2, cv::Vec3b(255, 255, 255) ); /// white } BOOST_AUTO_TEST_CASE( findRegion_invalid ) { Analysis object; object.findRegion( cv::Point(0, 0), cv::Vec3b(255, 0, 0) ); const cv::Mat& region = object.result(); BOOST_CHECK_EQUAL( region.empty(), true ); } BOOST_AUTO_TEST_CASE( findRegion_valid ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Point point(0, 30); const cv::Vec3b color(0, 0, 255); object.findRegion( point, color, 20 ); const cv::Mat& region = object.result(); BOOST_REQUIRE_EQUAL( region.empty(), false ); BOOST_CHECK_EQUAL( region.channels(), 1 ); BOOST_CHECK_EQUAL( region.rows, object.image().rows ); BOOST_CHECK_EQUAL( region.cols, object.image().cols ); BOOST_CHECK_EQUAL( region.at<uchar>(0, 0), 0 ); /// green RGB(5, 249, 37) background BOOST_CHECK_EQUAL( region.at<uchar>(40, 10), 255 ); /// first red RGB(249, 37, 7) rectangle BOOST_CHECK_EQUAL( region.at<uchar>(50, 100), 0 ); /// second red rectangle } BOOST_AUTO_TEST_CASE( findRegion_valid2 ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Point point(200, 200); const cv::Vec3b color(0, 0, 255); object.findRegion( point, color, 20 ); const cv::Mat& region = object.result(); BOOST_REQUIRE_EQUAL( region.empty(), false ); BOOST_CHECK_EQUAL( region.channels(), 1 ); BOOST_CHECK_EQUAL( region.rows, object.image().rows ); BOOST_CHECK_EQUAL( region.cols, object.image().cols ); BOOST_CHECK_EQUAL( region.at<uchar>(0, 0), 0 ); /// white RGB(255, 255, 255) background BOOST_CHECK_EQUAL( region.at<uchar>(40, 10), 0 ); /// first red RGB(255, 0, 0) rectangle BOOST_CHECK_EQUAL( region.at<uchar>(220, 220), 255 ); /// second red rectangle } BOOST_AUTO_TEST_CASE( findPerimeter_invalid_image ) { Analysis object; const cv::Mat region; object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findPerimeter_empty_region ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Mat region; object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findPerimeter_region_bad_size ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Mat region( 10, 10, CV_8UC1 ); object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findPerimeter_valid ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); object.findRegion( cv::Point(0, 30), cv::Vec3b(0, 0, 255), 20 ); const cv::Mat& region = object.result(); object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_REQUIRE_EQUAL( perimeter.empty(), false ); BOOST_CHECK_EQUAL( perimeter.channels(), 1 ); BOOST_CHECK_EQUAL( perimeter.rows, object.image().rows ); BOOST_CHECK_EQUAL( perimeter.cols, object.image().cols ); BOOST_CHECK_EQUAL( perimeter.at<uchar>(0, 0), 0 ); /// green RGB(5, 249, 37) background BOOST_CHECK_EQUAL( perimeter.at<uchar>(30, 0), 255 ); /// red RGB(249, 37, 7) rectangle } BOOST_AUTO_TEST_CASE( findPerimeter_valid2 ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Point point(100, 50); const cv::Vec3b color(7, 37, 249); object.findRegion( point, color, 20 ); const cv::Mat& region = object.result(); object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_REQUIRE_EQUAL( perimeter.empty(), false ); BOOST_CHECK_EQUAL( perimeter.channels(), 1 ); BOOST_CHECK_EQUAL( perimeter.rows, object.image().rows ); BOOST_CHECK_EQUAL( perimeter.cols, object.image().cols ); BOOST_CHECK_EQUAL( perimeter.at<uchar>(0, 0), 0 ); /// green RGB(5, 249, 37) background BOOST_CHECK_EQUAL( perimeter.at<uchar>(30, 0), 0 ); /// red RGB(249, 37, 7) rectangle } BOOST_AUTO_TEST_CASE( findSmoothPerimeter_invalid_image ) { Analysis object; const cv::Mat region; object.findSmoothPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findSmoothPerimeter_empty_region ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Mat region; object.findSmoothPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findSmoothPerimeter_region_bad_size ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); const cv::Mat region( 10, 10, CV_8UC1 ); object.findSmoothPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_CHECK_EQUAL( perimeter.empty(), true ); } BOOST_AUTO_TEST_CASE( findSmoothPerimeter_valid ) { Analysis object; const bool loaded = object.loadImage("data/test1.png"); BOOST_REQUIRE_EQUAL( loaded, true ); object.findRegion( cv::Point(0, 30), cv::Vec3b(7, 37, 249), 20 ); const cv::Mat& region = object.result(); object.findPerimeter( region ); const cv::Mat& perimeter = object.result(); BOOST_REQUIRE_EQUAL( perimeter.empty(), false ); // BOOST_CHECK_EQUAL( perimeter.channels(), 1 ); // BOOST_CHECK_EQUAL( perimeter.rows, object.image().rows ); // BOOST_CHECK_EQUAL( perimeter.cols, object.image().cols ); // // BOOST_CHECK_EQUAL( perimeter.at<uchar>(0, 0), 0 ); /// green RGB(5, 249, 37) background // BOOST_CHECK_EQUAL( perimeter.at<uchar>(30, 0), 255 ); /// red RGB(249, 37, 7) rectangle } BOOST_AUTO_TEST_SUITE_END()
35.746377
107
0.632982
anetczuk
0a7f7ff9084c32cdaa857adcc6691c16a32536c0
610
cpp
C++
examples/example_device/renderer/Raycast.cpp
Twinklebear/ANARI-SDK
d40eef6a8fb3bab65991f0ec1a347d7fcf7579e1
[ "Apache-2.0" ]
49
2021-11-02T13:05:57.000Z
2022-03-28T05:50:38.000Z
examples/example_device/renderer/Raycast.cpp
Twinklebear/ANARI-SDK
d40eef6a8fb3bab65991f0ec1a347d7fcf7579e1
[ "Apache-2.0" ]
25
2021-11-02T14:24:13.000Z
2022-03-28T13:40:57.000Z
examples/example_device/renderer/Raycast.cpp
Twinklebear/ANARI-SDK
d40eef6a8fb3bab65991f0ec1a347d7fcf7579e1
[ "Apache-2.0" ]
14
2021-11-02T14:19:35.000Z
2022-03-25T17:38:35.000Z
// Copyright 2021 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "Raycast.h" namespace anari { namespace example_device { RenderedSample Raycast::renderSample(Ray ray, const World &world) const { if (auto hit = closestHit(ray, world); hitGeometry(hit)) { GeometryInfo &info = getGeometryInfo(hit); vec3 color(info.color.x, info.color.y, info.color.z); if (info.material) color *= info.material->diffuse(); return {vec4(dot(info.normal, -ray.dir) * color, 1.f), hit->t.lower}; } else return m_bgColor; } } // namespace example_device } // namespace anari
23.461538
73
0.690164
Twinklebear
0a80ebb0bb5304e3df3e3c402222019b356db874
487
cpp
C++
ReverseAnArray/main.cpp
KhunJahad/Arrays
644e64fe2e88a4817afe1ce482e93f8876b85c6a
[ "MIT" ]
null
null
null
ReverseAnArray/main.cpp
KhunJahad/Arrays
644e64fe2e88a4817afe1ce482e93f8876b85c6a
[ "MIT" ]
null
null
null
ReverseAnArray/main.cpp
KhunJahad/Arrays
644e64fe2e88a4817afe1ce482e93f8876b85c6a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; void read_input(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif } int main(){ read_input(); int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int i=0; int j=n-1; while(i<j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; } for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } return 0; }
12.815789
35
0.527721
KhunJahad
0a82694de78ddc786187310c17ce3f7d0f5b6a0c
4,386
cpp
C++
Engine/Misc/Sources/Reflection/Archiver.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
1
2018-05-02T10:40:26.000Z
2018-05-02T10:40:26.000Z
Engine/Misc/Sources/Reflection/Archiver.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
9
2018-03-26T10:22:07.000Z
2018-05-22T20:43:14.000Z
Engine/Misc/Sources/Reflection/Archiver.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
6
2018-04-15T16:03:32.000Z
2018-05-21T22:02:49.000Z
#include "Archiver.hpp" #include "boost/property_tree/ptree.hpp" #include "boost/property_tree/json_parser.hpp" #include <iostream> namespace pt = boost::property_tree; #define CAUGORY_PREFIX '@' bool IsCategory(const std::string& str) { if (str.length()) { return str[0] == CAUGORY_PREFIX; } throw std::runtime_error("enpty name is inawalible"); } bool IsPlane(const std::string& str) { if (str.length()) { return *str. begin() != '{' || *++str.rbegin() != '}'; } throw std::runtime_error("enpty name is inawalible"); } std::string ShieldCategory(const std::string name) { return CAUGORY_PREFIX + name; } std::string UnshieldCategory(const std::string name) { return name.substr(1); } /** fillin the archive */ void ConstructTree(Archiver& ar, pt::ptree& tree, std::string prefix) { for (auto& val : tree) { auto& name = val.first; auto& subtree = val.second; if (IsCategory(name)) { auto freeName = UnshieldCategory(name); auto next = prefix + '.' + freeName; ConstructTree(ar, subtree, next); } else if (!subtree.empty()) { std::string s; std::stringstream ss(s); pt::write_json(ss, subtree); ar[prefix][name] = ss.str(); } else { ar[prefix][name] = subtree.get_value<std::string>(); } } } /** Contruct a ptree on base of the node */ pt::ptree ArchiveTree(Archiver::Node& node) { pt::ptree tree; for (auto& pair : node.category.params) { auto& member = pair.first; auto& value = pair.second; if (IsPlane(value)) { tree.add(member, value); } else { std::stringstream ss(value); pt::ptree subtree; pt::read_json(ss, subtree); tree.add_child(member, subtree); } } for (auto& child : node.children) { auto& name = ShieldCategory(child->name); auto subtree = ArchiveTree(*child.get()); tree.add_child(name, subtree); } return tree; } /****************************************************************************** * Archiver ******************************************************************************/ Archiver::Archiver() : root(*this, "") {} void Archiver::Constract(const std::string& json) { std::stringstream ss(json); pt::ptree tree; pt::read_json(ss, tree); ConstructTree(*this, tree, ""); // to avoid double assign exceptions members.clear(); } std::string Archiver::Archive() { auto tree = ArchiveTree(root); std::string s; std::stringstream ss(s); pt::write_json(ss, tree); return ss.str(); } Archiver::Category& Archiver::operator[](std::string category) { return GetCategory(category); } bool Archiver::RegisterMember(const std::string& member) { if (!members.count(member)) { members.emplace(member); return true; } else return false; } Archiver::Category& Archiver::GetCategory(const std::string& name) { auto tokens = GetTokens(name); Node* node = &root; for (auto& token : tokens) { if (token != "") { node = &node->GetOrCreate(token); } } return node->category; } std::vector<std::string> Archiver::GetTokens(const std::string& name) { std::vector<std::string> tokens; std::stringstream ss(name); std::string s; while (std::getline(ss, s, '.')) { tokens.emplace_back(s); } return tokens; } /****************************************************************************** * Category ******************************************************************************/ Archiver::Category::Category(Archiver& owner) : owner(owner) {} std::string& Archiver::Category::operator[](std::string member) { if (!owner.RegisterMember(member)) { throw std::runtime_error("The parametr already contains"); } return params[member]; } /****************************************************************************** * Node ******************************************************************************/ Archiver::Node::Node(Archiver& owner, const std::string& name) : category(owner) , owner (owner) , name (name) {} Archiver::Node& Archiver::Node::GetOrCreate(const std::string& subCategory) { auto itr = children.begin(); auto end = children.end(); auto pos = std::find_if(itr, end, [&subCategory](auto& ptr) { return ptr->name == subCategory; }); if (pos == end) { auto ptr = std::make_unique<Node>(owner, subCategory); auto raw = ptr.get(); children.emplace_back(std::move(ptr)); return *raw; } else return *pos->get(); }
19.321586
79
0.581167
kaluginadaria
0a82acaa5ff8e88df5a421e4c3718cb2a14054e3
606
cpp
C++
src/parser/statement/insert_statement.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
1
2022-02-07T14:37:01.000Z
2022-02-07T14:37:01.000Z
src/parser/statement/insert_statement.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
1
2021-12-23T10:01:18.000Z
2021-12-23T10:01:18.000Z
src/parser/statement/insert_statement.cpp
AldoMyrtaj/duckdb
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
[ "MIT" ]
null
null
null
#include "duckdb/parser/statement/insert_statement.hpp" namespace duckdb { InsertStatement::InsertStatement() : SQLStatement(StatementType::INSERT_STATEMENT), schema(DEFAULT_SCHEMA) { } InsertStatement::InsertStatement(const InsertStatement &other) : SQLStatement(other), select_statement(unique_ptr_cast<SQLStatement, SelectStatement>(other.select_statement->Copy())), columns(other.columns), table(other.table), schema(other.schema) { } unique_ptr<SQLStatement> InsertStatement::Copy() const { return unique_ptr<InsertStatement>(new InsertStatement(*this)); } } // namespace duckdb
31.894737
108
0.780528
AldoMyrtaj
0a8326a7dbeff6e00485ef6152f1a0f4098d6228
7,211
cpp
C++
src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_15_banking.cpp
tud-ccc/savina
914be6292f379a119751a8b5a38e35e6a99de69d
[ "MIT" ]
null
null
null
src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_15_banking.cpp
tud-ccc/savina
914be6292f379a119751a8b5a38e35e6a99de69d
[ "MIT" ]
1
2022-02-06T17:40:09.000Z
2022-02-10T22:48:19.000Z
src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_15_banking.cpp
tud-ccc/savina
914be6292f379a119751a8b5a38e35e6a99de69d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <limits> #include <fstream> #include "benchmark_runner.hpp" #include "pseudo_random.hpp" using namespace std; using std::chrono::seconds; using namespace caf; class config : public actor_system_config { public: int a = 1000; int n = 50000; static double initial_balance; config() { opt_group{custom_options_, "global"} .add(a, "aaa,a", "number of accounts") .add(n, "nnn,n", "number of transactions"); } void initalize() const { initial_balance = ((numeric_limits<double>::max() / (a * n)) / 1000) * 1000; } }; double config::initial_balance = 0; using start_msg_atom = atom_constant<atom("start")>; using stop_msg_atom = atom_constant<atom("stop")>; using reply_msg_atom = atom_constant<atom("reply")>; struct debit_msg { actor sender; double amount; }; CAF_ALLOW_UNSAFE_MESSAGE_TYPE(debit_msg); struct credit_msg { actor sender; double amount; actor recipient; }; CAF_ALLOW_UNSAFE_MESSAGE_TYPE(credit_msg); #ifdef REQUEST_AWAIT struct account_state { double balance; }; behavior account(stateful_actor<account_state>* self, int /*id*/, double balance_) { auto& s = self->state; s.balance = balance_; return { [=](debit_msg& dm) { self->state.balance += dm.amount; return reply_msg_atom::value; }, [=](credit_msg& cm) { auto& s = self->state; s.balance -= cm.amount; auto& dest_account = cm.recipient; auto sender = actor_cast<actor>(self->current_sender()); #ifdef INFINITE self->request(dest_account, infinite, debit_msg{actor_cast<actor>(self), cm.amount}).await( #elif HIGH_TIMEOUT self->request(dest_account, seconds(6000), debit_msg{actor_cast<actor>(self), cm.amount}).await( #endif [=](reply_msg_atom) { self->send(sender, reply_msg_atom::value); }); }, [=](stop_msg_atom) { self->quit(); } }; } #elif REQUEST_THEN struct account_state { double balance; }; behavior account(stateful_actor<account_state>* self, int /*id*/, double balance_) { auto& s = self->state; s.balance = balance_; return { [=](debit_msg& dm) { self->state.balance += dm.amount; return reply_msg_atom::value; }, [=](credit_msg& cm) { auto& s = self->state; s.balance -= cm.amount; auto& dest_account = cm.recipient; auto sender = actor_cast<actor>(self->current_sender()); #ifdef INFINITE self->request(dest_account, infinite, debit_msg{actor_cast<actor>(self), cm.amount}).then( #elif HIGH_TIMEOUT self->request(dest_account, seconds(6000), debit_msg{actor_cast<actor>(self), cm.amount}).then( #endif [=](reply_msg_atom) { self->send(sender, reply_msg_atom::value); }); }, [=](stop_msg_atom) { self->quit(); } }; } #elif BECOME_UNBECOME_FAST struct account_state { double balance; behavior wait_for_result; actor sender; }; behavior account(stateful_actor<account_state>* self, int /*id*/, double balance_) { auto& s = self->state; self->set_default_handler(skip); s.balance = balance_; s.wait_for_result = { [=](reply_msg_atom) { auto& s = self->state; self->send(s.sender, reply_msg_atom::value); self->unbecome(); } }; return { [=](debit_msg& dm) { self->state.balance += dm.amount; return reply_msg_atom::value; }, [=](credit_msg& cm) { auto& s = self->state; s.balance -= cm.amount; auto& dest_account = cm.recipient; s.sender = actor_cast<actor>(self->current_sender()); self->send(dest_account, debit_msg{actor_cast<actor>(self), cm.amount}); self->become(keep_behavior, s.wait_for_result); }, [=](stop_msg_atom) { self->quit(); } }; } #elif BECOME_UNBECOME_SLOW struct account_state { double balance; }; behavior account(stateful_actor<account_state>* self, int /*id*/, double balance_) { auto& s = self->state; self->set_default_handler(skip); s.balance = balance_; return { [=](debit_msg& dm) { self->state.balance += dm.amount; return reply_msg_atom::value; }, [=](credit_msg& cm) { auto& s = self->state; s.balance -= cm.amount; auto& dest_account = cm.recipient; auto sender = actor_cast<actor>(self->current_sender()); self->send(dest_account, debit_msg{actor_cast<actor>(self), cm.amount}); self->become(keep_behavior, [=](reply_msg_atom) { self->send(sender, reply_msg_atom::value); self->unbecome(); } ); }, [=](stop_msg_atom) { self->quit(); } }; } #endif struct teller_state { vector<actor> accounts; int num_completed_banks; pseudo_random random; }; behavior teller(stateful_actor<teller_state>* self, int num_accounts, int num_bankings) { auto& s = self->state; s.accounts.reserve(num_accounts); for (int i = 0; i < num_accounts; ++i) { s.accounts.emplace_back(self->spawn(account, i, config::initial_balance)); } s.num_completed_banks = 0; s.random.set_seed(123456); auto generate_work = [=]() { auto& s = self->state; //Warning s.accounts.size() musst be 10 or higher auto src_account_id = s.random.next_int((s.accounts.size() / 10) * 8); auto loop_id = s.random.next_int(s.accounts.size() - src_account_id); if (loop_id == 0) { ++loop_id; } auto dest_account_id = src_account_id + loop_id; auto& src_account = s.accounts[src_account_id]; auto& dest_account = s.accounts[dest_account_id]; auto amount = abs(s.random.next_double()) * 1000; auto sender = actor_cast<actor>(self); auto cm = credit_msg{move(sender), amount, dest_account}; self->send(src_account, move(cm)); }; return { [=](start_msg_atom) { for (int m = 0; m < num_bankings; ++m) { generate_work(); } }, [=](reply_msg_atom) { auto& s = self->state; ++s.num_completed_banks; if (s.num_completed_banks == num_bankings) { for (auto& loop_account : s.accounts) { self->send(loop_account, stop_msg_atom::value); } self->quit(); } } }; } class bench : public benchmark { public: void print_arg_info() const override { printf(benchmark_runner::arg_output_format(), "A (num accounts)", to_string(cfg_.a).c_str()); printf(benchmark_runner::arg_output_format(), "N (num transactions)", to_string(cfg_.n).c_str()); printf(benchmark_runner::arg_output_format(), "Initial Balance", to_string(cfg_.initial_balance).c_str()); } void initialize(int argc, char** argv) override { cfg_.parse(argc, argv); } void run_iteration() override { actor_system system{cfg_}; cfg_.initalize(); auto master = system.spawn(teller, cfg_.a, cfg_.n); anon_send(master, start_msg_atom::value); } protected: const char* current_file() const override { return __FILE__; } private: config cfg_; }; int main(int argc, char** argv) { benchmark_runner br; br.run_benchmark(argc, argv, bench{}); }
26.608856
89
0.631535
tud-ccc
0a84a29252caed809898f8295a3b742c5a02e20d
3,066
cpp
C++
src/util/fileloader.cpp
JGeicke/sdl-game-engine
4a656145a9fc4f4490e61cbc87040de9f1abbb72
[ "MIT" ]
null
null
null
src/util/fileloader.cpp
JGeicke/sdl-game-engine
4a656145a9fc4f4490e61cbc87040de9f1abbb72
[ "MIT" ]
null
null
null
src/util/fileloader.cpp
JGeicke/sdl-game-engine
4a656145a9fc4f4490e61cbc87040de9f1abbb72
[ "MIT" ]
null
null
null
#include "fileloader.h" /** * @brief Loads, parses and creates the tilemap from tilemap json files created with tiled. * @param path - File path to json file. * @param layerCount - Layer count of the tilemap. * @return Created tilemap. */ Tilemap* FileLoader::loadTilemap(const char* path, size_t layerCount) { std::ifstream file; std::string s; file.open(path); if (file.is_open()) { // first argument creates iterator at the beginning of the ifstream, second argument is the default constructor which represents the end of the stream. std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); json tilemap_raw = json::parse(content); Tilemap* result = new Tilemap(tilemap_raw["tilewidth"], tilemap_raw["tileheight"], tilemap_raw["width"], tilemap_raw["height"]); for (size_t i = 0; i < layerCount; i++) { std::string layerName = tilemap_raw["layers"][i]["name"]; std::string type = tilemap_raw["layers"][i]["type"]; if ((layerName == "Collision" || layerName == "collision") && type == "objectgroup") { for (auto obj : tilemap_raw["layers"][i]["objects"]) { result->addTilemapCollider({ obj["x"].get<int>(), obj["y"].get<int>() , obj["width"].get<int>() ,obj["height"].get<int>()}); } result->setCollisionLayerIndex(i); } else if (type == "objectgroup") { // add objects for (auto obj : tilemap_raw["layers"][i]["objects"]) { result->addTilemapObject({ obj["x"].get<int>(), obj["y"].get<int>() , obj["width"].get<int>() ,obj["height"].get<int>() }); } result->setTilemapObjectLayerIndex(i); } else { // add layer result->addLayer(i, tilemap_raw["layers"][i]["data"].get<std::vector<unsigned int>>()); } } file.close(); return result; } return NULL; } /** * @brief Loads texture from given path. * @param path - File path to texture file. * @param renderer - Reference to window renderer. * @return Created texture. */ Texture FileLoader::loadTexture(const char* path, SDL_Renderer* renderer) { Texture result; // create texture SDL_Surface* tempSurface = IMG_Load(path); if (!tempSurface) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Texture IO Error", IMG_GetError(), NULL); } result.texture = SDL_CreateTextureFromSurface(renderer, tempSurface); // get width & height of texture SDL_QueryTexture(result.texture, NULL, NULL, &result.textureWidth, &result.textureHeight); // cleanup surface SDL_FreeSurface(tempSurface); return result; } /** * @brief Loads SDL_Texture from given path. * @param path - File path to texture file. * @param renderer - Reference to window renderer. * @return Pointer to created SDL_Texture. */ SDL_Texture* FileLoader::loadSDLTexture(const char* path, SDL_Renderer* renderer) { SDL_Surface* tempSurface = IMG_Load(path); if (!tempSurface) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Texture IO Error", IMG_GetError(), NULL); } SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, tempSurface); SDL_FreeSurface(tempSurface); return texture; }
33.326087
153
0.69439
JGeicke
0a860bc9020a9e68525164d8f713d2b2eb6b0e6d
10,846
cpp
C++
src/tools/json/ConfigFileParser/ConfigFileParser.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
null
null
null
src/tools/json/ConfigFileParser/ConfigFileParser.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
null
null
null
src/tools/json/ConfigFileParser/ConfigFileParser.cpp
IgVelasco/Marvel_Vs_Capcom
a714453d1cba9596c1fdc99383a0228e62334cf7
[ "MIT" ]
1
2020-05-06T23:30:36.000Z
2020-05-06T23:30:36.000Z
/* * ConfigFileParser.cpp * * Created on: 23 mar. 2019 * Author: sebastian */ #include "ConfigFileParser.h" const string DEFAULT_CONFIG_FILE_PATH = "config/config_default.json"; const string ERROR = "ERROR"; const string INFO = "INFO"; const string DEBUG = "DEBUG"; ConfigFileParser::ConfigFileParser(string path) { this->logger = Logger::getInstance(); if(!this->fileExists(path)) { this->logger->log("Usando archivo de configuración por default ubicado en '" + DEFAULT_CONFIG_FILE_PATH, INFO); this->filePath = DEFAULT_CONFIG_FILE_PATH; } else { this->logger->log("Usando archivo de configuración ubicado en '" + path + "'.", INFO); this->filePath = path; } } bool ConfigFileParser::fileExists(string path) { this->logger->log("Verificando existencia del archivo de configuración '" + path + "'.", INFO); try { ifstream i(path.c_str()); if(i.good()) { this->logger->log("El archivo '" + path + "' existe.", INFO); return true; } else { throw runtime_error("El archivo '" + path + "' no existe."); } } catch(exception& e) { this->logger->log(string(e.what()), ERROR); return false; } } void ConfigFileParser::parse() { this->logger->log("Iniciando validación del archivo de configuración.", INFO); ifstream i(this->filePath.c_str()); try { this->config = json::parse(i); } catch(exception& e) { this->logger->log(string(e.what()), ERROR); } json defaultConfig; if(this->filePath != DEFAULT_CONFIG_FILE_PATH) { ifstream i(DEFAULT_CONFIG_FILE_PATH.c_str()); defaultConfig = json::parse(i); } this->validateLogLevel(defaultConfig); this->logger->setLogLevel(this->config["log"]); this->validateBattlefield(defaultConfig); this->validateCharacters(defaultConfig); this->validateWindow(defaultConfig); this->validatePlayers(defaultConfig); } void ConfigFileParser::validateLogLevel(json defaultConfig) { this->logger->log("Validando nivel de log...", INFO); if(this->config.find("log") == this->config.end()) { this->logError("log", "Nivel de log no especificado."); this->replaceByDefault("log", defaultConfig); } if(!this->config.find("log")->is_string()) { this->logError("log", "Campo 'log' invalido. Debe ser un string."); this->replaceByDefault("log", defaultConfig); } else { string logErrorLevel = this->config["log"]; if(logErrorLevel != ERROR && logErrorLevel != INFO && logErrorLevel != DEBUG) { this->logError("log", "No existe el nivel de log especificado."); this->replaceByDefault("log", defaultConfig); } } this->logger->log("Nivel de log validado OK.", INFO); } void ConfigFileParser::validateBattlefield(json defaultConfig) { this->logger->log("Validando battlefield...", INFO); if(this->config.find("battlefield") == this->config.end()) { this->logError("battlefield", "Battlefield no especificado."); this->replaceByDefault("battlefield", defaultConfig); } else { json battlefield = this->config["battlefield"]; if(!battlefield.is_array()) { this->logError("battlefield", "Battlefield no es un array."); this->replaceByDefault("battlefield", defaultConfig); } else { if(battlefield.empty()) { this->logError("battlefield", "Battlefield está vacío."); this->replaceByDefault("battlefield", defaultConfig); } if((int) battlefield.size() != 3) { this->logError("battlefield", "Battlefield no contiene la cantidad de backgrounds necesarios. Deben ser 3."); this->replaceByDefault("battlefield", defaultConfig); } else { this->logger->log("Verificando si todos los elementos tienen el atributo 'background' y dentro de este un 'filepath'", INFO); int count = 0; for(json::iterator it = battlefield.begin(); it != battlefield.end(); ++it) { if(it->find("background") == it->end()) { this->logError("battlefield bloque " + to_string(count), "Hay un background no especificado."); this->replaceByDefault("battlefield", defaultConfig,"",count); } else { //Filepath verification if((*it)["background"].find("filepath") == (*it)["background"].end()) { this->logError("battlefield bloque " + to_string(count), "Hay un filepath no especificado."); this->replaceByDefault("battlefield", defaultConfig,"",count); } else if(! (*it)["background"].find("filepath")->is_string()) { this->logError("battlefield bloque " + to_string(count), "Uno de los campos 'filepath' no es válido. Debe ser un string."); this->replaceByDefault("battlefield", defaultConfig,"",count); } //Z Index verification else if((*it)["background"].find("zindex") == (*it)["background"].end()) { this->logError("battlefield bloque " + to_string(count), "Hay un z index no especificado."); this->replaceByDefault("battlefield", defaultConfig,"",count); } else if(! (*it)["background"].find("zindex")->is_number_unsigned()) { this->logError("battlefield bloque " + to_string(count), "Uno de los campos 'z index' no es válido. Debe ser un número positivo."); this->replaceByDefault("battlefield", defaultConfig,"",count); } } count++; } } } } this->logger->log("Battlefield validado OK.", INFO); } void ConfigFileParser::validateCharacters(json defaultConfig) { this->logger->log("Validando characters...", INFO); if(this->config.find("characters") == this->config.end()) { this->logError("characters", "Characters no especificado."); this->replaceByDefault("characters", defaultConfig); } else { json characters = this->config["characters"]; if(!characters.is_array()) { this->logError("characters", "Characters no es un array."); this->replaceByDefault("characters", defaultConfig); } else { if(characters.empty()) { this->logError("characters", "Characters está vacío."); this->replaceByDefault("characters", defaultConfig); } else { this->logger->log("Verificando si todos los elementos tienen los atributos necesarios.", INFO); int count = 0; for(json::iterator it = characters.begin(); it != characters.end(); ++it) { //Name verification if(it->find("name") == it->end()) { this->logError("characters bloque " + to_string(count), "Hay un name no especificado."); this->replaceByDefault("characters", defaultConfig,"", count); } else if(!it->find("name")->is_string()){ this->logError("characters bloque " + to_string(count), "Uno de los campos 'name' no es válido. Debe ser un string."); this->replaceByDefault("characters", defaultConfig,"",count); } //Filepath verification else if(it->find("filepath") == it->end()) { this->logError("characters bloque " + to_string(count), "Hay un filepath no especificado."); this->replaceByDefault("characters", defaultConfig,"",count); } else if(!it->find("filepath")->is_string()) { this->logError("characters bloque " + to_string(count), "Uno de los campos 'filepath' no es válido. Debe ser un string."); this->replaceByDefault("characters", defaultConfig,"",count); } //Height verification else if(it->find("height") == it->end()) { this->logError("characters bloque " + to_string(count), "Hay un height no especificado."); this->replaceByDefault("characters", defaultConfig,"",count); } else if(!it->find("height")->is_number_unsigned()) { this->logError("characters bloque " + to_string(count), "Uno de los campos 'height' no es válido. Debe ser un número positivo."); this->replaceByDefault("characters", defaultConfig,"",count); } //Width verification else if(it->find("width") == it->end()) { this->logError("characters bloque " + to_string(count), "Hay un width no especificado."); this->replaceByDefault("characters", defaultConfig,"",count); } else if(!it->find("width")->is_number_unsigned()) { this->logError("characters bloque " + to_string(count), "Uno de los campos 'width' no es válido. Debe ser un número positivo."); this->replaceByDefault("characters", defaultConfig,"",count); } //Zindex verification else if(it->find("zindex") == it->end()) { this->logError("characters bloque " + to_string(count), "Hay un zindex no especificado."); this->replaceByDefault("characters", defaultConfig,"" ,count); } else if(!it->find("zindex")->is_number_unsigned()) { this->logError("characters bloque " + to_string(count), "Uno de los campos 'zindex' no es válido. Debe ser un número positivo."); this->replaceByDefault("characters", defaultConfig,"",count); } count++; } } } } this->logger->log("Characters validado OK.", INFO); } void ConfigFileParser::validateWindow(json defaultConfig) { this->logger->log("Validando window...", INFO); if(this->config.find("window") == this->config.end()) { this->logError("window", "Window no especificado."); this->replaceByDefault("window", defaultConfig); } else { json window = this->config["window"]; if(window.find("height") == window.end()) { this->logError("window", "Height no especificado."); this->replaceByDefault("window", defaultConfig); } if(window.find("width") == window.end()) { this->logError("window", "Width no especificado."); this->replaceByDefault("window", defaultConfig); } } this->logger->log("Window validado OK.", INFO); } void ConfigFileParser::logError(string key, string errorMsg) { this->logger->log(errorMsg, ERROR); this->logger->log("Usando " + key + " por default.", ERROR); } void ConfigFileParser::replaceByDefault(string key, json defaultConfig, string subKey, int posSubKey) { if(!subKey.empty() && posSubKey < 0) { this->config[key][subKey] = defaultConfig[key][subKey]; } else if(subKey.empty() && posSubKey >= 0){ this->config[key][posSubKey] = defaultConfig[key][posSubKey]; } else { this->config[key] = defaultConfig[key]; } } json ConfigFileParser::getConfig() { return this->config; } void ConfigFileParser::validatePlayers(json defaultConfig) { this->logger->log("Validando players...", INFO); if(this->config.find("server") == this->config.end()) { this->logError("players", "Players no especificado."); this->replaceByDefault("server", defaultConfig); } else { json server = this->config["server"]; if(server.find("players") == server.end()) { this->logError("players", "Players no especificado."); this->replaceByDefault("server", defaultConfig); } else { if(!((server["players"] == 2) || (server["players"] == 4) || (server["players"] == 3))){ this->logError("players", "Players incorrecto."); this->replaceByDefault("server", defaultConfig); } } } this->logger->log("Players validado OK.", INFO); }
36.766102
138
0.658676
IgVelasco
0a90b0ddbfc888a5313fc61f340dfb9c0ca68815
306
cpp
C++
tapi-master/test/Inputs/CPP2/CPP2.cpp
JunyiXie/ld64
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
[ "Apache-2.0" ]
null
null
null
tapi-master/test/Inputs/CPP2/CPP2.cpp
JunyiXie/ld64
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
[ "Apache-2.0" ]
null
null
null
tapi-master/test/Inputs/CPP2/CPP2.cpp
JunyiXie/ld64
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
[ "Apache-2.0" ]
null
null
null
#include "Templates.h" // Templates namespace templates { template int foo1<short>(short a); template <> int foo1<>(int a) { return a; } template <class T> Foo<T>::Foo() {} template <class T> Foo<T>::~Foo() {} template <class T> Bar<T>::Bar() {} template class Bar<int>; } // end namespace templates.
19.125
43
0.650327
JunyiXie
0a912c7fd635c13e6f7172ff61e5354d513b92d7
363
cpp
C++
Checking_tool_of_pouring_machine/main.cpp
MagicXran/artistic_work
7661f2df7ab642569752e64559e5176520b89369
[ "Apache-2.0" ]
1
2022-03-02T13:57:33.000Z
2022-03-02T13:57:33.000Z
Checking_tool_of_pouring_machine/main.cpp
MagicXran/artistic_work
7661f2df7ab642569752e64559e5176520b89369
[ "Apache-2.0" ]
null
null
null
Checking_tool_of_pouring_machine/main.cpp
MagicXran/artistic_work
7661f2df7ab642569752e64559e5176520b89369
[ "Apache-2.0" ]
null
null
null
#define CONSOLE 1 #define DEBUG 0 #include "mainwindow.h" #include <QApplication> #include <cmath> #include "HellQt_Clion.h" int main(int argc , char *argv[]) { #if (CONSOLE == 1) setbuf(stdout , nullptr); #endif #if DEBUG == 0 QApplication a(argc , argv); MainWindow w; w.show(); return QApplication::exec(); #else test(); #endif }
13.961538
35
0.636364
MagicXran
0a995fa2a52abcfefcaf592e01ded35168548582
2,618
cpp
C++
src/FileWatcher/FileWatcher.cpp
MisterVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
3
2017-05-10T10:58:17.000Z
2018-10-30T09:50:26.000Z
src/FileWatcher/FileWatcher.cpp
mVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
3
2017-05-09T21:17:09.000Z
2020-02-24T14:46:22.000Z
src/FileWatcher/FileWatcher.cpp
mVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
null
null
null
#include "FileWatcher/FileWatcher.h" namespace SteelEngine { bool FileWatcher::Contains(const std::string& key) { return m_Paths.find(key) != m_Paths.end(); } void FileWatcher::UpdateRecursive() { for(auto& file : std::filesystem::recursive_directory_iterator(m_Path)) { auto currentFileLastWriteTime = std::filesystem::last_write_time(file); std::string file_ = file.path().string(); if(!Contains(file_)) { m_Paths[file_] = currentFileLastWriteTime; m_Action(file_, FileStatus::CREATED); } else if(m_Paths[file_] != currentFileLastWriteTime) { m_Paths[file_] = currentFileLastWriteTime; m_Action(file_, FileStatus::MODIFIED); } } } void FileWatcher::UpdateNonRecursive() { for(auto& file : std::filesystem::directory_iterator(m_Path)) { auto currentFileLastWriteTime = std::filesystem::last_write_time(file); std::string file_ = file.path().string(); if(!Contains(file_)) { m_Paths[file_] = currentFileLastWriteTime; m_Action(file_, FileStatus::CREATED); } else if(m_Paths[file_] != currentFileLastWriteTime) { m_Paths[file_] = currentFileLastWriteTime; m_Action(file_, FileStatus::MODIFIED); } } } FileWatcher::FileWatcher( const std::filesystem::path& path, ActionFunction action, bool recursive) : m_Path(path), m_Action(action) { m_Running = true; for(auto &file : std::filesystem::recursive_directory_iterator(path)) { m_Paths[file.path().string()] = std::filesystem::last_write_time(file); } if(recursive) { m_UpdateFunction = std::bind(&FileWatcher::UpdateRecursive, this); } else { m_UpdateFunction = std::bind(&FileWatcher::UpdateNonRecursive, this); } } FileWatcher::~FileWatcher() { } void FileWatcher::Update() { auto it = m_Paths.begin(); while(it != m_Paths.end()) { if(!std::filesystem::exists(it->first)) { m_Action(it->first, FileStatus::DELETED); it = m_Paths.erase(it); } else { it++; } } m_UpdateFunction(); } }
24.698113
83
0.524064
MisterVento3
0a99b174d41fe78dae0410c38669f9d144d3afe7
222
cpp
C++
analyzer/test/ProtobufTest.cpp
corvofeng/Niftyflow
fb8012760cf68f7fb53d5160d3cf338a5312e956
[ "MIT" ]
4
2018-05-15T08:37:32.000Z
2020-08-07T07:06:14.000Z
analyzer/test/ProtobufTest.cpp
corvofeng/Niftyflow
fb8012760cf68f7fb53d5160d3cf338a5312e956
[ "MIT" ]
2
2019-01-26T02:19:55.000Z
2019-09-12T07:22:23.000Z
analyzer/test/ProtobufTest.cpp
corvofeng/Niftyflow
fb8012760cf68f7fb53d5160d3cf338a5312e956
[ "MIT" ]
3
2018-07-12T06:06:52.000Z
2019-09-11T01:30:00.000Z
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "proto/message.pb.h" int main() { using tutorial::Person; Person john; john.set_id(1234); john.set_name("John Doe"); return 0; }
13.058824
30
0.626126
corvofeng
0a9e468ee465c90ad835dc5d7ec3889de6be90f6
548
cpp
C++
src/Core/ECEditorModule/dllmain.cpp
antont/tundra
5c9b0a3957071f08ab425dff701cdbb34f9e1868
[ "Apache-2.0" ]
null
null
null
src/Core/ECEditorModule/dllmain.cpp
antont/tundra
5c9b0a3957071f08ab425dff701cdbb34f9e1868
[ "Apache-2.0" ]
null
null
null
src/Core/ECEditorModule/dllmain.cpp
antont/tundra
5c9b0a3957071f08ab425dff701cdbb34f9e1868
[ "Apache-2.0" ]
null
null
null
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "Framework.h" #include "ECEditorModule.h" #include "SceneStructureModule.h" extern "C" { DLLEXPORT void TundraPluginMain(Framework *fw) { Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object. IModule *ecModule = new ECEditorModule(); fw->RegisterModule(ecModule); IModule *ssModule = new SceneStructureModule(); fw->RegisterModule(ssModule); } } // ~extern "C"
24.909091
104
0.733577
antont
0aa2979cf89ce86a8ecae5c278315674edbc0f8f
110,684
cpp
C++
freeswitch/src/mod/endpoints/mod_khomp/src/khomp_pvt_kxe1.cpp
gidmoth/freeswitch-image-builder
f0169671d6a4683dd4ac7226a6b38ad94640e592
[ "BSD-2-Clause" ]
null
null
null
freeswitch/src/mod/endpoints/mod_khomp/src/khomp_pvt_kxe1.cpp
gidmoth/freeswitch-image-builder
f0169671d6a4683dd4ac7226a6b38ad94640e592
[ "BSD-2-Clause" ]
null
null
null
freeswitch/src/mod/endpoints/mod_khomp/src/khomp_pvt_kxe1.cpp
gidmoth/freeswitch-image-builder
f0169671d6a4683dd4ac7226a6b38ad94640e592
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* KHOMP generic endpoint/channel library. Copyright (C) 2007-2010 Khomp Ind. & Com. The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which case the provisions of "LGPL License" are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the LGPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the LGPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the LGPL License. The LGPL header follows below: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ #include "khomp_pvt_kxe1.h" #include "lock.h" #include "logger.h" bool BoardE1::KhompPvtE1::isOK() { try { ScopedPvtLock lock(this); K3L_CHANNEL_STATUS status; if (k3lGetDeviceStatus (_target.device, _target.object + ksoChannel, &status, sizeof (status)) != ksSuccess) return false; return ((status.AddInfo == kecsFree) || (!(status.AddInfo & kecsLocalFail) && !(status.AddInfo & kecsRemoteLock))); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); } return false; } bool BoardE1::KhompPvtE1::onChannelRelease(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(E1) c")); bool ret = true; try { ScopedPvtLock lock(this); if (call()->_flags.check(Kflags::FAX_SENDING)) { DBG(FUNC, PVT_FMT(_target, "stopping fax tx")); _fax->stopFaxTX(); } else if (call()->_flags.check(Kflags::FAX_RECEIVING)) { DBG(FUNC, PVT_FMT(_target, "stopping fax rx")); _fax->stopFaxRX(); } call()->_flags.clear(Kflags::HAS_PRE_AUDIO); command(KHOMP_LOG, CM_ENABLE_CALL_ANSWER_INFO); ret = KhompPvt::onChannelRelease(e); } catch(ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "(E1) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(E1) r")); return ret; } bool BoardE1::KhompPvtE1::onCallSuccess(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(E1) c")); bool ret; try { ScopedPvtLock lock(this); ret = KhompPvt::onCallSuccess(e); if (call()->_pre_answer) { dtmfSuppression(Opt::_options._out_of_band_dtmfs()&& !call()->_flags.check(Kflags::FAX_DETECTED)); startListen(); startStream(); switch_channel_mark_pre_answered(getFSChannel()); } else { call()->_flags.set(Kflags::GEN_PBX_RING); call()->_idx_pbx_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_pbx_delay(), &Board::KhompPvt::pbxRingGen,this, TM_VAL_CALL); } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to get device: %d!)") % err.device); return false; } DBG(FUNC, PVT_FMT(_target, "(E1) r")); return ret; } bool BoardE1::KhompPvtE1::onAudioStatus(K3L_EVENT *e) { DBG(STRM, PVT_FMT(_target, "(E1) c")); try { //ScopedPvtLock lock(this); if(e->AddInfo == kmtFax) { DBG(STRM, PVT_FMT(_target, "Fax detected")); /* hadn't we did this already? */ bool already_detected = call()->_flags.check(Kflags::FAX_DETECTED); time_t time_was = call()->_call_statistics->_base_time; time_t time_now = time(NULL); bool detection_timeout = (time_now > (time_was + (time_t) (Opt::_options._fax_adjustment_timeout()))); DBG(STRM, PVT_FMT(_target, "is set? (%s) timeout? (%s)") % (already_detected ? "true" : "false") % (detection_timeout ? "true" : "false")); BEGIN_CONTEXT { ScopedPvtLock lock(this); /* already adjusted? do not adjust again. */ if (already_detected || detection_timeout) break; if (callE1()->_call_info_drop != 0 || callE1()->_call_info_report) { /* we did not detected fax yet, send answer info! */ setAnswerInfo(Board::KhompPvt::CI_FAX); if (callE1()->_call_info_drop & Board::KhompPvt::CI_FAX) { /* fastest way to force a disconnection */ command(KHOMP_LOG,CM_DISCONNECT);//,SCE_HIDE); } } if (Opt::_options._auto_fax_adjustment()) { DBG(FUNC, PVT_FMT(_target, "communication will be adjusted for fax!")); _fax->adjustForFax(); } } END_CONTEXT if (!already_detected) { ScopedPvtLock lock(this); /* adjust the flag */ call()->_flags.set(Kflags::FAX_DETECTED); } } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "unable to lock %s!") % err._msg.c_str() ); return false; } bool ret = KhompPvt::onAudioStatus(e); DBG(STRM, PVT_FMT(_target, "(E1) r")); return ret; } bool BoardE1::KhompPvtE1::onCallAnswerInfo(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(E1) c")); try { ScopedPvtLock lock(this); int info_code = -1; switch (e->AddInfo) { case kcsiCellPhoneMessageBox: info_code = CI_MESSAGE_BOX; break; case kcsiHumanAnswer: info_code = CI_HUMAN_ANSWER; break; case kcsiAnsweringMachine: info_code = CI_ANSWERING_MACHINE; break; case kcsiCarrierMessage: info_code = CI_CARRIER_MESSAGE; break; case kcsiUnknown: info_code = CI_UNKNOWN; break; default: DBG(FUNC, PVT_FMT(_target, "got an unknown call answer info '%d', ignoring...") % e->AddInfo); break; } if (info_code != -1) { if (callE1()->_call_info_report) { //TODO: HOW WE TREAT THAT // make the channel export this setAnswerInfo(info_code); } if (callE1()->_call_info_drop & info_code) { // fastest way to force a disconnection //K::util::sendCmd(pvt->boardid, pvt->objectid, CM_DISCONNECT, true, false); command(KHOMP_LOG,CM_DISCONNECT/*,SCE_HIDE ?*/); } } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(E1) r")); return true; } bool BoardE1::KhompPvtE1::onDisconnect(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(E1) c")); bool ret = true; try { ScopedPvtLock lock(this); if (call()->_flags.check(Kflags::IS_OUTGOING) || call()->_flags.check(Kflags::IS_INCOMING)) { if(Opt::_options._disconnect_delay()== 0) { DBG(FUNC, PVT_FMT(_target, "queueing disconnecting outgoing channel!")); command(KHOMP_LOG, CM_DISCONNECT); } else { callE1()->_idx_disconnect = Board::board(_target.device)->_timers.add( 1000 * Opt::_options._disconnect_delay(),&BoardE1::KhompPvtE1::delayedDisconnect,this); } } else { /* in the case of a disconnect confirm is needed and a call was not started e.g. just after a ev_seizure_start */ command(KHOMP_LOG, CM_DISCONNECT); } ret = KhompPvt::onDisconnect(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "(E1) r (unable to get device: %d!)") % err.device); return false; } DBG(FUNC,PVT_FMT(_target, "(E1) r")); return ret; } void BoardE1::KhompPvtE1::delayedDisconnect(Board::KhompPvt * pvt) { DBG(FUNC,PVT_FMT(pvt->target(), "Delayed disconnect")); try { ScopedPvtLock lock(pvt); DBG(FUNC, PVT_FMT(pvt->target(), "queueing disconnecting outgoing channel after delaying!")); pvt->command(KHOMP_LOG,CM_DISCONNECT); pvt->cleanup(CLN_HARD); } catch (...) { LOG(ERROR, PVT_FMT(pvt->target(), "r (unable to lock the pvt !)")); } } bool BoardE1::onLinkStatus(K3L_EVENT *e) { DBG(FUNC, D("Link %02d on board %02d changed") % e->AddInfo % e->DeviceId); /* Fire a custom event about this */ /* switch_event_t * event; if (switch_event_create_subclass(&event, SWITCH_EVENT_CUSTOM, KHOMP_EVENT_MAINT) == SWITCH_STATUS_SUCCESS) { //khomp_add_event_board_data(e->AddInfo, event); Board::khomp_add_event_board_data(K3LAPI::target(Globals::k3lapi, K3LAPI::target::LINK, e->DeviceId, e->AddInfo), event); switch_event_add_header(event, SWITCH_STACK_BOTTOM, "EV_LINK_STATUS", "%d", e->AddInfo); switch_event_fire(&event); } */ return true; } bool BoardE1::KhompPvtISDN::onSyncUserInformation(K3L_EVENT *e) { DBG(FUNC,PVT_FMT(_target, "Synchronizing")); if(callISDN()->_uui_extended) { KUserInformationEx * info = (KUserInformationEx *) (((char*)e) + sizeof(K3L_EVENT)); callISDN()->_uui_descriptor = (long int) info->ProtocolDescriptor; /* clean string */ callISDN()->_uui_information.clear(); if (info->UserInfoLength) { /* append to a clean string */ for (unsigned int i = 0; i < info->UserInfoLength; ++i) callISDN()->_uui_information += STG(FMT("%02hhx") % ((unsigned char) info->UserInfo[i])); } } else { KUserInformation * info = (KUserInformation *) (((char*)e) + sizeof(K3L_EVENT)); callISDN()->_uui_descriptor = info->ProtocolDescriptor; /* clean string */ callISDN()->_uui_information.clear(); if (info->UserInfoLength) { for (unsigned int i = 0; i < info->UserInfoLength; ++i) callISDN()->_uui_information += STG(FMT("%02hhx") % ((unsigned char) info->UserInfo[i])); } } return true; } bool BoardE1::KhompPvtISDN::onIsdnProgressIndicator(K3L_EVENT *e) { //TODO: Do we need return something ? try { ScopedPvtLock lock(this); switch (e->AddInfo) { case kq931pTonesMaybeAvailable: case kq931pTonesAvailable: if (!call()->_is_progress_sent) { call()->_is_progress_sent = true; //Sinaliza para o Freeswitch PROGRESS DBG(FUNC, PVT_FMT(_target, "Pre answer")); //pvt->signal_state(SWITCH_CONTROL_PROGRESS); //switch_channel_pre_answer(channel); switch_channel_mark_pre_answered(getFSChannel()); } break; case kq931pDestinationIsNonIsdn: case kq931pOriginationIsNonIsdn: case kq931pCallReturnedToIsdn: default: break; } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "No valid channel: %s") % err._msg.c_str()); return false; } return true; } bool BoardE1::KhompPvtISDN::onNewCall(K3L_EVENT *e) { DBG(FUNC,PVT_FMT(_target, "(ISDN) c")); bool isdn_reverse_charge = false; std::string isdn_reverse_charge_str; bool ret; try { callISDN()->_isdn_orig_type_of_number = Globals::k3lapi.get_param(e, "isdn_orig_type_of_number"); callISDN()->_isdn_orig_numbering_plan = Globals::k3lapi.get_param(e, "isdn_orig_numbering_plan"); callISDN()->_isdn_dest_type_of_number = Globals::k3lapi.get_param(e, "isdn_dest_type_of_number"); callISDN()->_isdn_dest_numbering_plan = Globals::k3lapi.get_param(e, "isdn_dest_numbering_plan"); callISDN()->_isdn_orig_presentation = Globals::k3lapi.get_param(e, "isdn_orig_presentation"); isdn_reverse_charge_str = Globals::k3lapi.get_param(e, "isdn_reverse_charge"); isdn_reverse_charge = Strings::toboolean(isdn_reverse_charge_str); } catch(K3LAPI::get_param_failed & err) { LOG(WARNING, PVT_FMT(_target, "maybe the parameter is not sent (%s)'") % err.name.c_str()); } catch (Strings::invalid_value & err) { LOG(ERROR, PVT_FMT(_target, "unable to get param '%s'") % err.value().c_str()); } try { ScopedPvtLock lock(this); if(session()) { bool pvt_locked = true; bool is_ok = false; DBG(FUNC, PVT_FMT(_target, "Session has not been destroyed yet, waiting for khompDestroy")); for(unsigned int sleeps = 0; sleeps < 20; sleeps++) { /* unlock our pvt struct */ if(pvt_locked) { _mutex.unlock(); pvt_locked = false; } /* wait a little while (100ms is good?) */ usleep (100000); /* re-lock pvt struct */ switch (_mutex.lock()) { case SimpleLock::ISINUSE: case SimpleLock::FAILURE: LOG(ERROR, PVT_FMT(_target, "unable to lock pvt_mutex, trying again.")); sched_yield(); continue; default: break; } pvt_locked = true; if(!session()) { is_ok = true; break; } } if(is_ok) { DBG(FUNC, PVT_FMT(_target, "Session destroyed properly")); } else { LOG(ERROR, PVT_FMT(target(), "(ISDN) r (Session was not destroyed, stopping to wait)")); return false; } } if(isdn_reverse_charge) { call()->_collect_call = true; } ret = KhompPvtE1::onNewCall(e); } catch(ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "(ISDN) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(ISDN) r")); return ret; } bool BoardE1::KhompPvtISDN::onCallSuccess(K3L_EVENT *e) { bool ret = true; try { ScopedPvtLock lock(this); if(e->AddInfo > 0) { callISDN()->_isdn_cause = e->AddInfo; setFSChannelVar("KISDNGotCause", Verbose::isdnCause((KQ931Cause)callISDN()->_isdn_cause).c_str()); } ret = KhompPvtE1::onCallSuccess(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "%s") % err._msg.c_str()); return false; } return ret; } bool BoardE1::KhompPvtISDN::onCallFail(K3L_EVENT *e) { bool ret = true; try { ScopedPvtLock lock(this); if(e->AddInfo > 0) { callISDN()->_isdn_cause = e->AddInfo; setFSChannelVar("KISDNGotCause", Verbose::isdnCause((KQ931Cause)callISDN()->_isdn_cause).c_str()); } setHangupCause(causeFromCallFail(e->AddInfo),true); ret = KhompPvtE1::onCallFail(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "%s") % err._msg.c_str()); return false; } return ret; } RingbackDefs::RingbackStType BoardE1::KhompPvtISDN::sendRingBackStatus(int rb_value) { DBG(FUNC, PVT_FMT(target(), "this is the rdsi ringback procedure")); std::string cause = (rb_value == -1 ? "" : STG(FMT("isdn_cause=\"%d\"") % rb_value)); return (command(KHOMP_LOG, CM_RINGBACK, cause.c_str()) ? RingbackDefs::RBST_SUCCESS : RingbackDefs::RBST_FAILURE); } bool BoardE1::KhompPvtISDN::sendPreAudio(int rb_value) { if(!KhompPvtE1::sendPreAudio(rb_value)) return false; DBG(FUNC,PVT_FMT(_target, "doing the ISDN pre_connect")); if (call()->_flags.check(Kflags::HAS_PRE_AUDIO)) { DBG(FUNC, PVT_FMT(target(), "already pre_connect")); return true; } else { bool result = command(KHOMP_LOG, CM_PRE_CONNECT); if (result) call()->_flags.set(Kflags::HAS_PRE_AUDIO); return result; } } bool BoardE1::KhompPvtISDN::application(ApplicationType type, switch_core_session_t * session, const char *data) { switch(type) { case USER_TRANSFER: return _transfer->userTransfer(session, data); default: return KhompPvtE1::application(type, session, data); } return true; } bool BoardE1::KhompPvtISDN::sendDtmf(std::string digit) { if(_transfer->checkUserXferUnlocked(digit)) { DBG(FUNC, PVT_FMT(target(), "started (or waiting for) an user xfer")); return true; } bool ret = KhompPvtE1::sendDtmf(callISDN()->_digits_buffer); callISDN()->_digits_buffer.clear(); return ret; } int BoardE1::KhompPvtE1::makeCall(std::string params) { if(callE1()->_call_info_drop == 0 && !callE1()->_call_info_report) { command(KHOMP_LOG, CM_DISABLE_CALL_ANSWER_INFO); } if(!_call->_orig_addr.empty()) params += STG(FMT(" orig_addr=\"%s\"") % _call->_orig_addr); int ret = KhompPvt::makeCall(params); if(ret == ksSuccess) { startListen(); } else { LOG(ERROR, PVT_FMT(target(), "Fail on make call")); } return ret; } bool BoardE1::KhompPvtE1::indicateBusyUnlocked(int cause, bool sent_signaling) { DBG(FUNC, PVT_FMT(_target, "(E1) c")); if(!KhompPvt::indicateBusyUnlocked(cause, sent_signaling)) { DBG(FUNC, PVT_FMT(_target, "(E1) r (false)")); return false; } if(call()->_flags.check(Kflags::IS_INCOMING)) { if(!call()->_flags.check(Kflags::CONNECTED) && !sent_signaling) { if(!call()->_flags.check(Kflags::HAS_PRE_AUDIO)) { int rb_value = callFailFromCause(call()->_hangup_cause); DBG(FUNC, PVT_FMT(target(), "sending the busy status")); if (sendRingBackStatus(rb_value) == RingbackDefs::RBST_UNSUPPORTED) { DBG(FUNC, PVT_FMT(target(), "falling back to audio indication!")); /* stop the line audio */ stopStream(); /* just pre connect, no ringback */ if (!sendPreAudio()) DBG(FUNC, PVT_FMT(target(), "everything else failed, just sending audio indication...")); /* be very specific about the situation. */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else { DBG(FUNC, PVT_FMT(target(), "going to play busy")); /* stop the line audio */ stopStream(); /* be very specific about the situation. */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else { /* already connected or sent signaling... */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else if(call()->_flags.check(Kflags::IS_OUTGOING)) { /* already connected or sent signaling... */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } DBG(FUNC,PVT_FMT(_target, "(E1) r")); return true; } void BoardE1::KhompPvtE1::setAnswerInfo(int answer_info) { const char * value = answerInfoToString(answer_info); if (value == NULL) { DBG(FUNC, PVT_FMT(_target, "signaled unknown call answer info '%d', using 'Unknown'...") % answer_info); value = "Unknown"; } DBG(FUNC,PVT_FMT(_target, "KCallAnswerInfo: %s") % value); try { setFSChannelVar("KCallAnswerInfo",value); } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "%s") % err._msg.c_str()); } } bool BoardE1::KhompPvtE1::setupConnection() { if(!call()->_flags.check(Kflags::IS_INCOMING) && !call()->_flags.check(Kflags::IS_OUTGOING)) { DBG(FUNC,PVT_FMT(_target, "Channel already disconnected")); return false; } /* if received some disconnect from 'drop collect call' feature of some pbx, then leave the call rock and rolling */ Board::board(_target.device)->_timers.del(callE1()->_idx_disconnect); bool fax_detected = callE1()->_flags.check(Kflags::FAX_DETECTED) || (callE1()->_var_fax_adjust == T_TRUE); bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN || fax_detected ? Opt::_options._suppression_delay()&& Opt::_options._out_of_band_dtmfs()&& !fax_detected : (call()->_var_dtmf_state == T_TRUE)); bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN || fax_detected ? Opt::_options._echo_canceller()&& !fax_detected : (call()->_var_echo_state == T_TRUE)); bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN || fax_detected ? Opt::_options._auto_gain_control()&& !fax_detected : (call()->_var_gain_state == T_TRUE)); if (!call()->_flags.check(Kflags::REALLY_CONNECTED)) { obtainRX(res_out_of_band_dtmf); /* esvazia buffers de leitura/escrita */ cleanupBuffers(); if (!call()->_flags.check(Kflags::KEEP_DTMF_SUPPRESSION)) dtmfSuppression(res_out_of_band_dtmf); if (!call()->_flags.check(Kflags::KEEP_ECHO_CANCELLATION)) echoCancellation(res_echo_cancellator); if (!call()->_flags.check(Kflags::KEEP_AUTO_GAIN_CONTROL)) autoGainControl(res_auto_gain_cntrol); startListen(false); startStream(); DBG(FUNC, PVT_FMT(_target, "(E1) Audio callbacks initialized successfully")); } return Board::KhompPvt::setupConnection(); } bool BoardE1::KhompPvtE1::application(ApplicationType type, switch_core_session_t * session, const char *data) { switch(type) { case FAX_ADJUST: return _fax->adjustForFax(); case FAX_SEND: return _fax->sendFax(session, data); case FAX_RECEIVE: return _fax->receiveFax(session, data); default: return KhompPvt::application(type, session, data); } return true; } bool BoardE1::KhompPvtE1::validContexts( MatchExtension::ContextListType & contexts, std::string extra_context) { DBG(FUNC,PVT_FMT(_target, "(E1) c")); if(!_group_context.empty()) { contexts.push_back(_group_context); } contexts.push_back(Opt::_options._context_digital()); for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++) { replaceTemplate((*i), "LL", ((_target.object)/30)); replaceTemplate((*i), "CCC", _target.object); } bool ret = Board::KhompPvt::validContexts(contexts,extra_context); DBG(FUNC,PVT_FMT(_target, "(E1) r")); return ret; } int BoardE1::KhompPvtISDN::makeCall(std::string params) { DBG(FUNC,PVT_FMT(_target, "(ISDN) c")); CallISDN * call = callISDN(); if(call->_uui_descriptor != -1) { DBG(FUNC,PVT_FMT(_target, "got userinfo")); /* grab this information first, avoiding latter side-effects */ const bool info_extd = call->_uui_extended; const long int info_desc = call->_uui_descriptor; const std::string info_data = call->_uui_information.c_str(); const size_t info_size = std::min<size_t>(call->_uui_information.size(), (info_extd ? KMAX_USER_USER_EX_LEN : KMAX_USER_USER_LEN) << 1) >> 1; bool res = true; if(info_extd) { KUserInformationEx info; info.ProtocolDescriptor = info_desc; info.UserInfoLength = info_size; for (unsigned int pos = 0u, index = 0u; pos < info_size; index+=2, ++pos) info.UserInfo[pos] = (unsigned char)Strings::toulong(info_data.substr(index,2), 16); if (!command(KHOMP_LOG, CM_USER_INFORMATION_EX, (const char *) &info)) { LOG(ERROR,PVT_FMT(_target, "UUI could not be sent before dialing!")); } } else { KUserInformation info; info.ProtocolDescriptor = info_desc; info.UserInfoLength = info_size; for (unsigned int pos = 0u, index = 0u; pos < info_size; index+=2, ++pos) info.UserInfo[pos] = (unsigned char)Strings::toulong(info_data.substr(index,2), 16); if (!command(KHOMP_LOG, CM_USER_INFORMATION, (const char *) &info)) { LOG(ERROR,PVT_FMT(_target, "UUI could not be sent before dialing!")); } } call->_uui_extended = false; call->_uui_descriptor = -1; call->_uui_information.clear(); } if (!callISDN()->_isdn_orig_type_of_number.empty()) { params += "isdn_orig_type_of_number=\""; params += callISDN()->_isdn_orig_type_of_number; params += "\" "; } if (!callISDN()->_isdn_dest_type_of_number.empty()) { params += "isdn_dest_type_of_number=\""; params += callISDN()->_isdn_dest_type_of_number; params += "\" "; } if (!callISDN()->_isdn_orig_numbering_plan.empty()) { params += "isdn_orig_numbering_plan=\""; params += callISDN()->_isdn_orig_numbering_plan; params += "\" "; } if (!callISDN()->_isdn_dest_numbering_plan.empty()) { params += "isdn_dest_numbering_plan=\""; params += callISDN()->_isdn_dest_numbering_plan; params += "\" "; } if (!callISDN()->_isdn_orig_presentation.empty()) { params += "isdn_orig_presentation=\""; params += callISDN()->_isdn_orig_presentation; params += "\" "; } int ret = KhompPvtE1::makeCall(params); call->_cleanup_upon_hangup = (ret == ksInvalidParams || ret == ksBusy); DBG(FUNC,PVT_FMT(_target, "(ISDN) r")); return ret; } void BoardE1::KhompPvtISDN::reportFailToReceive(int fail_code) { KhompPvt::reportFailToReceive(fail_code); if(fail_code != -1) { DBG(FUNC,PVT_FMT(_target, "sending a 'unknown number' message/audio")); if(sendRingBackStatus(fail_code) == RingbackDefs::RBST_UNSUPPORTED) { sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } else { DBG(FUNC, PVT_FMT(_target, "sending fast busy audio directly")); sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } bool BoardE1::KhompPvtISDN::doChannelAnswer(CommandRequest &cmd) { bool ret = true; try { ScopedPvtLock lock(this); // is this a collect call? bool has_recv_collect_call = _call->_collect_call; if(has_recv_collect_call) DBG(FUNC, PVT_FMT(target(), "receive a collect call")); if(call()->_flags.check(Kflags::DROP_COLLECT)) DBG(FUNC, PVT_FMT(target(), "flag DROP_COLLECT == true")); // do we have to drop collect calls? bool has_drop_collect_call = call()->_flags.check(Kflags::DROP_COLLECT); // do we have to drop THIS call? bool do_drop_call = has_drop_collect_call && has_recv_collect_call; if(!do_drop_call) { command(KHOMP_LOG, CM_CONNECT); } else { usleep(75000); DBG(FUNC, PVT_FMT(target(), "disconnecting collect call doChannelAnswer ISDN")); command(KHOMP_LOG,CM_DISCONNECT); // thou shalt not talk anymore! stopListen(); stopStream(); } ret = KhompPvtE1::doChannelAnswer(cmd); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "unable to lock %s!") % err._msg.c_str() ); return false; } return ret; } int BoardE1::KhompPvtR2::makeCall(std::string params) { DBG(FUNC,PVT_FMT(_target, "(R2) c")); if (callR2()->_r2_category != -1) params += STG(FMT(" r2_categ_a=\"%ld\"") % callR2()->_r2_category); int ret = KhompPvtE1::makeCall(params); call()->_cleanup_upon_hangup = (ret == ksInvalidParams); DBG(FUNC,PVT_FMT(_target, "(R2) r")); return ret; } bool BoardE1::KhompPvtR2::doChannelAnswer(CommandRequest &cmd) { bool ret = true; try { ScopedPvtLock lock(this); // is this a collect call? bool has_recv_collect_call = _call->_collect_call; // do we have to drop collect calls? bool has_drop_collect_call = call()->_flags.check(Kflags::DROP_COLLECT); // do we have to drop THIS call? bool do_drop_call = has_drop_collect_call && has_recv_collect_call; bool do_send_ring = call()->_flags.check(Kflags::NEEDS_RINGBACK_CMD); // do we have to send ringback? yes we need !!! if(do_send_ring) { call()->_flags.clear(Kflags::NEEDS_RINGBACK_CMD); //TODO: callFailFromCause ?? std::string cause = ( do_drop_call ? STG(FMT("r2_cond_b=\"%d\"") % kgbBusy) : "" ); command(KHOMP_LOG,CM_RINGBACK,cause.c_str()); usleep(75000); } if(!do_drop_call) { command(KHOMP_LOG, CM_CONNECT); } if(!do_send_ring && has_drop_collect_call) { usleep(75000); if(has_recv_collect_call) { // thou shalt not talk anymore! stopListen(); stopStream(); if (call()->_indication == INDICA_NONE) { call()->_indication = INDICA_BUSY; mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } DBG(FUNC, PVT_FMT(_target,"forcing disconnect for collect call")); forceDisconnect(); } else { DBG(FUNC, PVT_FMT(target(), "dropping collect call at doChannelAnswer")); command(KHOMP_LOG, CM_DROP_COLLECT_CALL); } } ret = KhompPvtE1::doChannelAnswer(cmd); } catch (ScopedLockFailed & err) { LOG(ERROR,PVT_FMT(_target, "unable to lock %s!") % err._msg.c_str() ); return false; } return ret; } bool BoardE1::KhompPvtR2::doChannelHangup(CommandRequest &cmd) { DBG(FUNC, PVT_FMT(_target, "(R2) c")); bool answered = true; bool disconnected = false; try { ScopedPvtLock lock(this); if (call()->_flags.check(Kflags::IS_INCOMING)) { DBG(FUNC,PVT_FMT(_target, "disconnecting incoming channel")); //disconnected = command(KHOMP_LOG, CM_DISCONNECT); } else if (call()->_flags.check(Kflags::IS_OUTGOING)) { if(call()->_cleanup_upon_hangup) { DBG(FUNC,PVT_FMT(_target, "disconnecting not allocated outgoing channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); cleanup(KhompPvt::CLN_HARD); answered = false; } else { DBG(FUNC,PVT_FMT(_target, "disconnecting outgoing channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); } } else { DBG(FUNC,PVT_FMT(_target, "already disconnected")); return true; } if(answered) { indicateBusyUnlocked(SWITCH_CAUSE_USER_BUSY, disconnected); } if (call()->_flags.check(Kflags::IS_INCOMING) && !call()->_flags.check(Kflags::NEEDS_RINGBACK_CMD)) { DBG(FUNC,PVT_FMT(_target, "disconnecting incoming channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); } stopStream(); stopListen(); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(R2) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(R2) r")); return true; } int BoardE1::KhompPvtISDN::causeFromCallFail(int fail) { int switch_cause = SWITCH_CAUSE_USER_BUSY; if (fail <= 127) switch_cause = fail; else switch_cause = SWITCH_CAUSE_INTERWORKING; return switch_cause; } void BoardE1::KhompPvtR2::reportFailToReceive(int fail_code) { KhompPvt::reportFailToReceive(fail_code); if (Opt::_options._r2_strict_behaviour()&& fail_code != -1) { DBG(FUNC,PVT_FMT(_target, "sending a 'unknown number' message/audio")); if(sendRingBackStatus(fail_code) == RingbackDefs::RBST_UNSUPPORTED) { sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } else { DBG(FUNC, PVT_FMT(_target, "sending fast busy audio directly")); sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } int BoardE1::KhompPvtR2::causeFromCallFail(int fail) { int switch_cause = SWITCH_CAUSE_USER_BUSY; try { bool handled = false; switch (_r2_country) { case Verbose::R2_COUNTRY_ARG: switch (fail) { case kgbArBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; case kgbArNumberChanged: switch_cause = SWITCH_CAUSE_NUMBER_CHANGED; break; case kgbArCongestion: switch_cause = SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION; break; case kgbArInvalidNumber: switch_cause = SWITCH_CAUSE_UNALLOCATED_NUMBER; break; case kgbArLineOutOfOrder: switch_cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL; break; } handled = true; break; case Verbose::R2_COUNTRY_BRA: switch (fail) { case kgbBrBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; case kgbBrNumberChanged: switch_cause = SWITCH_CAUSE_NUMBER_CHANGED; break; case kgbBrCongestion: switch_cause = SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION; break; case kgbBrInvalidNumber: switch_cause = SWITCH_CAUSE_UNALLOCATED_NUMBER; break; case kgbBrLineOutOfOrder: switch_cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL; break; } handled = true; break; case Verbose::R2_COUNTRY_CHI: switch (fail) { case kgbClBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; case kgbClNumberChanged: switch_cause = SWITCH_CAUSE_NUMBER_CHANGED; break; case kgbClCongestion: switch_cause = SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION; break; case kgbClInvalidNumber: switch_cause = SWITCH_CAUSE_UNALLOCATED_NUMBER; break; case kgbClLineOutOfOrder: switch_cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL; break; } handled = true; break; case Verbose::R2_COUNTRY_MEX: switch (fail) { case kgbMxBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; } handled = true; break; case Verbose::R2_COUNTRY_URY: switch (fail) { case kgbUyBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; case kgbUyNumberChanged: switch_cause = SWITCH_CAUSE_NUMBER_CHANGED; break; case kgbUyCongestion: switch_cause = SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION; break; case kgbUyInvalidNumber: switch_cause = SWITCH_CAUSE_UNALLOCATED_NUMBER; break; case kgbUyLineOutOfOrder: switch_cause = SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL; break; } handled = true; break; case Verbose::R2_COUNTRY_VEN: switch (fail) { case kgbVeBusy: switch_cause = SWITCH_CAUSE_USER_BUSY; break; case kgbVeNumberChanged: switch_cause = SWITCH_CAUSE_NUMBER_CHANGED; break; case kgbVeCongestion: switch_cause = SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION; break; case kgbVeLineBlocked: switch_cause = SWITCH_CAUSE_OUTGOING_CALL_BARRED; break; } handled = true; break; } if (!handled) throw std::runtime_error(""); } catch (...) { LOG(ERROR, PVT_FMT(_target, "country signaling not found, unable to report R2 hangup code..")); } return switch_cause; } int BoardE1::KhompPvtR2::callFailFromCause(int cause) { int k3l_fail = -1; // default try { bool handled = false; switch (_r2_country) { case Verbose::R2_COUNTRY_ARG: switch (cause) { case SWITCH_CAUSE_UNALLOCATED_NUMBER: case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET: case SWITCH_CAUSE_NO_ROUTE_DESTINATION: case SWITCH_CAUSE_INVALID_NUMBER_FORMAT: case SWITCH_CAUSE_INVALID_GATEWAY: case SWITCH_CAUSE_INVALID_URL: case SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED: case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION: case SWITCH_CAUSE_INCOMING_CALL_BARRED: /* ?? */ case SWITCH_CAUSE_OUTGOING_CALL_BARRED: /* ?? */ k3l_fail = kgbArInvalidNumber; break; case SWITCH_CAUSE_USER_BUSY: case SWITCH_CAUSE_NO_USER_RESPONSE: case SWITCH_CAUSE_CALL_REJECTED: k3l_fail = kgbArBusy; break; case SWITCH_CAUSE_NUMBER_CHANGED: k3l_fail = kgbArNumberChanged; break; case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION: case SWITCH_CAUSE_SWITCH_CONGESTION: case SWITCH_CAUSE_NORMAL_CLEARING: case SWITCH_CAUSE_NORMAL_UNSPECIFIED: case SWITCH_CAUSE_CALL_AWARDED_DELIVERED: /* ?? */ // this preserves semantics.. k3l_fail = kgbArCongestion; break; case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL: case SWITCH_CAUSE_CHANNEL_UNACCEPTABLE: case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER: case SWITCH_CAUSE_INVALID_PROFILE: case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER: case SWITCH_CAUSE_GATEWAY_DOWN: case SWITCH_CAUSE_FACILITY_REJECTED: case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED: case SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED: default: k3l_fail = kgbArLineOutOfOrder; break; } handled = true; break; case Verbose::R2_COUNTRY_BRA: switch (cause) { case SWITCH_CAUSE_UNALLOCATED_NUMBER: case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET: case SWITCH_CAUSE_NO_ROUTE_DESTINATION: case SWITCH_CAUSE_INVALID_NUMBER_FORMAT: case SWITCH_CAUSE_INVALID_GATEWAY: case SWITCH_CAUSE_INVALID_URL: case SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED: case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION: case SWITCH_CAUSE_INCOMING_CALL_BARRED: /* ?? */ case SWITCH_CAUSE_OUTGOING_CALL_BARRED: /* ?? */ k3l_fail = kgbBrInvalidNumber; break; case SWITCH_CAUSE_USER_BUSY: case SWITCH_CAUSE_NO_USER_RESPONSE: case SWITCH_CAUSE_CALL_REJECTED: k3l_fail = kgbBrBusy; break; case SWITCH_CAUSE_NUMBER_CHANGED: k3l_fail = kgbBrNumberChanged; break; case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION: case SWITCH_CAUSE_SWITCH_CONGESTION: case SWITCH_CAUSE_NORMAL_CLEARING: case SWITCH_CAUSE_NORMAL_UNSPECIFIED: case SWITCH_CAUSE_CALL_AWARDED_DELIVERED: /* ?? */ // this preserves semantics.. k3l_fail = kgbBrCongestion; break; case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL: case SWITCH_CAUSE_CHANNEL_UNACCEPTABLE: case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER: case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER: case SWITCH_CAUSE_GATEWAY_DOWN: case SWITCH_CAUSE_FACILITY_REJECTED: case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED: case SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED: default: k3l_fail = kgbBrLineOutOfOrder; break; } handled = true; break; case Verbose::R2_COUNTRY_CHI: switch (cause) { case SWITCH_CAUSE_UNALLOCATED_NUMBER: case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET: case SWITCH_CAUSE_NO_ROUTE_DESTINATION: case SWITCH_CAUSE_INVALID_NUMBER_FORMAT: case SWITCH_CAUSE_INVALID_GATEWAY: case SWITCH_CAUSE_INVALID_URL: case SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED: case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION: case SWITCH_CAUSE_INCOMING_CALL_BARRED: /* ?? */ case SWITCH_CAUSE_OUTGOING_CALL_BARRED: /* ?? */ k3l_fail = kgbClInvalidNumber; break; case SWITCH_CAUSE_USER_BUSY: case SWITCH_CAUSE_NO_USER_RESPONSE: case SWITCH_CAUSE_CALL_REJECTED: k3l_fail = kgbClBusy; break; case SWITCH_CAUSE_NUMBER_CHANGED: k3l_fail = kgbClNumberChanged; break; case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION: case SWITCH_CAUSE_SWITCH_CONGESTION: case SWITCH_CAUSE_NORMAL_CLEARING: case SWITCH_CAUSE_NORMAL_UNSPECIFIED: case SWITCH_CAUSE_CALL_AWARDED_DELIVERED: /* ?? */ // this preserves semantics.. k3l_fail = kgbClCongestion; break; case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL: case SWITCH_CAUSE_CHANNEL_UNACCEPTABLE: case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER: case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER: case SWITCH_CAUSE_GATEWAY_DOWN: case SWITCH_CAUSE_FACILITY_REJECTED: case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED: case SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED: default: k3l_fail = kgbClLineOutOfOrder; break; } handled = true; break; case Verbose::R2_COUNTRY_MEX: k3l_fail = kgbMxBusy; handled = true; break; case Verbose::R2_COUNTRY_URY: switch (cause) { case SWITCH_CAUSE_UNALLOCATED_NUMBER: case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET: case SWITCH_CAUSE_NO_ROUTE_DESTINATION: case SWITCH_CAUSE_INVALID_NUMBER_FORMAT: case SWITCH_CAUSE_INVALID_GATEWAY: case SWITCH_CAUSE_INVALID_URL: case SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED: case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION: case SWITCH_CAUSE_INCOMING_CALL_BARRED: /* ?? */ case SWITCH_CAUSE_OUTGOING_CALL_BARRED: /* ?? */ k3l_fail = kgbUyInvalidNumber; break; case SWITCH_CAUSE_USER_BUSY: case SWITCH_CAUSE_NO_USER_RESPONSE: case SWITCH_CAUSE_CALL_REJECTED: k3l_fail = kgbUyBusy; break; case SWITCH_CAUSE_NUMBER_CHANGED: k3l_fail = kgbUyNumberChanged; break; case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION: case SWITCH_CAUSE_SWITCH_CONGESTION: case SWITCH_CAUSE_NORMAL_CLEARING: case SWITCH_CAUSE_NORMAL_UNSPECIFIED: case SWITCH_CAUSE_CALL_AWARDED_DELIVERED: /* ?? */ // this preserves semantics.. k3l_fail = kgbUyCongestion; break; case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL: case SWITCH_CAUSE_CHANNEL_UNACCEPTABLE: case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER: case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER: case SWITCH_CAUSE_GATEWAY_DOWN: case SWITCH_CAUSE_FACILITY_REJECTED: case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED: case SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED: default: k3l_fail = kgbUyLineOutOfOrder; break; } handled = true; break; case Verbose::R2_COUNTRY_VEN: switch (cause) { case SWITCH_CAUSE_INCOMING_CALL_BARRED: case SWITCH_CAUSE_OUTGOING_CALL_BARRED: k3l_fail = kgbVeLineBlocked; break; case SWITCH_CAUSE_NUMBER_CHANGED: k3l_fail = kgbVeNumberChanged; break; case SWITCH_CAUSE_NORMAL_CIRCUIT_CONGESTION: case SWITCH_CAUSE_SWITCH_CONGESTION: case SWITCH_CAUSE_NORMAL_CLEARING: case SWITCH_CAUSE_NORMAL_UNSPECIFIED: case SWITCH_CAUSE_CALL_AWARDED_DELIVERED: /* ?? */ // this preserves semantics.. k3l_fail = kgbVeCongestion; break; case SWITCH_CAUSE_UNALLOCATED_NUMBER: case SWITCH_CAUSE_NO_ROUTE_TRANSIT_NET: case SWITCH_CAUSE_NO_ROUTE_DESTINATION: case SWITCH_CAUSE_INVALID_NUMBER_FORMAT: case SWITCH_CAUSE_INVALID_GATEWAY: case SWITCH_CAUSE_INVALID_URL: case SWITCH_CAUSE_FACILITY_NOT_SUBSCRIBED: case SWITCH_CAUSE_INCOMPATIBLE_DESTINATION: case SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL: case SWITCH_CAUSE_CHANNEL_UNACCEPTABLE: case SWITCH_CAUSE_DESTINATION_OUT_OF_ORDER: case SWITCH_CAUSE_NETWORK_OUT_OF_ORDER: case SWITCH_CAUSE_GATEWAY_DOWN: case SWITCH_CAUSE_FACILITY_REJECTED: case SWITCH_CAUSE_FACILITY_NOT_IMPLEMENTED: case SWITCH_CAUSE_CHAN_NOT_IMPLEMENTED: case SWITCH_CAUSE_USER_BUSY: case SWITCH_CAUSE_NO_USER_RESPONSE: case SWITCH_CAUSE_CALL_REJECTED: default: k3l_fail = kgbVeBusy; break; } handled = true; break; } if (!handled) throw std::runtime_error(""); } catch(...) { LOG(ERROR,PVT_FMT(_target, "country signaling not found, unable to report R2 hangup code.")); } return k3l_fail; } int BoardE1::KhompPvtISDN::callFailFromCause(int cause) { int k3l_fail = -1; // default if (cause <= 127) k3l_fail = cause; else k3l_fail = kq931cInterworking; return k3l_fail; } RingbackDefs::RingbackStType BoardE1::KhompPvtR2::sendRingBackStatus(int rb_value) { DBG(FUNC,PVT_FMT(_target, "(p=%p) this is the r2 ringback procedure") % this); std::string cause = (rb_value == -1 ? "" : STG(FMT("r2_cond_b=\"%d\"") % rb_value)); return (command(KHOMP_LOG, CM_RINGBACK, cause.c_str()) ? RingbackDefs::RBST_SUCCESS : RingbackDefs::RBST_FAILURE); } bool BoardE1::KhompPvtR2::sendPreAudio(int rb_value) { DBG(FUNC,PVT_FMT(_target, "must send R2 preaudio ?")); if(!KhompPvtE1::sendPreAudio(rb_value)) return false; DBG(FUNC,PVT_FMT(_target, "doing the R2 pre_connect wait...")); /* wait some ms, just to be sure the command has been sent. */ usleep(Opt::_options._r2_preconnect_wait()* 1000); if (call()->_flags.check(Kflags::HAS_PRE_AUDIO)) { DBG(FUNC, PVT_FMT(target(), "(p=%p) already pre_connect") % this); return true; } else { bool result = command(KHOMP_LOG, CM_PRE_CONNECT); if (result) call()->_flags.set(Kflags::HAS_PRE_AUDIO); return result; } } void BoardE1::KhompPvtR2::numberDialTimer(Board::KhompPvt * pvt) { try { ScopedPvtLock lock(pvt); if (!pvt->call()->_flags.check(Kflags::NUMBER_DIAL_ONGOING) || pvt->call()->_flags.check(Kflags::NUMBER_DIAL_FINISHD)) { return; } pvt->call()->_flags.set(Kflags::NUMBER_DIAL_FINISHD); static_cast<BoardE1::KhompPvtR2*>(pvt)->callR2()->_incoming_exten.clear(); pvt->command(KHOMP_LOG, CM_END_OF_NUMBER); } catch (...) { // TODO: log something. } } bool BoardE1::KhompPvtR2::indicateRinging() { DBG(FUNC, PVT_FMT(_target, "(R2) c")); bool ret = false; try { ScopedPvtLock lock(this); /* already playing! */ if (call()->_indication != INDICA_NONE) { DBG(FUNC, PVT_FMT(_target, "(R2) r (already playing something: %d)") % call()->_indication); return false; } // any collect calls ? setCollectCall(); call()->_indication = INDICA_RING; bool send_ringback = true; if (!call()->_flags.check(Kflags::CONNECTED)) { int ringback_value = RingbackDefs::RB_SEND_DEFAULT; bool do_drop_call = Opt::_options._drop_collect_call() || call()->_flags.check(Kflags::DROP_COLLECT); if (do_drop_call && call()->_collect_call) { ringback_value = kgbBusy; DBG(FUNC, PVT_FMT(_target, "ringback value adjusted to refuse collect call: %d") % ringback_value); } const char *condition_string = getFSChannelVar("KR2SendCondition"); try { if (condition_string) { ringback_value = Strings::toulong(condition_string); DBG(FUNC, PVT_FMT(_target, "KR2SendCondition adjusted ringback value to %d") % ringback_value); } } catch (Strings::invalid_value e) { LOG(ERROR, PVT_FMT(_target, "invalid value '%s', adjusted in KR2SendCondition: not a valid number.") % condition_string); } if (Opt::_options._r2_strict_behaviour()) { /* send ringback too? */ send_ringback = sendPreAudio(ringback_value); if (!send_ringback) { /* warn the developer which may be debugging some "i do not have ringback!" issue. */ DBG(FUNC, PVT_FMT(_target, "not sending pre connection audio")); } call()->_flags.clear(Kflags::NEEDS_RINGBACK_CMD); } } if (send_ringback) { DBG(FUNC, PVT_FMT(_target, "Send ringback!")); call()->_flags.set(Kflags::GEN_CO_RING); call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_co_delay(), &Board::KhompPvt::coRingGen,this); /* start grabbing audio */ startListen(); /* start stream if it is not already */ startStream(); ret = true; } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(R2) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "(R2) r (%s)") % err._msg.c_str()); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "(R2) r (unable to get device: %d!)") % err.device); return false; } DBG(FUNC, PVT_FMT(_target, "(R2) r")); return ret; } bool BoardE1::KhompPvtR2::onNewCall(K3L_EVENT *e) { DBG(FUNC,PVT_FMT(_target, "(R2) c")); std::string r2_categ_a; int status = Globals::k3lapi.get_param(e, "r2_categ_a", r2_categ_a); try { ScopedPvtLock lock(this); if (status == ksSuccess && !r2_categ_a.empty()) { try { callR2()->_r2_category = Strings::toulong(r2_categ_a); } catch (Strings::invalid_value e) { /* do nothing */ }; /* channel will know if is a collect call or not */ if (callR2()->_r2_category == kg2CollectCall) { call()->_collect_call = true; } } bool ret = KhompPvtE1::onNewCall(e); if(!ret) return false; if (!Opt::_options._r2_strict_behaviour()) { bool do_drop_collect = Opt::_options._drop_collect_call(); const char* drop_str = getFSGlobalVar("KDropCollectCall"); if(checkTrueString(drop_str)) { do_drop_collect = true; call()->_flags.set(Kflags::DROP_COLLECT); DBG(FUNC,PVT_FMT(_target, "Setting DROP_COLLECT flag")); } freeFSGlobalVar(&drop_str); // keeping the hardcore mode if (do_drop_collect && call()->_collect_call) { // kill, kill, kill!!! DBG(FUNC,PVT_FMT(_target, "dropping collect call at onNewCall")); sendRingBackStatus(callFailFromCause(SWITCH_CAUSE_CALL_REJECTED)); usleep(75000); } else { // send ringback too! sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startStream(); } } else { _call->_flags.set(Kflags::NEEDS_RINGBACK_CMD); } } catch(ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "(R2) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC,PVT_FMT(_target, "(R2) r")); return true; } bool BoardE1::KhompPvtR2::onCallSuccess(K3L_EVENT *e) { try { ScopedPvtLock lock(this); if(e->AddInfo > 0) { callR2()->_r2_condition = e->AddInfo; setFSChannelVar("KR2GotCondition", Verbose::signGroupB((KSignGroupB)callR2()->_r2_condition).c_str()); } KhompPvtE1::onCallSuccess(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "%s") % err._msg.c_str()); return false; } return true; } bool BoardE1::KhompPvtR2::onCallFail(K3L_EVENT *e) { bool ret = true; try { ScopedPvtLock lock(this); if(e->AddInfo > 0) { callR2()->_r2_condition = e->AddInfo; setFSChannelVar("KR2GotCondition", Verbose::signGroupB((KSignGroupB)callR2()->_r2_condition).c_str()); } setHangupCause(causeFromCallFail(e->AddInfo),true); ret = KhompPvtE1::onCallFail(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR,PVT_FMT(_target, "%s") % err._msg.c_str()); return false; } return ret; } bool BoardE1::KhompPvtR2::onNumberDetected(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(digit=%d) c") % e->AddInfo); try { ScopedPvtLock lock(this); if (call()->_flags.check(Kflags::NUMBER_DIAL_FINISHD)) return false; if (!call()->_flags.check(Kflags::NUMBER_DIAL_ONGOING)) { DBG(FUNC, PVT_FMT(_target, "incoming number start...")); call()->_flags.set(Kflags::NUMBER_DIAL_ONGOING); callR2()->_incoming_exten.clear(); callR2()->_idx_number_dial = Board::board(_target.device)->_timers.add(4000, &BoardE1::KhompPvtR2::numberDialTimer, this, TM_VAL_CALL); } else { Board::board(_target.device)->_timers.restart(callR2()->_idx_number_dial); } callR2()->_incoming_exten += e->AddInfo; DBG(FUNC, PVT_FMT(_target, "incoming exten %s") % callR2()->_incoming_exten); /* begin context adjusting + processing */ MatchExtension::ContextListType contexts; validContexts(contexts); /* temporary */ std::string tmp_exten; std::string tmp_context; std::string tmp_orig(""); switch (MatchExtension::findExtension(tmp_exten, tmp_context, contexts, callR2()->_incoming_exten,tmp_orig, false, false)) { case MatchExtension::MATCH_EXACT: case MatchExtension::MATCH_NONE: call()->_flags.set(Kflags::NUMBER_DIAL_FINISHD); DBG(FUNC,FMT("incoming exten matched: %s") % callR2()->_incoming_exten); callR2()->_incoming_exten.clear(); command(KHOMP_LOG,CM_END_OF_NUMBER); break; case MatchExtension::MATCH_MORE: DBG(FUNC, "didn't match exact extension, waiting..."); // cannot say anything exact about the number, do nothing... break; } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device); return false; } return true; } bool BoardE1::KhompPvtFlash::application(ApplicationType type, switch_core_session_t * session, const char *data) { switch(type) { case USER_TRANSFER: return _transfer->userTransfer(session, data); default: return KhompPvtR2::application(type, session, data); } return true; } bool BoardE1::KhompPvtFlash::sendDtmf(std::string digit) { if(_transfer->checkUserXferUnlocked(digit)) { DBG(FUNC, PVT_FMT(target(), "started (or waiting for) an user xfer")); return true; } bool ret = KhompPvtR2::sendDtmf(callFlash()->_digits_buffer); callFlash()->_digits_buffer.clear(); return ret; } OrigToNseqMapType BoardE1::KhompPvtFXS::generateNseqMap() { OrigToNseqMapType fxs_nseq; /* sequence numbers on FXS */ fxs_nseq.insert(OrigToNseqPairType("", 0)); /* global sequence */ for (BoardToOrigMapType::iterator i = Opt::_fxs_orig_base.begin(); i != Opt::_fxs_orig_base.end(); i++) { fxs_nseq.insert(OrigToNseqPairType((*i).second, 0)); } return fxs_nseq; } void BoardE1::KhompPvtFXS::load(OrigToNseqMapType & fxs_nseq) { BoardToOrigMapType::iterator it1 = Opt::_fxs_orig_base.find(_target.device); OrigToNseqMapType::iterator it2; std::string orig_base("invalid"); /* will have orig base */ if (it1 == Opt::_fxs_orig_base.end()) { it2 = fxs_nseq.find(""); orig_base = Opt::_options._fxs_global_orig_base(); } else { it2 = fxs_nseq.find((*it1).second); orig_base = (*it1).second; } if (it2 == fxs_nseq.end()) { LOG(ERROR, PVT_FMT(_target, "could not find sequence number for FXS channel")); /* Ok, load the default options */ loadOptions(); } else { try { /* generate orig_addr, padding to the original size (adding zeros at left) */ _fxs_fisical_addr = padOrig(orig_base, (*it2).second); /* Set this branch options to get right callerid before mapping */ loadOptions(); /* makes a "reverse mapping" for Dial using 'r' identifiers */ Opt::_fxs_branch_map.insert(BranchToObjectPairType(_fxs_orig_addr, ObjectIdType(_target.device, _target.object))); /* increment sequence number */ ++((*it2).second); } catch (Strings::invalid_value e) { LOG(ERROR, PVT_FMT(_target, "expected an integer, got string '%s'") % e.value() ); } } } void BoardE1::KhompPvtFXS::loadOptions() { /* the fxs_orig_addr can be reset on parse_branch_options */ _fxs_orig_addr = _fxs_fisical_addr; /* Initialize fxs default options */ _calleridname.clear(); //_amaflags = Opt::_amaflags; _callgroup = Opt::_options._callgroup(); _pickupgroup = Opt::_options._pickupgroup(); _context.clear(); _input_volume = Opt::_options._input_volume(); _output_volume = Opt::_options._output_volume(); _mailbox.clear(); _flash = Opt::_options._flash(); BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr); if (it3 != Opt::_branch_options.end()) { parseBranchOptions(it3->second); } //TODO: Implementar o setVolume para levar em consideracao que o // padrao pode ser o da FXS if (_input_volume != Opt::_options._input_volume()) setVolume("input", _input_volume); if (_output_volume != Opt::_options._output_volume()) setVolume("output", _output_volume); } bool BoardE1::KhompPvtFXS::parseBranchOptions(std::string options_str) { Strings::vector_type options; Strings::tokenize(options_str, options, "|/"); if (options.size() < 1) { DBG(FUNC, PVT_FMT(_target, "[fxs-options] no options are set for branch %s.") % _fxs_orig_addr.c_str()); return false; } try { for (Strings::vector_type::iterator it = options.begin(); it != options.end(); it++) { Strings::vector_type par; Strings::tokenize(Strings::trim(*it), par, ":"); if ( par.size() != 2 ) { LOG(WARNING, PVT_FMT(_target, "[fxs-options] error on parsing options for branch %s.") % _fxs_orig_addr.c_str()); return false; } std::string opt_name = Strings::trim(par.at(0)); std::string opt_value = Strings::trim(par.at(1)); if (opt_name == "pickupgroup") { _pickupgroup = opt_value;//ast_get_group(opt_value.c_str()); } else if (opt_name == "callgroup") { _callgroup = opt_value;//ast_get_group(opt_value.c_str()); } /* else if (opt_name == "amaflags") { int amaflags = ast_cdr_amaflags2int(opt_value.c_str()); if (amaflags < 0) DBG(FUNC, PVT_FMT(_target, "[fxs-options] invalid AMA flags on branch %s.") % _fxs_orig_addr.c_str()); else _amaflags = amaflags; } */ else if (opt_name == "context") { _context = opt_value; } else if (opt_name == "input-volume") { long long volume = Strings::tolong(opt_value); if ( (volume < -10) || (volume > 10) ) { DBG(FUNC, PVT_FMT(_target, "[fxs-options] input-volume on branch %s.") % _fxs_orig_addr.c_str()); } else { _input_volume = volume; } } else if (opt_name == "output-volume") { long long volume = Strings::tolong(opt_value); if ( (volume < -10) || (volume > 10) ) { DBG(FUNC, PVT_FMT(_target, "[fxs-options] ouput-volume on branch %s.") % _fxs_orig_addr.c_str()); } else { _output_volume = volume; } } else if (opt_name == "language") { _language = opt_value; } else if (opt_name == "mohclass") { _mohclass = opt_value; } else if (opt_name == "accountcode") { _accountcode = opt_value; } else if (opt_name == "calleridnum") // conscious ultra chuncho! { BranchToOptMapType::iterator it3 = Opt::_branch_options.find(_fxs_orig_addr); if (it3 != Opt::_branch_options.end()) { Opt::_branch_options.insert(BranchToOptPairType(opt_value, it3->second)); Opt::_branch_options.erase(it3); } _fxs_orig_addr = opt_value; } else if (opt_name == "calleridname") { _calleridname = opt_value; } else if (opt_name == "mailbox") { _mailbox = opt_value; } else if (opt_name == "flash-to-digits") { _flash = opt_value; } else { DBG(FUNC, PVT_FMT(_target, "[fxs-options] invalid option on branch %s: \"%s\".") % _fxs_orig_addr.c_str() % opt_name.c_str()); } } } catch (Strings::invalid_value e) { LOG(WARNING, PVT_FMT(_target, "[fxs-options] number expected on Khomp configuration file, got '%s'.") % e.value().c_str()); return false; } return true; } bool BoardE1::KhompPvtFXS::alloc() { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); callFXS()->_flags.set(Kflags::FXS_DIAL_FINISHD); if(justStart(/*need_context*/) != SWITCH_STATUS_SUCCESS) { int fail_code = callFailFromCause(SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL); setHangupCause(SWITCH_CAUSE_REQUESTED_CHAN_UNAVAIL); cleanup(CLN_FAIL); reportFailToReceive(fail_code); LOG(ERROR, PVT_FMT(target(), "(FXS) r (Initilization Error on start!)")); return false; } startListen(); startStream(); /* do this procedures early (as audio is already being heard) */ dtmfSuppression(Opt::_options._out_of_band_dtmfs() && !callFXS()->_flags.check(Kflags::FAX_DETECTED)); echoCancellation(Opt::_options._echo_canceller() && !callFXS()->_flags.check(Kflags::FAX_DETECTED)); autoGainControl(Opt::_options._auto_gain_control() && !callFXS()->_flags.check(Kflags::FAX_DETECTED)); //TODO: NEED RECORD HERE !? /* if it does not need context, probably it's a pickupcall and will not pass throw setup_connection, so we start recording here*/ //if (!need_context && K::opt::recording && !pvt->is_recording) //startRecord(); DBG(FUNC, "(FXS) r"); return true; } bool BoardE1::KhompPvtFXS::onSeizureStart(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret = true; try { ScopedPvtLock lock(this); /* we always have audio */ call()->_flags.set(Kflags::HAS_PRE_AUDIO); ret = KhompPvt::onSeizureStart(e); if (justAlloc(true) != SWITCH_STATUS_SUCCESS) { int fail_code = callFailFromCause(SWITCH_CAUSE_UNALLOCATED_NUMBER); setHangupCause(SWITCH_CAUSE_UNALLOCATED_NUMBER); cleanup(CLN_FAIL); reportFailToReceive(fail_code); LOG(ERROR,PVT_FMT(_target, "(FXS) r (Initilization Error on alloc!)")); return false; } /* disable to avoid problems with DTMF detection */ echoCancellation(false); autoGainControl(false); call()->_orig_addr = _fxs_orig_addr; OrigToDestMapType::iterator i = Opt::_fxs_hotline.find(_fxs_orig_addr); if (i != Opt::_fxs_hotline.end()) { /* make it burn! */ call()->_dest_addr = (*i).second; alloc(); } else { /* normal line */ if (!_mailbox.empty() /*&& (ast_app_has_voicemail(pvt->fxs_opt.mailbox.c_str(), NULL) == 1)*/) startCadence(PLAY_VM_TONE); else startCadence(PLAY_PBX_TONE); call()->_flags.clear(Kflags::FXS_DIAL_ONGOING); call()->_flags.set(Kflags::FXS_OFFHOOK); } } catch (ScopedLockFailed & err) { LOG(ERROR,PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } bool BoardE1::KhompPvtFXS::onCallSuccess(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret; try { ScopedPvtLock lock(this); ret = KhompPvt::onCallSuccess(e); if (call()->_pre_answer) { dtmfSuppression(Opt::_options._out_of_band_dtmfs()); startListen(); startStream(); switch_channel_mark_pre_answered(getFSChannel()); } else { call()->_flags.set(Kflags::GEN_PBX_RING); call()->_idx_pbx_ring = Board::board(_target.device)->_timers.add( Opt::_options._ringback_pbx_delay(), &Board::KhompPvt::pbxRingGen, this, TM_VAL_CALL); } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to get device: %d!)") % err.device); return false; } catch (Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(target(), "(FXS) r (%s)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } void BoardE1::KhompPvtFXS::dialTimer(KhompPvt * pvt) { DBG(FUNC, PVT_FMT(pvt->target(), "FXS Dial timer")); try { ScopedPvtLock lock(pvt); KhompPvtFXS * pvt_fxs = static_cast<BoardE1::KhompPvtFXS*>(pvt); if(!pvt_fxs->callFXS()->_flags.check(Kflags::FXS_DIAL_ONGOING) || pvt_fxs->callFXS()->_flags.check(Kflags::FXS_DIAL_FINISHD)) return; pvt_fxs->call()->_dest_addr = pvt_fxs->callFXS()->_incoming_exten; pvt_fxs->alloc(); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(pvt->target(), "unable to lock %s!") % err._msg.c_str()); } } /* void BoardE1::KhompPvtFXS::transferTimer(KhompPvt * pvt) { DBG(FUNC, PVT_FMT(pvt->target(), "c")); try { ScopedPvtLock lock(pvt); KhompPvtFXS * pvt_fxs = static_cast<BoardE1::KhompPvtFXS*>(pvt); if(!pvt_fxs->callFXS()->_flags.check(Kflags::FXS_FLASH_TRANSFER)) { DBG(FUNC, PVT_FMT(pvt->target(), "r (Flag not set)")); return; } pvt_fxs->callFXS()->_flags.clear(Kflags::FXS_FLASH_TRANSFER); if(pvt_fxs->callFXS()->_flash_transfer.empty()) { DBG(FUNC, PVT_FMT(pvt->target(), "r (Number is empty)")); if(!pvt_fxs->stopTransfer()) { pvt_fxs->cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(pvt_fxs->target(), "r (unable to stop transfer)")); return; } return; } // begin context adjusting + processing MatchExtension::ContextListType contexts; pvt_fxs->validContexts(contexts); std::string tmp_exten; std::string tmp_context; switch (MatchExtension::findExtension(tmp_exten, tmp_context, contexts, pvt_fxs->callFXS()->_flash_transfer, pvt_fxs->call()->_orig_addr, false, false)) { case MatchExtension::MATCH_EXACT: case MatchExtension::MATCH_MORE: { pvt_fxs->callFXS()->_flash_transfer = tmp_exten; DBG(FUNC,FMT("incoming exten matched: %s") % pvt_fxs->callFXS()->_flash_transfer); if(!pvt_fxs->transfer(tmp_context)) { pvt_fxs->cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(pvt_fxs->target(), "r (unable to transfer)")); return; } break; } case MatchExtension::MATCH_NONE: { DBG(FUNC, PVT_FMT(pvt_fxs->target(), "match none!")); if(!pvt_fxs->stopTransfer()) { pvt_fxs->cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(pvt_fxs->target(), "r (unable to stop transfer)")); return; } break; } } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(pvt->target(), "r (unable to lock %s!)") % err._msg.c_str()); return; } DBG(FUNC, PVT_FMT(pvt->target(), "r")); } */ bool BoardE1::KhompPvtFXS::onChannelRelease(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret = true; try { ScopedPvtLock lock(this); /* if(!callFXS()->_uuid_other_session.empty() && session()) { //switch_core_session_t *hold_session; //if ((hold_session = switch_core_session_locate(callFXS()->_uuid_other_session.c_str()))) //{ // switch_channel_t * hold = switch_core_session_get_channel(hold_session); // switch_channel_stop_broadcast(hold); // switch_channel_wait_for_flag(hold, CF_BROADCAST, SWITCH_FALSE, 5000, NULL); // switch_core_session_rwunlock(hold_session); //} try { // get other side of the bridge switch_core_session_t * peer_session = getFSLockedPartnerSession(); unlockPartner(peer_session); DBG(FUNC, PVT_FMT(target(), "bridge with the new session")); switch_ivr_uuid_bridge(getUUID(peer_session), callFXS()->_uuid_other_session.c_str()); } catch(Board::KhompPvt::InvalidSwitchChannel & err) { DBG(FUNC, PVT_FMT(target(), "no partner: %s!") % err._msg.c_str()); } callFXS()->_uuid_other_session.clear(); } */ ret = KhompPvt::onChannelRelease(e); } catch(ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } /* bool BoardE1::KhompPvtFXS::startTransfer() { DBG(FUNC, PVT_FMT(target(), "c")); try { switch_core_session_t *peer_session = getFSLockedPartnerSession(); switch_channel_t *peer_channel = getFSChannel(peer_session); const char *stream = NULL; if (!(stream = getFSChannelVar(peer_channel, SWITCH_HOLD_MUSIC_VARIABLE))) { stream = "silence"; } unlockPartner(peer_session); DBG(FUNC, PVT_FMT(target(), "stream=%s") % stream); if (stream && strcasecmp(stream, "silence")) { // Freeswitch not get/put frames //switch_channel_set_flag(channel, CF_HOLD); switch_ivr_broadcast(getUUID(peer_session), stream, SMF_ECHO_ALEG | SMF_LOOP); } callFXS()->_flags.set(Kflags::FXS_FLASH_TRANSFER); startCadence(PLAY_PBX_TONE); callFXS()->_idx_transfer = Board::board(_target.device)->_timers.add(Opt::_options._fxs_digit_timeout()* 1000, &BoardE1::KhompPvtFXS::transferTimer, this, TM_VAL_CALL); } catch(Board::KhompPvt::InvalidSwitchChannel & err) { //cleanup(KhompPvt::CLN_HARD); LOG(ERROR, PVT_FMT(target(), "r (no valid partner %s!)") % err._msg.c_str()); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device); } //switch_ivr_hold_uuid(switch_core_session_get_uuid(session()), NULL, SWITCH_TRUE); DBG(FUNC, PVT_FMT(target(), "r")); return true; } bool BoardE1::KhompPvtFXS::stopTransfer() { DBG(FUNC, PVT_FMT(target(), "c")); callFXS()->_flags.clear(Kflags::FXS_FLASH_TRANSFER); callFXS()->_flash_transfer.clear(); stopCadence(); try { Board::board(_target.device)->_timers.del(callFXS()->_idx_transfer); } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device); } try { // get other side of the bridge switch_core_session_t * peer_session = getFSLockedPartnerSession(); switch_channel_t * peer_channel = getFSChannel(peer_session); switch_channel_stop_broadcast(peer_channel); switch_channel_wait_for_flag(peer_channel, CF_BROADCAST, SWITCH_FALSE, 5000, NULL); unlockPartner(peer_session); //switch_ivr_unhold_uuid(switch_core_session_get_uuid(session())); } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(target(), "r (no valid partner %s!)") % err._msg.c_str()); return false; } DBG(FUNC, PVT_FMT(target(), "r")); return true; } static switch_status_t xferHook(switch_core_session_t *session) { switch_channel_t *channel = switch_core_session_get_channel(session); switch_channel_state_t state = switch_channel_get_state(channel); DBG(FUNC, D("state change=%d") % state); if (state == CS_PARK) { switch_core_event_hook_remove_state_change(session, xferHook); BoardE1::KhompPvtFXS * pvt = static_cast<BoardE1::KhompPvtFXS*>(switch_core_session_get_private(session)); if(!pvt) { DBG(FUNC, D("pvt is NULL")); return SWITCH_STATUS_FALSE; } try { ScopedPvtLock lock(pvt); if(!pvt->callFXS()->_uuid_other_session.empty()) { DBG(FUNC, D("bridge after park")); std::string number = pvt->callFXS()->_uuid_other_session; pvt->callFXS()->_uuid_other_session.clear(); switch_ivr_uuid_bridge(pvt->getUUID(), number.c_str()); } } catch(ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(pvt->target(), "unable to lock: %s!") % err._msg.c_str()); return SWITCH_STATUS_FALSE; } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(pvt->target(), "%s!") % err._msg.c_str()); return SWITCH_STATUS_FALSE; } } else if (state == CS_HANGUP) { switch_core_event_hook_remove_state_change(session, xferHook); //BoardE1::KhompPvtFXS * pvt = static_cast<BoardE1::KhompPvtFXS*>(switch_core_session_get_private(session)); // //if(!pvt) //{ // DBG(FUNC, D("pvt is NULL")); // return SWITCH_STATUS_FALSE; //} //try //{ // ScopedPvtLock lock(pvt); // if(!pvt->callFXS()->_uuid_other_session.empty()) // { // DBG(FUNC, D("bridge after hangup")); // std::string number = pvt->callFXS()->_uuid_other_session; // pvt->callFXS()->_uuid_other_session.clear(); // switch_ivr_uuid_bridge(switch_core_session_get_uuid(session), number.c_str()); // } //} //catch(ScopedLockFailed & err) //{ // LOG(ERROR, PVT_FMT(pvt->target(), "unable to lock: %s!") % err._msg.c_str()); //} } return SWITCH_STATUS_SUCCESS; } bool BoardE1::KhompPvtFXS::transfer(std::string & context, bool blind) { DBG(FUNC, PVT_FMT(target(), "c")); callFXS()->_flags.clear(Kflags::FXS_FLASH_TRANSFER); std::string number = callFXS()->_flash_transfer; callFXS()->_flash_transfer.clear(); try { Board::board(_target.device)->_timers.del(callFXS()->_idx_transfer); } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device); } try { // get other side of the bridge switch_core_session_t * peer_session = getFSLockedPartnerSession(); switch_channel_t * peer_channel = getFSChannel(peer_session); switch_channel_stop_broadcast(peer_channel); switch_channel_wait_for_flag(peer_channel, CF_BROADCAST, SWITCH_FALSE, 5000, NULL); unlockPartner(peer_session); if(blind) { DBG(FUNC, PVT_FMT(_target, "Blind Transfer")); switch_ivr_session_transfer(peer_session, number.c_str(), Opt::_options._dialplan().c_str(), context.c_str()); } else { DBG(FUNC, PVT_FMT(_target, "Attended Transfer")); if(!callFXS()->_uuid_other_session.empty()) { DBG(FUNC, PVT_FMT(target(), "second transfer, hang up session")); } else { DBG(FUNC, PVT_FMT(target(), "first transfer")); callFXS()->_uuid_other_session = getUUID(peer_session); const char *stream = NULL; if (!(stream = switch_channel_get_hold_music(peer_channel))) { stream = "silence"; } DBG(FUNC, PVT_FMT(target(), "transfer stream=%s") % stream); if (stream && strcasecmp(stream, "silence")) { std::string moh = STR(FMT("endless_playback:%s,park") % stream); switch_ivr_session_transfer(peer_session, moh.c_str(), "inline", NULL); } else { switch_ivr_session_transfer(peer_session, "endless_playback:local_stream://moh,park", "inline", NULL); //switch_ivr_session_transfer(peer_session, "park", "inline", NULL); } } switch_channel_t * channel = getFSChannel(); switch_channel_set_variable(channel, SWITCH_PARK_AFTER_BRIDGE_VARIABLE, "true"); switch_core_event_hook_add_state_change(session(), xferHook); switch_ivr_session_transfer(session(), number.c_str(), Opt::_options._dialplan().c_str(), context.c_str()); DBG(FUNC, PVT_FMT(target(), "Generating ring")); call()->_indication = INDICA_RING; call()->_flags.set(Kflags::GEN_CO_RING); startCadence(PLAY_RINGBACK); //try //{ // call()->_idx_co_ring = Board::board(_target.device)->_timers.add(Opt::_options._ringback_co_delay(), &Board::KhompPvt::coRingGen,this); //} //catch (K3LAPITraits::invalid_device & err) //{ // LOG(ERROR, PVT_FMT(_target, "unable to get device: %d!") % err.device); //} } } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(target(), "r (no valid partner %s!)") % err._msg.c_str()); return false; } DBG(FUNC, PVT_FMT(target(), "r")); return true; } */ bool BoardE1::KhompPvtFXS::onDtmfDetected(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c (dtmf=%c)") % (char) e->AddInfo); bool ret = true; try { ScopedPvtLock lock(this); if (call()->_flags.check(Kflags::IS_INCOMING) && callFXS()->_flags.check(Kflags::FXS_OFFHOOK) && !callFXS()->_flags.check(Kflags::FXS_DIAL_FINISHD)) { DBG(FUNC, PVT_FMT(_target, "dialing")); if (call()->_cadence == PLAY_PBX_TONE) { stopCadence(); } if (call()->_cadence == PLAY_PUB_TONE) { stopCadence(); //call()->_cadence = PLAY_NONE; //mixer(KHOMP_LOG, 1, kmsGenerator, kmtSilence); } if (!callFXS()->_flags.check(Kflags::FXS_DIAL_ONGOING)) { DBG(FUNC, PVT_FMT(_target, "dialing started now, clearing stuff..")); callFXS()->_flags.set(Kflags::FXS_DIAL_ONGOING); callFXS()->_incoming_exten.clear(); mixer(KHOMP_LOG, 1, kmsGenerator, kmtSilence); callFXS()->_idx_dial = Board::board(_target.device)->_timers.add(Opt::_options._fxs_digit_timeout()* 1000, &BoardE1::KhompPvtFXS::dialTimer, this, TM_VAL_CALL); } else { Board::board(_target.device)->_timers.restart(callFXS()->_idx_dial); } callFXS()->_incoming_exten += e->AddInfo; /* begin context adjusting + processing */ MatchExtension::ContextListType contexts; validContexts(contexts); std::string tmp_exten; std::string tmp_context; switch (MatchExtension::findExtension(tmp_exten, tmp_context, contexts, callFXS()->_incoming_exten, call()->_orig_addr, false, false)) { case MatchExtension::MATCH_EXACT: callFXS()->_incoming_exten = tmp_exten; DBG(FUNC,FMT("incoming exten matched: %s") % callFXS()->_incoming_exten); Board::board(_target.device)->_timers.del(callFXS()->_idx_dial); call()->_dest_addr = callFXS()->_incoming_exten; call()->_incoming_context = tmp_context; alloc(); break; case MatchExtension::MATCH_MORE: DBG(FUNC, PVT_FMT(target(), "match more...")); /* can match, will match more, and it's an external call? */ for (DestVectorType::const_iterator i = Opt::_options._fxs_co_dialtone().begin(); i != Opt::_options._fxs_co_dialtone().end(); i++) { if (callFXS()->_incoming_exten == (*i)) { startCadence(PLAY_PUB_TONE); break; } } break; case MatchExtension::MATCH_NONE: DBG(FUNC, PVT_FMT(target(), "match none!")); std::string invalid = "i"; Board::board(_target.device)->_timers.del(callFXS()->_idx_dial); switch (MatchExtension::findExtension(tmp_exten, tmp_context, contexts, invalid, call()->_orig_addr, true, false)) { case MatchExtension::MATCH_EXACT: // this dialing is invalid, and we can handle it... call()->_dest_addr = invalid; call()->_incoming_context = tmp_context; alloc(); break; case MatchExtension::MATCH_MORE: case MatchExtension::MATCH_NONE: callFXS()->_flags.set(Kflags::FXS_DIAL_FINISHD); startCadence(PLAY_FASTBUSY); break; } break; } } /* else if(callFXS()->_flags.check(Kflags::FXS_OFFHOOK) && callFXS()->_flags.check(Kflags::FXS_FLASH_TRANSFER)) { Board::board(_target.device)->_timers.restart(callFXS()->_idx_transfer); DBG(FUNC, PVT_FMT(target(), "Flash Transfer")); if (call()->_cadence == PLAY_PBX_TONE) { stopCadence(); } if (call()->_cadence == PLAY_PUB_TONE) { stopCadence(); //call()->_cadence = PLAY_NONE; //mixer(KHOMP_LOG, 1, kmsGenerator, kmtSilence); } callFXS()->_flash_transfer += e->AddInfo; // begin context adjusting + processing MatchExtension::ContextListType contexts; validContexts(contexts); std::string tmp_exten; std::string tmp_context; switch (MatchExtension::findExtension(tmp_exten, tmp_context, contexts, callFXS()->_flash_transfer, call()->_orig_addr, false, false)) { case MatchExtension::MATCH_EXACT: { callFXS()->_flash_transfer = tmp_exten; DBG(FUNC,FMT("incoming exten matched: %s") % callFXS()->_flash_transfer); if(!transfer(tmp_context)) { cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(target(), "(FXS) r (unable to transfer)")); return false; } break; } case MatchExtension::MATCH_MORE: DBG(FUNC, PVT_FMT(target(), "match more...")); // can match, will match more, and it's an external call? for (DestVectorType::const_iterator i = Opt::_options._fxs_co_dialtone().begin(); i != Opt::_options._fxs_co_dialtone().end(); i++) { if (callFXS()->_flash_transfer == (*i)) { startCadence(PLAY_PUB_TONE); break; } } break; case MatchExtension::MATCH_NONE: { DBG(FUNC, PVT_FMT(target(), "match none!")); if(!stopTransfer()) { cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(target(), "(FXS) r (unable to stop transfer)")); return false; } break; } } } */ else { ret = KhompPvt::onDtmfDetected(e); } } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch (K3LAPITraits::invalid_device & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to get device: %d!)") % err.device); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } /* bool BoardE1::KhompPvtFXS::onDtmfSendFinish(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret = true; try { ScopedPvtLock lock(this); ret = KhompPvt::onDtmfSendFinish(e); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } */ bool BoardE1::KhompPvtFXS::onFlashDetected(K3L_EVENT *e) { DBG(FUNC, PVT_FMT(_target, "(FXS) c (%s)") % _flash); try { ScopedPvtLock lock(this); for(std::string::const_iterator it = _flash.begin(); it != _flash.end(); it++) { signalDTMF(*it); } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return true; /******************************************************************************/ //Old implementation, not used /* if(callFXS()->_flags.check(Kflags::FXS_FLASH_TRANSFER)) { DBG(FUNC, PVT_FMT(_target, "(FXS) transfer canceled")); if(!stopTransfer()) { cleanup(KhompPvt::CLN_HARD); DBG(FUNC, PVT_FMT(target(), "(FXS) r (unable to stop transfer)")); return false; } DBG(FUNC, PVT_FMT(target(), "(FXS) r")); return true; } if(call()->_flags.check(Kflags::IS_INCOMING)) { DBG(FUNC, PVT_FMT(_target, "incoming call")); } else if(call()->_flags.check(Kflags::IS_OUTGOING)) { DBG(FUNC, PVT_FMT(_target, "outgoing call")); } else { DBG(FUNC, PVT_FMT(_target, "(FXS) r (!incoming and !outgoing call)")); return true; } echoCancellation(false); if(!startTransfer()) { DBG(FUNC, PVT_FMT(target(), "(FXS) r (unable to start transfer)")); return false; } */ /******************************************************************************/ } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return true; } int BoardE1::KhompPvtFXS::makeCall(std::string params) { DBG(FUNC,PVT_FMT(_target, "(FXS) c")); /* we always have audio */ call()->_flags.set(Kflags::HAS_PRE_AUDIO); if (Opt::_options._fxs_bina()&& !call()->_orig_addr.empty()) { /* Sending Bina DTMF*/ callFXS()->_flags.set(Kflags::WAIT_SEND_DTMF); std::stringstream dial_bina; dial_bina << "A1" << call()->_orig_addr << "C"; if (!command(KHOMP_LOG, CM_DIAL_DTMF, dial_bina.str().c_str())) { return ksFail; //throw call_error("something went while sending BINA digits to FXS branch"); } int timeout = 150; if(!loopWhileFlagTimed(Kflags::WAIT_SEND_DTMF, timeout)) return ksFail; //throw call_error("call has been dropped while sending digits"); if(timeout <= 0) return ksFail; //throw call_error("sending number of A caused timeout of this call"); } if(!call()->_orig_addr.empty()) params += STG(FMT(" orig_addr=\"%s\"") % _call->_orig_addr); if (callFXS()->_ring_on != -1) params += STG(FMT(" ring_on=\"%ld\"") % callFXS()->_ring_on); if (callFXS()->_ring_off != -1) params += STG(FMT(" ring_off=\"%ld\"") % callFXS()->_ring_off); if (callFXS()->_ring_on_ext != -1) params += STG(FMT(" ring_on_ext=\"%ld\"") % callFXS()->_ring_on_ext); if (callFXS()->_ring_off_ext != -1) params += STG(FMT(" ring_off_ext=\"%ld\"") % callFXS()->_ring_off_ext); int ret = KhompPvt::makeCall(params); if(ret == ksSuccess) { try { switch_channel_mark_ring_ready(getFSChannel()); //signal_state(AST_CONTROL_RINGING); } catch(Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(_target, "No valid channel: %s") % err._msg.c_str()); } } else { LOG(ERROR, PVT_FMT(target(), "Fail on make call")); } call()->_cleanup_upon_hangup = (ret == ksInvalidParams || ret == ksInvalidState); DBG(FUNC,PVT_FMT(_target, "(FXS) r")); return ret; } bool BoardE1::KhompPvtFXS::doChannelAnswer(CommandRequest &cmd) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret = true; try { ScopedPvtLock lock(this); setupConnection(); ret = KhompPvt::doChannelAnswer(cmd); } catch (ScopedLockFailed & err) { LOG(ERROR,PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } catch (Board::KhompPvt::InvalidSwitchChannel & err) { LOG(ERROR, PVT_FMT(target(), "r (%s)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } bool BoardE1::KhompPvtFXS::doChannelHangup(CommandRequest &cmd) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); bool ret = true; bool answered = true; bool disconnected = false; try { ScopedPvtLock lock(this); /* if(!callFXS()->_uuid_other_session.empty()) { DBG(FUNC,PVT_FMT(_target, "unable to transfer")); switch_core_session_t *hold_session; if ((hold_session = switch_core_session_locate(callFXS()->_uuid_other_session.c_str()))) { switch_channel_t *hold_channel = switch_core_session_get_channel(hold_session); switch_core_session_rwunlock(hold_session); if(hold_channel) switch_channel_hangup(hold_channel, (switch_call_cause_t)call()->_hangup_cause); //switch_channel_hangup(hold_channel, SWITCH_CAUSE_ATTENDED_TRANSFER); } callFXS()->_uuid_other_session.clear(); } */ if (call()->_flags.check(Kflags::IS_INCOMING)) { DBG(FUNC,PVT_FMT(_target, "disconnecting incoming channel")); } else if (call()->_flags.check(Kflags::IS_OUTGOING)) { if (!call()->_flags.check(Kflags::FXS_OFFHOOK)) { DBG(FUNC, PVT_FMT(_target, "disconnecting not answered outgoing FXS channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); cleanup(KhompPvt::CLN_HARD); answered = false; } else if(call()->_cleanup_upon_hangup) { DBG(FUNC,PVT_FMT(_target, "disconnecting not allocated outgoing channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); cleanup(KhompPvt::CLN_HARD); answered = false; } else { DBG(FUNC,PVT_FMT(_target, "disconnecting outgoing channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); } } else { DBG(FUNC,PVT_FMT(_target, "already disconnected")); return true; } if(answered) { indicateBusyUnlocked(SWITCH_CAUSE_USER_BUSY, disconnected); } if (call()->_flags.check(Kflags::IS_INCOMING) && !call()->_flags.check(Kflags::NEEDS_RINGBACK_CMD)) { DBG(FUNC,PVT_FMT(_target, "disconnecting incoming channel...")); disconnected = command(KHOMP_LOG, CM_DISCONNECT); } stopStream(); stopListen(); //ret = KhompPvt::doChannelHangup(cmd); } catch (ScopedLockFailed & err) { LOG(ERROR,PVT_FMT(_target, "(FXS) r (unable to lock %s!)") % err._msg.c_str() ); return false; } DBG(FUNC, PVT_FMT(_target, "(FXS) r")); return ret; } bool BoardE1::KhompPvtFXS::setupConnection() { if(!call()->_flags.check(Kflags::IS_INCOMING) && !call()->_flags.check(Kflags::IS_OUTGOING)) { DBG(FUNC,PVT_FMT(_target, "Channel already disconnected")); return false; } bool res_out_of_band_dtmf = (call()->_var_dtmf_state == T_UNKNOWN ? Opt::_options._suppression_delay() && Opt::_options._out_of_band_dtmfs(): (call()->_var_dtmf_state == T_TRUE)); bool res_echo_cancellator = (call()->_var_echo_state == T_UNKNOWN ? Opt::_options._echo_canceller() : (call()->_var_echo_state == T_TRUE)); bool res_auto_gain_cntrol = (call()->_var_gain_state == T_UNKNOWN ? Opt::_options._auto_gain_control() : (call()->_var_gain_state == T_TRUE)); if (!call()->_flags.check(Kflags::REALLY_CONNECTED)) { obtainRX(res_out_of_band_dtmf); /* esvazia buffers de leitura/escrita */ cleanupBuffers(); if (!call()->_flags.check(Kflags::KEEP_DTMF_SUPPRESSION)) dtmfSuppression(res_out_of_band_dtmf); if (!call()->_flags.check(Kflags::KEEP_ECHO_CANCELLATION)) echoCancellation(res_echo_cancellator); if (!call()->_flags.check(Kflags::KEEP_AUTO_GAIN_CONTROL)) autoGainControl(res_auto_gain_cntrol); startListen(false); startStream(); DBG(FUNC, PVT_FMT(_target, "(FXS) Audio callbacks initialized successfully")); } call()->_flags.set(Kflags::FXS_OFFHOOK); return KhompPvt::setupConnection(); } bool BoardE1::KhompPvtFXS::indicateBusyUnlocked(int cause, bool sent_signaling) { DBG(FUNC, PVT_FMT(_target, "(FXS) c")); if(!KhompPvt::indicateBusyUnlocked(cause, sent_signaling)) { DBG(FUNC, PVT_FMT(_target, "(FXS) r (false)")); return false; } if(call()->_flags.check(Kflags::IS_INCOMING)) { if(!call()->_flags.check(Kflags::CONNECTED) && !sent_signaling) { if(!call()->_flags.check(Kflags::HAS_PRE_AUDIO)) { int rb_value = callFailFromCause(call()->_hangup_cause); DBG(FUNC, PVT_FMT(target(), "sending the busy status")); if (sendRingBackStatus(rb_value) == RingbackDefs::RBST_UNSUPPORTED) { DBG(FUNC, PVT_FMT(target(), "falling back to audio indication!")); /* stop the line audio */ stopStream(); /* just pre connect, no ringback */ if (!sendPreAudio()) DBG(FUNC, PVT_FMT(target(), "everything else failed, just sending audio indication...")); /* be very specific about the situation. */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else { DBG(FUNC, PVT_FMT(target(), "going to play busy")); /* stop the line audio */ stopStream(); /* be very specific about the situation. */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else { /* already connected or sent signaling... */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } } else if(call()->_flags.check(Kflags::IS_OUTGOING)) { /* already connected or sent signaling... */ mixer(KHOMP_LOG, 1, kmsGenerator, kmtBusy); } DBG(FUNC,PVT_FMT(_target, "(FXS) r")); return true; } void BoardE1::KhompPvtFXS::reportFailToReceive(int fail_code) { KhompPvt::reportFailToReceive(fail_code); if(fail_code != -1) { DBG(FUNC,PVT_FMT(_target, "sending a 'unknown number' message/audio")); if(sendRingBackStatus(fail_code) == RingbackDefs::RBST_UNSUPPORTED) { sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } else { DBG(FUNC, PVT_FMT(_target, "sending fast busy audio directly")); sendPreAudio(RingbackDefs::RB_SEND_DEFAULT); startCadence(PLAY_FASTBUSY); } } bool BoardE1::KhompPvtFXS::validContexts( MatchExtension::ContextListType & contexts, std::string extra_context) { DBG(FUNC,PVT_FMT(_target, "(FXS) c")); if(!_context.empty()) contexts.push_back(_context); if(!_group_context.empty()) { contexts.push_back(_group_context); } contexts.push_back(Opt::_options._context_fxs()); contexts.push_back(Opt::_options._context2_fxs()); for (MatchExtension::ContextListType::iterator i = contexts.begin(); i != contexts.end(); i++) { replaceTemplate((*i), "CC", _target.object); } bool ret = Board::KhompPvt::validContexts(contexts,extra_context); DBG(FUNC,PVT_FMT(_target, "(FXS) r")); return ret; } bool BoardE1::KhompPvtFXS::isOK() { try { ScopedPvtLock lock(this); K3L_CHANNEL_STATUS status; if (k3lGetDeviceStatus (_target.device, _target.object + ksoChannel, &status, sizeof (status)) != ksSuccess) return false; return (status.AddInfo != kfxsFail); } catch (ScopedLockFailed & err) { LOG(ERROR, PVT_FMT(target(), "unable to lock %s!") % err._msg.c_str() ); } return false; }
30.822612
176
0.54792
gidmoth
0aa4a664dab1a1b3e258056d127c70c106773801
2,137
hpp
C++
area_light.hpp
miky-kr5/PhotonMF
fcc1643c53a9e95963482d80b14a196ac1993d04
[ "BSD-2-Clause" ]
1
2021-04-02T08:14:23.000Z
2021-04-02T08:14:23.000Z
EVI - 2017/EVI 21/EVIray/area_light.hpp
miky-kr5/Presentations
338669e488aecf796da4086fdea8389891294624
[ "CC0-1.0" ]
1
2021-04-19T10:37:24.000Z
2021-04-19T12:13:30.000Z
area_light.hpp
miky-kr5/PhotonMF
fcc1643c53a9e95963482d80b14a196ac1993d04
[ "BSD-2-Clause" ]
null
null
null
#pragma once #ifndef AREA_LIGHT_HPP #define AREA_LIGHT_HPP #include "light.hpp" using glm::length; using glm::normalize; using glm::dot; class AreaLight: public Light { public: float m_const_att; float m_lin_att; float m_quad_att; Figure * m_figure; AreaLight(): Light(AREA), m_const_att(1.0), m_lin_att(0.0), m_quad_att(0.0), m_figure(NULL), m_last_sample(vec3()), m_n_at_last_sample(vec3()) { } AreaLight(Figure * _f, float _c = 1.0, float _l = 0.0, float _q = 0.0): Light(AREA), m_const_att(_c), m_lin_att(_l), m_quad_att(_q), m_figure(_f), m_last_sample(vec3()), m_n_at_last_sample(vec3()) { } virtual vec3 direction(vec3 point) const { return normalize(m_last_sample - point); } virtual float distance(vec3 point) const { return length(m_last_sample - point); } vec3 diffuse(vec3 normal, Ray & r, vec3 i_pos, Material & m) const { float d, att, ln_dot_d, d2, g; vec3 l_dir, ref; l_dir = normalize(direction(i_pos)); ln_dot_d = dot(m_n_at_last_sample, l_dir); if (ln_dot_d > 0.0f) { d2 = distance(i_pos); d2 *= d2; g = ln_dot_d / d2; d = distance(i_pos); att = 1.0f / (m_const_att + (m_lin_att * d) + (m_quad_att * (d * d))); return (att * m.m_brdf->diffuse(l_dir, normal, r, i_pos, m_figure->m_mat->m_emission) * g) / m_figure->pdf(); } else return vec3(0.0f); } vec3 specular(vec3 normal, Ray & r, vec3 i_pos, Material & m) const { float d, att, ln_dot_d; vec3 l_dir, ref; l_dir = normalize(direction(i_pos)); ln_dot_d = dot(m_n_at_last_sample, l_dir); if (ln_dot_d > 0.0f) { d = distance(i_pos); att = 1.0f / (m_const_att + (m_lin_att * d) + (m_quad_att * (d * d))); return (att * m.m_brdf->specular(l_dir, normal, r, i_pos, m_figure->m_mat->m_emission, m.m_shininess)) / m_figure->pdf(); } else return vec3(0.0f); } virtual vec3 normal_at_last_sample() { return m_n_at_last_sample; } virtual vec3 sample_at_surface() = 0; protected: vec3 m_last_sample; vec3 m_n_at_last_sample; }; #endif
23.483516
127
0.631259
miky-kr5
0aa4e7039a887f59c61bd7854672b961561e533a
594
cpp
C++
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
tryptichon/Tool-IOStreams-for-CPP
7da340735c95d7f0b7bd861a6335b1aecad02d21
[ "MIT" ]
1
2018-06-21T16:23:17.000Z
2018-06-21T16:23:17.000Z
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
tryptichon/Tool-IOStreams-for-CPP
7da340735c95d7f0b7bd861a6335b1aecad02d21
[ "MIT" ]
null
null
null
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
tryptichon/Tool-IOStreams-for-CPP
7da340735c95d7f0b7bd861a6335b1aecad02d21
[ "MIT" ]
null
null
null
/** * @file IconvStringStream.cpp * * @brief File for class IconvStringStream * @date 04.08.2016 * @author duke */ #include "IconvStringStream.h" using namespace std; IconvStringStream::IconvStringStream(const string& a_from, const string& a_to) : IconvStream(c_str, a_from, a_to) { } IconvStringStream::IconvStringStream(const string& a_input, const string& a_from, const string& a_to) : IconvStream(c_str, a_from, a_to) { *this << a_input; } IconvStringStream::~IconvStringStream() { } string IconvStringStream::str() { flush(); return c_str.str(); }
17.470588
103
0.69697
tryptichon
0aa9c0988648259660915b88a372b7e8c2b1b5d3
692
cpp
C++
functions.cpp
davidlares/davidC-
7c479757ec8574623c02b03ad5b1223a43805f5c
[ "MIT" ]
null
null
null
functions.cpp
davidlares/davidC-
7c479757ec8574623c02b03ad5b1223a43805f5c
[ "MIT" ]
null
null
null
functions.cpp
davidlares/davidC-
7c479757ec8574623c02b03ad5b1223a43805f5c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; // this is a global variable int globalVar = 50; // returning string string sayName(string name){ return "Hello, " + name; } // not returning void otherFunction(){ cout << "Yep, Buddy"; } // default arg declaration int sum(int a, int b = 20){ int c = 20; // local scope variable return a + (c+b); } // declarations should be up, unless it takes the prototype int main(){ cout << "Global Variable: " << globalVar << endl; cout <<::globalVar << endl; // this is considered as a global variable cout << sayName("David"); otherFunction(); int result = sum(10); cout << "The result is: " << result; return 0; }
19.771429
74
0.631503
davidlares
0aaa65314229355d95678cc1327d75b31d72cdcc
866
c++
C++
42.1_Square_Root_Decomposition-introduction.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
42.1_Square_Root_Decomposition-introduction.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
42.1_Square_Root_Decomposition-introduction.c++
Sambitcr-7/DSA-C-
f3c80f54fa6160a99f39a934f330cdf40711de50
[ "Apache-2.0" ]
null
null
null
#include "bits/stdc++.h" using namespace std; #define int long long const int N = 1e5+2, MOD = 1e9+7; signed main() { int n; cin >> n; vector<int> a(n); for(int i = 0 ; i < n; i++) cin >> a[i]; int len = sqrtl(n) + 1; vector<int> b(len); for(int i = 0; i < n; i++){ b[i/len] += a[i]; } int q; cin >> q; while (q--) { int l,r; cin >> l >> r; l--; r--; int sum = 0; for(int i = l; i<=r; ){ if(i % len == 0 && i + len-1 <= r){ sum += b[i/len]; i += len; } else{ sum += a[i]; i++; } } cout << sum << endl; } return 0; } // 9 // 1 5 -2 6 8 -7 2 // 1 11 // 2 // 1 6 // 2 7
16.653846
48
0.312933
Sambitcr-7
0aac5d609f834dca378b8a0480db5d9e68e7370f
1,725
cpp
C++
sse/features/detector.cpp
phygitalism/opensse
9611503bd09009cd5319f15cac8511dfb7d7b388
[ "Apache-2.0" ]
628
2015-01-07T09:27:12.000Z
2022-03-24T04:52:33.000Z
sse/features/detector.cpp
phygitalism/opensse
9611503bd09009cd5319f15cac8511dfb7d7b388
[ "Apache-2.0" ]
21
2015-09-11T11:30:53.000Z
2020-06-29T14:23:55.000Z
sse/features/detector.cpp
phygitalism/opensse
9611503bd09009cd5319f15cac8511dfb7d7b388
[ "Apache-2.0" ]
164
2015-01-06T11:00:54.000Z
2022-03-09T03:47:19.000Z
/************************************************************************* * Copyright (c) 2014 Zhang Dongdong * 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 "detector.h" namespace sse { GridDetector::GridDetector(uint numSamples) : _numSamples(numSamples) { } /** * @brief GridDetector::detect * Keypoints are cross points, when we divide image to square grid. * * _numSamples, default value is 625 */ void GridDetector::detect(const cv::Mat &image, KeyPoints_t &keypoints) const { cv::Rect samplingArea(0, 0, image.size().width, image.size().height); uint numSample1D = std::ceil(std::sqrt(static_cast<float>(_numSamples))); float stepX = samplingArea.width / static_cast<float>(numSample1D+1); float stepY = samplingArea.height / static_cast<float>(numSample1D+1); for(uint x = 1; x < numSample1D; x++) { uint posX = x*stepX; for(uint y = 1; y <= numSample1D; y++) { uint posY = y*stepY; Vec_f32_t p(2); p[0] = posX; p[1] = posY; keypoints.push_back(p); } } } } //namespace sse
31.944444
77
0.611014
phygitalism
0aadb43caabd239e05efb407e6b17daf5194c6da
9,332
cpp
C++
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
normalvector/ue4_procedural_toolkit_demos
90021f805150d4af85cbcd063cef5379a3a2a184
[ "Unlicense", "MIT" ]
3
2017-03-23T10:22:50.000Z
2017-07-12T23:48:06.000Z
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
normalvector/ue4_procedural_toolkit_demos
90021f805150d4af85cbcd063cef5379a3a2a184
[ "Unlicense", "MIT" ]
null
null
null
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
normalvector/ue4_procedural_toolkit_demos
90021f805150d4af85cbcd063cef5379a3a2a184
[ "Unlicense", "MIT" ]
null
null
null
// (c)2017 Paul Golds, released under MIT License. #include "ProceduralToolkit.h" #include "MeshGeometry.h" #include "MeshDeformationComponent.h" // Sets default values for this component's properties UMeshDeformationComponent::UMeshDeformationComponent() { // This component can never tick, it doesn't update itself. PrimaryComponentTick.bCanEverTick = false; // ... } bool UMeshDeformationComponent::LoadFromStaticMesh(UMeshDeformationComponent *&MeshDeformationComponent, UStaticMesh *staticMesh, int32 LOD /*= 0*/) { /// \todo Err.. ? Should this be here? Have I broken the API? MeshDeformationComponent = this; MeshGeometry = NewObject<UMeshGeometry>(this); bool success = MeshGeometry->LoadFromStaticMesh(staticMesh); if (!success) { MeshGeometry = nullptr; } return success; } bool UMeshDeformationComponent::UpdateProceduralMeshComponent(UMeshDeformationComponent *&MeshDeformationComponent, UProceduralMeshComponent *proceduralMeshComponent, bool createCollision) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("UpdateProceduralMeshComponent: No meshGeometry loaded")); return false; } return MeshGeometry->UpdateProceduralMeshComponent(proceduralMeshComponent, createCollision); } USelectionSet * UMeshDeformationComponent::SelectAll() { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("UMeshDeformationComponent: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectAll(); } USelectionSet * UMeshDeformationComponent::SelectNear(FVector center /*= FVector::ZeroVector*/, float innerRadius /*= 0*/, float outerRadius /*= 100*/) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectNear: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectNear(center, innerRadius, outerRadius); } USelectionSet * UMeshDeformationComponent::SelectNearSpline(USplineComponent *spline, float innerRadius /*= 0*/, float outerRadius /*= 100*/) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectNearSpline: No meshGeometry loaded")); return nullptr; } // Get the actor's local->world transform- we're going to need it for the spline. FTransform actorTransform = this->GetOwner()->GetTransform(); return MeshGeometry->SelectNearSpline(spline, actorTransform, innerRadius, outerRadius); } USelectionSet * UMeshDeformationComponent::SelectNearLine(FVector lineStart, FVector lineEnd, float innerRadius /*=0*/, float outerRadius/*= 100*/, bool lineIsInfinite/* = false */) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectNearLine: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectNearLine(lineStart, lineEnd, innerRadius, outerRadius, lineIsInfinite); } USelectionSet * UMeshDeformationComponent::SelectFacing(FVector Facing /*= FVector::UpVector*/, float InnerRadiusInDegrees /*= 0*/, float OuterRadiusInDegrees /*= 30.0f*/) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectFacing: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectFacing(Facing, InnerRadiusInDegrees, OuterRadiusInDegrees); } USelectionSet * UMeshDeformationComponent::SelectByNoise( int32 Seed /*= 1337*/, float Frequency /*= 0.01*/, ENoiseInterpolation NoiseInterpolation /*= ENoiseInterpolation::Quintic*/, ENoiseType NoiseType /*= ENoiseType::Simplex */, uint8 FractalOctaves /*= 3*/, float FractalLacunarity /*= 2.0*/, float FractalGain /*= 0.5*/, EFractalType FractalType /*= EFractalType::FBM*/, ECellularDistanceFunction CellularDistanceFunction /*= ECellularDistanceFunction::Euclidian*/ ) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectByNoise: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectByNoise( Seed, Frequency, NoiseInterpolation, NoiseType, FractalOctaves, FractalLacunarity, FractalGain, FractalType, CellularDistanceFunction ); } USelectionSet * UMeshDeformationComponent::SelectByTexture(UTexture2D *Texture2D, ETextureChannel TextureChannel /*= ETextureChannel::Red*/) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("SelectByTexture: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectByTexture(Texture2D, TextureChannel); } USelectionSet * UMeshDeformationComponent::SelectLinear(FVector LineStart, FVector LineEnd, bool Reverse /*= false*/, bool LimitToLine /*= false*/) { if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Jitter: No meshGeometry loaded")); return nullptr; } return MeshGeometry->SelectLinear(LineStart, LineEnd, Reverse, LimitToLine); } void UMeshDeformationComponent::Jitter(UMeshDeformationComponent *&MeshDeformationComponent, FRandomStream &randomStream, FVector min, FVector max, USelectionSet *selection) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Jitter: No meshGeometry loaded")); return; } MeshGeometry->Jitter(randomStream, min, max, selection); } void UMeshDeformationComponent::Translate(UMeshDeformationComponent *&MeshDeformationComponent, FVector delta, USelectionSet *selection) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Translate: No meshGeometry loaded")); return; } MeshGeometry->Translate(delta, selection); } void UMeshDeformationComponent::Rotate(UMeshDeformationComponent *&MeshDeformationComponent, FRotator Rotation/*= FRotator::ZeroRotator*/, FVector CenterOfRotation /*= FVector::ZeroVector*/, USelectionSet *Selection /*=nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Rotate: No meshGeometry loaded")); return; } MeshGeometry->Rotate(Rotation, CenterOfRotation, Selection); } void UMeshDeformationComponent::Scale(UMeshDeformationComponent *&MeshDeformationComponent, FVector Scale3d /*= FVector(1, 1, 1)*/, FVector CenterOfScale /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Scale: No meshGeometry loaded")); return; } MeshGeometry->Scale(Scale3d, CenterOfScale, Selection); } void UMeshDeformationComponent::Transform(UMeshDeformationComponent *&MeshDeformationComponent, FTransform Transform, FVector CenterOfTransform /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Transform: No meshGeometry loaded")); return; } MeshGeometry->Transform(Transform, CenterOfTransform, Selection); } void UMeshDeformationComponent::Spherize(UMeshDeformationComponent *&MeshDeformationComponent, float SphereRadius /*= 100.0f*/, float FilterStrength /*= 1.0f*/, FVector SphereCenter /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded")); return; } MeshGeometry->Spherize(SphereRadius, FilterStrength, SphereCenter, Selection); } void UMeshDeformationComponent::Inflate(UMeshDeformationComponent *&MeshDeformationComponent, float Offset /*= 0.0f*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded")); return; } MeshGeometry->Inflate(Offset, Selection); } void UMeshDeformationComponent::ScaleAlongAxis(UMeshDeformationComponent *&MeshDeformationComponent, FVector CenterOfScale /*= FVector::ZeroVector*/, FVector Axis /*= FVector::UpVector*/, float Scale /*= 1.0f*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded")); return; } MeshGeometry->ScaleAlongAxis(CenterOfScale, Axis, Scale, Selection); } void UMeshDeformationComponent::RotateAroundAxis(UMeshDeformationComponent *&MeshDeformationComponent, FVector CenterOfRotation /*= FVector::ZeroVector*/, FVector Axis /*= FVector::UpVector*/, float AngleInDegrees /*= 0.0f*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded")); return; } MeshGeometry->RotateAroundAxis(CenterOfRotation, Axis, AngleInDegrees, Selection); } void UMeshDeformationComponent::Lerp( UMeshDeformationComponent *&MeshDeformationComponent, UMeshDeformationComponent *TargetMeshDeformationComponent, float Alpha /*= 0.0*/, USelectionSet *Selection /*= nullptr*/) { MeshDeformationComponent = this; if (!MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Lerp: No meshGeometry loaded")); return; } if (!TargetMeshDeformationComponent) { UE_LOG(LogTemp, Warning, TEXT("Lerp: No TargetMeshDeformationComponent")); return; } if (!TargetMeshDeformationComponent->MeshGeometry) { UE_LOG(LogTemp, Warning, TEXT("Lerp: TargetMeshDeformationComponent has no geometry")); return; } MeshGeometry->Lerp( TargetMeshDeformationComponent->MeshGeometry, Alpha, Selection ); }
37.031746
266
0.747857
normalvector
0ab0e4296c8448eed643b8b691d1ad461c57b101
677
cpp
C++
Arrays/Rearrange the array in alternating positive and negative items.cpp
akshay-thummar/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
17
2021-12-03T14:29:01.000Z
2022-03-09T18:25:05.000Z
Arrays/Rearrange the array in alternating positive and negative items.cpp
riti2409/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
null
null
null
Arrays/Rearrange the array in alternating positive and negative items.cpp
riti2409/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
4
2022-01-29T14:03:48.000Z
2022-03-01T22:53:41.000Z
#include <bits/stdc++.h> using namespace std; void rearrange(int arr[], int n) { int i = -1, j = n; while (i < j) { while(i <= n - 1 and arr[i] > 0) i += 1; while (j >= 0 and arr[j] < 0) j -= 1; if (i < j) swap(arr[i], arr[j]); } if (i == 0 || i == n) return; int k = 0; while (k < n && i < n) { swap(arr[k], arr[i]); i = i + 1; k = k + 2; } } // Utility function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {2, 3, -4, -1, 6, -9}; int n = 6; cout << "Given array is \n"; printArray(arr, n); rearrange(arr, n); return 0; }
13.019231
37
0.472674
akshay-thummar
0ab16f352baed697459b0e8a44486f9a280441e2
34,465
cxx
C++
com/ole32/dcomss/olescm/launch.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/dcomss/olescm/launch.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/dcomss/olescm/launch.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997. // // File: launch.cxx // // Contents: // // History: ?-??-?? ??? Created // 6-17-99 a-sergiv Added event log filtering // //-------------------------------------------------------------------------- #include "act.hxx" #include <winbasep.h> // For CreateProcessInternalW extern "C" { #include <execsrv.h> } #include "execclt.hxx" const ULONG MAX_SERVICE_ARGS = 16; const WCHAR REGEVENT_PREFIX[] = L"RPCSS_REGEVENT:"; const DWORD REGEVENT_PREFIX_STRLEN = sizeof(REGEVENT_PREFIX) / sizeof(WCHAR) - 1; const WCHAR INITEVENT_PREFIX[] = L"RPCSS_INITEVENT:"; const DWORD INITEVENT_PREFIX_STRLEN = sizeof(INITEVENT_PREFIX) / sizeof(WCHAR) - 1; HRESULT CClsidData::GetAAASaferToken( IN CToken *pClientToken, OUT HANDLE *pTokenOut ) /*++ Routine Description: Get the token that will be used in an Activate As Activator launch. This token is the more restricted of the incoming token and the configured safer level. Arguments: pClientToken - token of the user doing the activation pTokenOut - out parameter that will recieve the handle to use in the activation. Return Value: S_OK: Everything went fine. The caller owns a reference on pTokenOut and must close it. S_FALSE: Everything went fine. The caller does not own a reference on pToken out and does not need to close it. Anything else: An error occured. --*/ { HANDLE hSaferToken = NULL; HRESULT hr = S_OK; BOOL bStatus = TRUE; *pTokenOut = NULL; ASSERT(SaferLevel() && "Called GetAAASaferToken with SAFER disabled!"); if (!SaferLevel()) return E_UNEXPECTED; // Get the safer token for this configuration. bStatus = SaferComputeTokenFromLevel(SaferLevel(), pClientToken->GetToken(), &hSaferToken, 0, NULL); if (bStatus) { hr = pClientToken->CompareSaferLevels(hSaferToken); if (hr == S_OK) { CloseHandle(hSaferToken); hSaferToken = pClientToken->GetToken(); // Shared reference, return S_FALSE. hr = S_FALSE; } else { hr = S_OK; } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } *pTokenOut = hSaferToken; return hr; } HRESULT CClsidData::LaunchActivatorServer( IN CToken * pClientToken, IN WCHAR * pEnvBlock, IN DWORD EnvBlockLength, IN BOOL fIsRemoteActivation, IN BOOL fClientImpersonating, IN WCHAR* pwszWinstaDesktop, IN DWORD clsctx, OUT HANDLE * phProcess, OUT DWORD * pdwProcessId ) { WCHAR * pwszCommandLine; WCHAR * pFinalEnvBlock; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo; SECURITY_ATTRIBUTES saProcess; PSECURITY_DESCRIPTOR psdNewProcessSD; HRESULT hr; DWORD CreateFlags; BOOL bStatus = FALSE; ULONG SessionId = 0; HANDLE hSaferToken = NULL; BOOL bCloseSaferToken = TRUE; *phProcess = NULL; *pdwProcessId = 0; if ( ! pClientToken ) return (E_ACCESSDENIED); pFinalEnvBlock = NULL; StartupInfo.cb = sizeof(StartupInfo); StartupInfo.lpReserved = NULL; // Choose desktop for new server: // client remote -> system chooses desktop // client local, not impersonating -> we pick client's desktop // client local, impersonating -> system chooses desktop StartupInfo.lpDesktop = (fIsRemoteActivation || fClientImpersonating) ? L"" : pwszWinstaDesktop; StartupInfo.lpTitle = (SERVERTYPE_SURROGATE == _ServerType) ? NULL : _pwszServer; StartupInfo.dwX = 40; StartupInfo.dwY = 40; StartupInfo.dwXSize = 80; StartupInfo.dwYSize = 40; StartupInfo.dwFlags = 0; StartupInfo.wShowWindow = SW_SHOWNORMAL; StartupInfo.cbReserved2 = 0; StartupInfo.lpReserved2 = NULL; ProcessInfo.hThread = 0; ProcessInfo.hProcess = 0; ProcessInfo.dwProcessId = 0; hr = GetLaunchCommandLine( &pwszCommandLine ); if ( hr != S_OK ) return (hr); if ( pEnvBlock ) { hr = AddAppPathsToEnv( pEnvBlock, EnvBlockLength, &pFinalEnvBlock ); if ( hr != S_OK ) { PrivMemFree( pwszCommandLine ); return (hr); } } CreateFlags = CREATE_NEW_CONSOLE; if ( pFinalEnvBlock ) CreateFlags |= CREATE_UNICODE_ENVIRONMENT; CAccessInfo AccessInfo( pClientToken->GetSid() ); // // Apply configured safer restrictions to the token we're using to launch. // SAFER might not be enabled at all, in which case we don't need to do this. // if ( gbSAFERAAAChecksEnabled && SaferLevel() ) { hr = GetAAASaferToken( pClientToken, &hSaferToken ); if ( FAILED(hr) ) goto LaunchServerEnd; if ( hr == S_FALSE ) { // GetAAASaferToken has returned a shared reference // to pClientToken. bCloseSaferToken = FALSE; hr = S_OK; } else bCloseSaferToken = TRUE; } else { hSaferToken = pClientToken->GetToken(); bCloseSaferToken = FALSE; } // // This should never fail here, but if it did that would be a really, // really bad security breach, so check it anyway. // if ( ! ImpersonateLoggedOnUser( hSaferToken ) ) { hr = E_ACCESSDENIED; goto LaunchServerEnd; } // // Initialize process security info (SDs). We need both SIDs to // do this, so here is the 1st time we can. We Delete the SD right // after the CreateProcess call, no matter what happens. // psdNewProcessSD = AccessInfo.IdentifyAccess( FALSE, PROCESS_ALL_ACCESS, PROCESS_SET_INFORMATION | // Allow primary token to be set PROCESS_TERMINATE | SYNCHRONIZE // Allow screen-saver control ); if ( ! psdNewProcessSD ) { RevertToSelf(); hr = E_OUTOFMEMORY; goto LaunchServerEnd; } saProcess.nLength = sizeof(SECURITY_ATTRIBUTES); saProcess.lpSecurityDescriptor = psdNewProcessSD; saProcess.bInheritHandle = FALSE; SessionId = fIsRemoteActivation ? 0 : pClientToken->GetSessionId(); if( SessionId != 0 ) { // // We must send the request to the remote WinStation // of the requestor // // NOTE: The current WinStationCreateProcessW() does not use // the supplied security descriptor, but creates the // process under the account of the logged on user. // // We do not stuff the security descriptor, so clear the suspend flag #if DBGX CairoleDebugOut((DEB_TRACE, "SCM: Sending CreateProcess to SessionId %d\n",SessionId)); #endif // Non-zero sessions have only one winstation/desktop which is // the default one. We will ignore the winstation/desktop passed // in and use the default one. // review: Figure this out TarunA 05/07/99 //StartupInfo.lpDesktop = L"WinSta0\\Default"; // jsimmons 4/6/00 -- note that if the client was impersonating, then we won't // launch the server under the correct identity. More work needed to determine // if we can fully support this. // // Stop impersonating before doing the WinStationCreateProcess. // The remote winstation exec thread will launch the app under // the users context. We must not be impersonating because this // call only lets SYSTEM request the remote execute. // RevertToSelf(); HANDLE hDuplicate = NULL; // We need to pass in the SAFER blessed token to TS so that the // server can use that token // TS code will call CreateProcessAsUser, so we need to get a primary token if (DuplicateTokenForSessionUse(hSaferToken, &hDuplicate)) { if (bCloseSaferToken) { CloseHandle(hSaferToken); } hSaferToken = hDuplicate; bCloseSaferToken = TRUE; bStatus = CreateRemoteSessionProcess( SessionId, hSaferToken, FALSE, // Run as Logged on USER ServerExecutable(), // application name pwszCommandLine, // command line &saProcess, // process sec attributes NULL, // default thread sec attributes // (this was &saThread, but isn't needed) FALSE, // dont inherit handles CreateFlags, // creation flags pFinalEnvBlock, // use same enviroment block as the client NULL, // use same directory &StartupInfo, // startup info &ProcessInfo // proc info returned ); } } else { HANDLE hPrimary = NULL; if (DuplicateTokenAsPrimary(hSaferToken, pClientToken->GetSid(), &hPrimary)) { if (bCloseSaferToken) { CloseHandle(hSaferToken); } hSaferToken = hPrimary; bCloseSaferToken = TRUE; // // Do the exec while impersonating so the file access gets ACL // checked correctly. // // bStatus = CreateProcessAsUser( hSaferToken, ServerExecutable(), pwszCommandLine, &saProcess, NULL, FALSE, CreateFlags, pFinalEnvBlock, NULL, &StartupInfo, &ProcessInfo); } RevertToSelf(); } if ( ! bStatus ) { hr = HRESULT_FROM_WIN32( GetLastError() ); LogServerStartError( &_Clsid, clsctx, pClientToken, pwszCommandLine ); goto LaunchServerEnd; } LaunchServerEnd: if ( pFinalEnvBlock && pFinalEnvBlock != pEnvBlock ) PrivMemFree( pFinalEnvBlock ); if ( ProcessInfo.hThread ) CloseHandle( ProcessInfo.hThread ); if ( ProcessInfo.hProcess && ! bStatus ) { CloseHandle( ProcessInfo.hProcess ); ProcessInfo.hProcess = 0; } if ( hSaferToken && bCloseSaferToken ) { CloseHandle( hSaferToken ); } *phProcess = ProcessInfo.hProcess; *pdwProcessId = ProcessInfo.dwProcessId; PrivMemFree( pwszCommandLine ); return (hr); } //+------------------------------------------------------------------------- // // LaunchRunAsServer // //-------------------------------------------------------------------------- HRESULT CClsidData::LaunchRunAsServer( IN CToken * pClientToken, IN BOOL fIsRemoteActivation, IN ActivationPropertiesIn *pActIn, IN DWORD clsctx, OUT HANDLE * phProcess, OUT DWORD * pdwProcessId, OUT void** ppvRunAsHandle ) { WCHAR * pwszCommandLine; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo = {0}; HANDLE hToken; SECURITY_ATTRIBUTES saProcess; PSECURITY_DESCRIPTOR psdNewProcessSD; PSID psidUserSid; HRESULT hr; BOOL bStatus = FALSE; ULONG ulSessionId; BOOL bFromRunAsCache = FALSE; hr = GetLaunchCommandLine( &pwszCommandLine ); if ( hr != S_OK ) return (hr); *phProcess = NULL; *pdwProcessId = 0; hToken = NULL; bStatus = FALSE; StartupInfo.cb = sizeof(STARTUPINFO); StartupInfo.lpReserved = NULL; StartupInfo.lpDesktop = NULL; StartupInfo.lpTitle = (SERVERTYPE_SURROGATE == _ServerType) ? NULL : _pwszServer; StartupInfo.dwFlags = 0; StartupInfo.cbReserved2 = 0; StartupInfo.lpReserved2 = NULL; ulSessionId = 0; if( IsInteractiveUser() ) { if (!fIsRemoteActivation) { // This code seems to be saying, "if the client is local then I // should always be able to impersonate him". Which is true under // normal circumstances, but we have seen a case (stress machine // shutdowns) where the client is local but came in un-authenticated. if (!pClientToken) return E_ACCESSDENIED; if ( !ImpersonateLoggedOnUser( pClientToken->GetToken() ) ) { PrivMemFree(pwszCommandLine); return E_ACCESSDENIED; } RevertToSelf(); } ASSERT(pActIn); LONG lSessIdTemp; // Query for incoming session GetSessionIDFromActParams(pActIn, &lSessIdTemp); if (lSessIdTemp != INVALID_SESSION_ID) { ulSessionId = lSessIdTemp; } // Right now force all complus to // session 0. Session based activation // is still ill defined for complus // servers. if (_ServerType == SERVERTYPE_COMPLUS) { ulSessionId = 0; } hToken = GetUserTokenForSession(ulSessionId); } else { hToken = GetRunAsToken( clsctx, AppidString(), RunAsDomain(), RunAsUser(), TRUE); if (hToken) { hr = RunAsGetTokenElem(&hToken, ppvRunAsHandle); if (SUCCEEDED(hr)) bFromRunAsCache = TRUE; else { ASSERT((*ppvRunAsHandle == NULL) && "RunAsGetTokenElem failed but *ppvRunAsHandle is non-NULL"); PrivMemFree( pwszCommandLine ); CloseHandle(hToken); return hr; } } } if ( ! hToken ) { PrivMemFree( pwszCommandLine ); return (CO_E_RUNAS_LOGON_FAILURE); } psdNewProcessSD = 0; psidUserSid = GetUserSid(hToken); CAccessInfo AccessInfo(psidUserSid); // We have to get past the CAccessInfo before we can use a goto. if ( psidUserSid ) { psdNewProcessSD = AccessInfo.IdentifyAccess( FALSE, PROCESS_ALL_ACCESS, PROCESS_SET_INFORMATION | // Allow primary token to be set PROCESS_TERMINATE | SYNCHRONIZE // Allow screen-saver control ); } if ( ! psdNewProcessSD ) { hr = E_OUTOFMEMORY; goto LaunchRunAsServerEnd; } saProcess.nLength = sizeof(SECURITY_ATTRIBUTES); saProcess.lpSecurityDescriptor = psdNewProcessSD; saProcess.bInheritHandle = FALSE; { // // Get the environment block of the user // LPVOID lpEnvBlock = NULL; bStatus = CreateEnvironmentBlock(&lpEnvBlock, hToken, FALSE); HANDLE hSaferToken = NULL; if(bStatus && SaferLevel()) { bStatus = SaferComputeTokenFromLevel(SaferLevel(), hToken, &hSaferToken, 0, NULL); } else { hSaferToken = hToken; } if (bStatus && (ulSessionId != 0)) { bStatus = SetTokenInformation(hSaferToken, TokenSessionId, &ulSessionId, sizeof(ulSessionId)); } if(bStatus) { // // This allows the process create to work with paths to remote machines. // (void) ImpersonateLoggedOnUser( hSaferToken ); bStatus = CreateProcessAsUser(hSaferToken, ServerExecutable(), pwszCommandLine, &saProcess, NULL, FALSE, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, lpEnvBlock, NULL, &StartupInfo, &ProcessInfo); (void) RevertToSelf(); } // // Free the environment block buffer // if (lpEnvBlock) DestroyEnvironmentBlock(lpEnvBlock); if (hSaferToken && SaferLevel()) CloseHandle(hSaferToken); } if ( ! bStatus ) { hr = HRESULT_FROM_WIN32( GetLastError() ); LogRunAsServerStartError( &_Clsid, clsctx, pClientToken, pwszCommandLine, RunAsUser(), RunAsDomain() ); goto LaunchRunAsServerEnd; } *phProcess = ProcessInfo.hProcess; *pdwProcessId = ProcessInfo.dwProcessId; NtClose( ProcessInfo.hThread ); LaunchRunAsServerEnd: if ( hToken ) { NtClose( hToken ); } if ( psidUserSid ) { PrivMemFree(psidUserSid); } PrivMemFree( pwszCommandLine ); if (!bFromRunAsCache) *ppvRunAsHandle = NULL; else if (!SUCCEEDED(hr)) { RunAsRelease(*ppvRunAsHandle); *ppvRunAsHandle = NULL; } return (hr); } //+------------------------------------------------------------------------- // // Member: LaunchService // //-------------------------------------------------------------------------- HRESULT CClsidData::LaunchService( IN CToken * pClientToken, IN DWORD clsctx, OUT SC_HANDLE * phService ) { WCHAR *pwszArgs = NULL; ULONG cArgs = 0; WCHAR *apwszArgs[MAX_SERVICE_ARGS]; BOOL bStatus; HRESULT hr; ASSERT(g_hServiceController); *phService = OpenService( g_hServiceController, _pAppid->Service(), GENERIC_EXECUTE | GENERIC_READ ); if ( ! *phService ) return (HRESULT_FROM_WIN32( GetLastError() )); // Formulate the arguments (if any) if ( ServiceArgs() ) { UINT k = 0; // Make a copy of the service arguments pwszArgs = (WCHAR *) PrivMemAlloc( (lstrlenW(ServiceArgs()) + 1) * sizeof(WCHAR)); if ( pwszArgs == NULL ) { CloseServiceHandle(*phService); *phService = 0; return (E_OUTOFMEMORY); } lstrcpyW(pwszArgs, ServiceArgs()); // Scan the arguments do { // Scan to the next non-whitespace character while ( pwszArgs[k] && (pwszArgs[k] == L' ' || pwszArgs[k] == L'\t') ) { k++; } // Store the next argument if ( pwszArgs[k] ) { apwszArgs[cArgs++] = &pwszArgs[k]; } // Scan to the next whitespace char while ( pwszArgs[k] && pwszArgs[k] != L' ' && pwszArgs[k] != L'\t' ) { k++; } // Null terminate the previous argument if ( pwszArgs[k] ) { pwszArgs[k++] = L'\0'; } } while ( pwszArgs[k] ); } bStatus = StartService( *phService, cArgs, cArgs > 0 ? (LPCTSTR *) apwszArgs : NULL); PrivMemFree(pwszArgs); if ( bStatus ) return (S_OK); DWORD dwErr = GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); if ( dwErr == ERROR_SERVICE_ALREADY_RUNNING ) return (hr); CairoleDebugOut((DEB_ERROR, "StartService %ws failed, error = %#x\n",_pAppid->Service(),GetLastError())); CloseServiceHandle(*phService); *phService = 0; LogServiceStartError( &_Clsid, clsctx, pClientToken, _pAppid->Service(), ServiceArgs(), dwErr ); return (hr); } //+------------------------------------------------------------------------- // // LaunchAllowed // //-------------------------------------------------------------------------- BOOL CClsidData::LaunchAllowed( IN CToken * pClientToken, IN DWORD clsctx ) { BOOL bStatus; ASSERT(pClientToken); #if DBG WCHAR wszUser[MAX_PATH]; ULONG cchSize = MAX_PATH; pClientToken->Impersonate(); GetUserName( wszUser, &cchSize ); pClientToken->Revert(); CairoleDebugOut((DEB_TRACE, "RPCSS : CClsidData::LaunchAllowed on %ws\n", wszUser)); #endif if ( LaunchPermission() ) bStatus = CheckForAccess( pClientToken, LaunchPermission() ); else { CSecDescriptor* pSD = GetDefaultLaunchPermissions(); if (pSD) { bStatus = CheckForAccess( pClientToken, pSD->GetSD() ); pSD->DecRefCount(); } else bStatus = FALSE; } if ( ! bStatus ) { LogLaunchAccessFailed( &_Clsid, clsctx, pClientToken, 0 == LaunchPermission() ); } return (bStatus); } HRESULT CClsidData::GetLaunchCommandLine( OUT WCHAR ** ppwszCommandLine ) { DWORD AllocBytes; *ppwszCommandLine = 0; if ( (SERVERTYPE_EXE16 == _ServerType) || (SERVERTYPE_EXE32 == _ServerType) ) { AllocBytes = ( 1 + lstrlenW( L"-Embedding" ) + 1 + lstrlenW( _pwszServer ) ) * sizeof(WCHAR); *ppwszCommandLine = (WCHAR *) PrivMemAlloc( AllocBytes ); if ( *ppwszCommandLine != NULL ) { lstrcpyW( *ppwszCommandLine, _pwszServer ); lstrcatW( *ppwszCommandLine, L" -Embedding" ); } } else { ASSERT( SERVERTYPE_SURROGATE == _ServerType || SERVERTYPE_COMPLUS == _ServerType || SERVERTYPE_DLLHOST == _ServerType ); AllocBytes = ( 1 + lstrlenW( DllSurrogate() ) ) * sizeof(WCHAR); *ppwszCommandLine = (WCHAR *) PrivMemAlloc( AllocBytes ); if ( *ppwszCommandLine != NULL ) { lstrcpyW( *ppwszCommandLine, DllSurrogate() ); } } return (*ppwszCommandLine ? S_OK : E_OUTOFMEMORY); } CNamedObject* CClsidData::ServerLaunchMutex() { WCHAR* pwszPath = NULL; WCHAR* pszPathBuf = NULL; if ( SERVERTYPE_SURROGATE == _ServerType ) { pwszPath = DllSurrogate(); // Will never be called any more, ever if ( ! pwszPath || ! *pwszPath ) { ASSERT(_pAppid); pwszPath = _pAppid->AppidString(); //pwszPath = L"dllhost.exe"; } } else if ( DllHostOrComPlusProcess() ) { ASSERT(_pAppid); pwszPath = _pAppid->AppidString(); //pwszPath = L"dllhost.exe"; } else { pwszPath = Server(); // Need to use the base .exe part of the file path here, // there are tests that move the registration of their // server from one dir to another and we need to handle // this while concurrent activations are happening. LPWSTR pszBaseExeName = NULL; // First see how much of a buffer we need DWORD dwRet = GetFullPathName(pwszPath, 0, NULL, NULL); ASSERT(dwRet != 0); pszPathBuf = (WCHAR*)PrivMemAlloc(dwRet * sizeof(WCHAR)); if (!pszPathBuf) return NULL; dwRet = GetFullPathName(pwszPath, dwRet, pszPathBuf, &pszBaseExeName); if ((dwRet == 0) || !pszBaseExeName) { ASSERT(!"Unexpected failure from GetFullPathName"); PrivMemFree(pszPathBuf); return NULL; } // Use the base exe name for the event name pwszPath = pszBaseExeName; } if ( !pwszPath ) { ASSERT(0); PrivMemFree(pszPathBuf); return (NULL); } CNamedObject* pObject = gpNamedObjectTable->GetNamedObject(pwszPath, CNamedObject::MUTEX); PrivMemFree(pszPathBuf); if (pObject) { WaitForSingleObject(pObject->Handle(), INFINITE); } return pObject; } // // CClsidData::ServerRegisterEvent // // Returns a handle to the appropriate register // event for the server in question. // CNamedObject* CClsidData::ServerRegisterEvent() { if ( DllHostOrComPlusProcess() ) { // For dllhost\com+ surrogates, we delegate to the appid ASSERT(_pAppid); return _pAppid->ServerRegisterEvent(); } // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(REGEVENT_PREFIX)]; memcpy(wszEventName, REGEVENT_PREFIX, sizeof(REGEVENT_PREFIX)); memcpy(wszEventName + REGEVENT_PREFIX_STRLEN, _wszClsid, sizeof(_wszClsid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CClsidData::ServerInitializedEvent // // Returns a handle to the appropriate register // event for the server in question. This event is // signaled when initialization is finished. // CNamedObject* CAppidData::ServerInitializedEvent() { // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(INITEVENT_PREFIX)]; memcpy(wszEventName, INITEVENT_PREFIX, sizeof(INITEVENT_PREFIX)); memcpy(wszEventName + INITEVENT_PREFIX_STRLEN, _wszAppid, sizeof(_wszAppid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CClsidData::ServerInitializedEvent // // Returns a handle to the appropriate register // event for the server in question. This event is // signaled when initialization is finished. // // NOTE: The non-DllHost path is currently not used here. // CNamedObject* CClsidData::ServerInitializedEvent() { if ( DllHostOrComPlusProcess() ) { // For dllhost\com+ surrogates, we delegate to the appid ASSERT(_pAppid); return _pAppid->ServerInitializedEvent(); } // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(INITEVENT_PREFIX)]; memcpy(wszEventName, INITEVENT_PREFIX, sizeof(INITEVENT_PREFIX)); memcpy(wszEventName + INITEVENT_PREFIX_STRLEN, _wszClsid, sizeof(_wszClsid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CAppidData::ServerRegisterEvent // // Returns a handle to the appropriate register // event for the server in question. // CNamedObject* CAppidData::ServerRegisterEvent() { // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(REGEVENT_PREFIX)]; memcpy(wszEventName, REGEVENT_PREFIX, sizeof(REGEVENT_PREFIX)); memcpy(wszEventName + REGEVENT_PREFIX_STRLEN, _wszAppid, sizeof(_wszAppid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } //+------------------------------------------------------------------------- // // CClsidData::AddAppPathsToEnv // // Constructs a new environment block with an exe's AppPath value from the // registry appended to the Path environment variable. Simply returns the // given environment block if the clsid's server is not a 32 bit exe or if // no AppPath is found for the exe. // //-------------------------------------------------------------------------- HRESULT CClsidData::AddAppPathsToEnv( IN WCHAR * pEnvBlock, IN DWORD EnvBlockLength, OUT WCHAR ** ppFinalEnvBlock ) { HKEY hAppKey; WCHAR * pwszExe; WCHAR * pwszExeEnd; WCHAR * pwszAppPath; WCHAR * pPath; WCHAR * pNewEnvBlock; WCHAR wszStr[8]; WCHAR wszKeyName[APP_PATH_LEN+MAX_PATH]; DWORD AppPathLength; DWORD EnvFragLength; DWORD Status; BOOL bFoundPath; pwszAppPath = 0; pNewEnvBlock = 0; *ppFinalEnvBlock = pEnvBlock; if ( _ServerType != SERVERTYPE_EXE32 ) return (S_OK); // // Find the exe name by looking for the first .exe sub string which // is followed by a space or null. Only servers registered with a // .exe binary are supported. Otherwise the parsing is ambiguous since // the LocalServer32 can contain paths with spaces as well as optional // arguments. // if ( ! FindExeComponent( _pwszServer, L" ", &pwszExe, &pwszExeEnd ) ) return (S_OK); // // pwszExe points to the beginning of the binary name // pwszExeEnd points to one char past the end of the binary name // memcpy( wszKeyName, APP_PATH, APP_PATH_LEN * sizeof(WCHAR) ); memcpy( &wszKeyName[APP_PATH_LEN], pwszExe, (ULONG) (pwszExeEnd - pwszExe) * sizeof(WCHAR) ); wszKeyName[APP_PATH_LEN + (pwszExeEnd - pwszExe)] = 0; Status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, wszKeyName, 0, KEY_READ, &hAppKey ); if ( ERROR_SUCCESS == Status ) { Status = ReadStringValue( hAppKey, L"Path", &pwszAppPath ); RegCloseKey( hAppKey ); } if ( Status != ERROR_SUCCESS ) return (S_OK); AppPathLength = lstrlenW(pwszAppPath); // New env block size includes space for a new ';' separator in the path. pNewEnvBlock = (WCHAR *) PrivMemAlloc( (EnvBlockLength + 1 + AppPathLength) * sizeof(WCHAR) ); if ( ! pNewEnvBlock ) { PrivMemFree( pwszAppPath ); return (E_OUTOFMEMORY); } pPath = pEnvBlock; bFoundPath = FALSE; for ( ; *pPath; ) { memcpy( wszStr, pPath, 5 * sizeof(WCHAR) ); wszStr[5] = 0; pPath += lstrlenW( pPath ) + 1; if ( lstrcmpiW( wszStr, L"Path=" ) == 0 ) { bFoundPath = TRUE; break; } } if ( bFoundPath ) { pPath--; EnvFragLength = (ULONG) (pPath - pEnvBlock); memcpy( pNewEnvBlock, pEnvBlock, EnvFragLength * sizeof(WCHAR) ); pNewEnvBlock[EnvFragLength] = L';'; memcpy( &pNewEnvBlock[EnvFragLength + 1], pwszAppPath, AppPathLength * sizeof(WCHAR) ); memcpy( &pNewEnvBlock[EnvFragLength + 1 + AppPathLength], pPath, (EnvBlockLength - EnvFragLength) * sizeof(WCHAR) ); *ppFinalEnvBlock = pNewEnvBlock; } else { PrivMemFree( pNewEnvBlock ); } PrivMemFree( pwszAppPath ); return (S_OK); }
30.554078
125
0.509125
npocmaka
0ab21f1f6a3c12d070a8c3a8429e872838c2f35a
1,670
hpp
C++
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #ifndef __NAMEID_HPP #define __NAMEID_HPP #include <dbxml/XmlPortability.hpp> #include <iosfwd> #include <db.h> /** NameID * A class to encapsulate Name IDs, which are primary * keys into the DB RECNO dictionary database (32-bit) */ typedef u_int32_t nameId_t; namespace DbXml { class DbXmlDbt; class DbtOut; class DBXML_EXPORT NameID { public: NameID() : id_(0) {} NameID(nameId_t id) : id_(id) { } void reset() { id_ = 0; } nameId_t raw() const { return id_; } const void *rawPtr() const { return &id_; } void setThisFromDbt(const DbXmlDbt &dbt); void setDbtFromThis(DbtOut &dbt) const; void setThisFromDbtAsId(const DbXmlDbt &dbt); void setDbtFromThisAsId(DbtOut &dbt) const; u_int32_t unmarshal(const void *buf); u_int32_t marshal(void *buf) const; u_int32_t size() const { return sizeof(nameId_t); } u_int32_t marshalSize() const; bool operator==(const NameID &o) const { return id_ == o.id_; } bool operator==(nameId_t id) const { return id_ == id; } bool operator!=(const NameID &o) const { return id_ != o.id_; } bool operator!=(nameId_t id) const { return id_ != id; } bool operator<(const NameID &o) const { return id_ < o.id_; } bool operator>(const NameID &o) const { return id_ > o.id_; } static int compareMarshaled(const unsigned char *&p1, const unsigned char *&p2); // default implementation // NameID(const NameID&); // void operator=(const NameID &); private: nameId_t id_; }; std::ostream& operator<<(std::ostream& s, NameID id); } #endif
17.395833
56
0.682635
achilex
0ab923e2575c9df0a4a5a0d8c7646375cae8dd91
2,345
cc
C++
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
125
2021-08-09T02:14:04.000Z
2022-03-30T03:41:56.000Z
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
15
2021-08-31T06:12:31.000Z
2022-03-17T00:21:35.000Z
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
8
2021-08-10T03:08:10.000Z
2022-03-09T06:21:11.000Z
/*! * \file decode_3d_bbox.cc * \brief decode 3d bbox to laser frame * \author Lve Fan */ #include "./decode_3d_bbox-inl.h" #include <dmlc/parameter.h> #include "operator_common.h" namespace mxnet { namespace op { DMLC_REGISTER_PARAMETER(DecodeParam); NNVM_REGISTER_OP(_contrib_Decode3DBbox) .describe("Decode3DBbox foward.") .set_attr_parser(ParamParser<DecodeParam>) .set_num_inputs(2) .set_num_outputs(1) .set_attr<nnvm::FNumVisibleOutputs>("FNumVisibleOutputs", [](const NodeAttrs& attrs) { return 1; }) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"bbox_deltas", "pc_laser_frame"}; }) .set_attr<nnvm::FListOutputNames>("FListOutputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"decoded_bbox"}; }) .set_attr<mxnet::FInferShape>("FInferShape", [](const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_shape, mxnet::ShapeVector *out_shape){ using namespace mshadow; CHECK_EQ(in_shape->size(), 2) << "Input:[bbox_deltas, pc_laser_frame]"; mxnet::TShape dshape1 = in_shape->at(0); CHECK_EQ(dshape1.ndim(), 3) << "box deltas should be (b, n, 8)"; if (dshape1[2] != 8 && dshape1[2] != 7){ LOG_FATAL.stream() << "box deltas should be (b, n, 8), or (b, n, 7) when use bin loss"; } mxnet::TShape dshape2 = in_shape->at(1); CHECK_EQ(dshape2.ndim(), 3) << "point cloud in laser frame should be (b,n,3)"; if (dshape2[2] != 3){ LOG_FATAL.stream() << "point cloud in laser frame should be (b,n,3)"; } out_shape->clear(); out_shape->push_back(Shape3(dshape1[0], dshape1[1], 10)); return true; }) .set_attr<nnvm::FInferType>("FInferType", [](const nnvm::NodeAttrs& attrs, std::vector<int> *in_type, std::vector<int> *out_type) { CHECK_EQ(in_type->size(), 2); int dtype = (*in_type)[0]; // CHECK_EQ(dtype, (*in_type)[1]); CHECK_NE(dtype, -1) << "Input must have specified type"; out_type->clear(); out_type->push_back(dtype); return true; }) .set_attr<FCompute>("FCompute<cpu>", Decode3DBboxForward<cpu>) .set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes) .add_argument("bbox_deltas", "NDArray-or-Symbol", "2D boxes with rotation, 3D tensor") .add_argument("pc_laser_frame", "NDArray-or-Symbol", "2D boxes with rotation, 3D tensor") .add_arguments(DecodeParam::__FIELDS__()); } }
34.485294
92
0.695522
jie311
0abc9aafaf3e5f98171c88fc873d188176b666c0
7,865
cpp
C++
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. // ============================================================================= // Suffix Tree implementation based on: // http://llvm.org/doxygen/MachineOutliner_8cpp_source.html // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // NOTE: copyright for the code in the project may be held by contributors whose // names are not known. // ============================================================================= // 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. // // This file has been modified by Graphcore Ltd. // ============================================================================= #include <limits> #include <map> #include <memory> #include <sstream> #include <tuple> #include <vector> #include <popart/subgraph/suffixtree.hpp> namespace fwtools { namespace subgraph { namespace suffixtree { namespace { const int emptyIdx = std::numeric_limits<int>::max(); struct Node { std::map<int, Node *> children; int startIdx = emptyIdx; int *endIdx = nullptr; Node *link = nullptr; bool isRoot() const { return startIdx == emptyIdx; } size_t size() const { if (isRoot()) { return 0; } return *endIdx - startIdx + 1; } Node(int sIn, int *eIn, Node *lIn) : startIdx(sIn), endIdx(eIn), link(lIn) {} int suffixIdx = emptyIdx; int concatLen = 0; // int nDescendents = 0; std::vector<int> descendantStartIndices = {}; int nChildrenWaitingFor = 0; Node *parent = nullptr; }; class SuffixTree { public: const std::vector<int> &sequence; std::map<int, std::unique_ptr<Node>> nodeMap; int nodeMapSize = 0; Node *root = nullptr; private: std::map<int, int> internalEndIdxAllocator; int internalEndIdxAllocatorSize = 0; int leafEndIdx = std::numeric_limits<int>::max(); struct ActiveState { Node *node; int Idx = emptyIdx; int Len = 0; }; ActiveState Active; Node *insertLeaf(Node &parent, int startIdx, int edge) { nodeMap[nodeMapSize] = std::unique_ptr<Node>(new Node(startIdx, &leafEndIdx, nullptr)); Node *N = nodeMap[nodeMapSize].get(); nodeMapSize++; parent.children[edge] = N; return N; } Node *insertInternalNode(Node *parent, int startIdx, int endIdx, int edge) { internalEndIdxAllocator[internalEndIdxAllocatorSize] = endIdx; int *E = &internalEndIdxAllocator[internalEndIdxAllocatorSize]; internalEndIdxAllocatorSize++; nodeMap[nodeMapSize] = std::unique_ptr<Node>(new Node(startIdx, E, root)); Node *N = nodeMap[nodeMapSize].get(); nodeMapSize++; if (parent) { parent->children[edge] = N; } return N; } void setSuffixIndices(Node &currNode, int currNodeLen) { bool isLeaf = currNode.children.size() == 0 && !currNode.isRoot(); currNode.concatLen = currNodeLen; for (auto &childPair : currNode.children) { setSuffixIndices(*childPair.second, currNodeLen + static_cast<int>(childPair.second->size())); } if (isLeaf) { currNode.suffixIdx = static_cast<int>(sequence.size()) - currNodeLen; } } void setNDescendents() { std::vector<Node *> ready; for (auto &nodePair : nodeMap) { Node *n = nodePair.second.get(); n->nChildrenWaitingFor = static_cast<int>(n->children.size()); for (auto &childPair : n->children) { Node *child = childPair.second; child->parent = n; } if (n->nChildrenWaitingFor == 0) { n->descendantStartIndices = {n->suffixIdx}; ready.push_back(n); } } while (ready.size() != 0) { Node *n = ready.back(); ready.resize(ready.size() - 1); if (n->parent) { n->parent->nChildrenWaitingFor--; for (auto &l : n->descendantStartIndices) { n->parent->descendantStartIndices.push_back(l); } if (n->parent->nChildrenWaitingFor == 0) { ready.push_back(n->parent); } } } } int extend(int endIdx, int nSuffixesToAdd) { Node *Needslink = nullptr; while (nSuffixesToAdd > 0) { if (Active.Len == 0) { Active.Idx = endIdx; } int FirstChar = sequence[Active.Idx]; if (Active.node->children.count(FirstChar) == 0) { insertLeaf(*Active.node, endIdx, FirstChar); if (Needslink) { Needslink->link = Active.node; Needslink = nullptr; } } else { Node *NextNode = Active.node->children[FirstChar]; int SubstringLen = static_cast<int>(NextNode->size()); if (Active.Len >= SubstringLen) { Active.Idx += SubstringLen; Active.Len -= SubstringLen; Active.node = NextNode; continue; } int LastChar = sequence[endIdx]; if (sequence[NextNode->startIdx + Active.Len] == LastChar) { if (Needslink && !Active.node->isRoot()) { Needslink->link = Active.node; Needslink = nullptr; } Active.Len++; break; } Node *SplitNode = insertInternalNode(Active.node, NextNode->startIdx, NextNode->startIdx + Active.Len - 1, FirstChar); insertLeaf(*SplitNode, endIdx, LastChar); NextNode->startIdx += Active.Len; SplitNode->children[sequence[NextNode->startIdx]] = NextNode; if (Needslink) Needslink->link = SplitNode; Needslink = SplitNode; } nSuffixesToAdd--; if (Active.node->isRoot()) { if (Active.Len > 0) { Active.Len--; Active.Idx = endIdx - nSuffixesToAdd + 1; } } else { Active.node = Active.node->link; } } return nSuffixesToAdd; } public: SuffixTree(const std::vector<int> &seq0) : sequence(seq0) { root = insertInternalNode(nullptr, emptyIdx, emptyIdx, 0); Active.node = root; int nSuffixesToAdd = 0; for (int PfxendIdx = 0, End = static_cast<int>(sequence.size()); PfxendIdx < End; PfxendIdx++) { nSuffixesToAdd++; leafEndIdx = PfxendIdx; nSuffixesToAdd = extend(PfxendIdx, nSuffixesToAdd); } setSuffixIndices(*root, 0); setNDescendents(); } }; } // namespace std::vector<Match> getInternal(const std::vector<int> &s) { SuffixTree tree(s); // matches[i] will be be all internal nodes with concatLen = i std::vector<std::vector<Match>> matches(s.size() + 1); for (auto &x : tree.nodeMap) { auto node = x.second.get(); // not a leaf, not the root if (node->children.size() != 0 && node->parent != nullptr) { matches[node->concatLen].push_back( {node->descendantStartIndices, node->concatLen}); } } std::vector<Match> final_matches; final_matches.reserve(s.size()); for (int i = static_cast<int>(s.size()); i >= 1; --i) { if (matches[i].size() > 0) { final_matches.insert( final_matches.end(), matches[i].begin(), matches[i].end()); } } return final_matches; } } // namespace suffixtree } // namespace subgraph } // namespace fwtools
29.791667
80
0.587413
gglin001
0ac6e5afbba86fd00ebe35dbf33cba1369ea44d3
300
cpp
C++
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include "stdio.h" using namespace std; int main() { float vet[100]; for(int i = 0; i < 100; i++) cin >> vet[i]; for(int i = 0; i < 100; i++) { if(vet[i] <= 10) { printf("A[%d] = %.1f\n",i,vet[i]); } } return 0; }
13.043478
46
0.423333
AnneLivia
0aca5a38a4d748d628d59c2cdefe5d6ed8b86d93
6,578
hpp
C++
integrations/near/include/marlin/near/OnRampNear.hpp
marlinprotocol/OpenWeaver
7a8c668cccc933d652fabe8a141e702b8a0fd066
[ "MIT" ]
60
2020-07-01T17:37:34.000Z
2022-02-16T03:56:55.000Z
integrations/near/include/marlin/near/OnRampNear.hpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
5
2020-10-12T05:17:49.000Z
2021-05-25T15:47:01.000Z
integrations/near/include/marlin/near/OnRampNear.hpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
18
2020-07-01T17:43:18.000Z
2022-01-09T14:29:08.000Z
#ifndef MARLIN_ONRAMP_NEAR_HPP #define MARLIN_ONRAMP_NEAR_HPP #include <marlin/multicast/DefaultMulticastClient.hpp> #include <marlin/near/NearTransportFactory.hpp> #include <marlin/near/NearTransport.hpp> #include <cryptopp/blake2.h> #include <libbase58.h> #include <boost/filesystem.hpp> #include <marlin/pubsub/attestation/SigAttester.hpp> using namespace marlin::near; using namespace marlin::core; using namespace marlin::multicast; using namespace marlin::pubsub; namespace marlin { namespace near { class OnRampNear { public: DefaultMulticastClient<OnRampNear, SigAttester> multicastClient; uint8_t static_sk[crypto_sign_SECRETKEYBYTES], static_pk[crypto_sign_PUBLICKEYBYTES]; // should be moved to DefaultMulticastClient and add a function there to sign a message. NearTransportFactory<OnRampNear, OnRampNear> f; std::unordered_set<NearTransport<OnRampNear>*> transport_set; void handle_handshake(NearTransport<OnRampNear> &, core::Buffer &&message); void handle_transaction(core::Buffer &&message); void handle_block(core::Buffer &&message); template<typename... Args> OnRampNear(DefaultMulticastClientOptions clop, SocketAddress listen_addr, Args&&... args): multicastClient(clop, std::forward<Args>(args)...) { multicastClient.delegate = this; if(sodium_init() == -1) { throw; } if(boost::filesystem::exists("./.marlin/keys/near_gateway")) { std::ifstream sk("./.marlin/keys/near_gateway", std::ios::binary); if(!sk.read((char *)static_sk, crypto_sign_SECRETKEYBYTES)) { throw; } crypto_sign_ed25519_sk_to_pk(static_pk, static_sk); } else { crypto_sign_keypair(static_pk, static_sk); boost::filesystem::create_directories("./.marlin/keys/"); std::ofstream sk("./.marlin/keys/near_gateway", std::ios::binary); sk.write((char *)static_sk, crypto_sign_SECRETKEYBYTES); } char b58[65]; size_t sz = 65; SPDLOG_DEBUG( "PrivateKey: {} \n PublicKey: {}", spdlog::to_hex(static_sk, static_sk + crypto_sign_SECRETKEYBYTES), spdlog::to_hex(static_pk, static_pk + crypto_sign_PUBLICKEYBYTES) ); if(b58enc(b58, &sz, static_pk, 32)) { SPDLOG_INFO( "Node identity: {}", b58 ); } else { SPDLOG_ERROR("Failed to create base 58 of public key."); } f.bind(listen_addr); f.listen(*this); } void did_recv(NearTransport <OnRampNear> &transport, Buffer &&message) { SPDLOG_DEBUG( "Message received from Near: {} bytes: {}", message.size(), spdlog::to_hex(message.data(), message.data() + message.size()) ); SPDLOG_INFO( "Message received from Near: {} bytes", message.size() ); if(message.data()[0] == 0x10 || message.data()[0] == 0x0) { handle_handshake(transport, std::move(message)); } else if(message.data()[0] == 0xc) { handle_transaction(std::move(message)); } else if(message.data()[0] == 0xb) { handle_block(std::move(message)); } else if(message.data()[0] == 0xd) { SPDLOG_DEBUG( "This is a RoutedMessage" ); } else { SPDLOG_WARN( "Unhandled: {}", message.data()[0] ); } } template<typename T> // TODO: Code smell, remove later void did_recv( DefaultMulticastClient<OnRampNear, SigAttester> &, Buffer &&bytes [[maybe_unused]], T, uint16_t, uint64_t ) { SPDLOG_DEBUG( "OnRampNear:: did_recv, forwarding message: {}", spdlog::to_hex(bytes.data(), bytes.data() + bytes.size()) ); // for(auto iter = transport_set.begin(); iter != transport_set.end(); iter++) { // Buffer buf(bytes.size()); // buf.write_unsafe(0, bytes.data(), bytes.size()); // (*iter)->send(std::move(buf)); // } } void did_send_message(NearTransport<OnRampNear> &, Buffer &&message [[maybe_unused]]) { SPDLOG_DEBUG( "Transport: Did send message: {} bytes", // transport.src_addr.to_string(), // transport.dst_addr.to_string(), message.size() ); } void did_dial(NearTransport<OnRampNear> &) { } bool should_accept(SocketAddress const &) { return true; } void did_subscribe( DefaultMulticastClient<OnRampNear, SigAttester> &, uint16_t ) {} void did_unsubscribe( DefaultMulticastClient<OnRampNear, SigAttester> &, uint16_t ) {} void did_close(NearTransport<OnRampNear> &transport, uint16_t) { transport_set.erase(&transport); } void did_create_transport(NearTransport <OnRampNear> &transport) { transport_set.insert(&transport); transport.setup(this); } }; void OnRampNear::handle_transaction(core::Buffer &&message) { SPDLOG_DEBUG( "Handling transaction: {}", spdlog::to_hex(message.data(), message.data() + message.size()) ); message.uncover_unsafe(4); CryptoPP::BLAKE2b blake2b((uint)8); blake2b.Update((uint8_t *)message.data(), message.size()); uint64_t message_id; blake2b.TruncatedFinal((uint8_t *)&message_id, 8); multicastClient.ps.send_message_on_channel( 1, message_id, message.data(), message.size() ); } void OnRampNear::handle_block(core::Buffer &&message) { SPDLOG_DEBUG("Handling block"); message.uncover_unsafe(4); CryptoPP::BLAKE2b blake2b((uint)8); blake2b.Update((uint8_t *)message.data(), message.size()); uint64_t message_id; blake2b.TruncatedFinal((uint8_t *)&message_id, 8); multicastClient.ps.send_message_on_channel( 0, message_id, message.data(), message.size() ); } void OnRampNear::handle_handshake(NearTransport <OnRampNear> &transport, core::Buffer &&message) { SPDLOG_DEBUG("Handshake replying"); uint8_t *buf = message.data(); uint32_t buf_size = message.size(); std::swap_ranges(buf + 9, buf + 42, buf + 42); uint8_t near_key_offset = 42, gateway_key_offset = 9; using namespace CryptoPP; CryptoPP::SHA256 sha256; uint8_t hashed_message[32]; int flag = std::memcmp(buf + near_key_offset, buf + gateway_key_offset, 33); if(flag < 0) { sha256.Update(buf + near_key_offset, 33); sha256.Update(buf + gateway_key_offset, 33); } else { sha256.Update(buf + gateway_key_offset, 33); sha256.Update(buf + near_key_offset, 33); } sha256.Update(buf + buf_size - 73, 8); sha256.TruncatedFinal(hashed_message, 32); uint8_t *near_node_signature = buf + buf_size - crypto_sign_BYTES; if(crypto_sign_verify_detached(near_node_signature, hashed_message, 32, buf + near_key_offset + 1) != 0) { SPDLOG_ERROR("Signature verification failed"); return; } else { SPDLOG_DEBUG("Signature verified successfully"); } uint8_t *mySignature = buf + buf_size - 64; crypto_sign_detached(mySignature, NULL, hashed_message, 32, static_sk); message.uncover_unsafe(4); transport.send(std::move(message)); } } // near } // marlin #endif // MARLIN_ONRAMP_NEAR_HPP
27.991489
175
0.710702
marlinprotocol
0acc0091c5b171f1dc9e5a815584daee9c772ba3
4,942
cpp
C++
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "CoronaSkyShader.h" #include <maya/MIOStream.h> #include <maya/MString.h> #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MArrayDataHandle.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnLightDataAttribute.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnMessageAttribute.h> #include <maya/MFnGenericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFloatVector.h> #include <maya/MGlobal.h> #include <maya/MDrawRegistry.h> #include <maya/MDGModifier.h> MTypeId CoronaSkyShader::id(0x0011CF46); MObject CoronaSkyShader::pSkyModel; MObject CoronaSkyShader::pSkyMultiplier; MObject CoronaSkyShader::pSkyHorizBlur; MObject CoronaSkyShader::pSkyGroundColor; MObject CoronaSkyShader::pSkyAffectGround; MObject CoronaSkyShader::pSkyPreethamTurb; MObject CoronaSkyShader::pSkySunFalloff; MObject CoronaSkyShader::pSkyZenith; MObject CoronaSkyShader::pSkyHorizon; MObject CoronaSkyShader::pSkySunGlow; MObject CoronaSkyShader::pSkySunSideGlow; MObject CoronaSkyShader::pSkySunBleed; MObject CoronaSkyShader::sunSizeMulti; MObject CoronaSkyShader::outColor; void CoronaSkyShader::postConstructor( ) { MStatus stat; setMPSafe( true ); this->setExistWithoutInConnections(true); } CoronaSkyShader::CoronaSkyShader() { } CoronaSkyShader::~CoronaSkyShader() { } void* CoronaSkyShader::creator() { return new CoronaSkyShader(); } MStatus CoronaSkyShader::initialize() { MFnNumericAttribute nAttr; MFnLightDataAttribute lAttr; MFnTypedAttribute tAttr; MFnGenericAttribute gAttr; MFnEnumAttribute eAttr; MFnMessageAttribute mAttr; MStatus stat; pSkyModel = eAttr.create("pSkyModel", "pSkyModel", 2, &stat); stat = eAttr.addField("Preetham", 0); stat = eAttr.addField("Rawafake", 1); stat = eAttr.addField("Hosek", 2); CHECK_MSTATUS(addAttribute(pSkyModel)); pSkyMultiplier = nAttr.create("pSkyMultiplier", "pSkyMultiplier", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0001f); nAttr.setSoftMax(1.0f); CHECK_MSTATUS(addAttribute(pSkyMultiplier)); pSkyHorizBlur = nAttr.create("pSkyHorizBlur", "pSkyHorizBlur", MFnNumericData::kFloat, 0.1); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkyHorizBlur)); pSkyGroundColor = nAttr.createColor("pSkyGroundColor", "pSkyGroundColor"); nAttr.setDefault(0.25, 0.25, 0.25); CHECK_MSTATUS(addAttribute(pSkyGroundColor)); pSkyAffectGround = nAttr.create("pSkyAffectGround", "pSkyAffectGround", MFnNumericData::kBoolean, true); CHECK_MSTATUS(addAttribute(pSkyAffectGround)); pSkyPreethamTurb = nAttr.create("pSkyPreethamTurb", "pSkyPreethamTurb", MFnNumericData::kFloat, 2.5); nAttr.setMin(1.7f); nAttr.setMax(10.0f); CHECK_MSTATUS(addAttribute(pSkyPreethamTurb)); pSkySunFalloff = nAttr.create("pSkySunFalloff", "pSkySunFalloff", MFnNumericData::kFloat, 3.0); nAttr.setMin(0.0001f); nAttr.setSoftMax(10.0f); CHECK_MSTATUS(addAttribute(pSkySunFalloff)); pSkyZenith = nAttr.createColor("pSkyZenith", "pSkyZenith"); nAttr.setDefault(0.1, 0.1, 0.5); CHECK_MSTATUS(addAttribute(pSkyZenith)); pSkyHorizon = nAttr.createColor("pSkyHorizon", "pSkyHorizon"); nAttr.setDefault(0.25, 0.5, 0.5); CHECK_MSTATUS(addAttribute(pSkyHorizon)); pSkySunGlow = nAttr.create("pSkySunGlow", "pSkySunGlow", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunGlow)); pSkySunSideGlow = nAttr.create("pSkySunSideGlow", "pSkySunSideGlow", MFnNumericData::kFloat, 0.2); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunSideGlow)); pSkySunBleed = nAttr.create("pSkySunBleed", "pSkySunBleed", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunBleed)); sunSizeMulti = nAttr.create("sunSizeMulti", "sunSizeMulti", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.1); nAttr.setSoftMax(64.0); CHECK_MSTATUS(addAttribute(sunSizeMulti)); outColor = nAttr.createColor("outColor", "outColor"); nAttr.setKeyable(false); nAttr.setStorable(false); nAttr.setReadable(true); nAttr.setWritable(false); CHECK_MSTATUS(addAttribute(outColor)); CHECK_MSTATUS(attributeAffects(pSkyMultiplier, outColor)); CHECK_MSTATUS(attributeAffects(pSkyHorizBlur, outColor)); CHECK_MSTATUS(attributeAffects(pSkyGroundColor, outColor)); CHECK_MSTATUS(attributeAffects(pSkyAffectGround, outColor)); CHECK_MSTATUS(attributeAffects(pSkyPreethamTurb, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunFalloff, outColor)); CHECK_MSTATUS(attributeAffects(pSkyZenith, outColor)); CHECK_MSTATUS(attributeAffects(pSkyHorizon, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunGlow, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunBleed, outColor)); CHECK_MSTATUS(attributeAffects(sunSizeMulti, outColor)); return( MS::kSuccess ); } MStatus CoronaSkyShader::compute( const MPlug& plug, MDataBlock& block ) { return( MS::kSuccess ); }
32.090909
105
0.784298
haggi
0ace9a65a4c571ade034821a6875ff8836c32a7f
1,772
cpp
C++
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
58
2016-08-27T03:19:14.000Z
2022-01-05T17:33:44.000Z
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
14
2017-12-01T17:16:59.000Z
2020-12-21T12:16:35.000Z
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
22
2016-11-27T09:53:31.000Z
2021-11-22T00:22:53.000Z
// RUN: %clang_cc1 -triple i686-pc-win32 -std=c++11 -fms-extensions -verify %s __thread __declspec(thread) int a; // expected-error {{already has a thread-local storage specifier}} __declspec(thread) __thread int b; // expected-error {{already has a thread-local storage specifier}} __declspec(thread) int c(); // expected-warning {{only applies to variables}} __declspec(thread) int d; int foo(); __declspec(thread) int e = foo(); // expected-error {{must be a constant expression}} expected-note {{thread_local}} struct HasCtor { HasCtor(); int x; }; __declspec(thread) HasCtor f; // expected-error {{must be a constant expression}} expected-note {{thread_local}} struct HasDtor { ~HasDtor(); int x; }; __declspec(thread) HasDtor g; // expected-error {{non-trivial destruction}} expected-note {{thread_local}} struct HasDefaultedDefaultCtor { HasDefaultedDefaultCtor() = default; int x; }; __declspec(thread) HasDefaultedDefaultCtor h; struct HasConstexprCtor { constexpr HasConstexprCtor(int x) : x(x) {} int x; }; __declspec(thread) HasConstexprCtor i(42); int foo() { __declspec(thread) int a; // expected-error {{must have global storage}} static __declspec(thread) int b; } extern __declspec(thread) int fwd_thread_var; __declspec(thread) int fwd_thread_var = 5; extern int fwd_thread_var_mismatch; // expected-note {{previous declaration}} __declspec(thread) int fwd_thread_var_mismatch = 5; // expected-error-re {{thread-local {{.*}} follows non-thread-local}} extern __declspec(thread) int thread_mismatch_2; // expected-note {{previous declaration}} int thread_mismatch_2 = 5; // expected-error-re {{non-thread-local {{.*}} follows thread-local}} typedef __declspec(thread) int tls_int_t; // expected-warning {{only applies to variables}}
41.209302
121
0.743228
oslab-swrc
0ad04d8b69dc66dd4d445976f266f906996e366d
14,363
cc
C++
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "floyd/src/floyd_peer_thread.h" #include <google/protobuf/text_format.h> #include <algorithm> #include <climits> #include <vector> #include <string> #include "slash/include/env.h" #include "slash/include/slash_mutex.h" #include "slash/include/xdebug.h" #include "floyd/src/floyd_primary_thread.h" #include "floyd/src/floyd_context.h" #include "floyd/src/floyd_client_pool.h" #include "floyd/src/raft_log.h" #include "floyd/src/floyd.pb.h" #include "floyd/src/logger.h" #include "floyd/src/raft_meta.h" #include "floyd/src/floyd_apply.h" namespace floyd { Peer::Peer(std::string server, PeersSet* peers, FloydContext* context, FloydPrimary* primary, RaftMeta* raft_meta, RaftLog* raft_log, ClientPool* pool, FloydApply* apply, const Options& options, Logger* info_log) : peer_addr_(server), peers_(peers), context_(context), primary_(primary), raft_meta_(raft_meta), raft_log_(raft_log), pool_(pool), apply_(apply), options_(options), info_log_(info_log), next_index_(1), match_index_(0), peer_last_op_time(0), bg_thread_(1024 * 1024 * 256) { next_index_ = raft_log_->GetLastLogIndex() + 1; match_index_ = raft_meta_->GetLastApplied(); } int Peer::Start() { std::string name = "P" + std::to_string(options_.local_port) + ":" + peer_addr_.substr(peer_addr_.find(':')); bg_thread_.set_thread_name(name); LOGV(INFO_LEVEL, info_log_, "Peer::Start Start a peer thread to %s", peer_addr_.c_str()); return bg_thread_.StartThread(); } Peer::~Peer() { LOGV(INFO_LEVEL, info_log_, "Peer::~Peer peer thread %s exit", peer_addr_.c_str()); } int Peer::Stop() { return bg_thread_.StopThread(); } bool Peer::CheckAndVote(uint64_t vote_term) { if (context_->current_term != vote_term) { return false; } return (++context_->vote_quorum) > (options_.members.size() / 2); } void Peer::UpdatePeerInfo() { for (auto& pt : (*peers_)) { pt.second->set_next_index(raft_log_->GetLastLogIndex() + 1); pt.second->set_match_index(0); } } void Peer::AddRequestVoteTask() { /* * int timer_queue_size, queue_size; * bg_thread_.QueueSize(&timer_queue_size, &queue_size); * LOGV(INFO_LEVEL, info_log_, "Peer::AddRequestVoteTask peer_addr %s timer_queue size %d queue_size %d", * peer_addr_.c_str(),timer_queue_size, queue_size); */ bg_thread_.Schedule(&RequestVoteRPCWrapper, this); } void Peer::RequestVoteRPCWrapper(void *arg) { reinterpret_cast<Peer*>(arg)->RequestVoteRPC(); } void Peer::RequestVoteRPC() { uint64_t last_log_term; uint64_t last_log_index; CmdRequest req; { slash::MutexLock l(&context_->global_mu); raft_log_->GetLastLogTermAndIndex(&last_log_term, &last_log_index); req.set_type(Type::kRequestVote); CmdRequest_RequestVote* request_vote = req.mutable_request_vote(); request_vote->set_ip(options_.local_ip); request_vote->set_port(options_.local_port); request_vote->set_term(context_->current_term); request_vote->set_last_log_term(last_log_term); request_vote->set_last_log_index(last_log_index); LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC server %s:%d Send RequestVoteRPC message to %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); } CmdResponse res; Status result = pool_->SendAndRecv(peer_addr_, req, &res); if (!result.ok()) { LOGV(DEBUG_LEVEL, info_log_, "Peer::RequestVoteRPC: RequestVote to %s failed %s", peer_addr_.c_str(), result.ToString().c_str()); return; } { slash::MutexLock l(&context_->global_mu); if (!result.ok()) { LOGV(WARN_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d SendAndRecv to %s failed %s", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str()); return; } if (res.request_vote_res().term() > context_->current_term) { // RequestVote fail, maybe opposite has larger term, or opposite has // longer log. if opposite has larger term, this node will become follower // otherwise we will do nothing LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Become Follower, Candidate %s:%d vote request denied by %s," " request_vote_res.term()=%lu, current_term=%lu", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), res.request_vote_res().term(), context_->current_term); context_->BecomeFollower(res.request_vote_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); return; } if (context_->role == Role::kCandidate) { // kOk means RequestVote success, opposite vote for me if (res.request_vote_res().vote_granted() == true) { // granted LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d get vote from node %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); // However, we need check whether this vote is vote for old term // we need ignore these type of vote if (CheckAndVote(res.request_vote_res().term())) { context_->BecomeLeader(); UpdatePeerInfo(); LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: %s:%d become leader at term %d", options_.local_ip.c_str(), options_.local_port, context_->current_term); primary_->AddTask(kHeartBeat, false); } } else { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d deny vote from node %s at term %d, " "transfer from candidate to follower", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); context_->BecomeFollower(res.request_vote_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); } } else if (context_->role == Role::kFollower) { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d have transformed to follower when doing RequestVoteRPC, " "The leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(), context_->leader_port, context_->current_term); } else if (context_->role == Role::kLeader) { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d is already a leader at term %lu, " "get vote from node %s at term %d", options_.local_ip.c_str(), options_.local_port, context_->current_term, peer_addr_.c_str(), res.request_vote_res().term()); } } return; } uint64_t Peer::QuorumMatchIndex() { std::vector<uint64_t> values; std::map<std::string, Peer*>::iterator iter; for (iter = peers_->begin(); iter != peers_->end(); iter++) { if (iter->first == peer_addr_) { values.push_back(match_index_); continue; } values.push_back(iter->second->match_index()); } LOGV(DEBUG_LEVEL, info_log_, "Peer::QuorumMatchIndex: Get peers match_index %d %d %d %d", values[0], values[1], values[2], values[3]); std::sort(values.begin(), values.end()); return values.at(values.size() / 2); } // only leader will call AdvanceCommitIndex // follower only need set commit as leader's void Peer::AdvanceLeaderCommitIndex() { Entry entry; uint64_t new_commit_index = QuorumMatchIndex(); if (context_->commit_index < new_commit_index) { context_->commit_index = new_commit_index; raft_meta_->SetCommitIndex(context_->commit_index); } return; } void Peer::AddAppendEntriesTask() { /* * int timer_queue_size, queue_size; * bg_thread_.QueueSize(&timer_queue_size, &queue_size); * LOGV(INFO_LEVEL, info_log_, "Peer::AddAppendEntriesTask peer_addr %s timer_queue size %d queue_size %d", * peer_addr_.c_str(),timer_queue_size, queue_size); */ bg_thread_.Schedule(&AppendEntriesRPCWrapper, this); } void Peer::AppendEntriesRPCWrapper(void *arg) { reinterpret_cast<Peer*>(arg)->AppendEntriesRPC(); } void Peer::AppendEntriesRPC() { uint64_t prev_log_index = 0; uint64_t num_entries = 0; uint64_t prev_log_term = 0; uint64_t last_log_index = 0; uint64_t current_term = 0; CmdRequest req; CmdRequest_AppendEntries* append_entries = req.mutable_append_entries(); { slash::MutexLock l(&context_->global_mu); prev_log_index = next_index_ - 1; last_log_index = raft_log_->GetLastLogIndex(); /* * LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: next_index_ %d last_log_index %d peer_last_op_time %lu nowmicros %lu", * next_index_.load(), last_log_index, peer_last_op_time, slash::NowMicros()); */ if (next_index_ > last_log_index && peer_last_op_time + options_.heartbeat_us > slash::NowMicros()) { return; } peer_last_op_time = slash::NowMicros(); if (prev_log_index != 0) { Entry entry; if (raft_log_->GetEntry(prev_log_index, &entry) != 0) { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: Get my(%s:%d) Entry index %llu " "not found", options_.local_ip.c_str(), options_.local_port, prev_log_index); } else { prev_log_term = entry.term(); } } current_term = context_->current_term; req.set_type(Type::kAppendEntries); append_entries->set_ip(options_.local_ip); append_entries->set_port(options_.local_port); append_entries->set_term(current_term); append_entries->set_prev_log_index(prev_log_index); append_entries->set_prev_log_term(prev_log_term); append_entries->set_leader_commit(context_->commit_index); } Entry *tmp_entry = new Entry(); for (uint64_t index = next_index_; index <= last_log_index; index++) { if (raft_log_->GetEntry(index, tmp_entry) == 0) { // TODO(ba0tiao) how to avoid memory copy here Entry *entry = append_entries->add_entries(); *entry = *tmp_entry; } else { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr %s can't get Entry " "from raft_log, index %lld", peer_addr_.c_str(), index); break; } num_entries++; if (num_entries >= options_.append_entries_count_once || (uint64_t)append_entries->ByteSize() >= options_.append_entries_size_once) { break; } } delete tmp_entry; LOGV(DEBUG_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr(%s)'s next_index_ %llu, my last_log_index %llu" " AppendEntriesRPC will send %d iterm", peer_addr_.c_str(), next_index_.load(), last_log_index, num_entries); // if the AppendEntries don't contain any log item if (num_entries == 0) { LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntryRpc server %s:%d Send pingpong appendEntries message to %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), current_term); } CmdResponse res; Status result = pool_->SendAndRecv(peer_addr_, req, &res); { slash::MutexLock l(&context_->global_mu); if (!result.ok()) { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntries: Leader %s:%d SendAndRecv to %s failed, result is %s\n", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str()); return; } // here we may get a larger term, and transfer to follower // so we need to judge the role here if (context_->role == Role::kLeader) { /* * receiver has higer term than myself, so turn from candidate to follower */ if (res.append_entries_res().term() > context_->current_term) { LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: %s:%d Transfer from Leader to Follower since get A larger term" "from peer %s, local term is %d, peer term is %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term, res.append_entries_res().term()); context_->BecomeFollower(res.append_entries_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); } else if (res.append_entries_res().success() == true) { if (num_entries > 0) { match_index_ = prev_log_index + num_entries; // only log entries from the leader's current term are committed // by counting replicas if (append_entries->entries(num_entries - 1).term() == context_->current_term) { AdvanceLeaderCommitIndex(); apply_->ScheduleApply(); } next_index_ = prev_log_index + num_entries + 1; } } else { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Send AppEntriesRPC failed," "peer's last_log_index %lu, peer's next_index_ %lu", peer_addr_.c_str(), res.append_entries_res().last_log_index(), next_index_.load()); uint64_t adjust_index = std::min(res.append_entries_res().last_log_index() + 1, next_index_ - 1); if (adjust_index > 0) { // Prev log don't match, so we retry with more prev one according to // response next_index_ = adjust_index; LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Adjust peer next_index_, Now next_index_ is %lu", peer_addr_.c_str(), next_index_.load()); AddAppendEntriesTask(); } } } else if (context_->role == Role::kFollower) { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to follower when doing AppEntriesRPC, " "new leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(), context_->leader_port, context_->current_term); } else if (context_->role == Role::kCandidate) { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to candidate when doing AppEntriesRPC, " "new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->current_term); } } return; } } // namespace floyd
40.803977
128
0.695537
fasShare
bd5b2d5cb6ca0b2532b797a3479224695baa811f
930
cpp
C++
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; // Pobieramy wartosci od uzytkownika i liczymy sume w wierszach i ja wyswietlamy int main() { int rozmiar = 3; int losowe[rozmiar][rozmiar]; cout<<"Liczymy sume w wierszach. Prosze podac wartosci do tablicy\n"; for(int i = 0; i<rozmiar; i++) { for (int j=0; j<rozmiar; j++) { cout<<i<<","<<j<<" : "; cin>>losowe[i][j]; } } cout<<" "; for(int j=0; j<rozmiar; j++) cout<<setw(3)<<j; cout<<"\n"<<" ";; for(int j=0; j<=rozmiar; j++) cout<<"---"; cout<<"\n"; int suma = 0; for(int i = 0; i<rozmiar; i++) { cout<<i<<" |"; for (int j=0; j<rozmiar; j++) { suma+=losowe[i][j]; cout<<setw(3)<<losowe[i][j]<<" "; } cout<<" : "<<suma; suma=0; cout<<"\n"; } return 0; }
22.682927
80
0.452688
galursa
bd5f7e448e051e5da5b259abf12f1f6241da3b02
1,471
cpp
C++
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
1
2020-07-13T02:15:23.000Z
2020-07-13T02:15:23.000Z
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
3
2018-12-04T21:12:15.000Z
2019-09-08T05:54:48.000Z
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
null
null
null
#include "CANSendQueue.hpp" #include "CANHelpers.hpp" #include <mutex> #include <condition_variable> #include <thread> #include <ros/console.h> //#define DEBUG CANSendQueue& CANSendQueue::instance() { static CANSendQueue instance; return instance; } void CANSendQueue::push(const can_frame& frame) { std::unique_lock<std::mutex> lock{mutex}; q.push(frame); lock.unlock(); cv.notify_one(); } CANSendQueue::CANSendQueue() { std::thread sender{[this]() { while (true) { std::unique_lock<std::mutex> lock{mutex}; cv.wait(lock, [this](){ return q.size() > 0; }); const auto frame = q.front(); q.pop(); lock.unlock(); #ifdef DEBUG // debug exit condition if (frame.__res0 == 8) { ROS_INFO("exit condition"); break; } char str[1000] = {0}; sprintf(str, "Sending header = %#08X, length = %d, data:", frame.can_id, frame.can_dlc); for (int i = 0; i < frame.can_dlc;++i) { sprintf(str, "%s %02x", str, frame.data[i]); } ROS_DEBUG("%s", str); #endif // DEBUG // CAN port is assumed to be open if (CANHelpers::send_frame(frame) < 0) { ROS_ERROR("send failed: frame could not be sent"); } } }}; sender.detach(); }
24.516667
100
0.511217
bluesat
bd5f9fe5cad422e6b19dcfafae452e65e41f1db0
641
cpp
C++
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
1
2021-09-29T13:10:03.000Z
2021-09-29T13:10:03.000Z
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
null
null
null
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
null
null
null
class Solution { public: int minFlips(int a, int b, int c) { int flips=0; for(int i=0;i<32;++i){ bool aCheck=(a&(1<<i)); bool bCheck=(b&(1<<i)); bool aOrB= (aCheck | bCheck); bool cCheck=(c&(1<<i)); if(aOrB!=cCheck){ if(cCheck==true){ ++flips; } else{ if(aCheck==true && bCheck==true) flips+=2; else ++flips; } } } return flips; } };
23.740741
52
0.316693
raghavxk
bd611ede16ba1b25fefb73a03009e0673751893e
6,975
hpp
C++
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
5
2018-07-03T17:05:43.000Z
2020-02-03T00:23:46.000Z
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
// The IYFEngine // // Copyright (C) 2015-2018, Manvydas Šliamka // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY // WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef IYF_CONVERTER_STATE_HPP #define IYF_CONVERTER_STATE_HPP #include "core/Constants.hpp" #include "core/Platform.hpp" #include "io/interfaces/TextSerializable.hpp" #include "utilities/NonCopyable.hpp" #include "assetImport/ImportedAssetData.hpp" namespace iyf::editor { class Converter; class InternalConverterState { public: InternalConverterState(const Converter* converter) : converter(converter) { if (converter == nullptr) { throw std::logic_error("Converter cannot be nullptr"); } } virtual ~InternalConverterState() = 0; const Converter* getConverter() const { return converter; } private: const Converter* converter; }; inline InternalConverterState::~InternalConverterState() {} class ConverterState : private NonCopyable, public TextSerializable { public: ConverterState(PlatformIdentifier platformID, std::unique_ptr<InternalConverterState> internalState, const Path& sourcePath, FileHash sourceFileHash) : sourcePath(sourcePath), sourceFileHash(sourceFileHash), conversionComplete(false), debugOutputRequested(false), systemAsset(false), platformID(platformID), internalState(std::move(internalState)) {} /// If true, this represents a system asset inline bool isSystemAsset() const { return systemAsset; } /// \warning This should only be used internally (e.g., in SystemAssetPacker). Do not expose this in the editor inline void setSystemAsset(bool systemAsset) { this->systemAsset = systemAsset; } inline const std::vector<std::string>& getTags() const { return tags; } inline std::vector<std::string>& getTags() { return tags; } /// If true, some converters may export additional debug data. This parameter is not serialized inline void setDebugOutputRequested(bool requested) { debugOutputRequested = requested; } /// If true, some converters may export additional debug data. This parameter is not serialized inline bool isDebugOutputRequested() const { return debugOutputRequested; } /// \warning This value should only be modified by the ConverterManager, tests or in VERY special cases. inline void setConversionComplete(bool state) { conversionComplete = state; } inline bool isConversionComplete() const { return conversionComplete; } inline const InternalConverterState* getInternalState() const { return internalState.get(); } inline InternalConverterState* getInternalState() { return internalState.get(); } inline const Path& getSourceFilePath() const { return sourcePath; } virtual AssetType getType() const = 0; inline const std::vector<ImportedAssetData>& getImportedAssets() const { return importedAssets; } /// \warning The contents of this vector should only be modified by the ConverterManager, the Converters or in VERY special cases. inline std::vector<ImportedAssetData>& getImportedAssets() { return importedAssets; } inline FileHash getSourceFileHash() const { return sourceFileHash; } inline PlatformIdentifier getPlatformIdentifier() const { return platformID; } /// Derived classes should not create a root object in serializeJSON() virtual bool makesJSONRoot() const final override { return false; } /// Serializes the conversion settings stored in this ConverterState instance. virtual void serializeJSON(PrettyStringWriter& pw) const final override; /// Deserialized the conversion settings from the provided JSON object and into this one virtual void deserializeJSON(JSONObject& jo) final override; /// Obtain the preferred version for the serialized data. Derived classes should increment this whenever their /// serialization format changes. If an older format is provided, reasonable defaults should be set for data /// that is not present in it. virtual std::uint64_t getLatestSerializedDataVersion() const = 0; protected: virtual void serializeJSONImpl(PrettyStringWriter& pw, std::uint64_t version) const = 0; virtual void deserializeJSONImpl(JSONObject& jo, std::uint64_t version) = 0; private: std::vector<ImportedAssetData> importedAssets; std::vector<std::string> tags; Path sourcePath; FileHash sourceFileHash; bool conversionComplete; bool debugOutputRequested; bool systemAsset; PlatformIdentifier platformID; /// The internal state of the importer. Calling Converter::initializeConverter() typically loads the file /// into memory (to build initial metadata, importer settings, etc.). The contents of the said file can be /// stored in this variable and reused in Converter::convert() to avoid duplicate work. /// /// Moreover, by using an opaque pointer to a virtual base class, we allow the converters to safely store the /// state of external helper libraries while keeping their includes confined to the converters' cpp files. /// /// \warning This may depend on the context, Engine version, OS version, etc. and MUST NEVER BE SERIALIZED std::unique_ptr<InternalConverterState> internalState; }; } #endif // IYF_CONVERTER_STATE_HPP
39.40678
153
0.723441
manvis
bd6498ebcf6b3862846ab9fbc7cd8e06f8914bc6
1,887
cpp
C++
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
# include <stdio.h> enum Beep { B_IDLE1 = 1, B_IDLE2 = 2 }; int score[2]; char gameMode; char firstPlayer; # include "ttc_selectIdleBeep.cpp" int pass = 0; int fail = 0; int total = 0; void check(char gm, int sc0, int sc1, int res) { gameMode = gm; score[0] = sc0; score[1] = sc1; int r = selectIdleBeep(); printf( "%s GM=%d SC=%02d:%02d R=%d -> %d \n" ,( r == res ? ". " : "F ") ,gm,sc0,sc1,res,r ); total++; if (r == res) { pass++; } else { fail++; } } // checkfp() void test21low() { check(21,0,0, B_IDLE1); check(21,1,0, B_IDLE1); check(21,0,1, B_IDLE1); check(21,4,0, B_IDLE1); check(21,0,4, B_IDLE1); check(21,5,0, B_IDLE2); check(21,3,2, B_IDLE2); check(21,5,4, B_IDLE2); check(21,6,4, B_IDLE1); check(21,14,0, B_IDLE1); check(21,15,0, B_IDLE2); check(21,16,0, B_IDLE2); check(21,15,5, B_IDLE1); check(21,15,10, B_IDLE2); check(21,15,15, B_IDLE1); check(21,20,15, B_IDLE2); check(21,20,20, B_IDLE1); } void test11low() { check(11,0,0, B_IDLE1); check(11,1,0, B_IDLE1); check(11,0,1, B_IDLE1); check(11,3,0, B_IDLE2); check(11,0,3, B_IDLE2); check(11,2,1, B_IDLE2); check(11,1,2, B_IDLE2); check(11,3,2, B_IDLE2); check(11,4,2, B_IDLE1); check(11,9,0, B_IDLE2); check(11,9,3, B_IDLE1); check(11,9,6, B_IDLE2); check(11,9,8, B_IDLE2); check(11,9,9, B_IDLE1); } void test21high() { check(21,20,20, B_IDLE1); check(21,21,20, B_IDLE2); check(21,21,21, B_IDLE1); check(21,22,21, B_IDLE2); check(21,22,22, B_IDLE1); } void test11high() { check(11,9,9, B_IDLE1); check(11,10,9, B_IDLE1); check(11,10,10, B_IDLE1); check(11,11,10, B_IDLE2); check(11,11,11, B_IDLE1); check(11,12,11, B_IDLE2); } int main() { test21low(); test11low(); test21high(); test11high(); printf( "--------------------------------\n" " total=%d passed=%d failed=%d \n" ,total,pass,fail ); return 0; }
14.97619
48
0.595654
ern0
bd67a931654ebe222ab68bf555e3de5159fcec5a
1,315
cpp
C++
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
null
null
null
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
null
null
null
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
1
2021-11-12T21:19:28.000Z
2021-11-12T21:19:28.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads, pre-sm-60 // UNSUPPORTED: windows && pre-sm-70 // <cuda/std/atomic> // typedef enum memory_order // { // memory_order_relaxed, memory_order_consume, memory_order_acquire, // memory_order_release, memory_order_acq_rel, memory_order_seq_cst // } memory_order; #include <cuda/std/atomic> #include <cuda/std/cassert> #include "test_macros.h" int main(int, char**) { assert(static_cast<int>(cuda::std::memory_order_relaxed) == 0); assert(static_cast<int>(cuda::std::memory_order_consume) == 1); assert(static_cast<int>(cuda::std::memory_order_acquire) == 2); assert(static_cast<int>(cuda::std::memory_order_release) == 3); assert(static_cast<int>(cuda::std::memory_order_acq_rel) == 4); assert(static_cast<int>(cuda::std::memory_order_seq_cst) == 5); cuda::std::memory_order o = cuda::std::memory_order_seq_cst; assert(static_cast<int>(o) == 5); return 0; }
33.717949
80
0.624335
wmaxey
bd717254f479e9cdd051a705e97758ca777a24b8
9,223
hpp
C++
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
3
2018-03-21T18:04:42.000Z
2018-05-30T09:27:29.000Z
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
2
2018-06-28T14:39:19.000Z
2018-07-04T02:07:02.000Z
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
5
2018-05-24T10:59:32.000Z
2021-08-06T15:57:58.000Z
// ---------------------------------------------------------------------------- // @file lpc81x_pin.hpp // @brief NXP LPC81x pin class. // @date 28 February 2019 // ---------------------------------------------------------------------------- // // Xarmlib 0.1.0 - https://github.com/hparracho/Xarmlib // Copyright (c) 2018 Helder Parracho (hparracho@gmail.com) // // See README.md file for additional credits and acknowledgments. // // 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 __XARMLIB_TARGETS_LPC81X_PIN_HPP #define __XARMLIB_TARGETS_LPC81X_PIN_HPP #include "targets/LPC81x/lpc81x_cmsis.hpp" #include "core/target_specs.hpp" #include <array> #include <cassert> namespace xarmlib { namespace targets { namespace lpc81x { class PinDriver { public: // -------------------------------------------------------------------- // PUBLIC DEFINITIONS // -------------------------------------------------------------------- // Pin names according to the target package enum class Name { // The following pins are present in all packages p0_0 = 0, p0_1, p0_2, p0_3, p0_4, p0_5, #if (TARGET_PACKAGE_PIN_COUNT >= 16) // The following pins are only present in // TSSOP16 / XSON16 / SO20 / TSSOP20 packages p0_6, p0_7, p0_8, p0_9, p0_10, p0_11, p0_12, p0_13, #endif // (TARGET_PACKAGE_PIN_COUNT >= 16) #if (TARGET_PACKAGE_PIN_COUNT == 20) // The following pins are only present in // SO20 / TSSOP20 packages p0_14, p0_15, p0_16, p0_17, #endif // (TARGET_PACKAGE_PIN_COUNT == 20) // Not connected nc }; // Function modes (defined to map the PIO register directly) enum class FunctionMode { hiz = (0 << 3), pull_down = (1 << 3), pull_up = (2 << 3), repeater = (3 << 3) }; // Input hysteresis (defined to map the PIO register directly) enum class InputHysteresis { disable = (0 << 5), enable = (1 << 5) }; // Input invert (defined to map the PIO register directly) enum class InputInvert { normal = (0 << 6), inverted = (1 << 6) }; // I2C mode (defined to map the PIO register directly) enum class I2cMode { standard_fast_i2c = (0 << 8), standard_gpio = (1 << 8), fast_plus_i2c = (2 << 8) }; // Open-drain mode (defined to map the PIO register directly) enum class OpenDrain { disable = (0 << 10), enable = (1 << 10) }; // Input filter samples (defined to map the PIO register directly) enum class InputFilter { bypass = (0 << 11), clocks_1_clkdiv0 = (1 << 11) | (0 << 13), clocks_1_clkdiv1 = (1 << 11) | (1 << 13), clocks_1_clkdiv2 = (1 << 11) | (2 << 13), clocks_1_clkdiv3 = (1 << 11) | (3 << 13), clocks_1_clkdiv4 = (1 << 11) | (4 << 13), clocks_1_clkdiv5 = (1 << 11) | (5 << 13), clocks_1_clkdiv6 = (1 << 11) | (6 << 13), clocks_2_clkdiv0 = (2 << 11) | (0 << 13), clocks_2_clkdiv1 = (2 << 11) | (1 << 13), clocks_2_clkdiv2 = (2 << 11) | (2 << 13), clocks_2_clkdiv3 = (2 << 11) | (3 << 13), clocks_2_clkdiv4 = (2 << 11) | (4 << 13), clocks_2_clkdiv5 = (2 << 11) | (5 << 13), clocks_2_clkdiv6 = (2 << 11) | (6 << 13), clocks_3_clkdiv0 = (3 << 11) | (0 << 13), clocks_3_clkdiv1 = (3 << 11) | (1 << 13), clocks_3_clkdiv2 = (3 << 11) | (2 << 13), clocks_3_clkdiv3 = (3 << 11) | (3 << 13), clocks_3_clkdiv4 = (3 << 11) | (4 << 13), clocks_3_clkdiv5 = (3 << 11) | (5 << 13), clocks_3_clkdiv6 = (3 << 11) | (6 << 13) }; // -------------------------------------------------------------------- // PUBLIC MEMBER FUNCTIONS // -------------------------------------------------------------------- // Set mode of normal pins static void set_mode(const Name pin_name, const FunctionMode function_mode, const OpenDrain open_drain = OpenDrain::disable, const InputFilter input_filter = InputFilter::bypass, const InputInvert input_invert = InputInvert::normal, const InputHysteresis input_hysteresis = InputHysteresis::enable) { // Exclude NC assert(pin_name != Name::nc); #if (TARGET_PACKAGE_PIN_COUNT >= 16) // Exclude true open-drain pins assert(pin_name != Name::p0_10 && pin_name != Name::p0_11); #endif const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)]; LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(function_mode) | static_cast<uint32_t>(input_hysteresis) | static_cast<uint32_t>(input_invert) | static_cast<uint32_t>(open_drain) | (1 << 7) // RESERVED | static_cast<uint32_t>(input_filter); } #if (TARGET_PACKAGE_PIN_COUNT >= 16) // Set mode of true open-drain pins (only available on P0_10 and P0_11) static void set_mode(const Name pin_name, const I2cMode i2c_mode, const InputFilter input_filter, const InputInvert input_invert) { // Available only on true open-drain pins assert(pin_name == Name::p0_10 || pin_name == Name::p0_11); const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)]; LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(input_invert) | (1 << 7) // RESERVED | static_cast<uint32_t>(i2c_mode) | static_cast<uint32_t>(input_filter); } #endif private: // -------------------------------------------------------------------- // PRIVATE DEFINITIONS // -------------------------------------------------------------------- // IOCON pin values static constexpr std::array<uint8_t, TARGET_GPIO_COUNT> m_pin_number_to_iocon { // The following pins are present in all packages // PORT0 0x11, // p0.0 0x0b, // p0.1 0x06, // p0.2 0x05, // p0.3 0x04, // p0.4 0x03, // p0.5 #if (TARGET_PACKAGE_PIN_COUNT >= 16) // The following pins are only present in // TSSOP16 / XSON16 / SO20 / TSSOP20 packages 0x10, // p0.6 0x0f, // p0.7 0x0e, // p0.8 0x0d, // p0.9 0x08, // p0.10 0x07, // p0.11 0x02, // p0.12 0x01, // p0.13 #endif // (TARGET_PACKAGE_PIN_COUNT >= 16) #if (TARGET_PACKAGE_PIN_COUNT == 20) // The following pins are only present in // SO20 / TSSOP20 packages 0x12, // p0.14 0x0a, // p0.15 0x09, // p0.16 0x00 // p0.17 #endif // (TARGET_PACKAGE_PIN_COUNT == 20) }; }; } // namespace lpc81x } // namespace targets } // namespace xarmlib #endif // __XARMLIB_TARGETS_LPC81X_PIN_HPP
35.748062
115
0.479996
hparracho
bd7259cbf18f2a5279e6c1dfe77392674b0b55cd
3,804
cc
C++
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/qualitycheck/model/GetPrecisionTaskResult.h> #include <json/json.h> using namespace AlibabaCloud::Qualitycheck; using namespace AlibabaCloud::Qualitycheck::Model; GetPrecisionTaskResult::GetPrecisionTaskResult() : ServiceResult() {} GetPrecisionTaskResult::GetPrecisionTaskResult(const std::string &payload) : ServiceResult() { parse(payload); } GetPrecisionTaskResult::~GetPrecisionTaskResult() {} void GetPrecisionTaskResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["Name"].isNull()) data_.name = dataNode["Name"].asString(); if(!dataNode["Source"].isNull()) data_.source = std::stoi(dataNode["Source"].asString()); if(!dataNode["DataSetId"].isNull()) data_.dataSetId = std::stol(dataNode["DataSetId"].asString()); if(!dataNode["DataSetName"].isNull()) data_.dataSetName = dataNode["DataSetName"].asString(); if(!dataNode["TaskId"].isNull()) data_.taskId = dataNode["TaskId"].asString(); if(!dataNode["Duration"].isNull()) data_.duration = std::stoi(dataNode["Duration"].asString()); if(!dataNode["UpdateTime"].isNull()) data_.updateTime = dataNode["UpdateTime"].asString(); if(!dataNode["Status"].isNull()) data_.status = std::stoi(dataNode["Status"].asString()); if(!dataNode["TotalCount"].isNull()) data_.totalCount = std::stoi(dataNode["TotalCount"].asString()); if(!dataNode["VerifiedCount"].isNull()) data_.verifiedCount = std::stoi(dataNode["VerifiedCount"].asString()); if(!dataNode["IncorrectWords"].isNull()) data_.incorrectWords = std::stoi(dataNode["IncorrectWords"].asString()); auto allPrecisionsNode = dataNode["Precisions"]["Precision"]; for (auto dataNodePrecisionsPrecision : allPrecisionsNode) { Data::Precision precisionObject; if(!dataNodePrecisionsPrecision["ModelName"].isNull()) precisionObject.modelName = dataNodePrecisionsPrecision["ModelName"].asString(); if(!dataNodePrecisionsPrecision["ModelId"].isNull()) precisionObject.modelId = std::stol(dataNodePrecisionsPrecision["ModelId"].asString()); if(!dataNodePrecisionsPrecision["Precision"].isNull()) precisionObject.precision = std::stof(dataNodePrecisionsPrecision["Precision"].asString()); if(!dataNodePrecisionsPrecision["Status"].isNull()) precisionObject.status = std::stoi(dataNodePrecisionsPrecision["Status"].asString()); if(!dataNodePrecisionsPrecision["TaskId"].isNull()) precisionObject.taskId = dataNodePrecisionsPrecision["TaskId"].asString(); data_.precisions.push_back(precisionObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string GetPrecisionTaskResult::getMessage()const { return message_; } GetPrecisionTaskResult::Data GetPrecisionTaskResult::getData()const { return data_; } std::string GetPrecisionTaskResult::getCode()const { return code_; } bool GetPrecisionTaskResult::getSuccess()const { return success_; }
34.581818
94
0.740799
aliyun
bd75be9438489717135ee58ddca13deac6e3e5ae
444
cpp
C++
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
//Escrever um novo vetor,atraves de dois outros,mutiplicando valores de mesmo indice, #include<stdio.h> #include<conio.h> main() { int cont,num[10],num2[10],resul[10]; for (cont=0 ; cont<=9 ; cont++) { printf("Digite um valor "); scanf("%i",&num[10]); } for(cont=0; cont<=9 ; cont++) { printf("Digite um outro valor "); scanf("%i",&num2[10]); } for(cont=0 ; cont<=9 ; cont++) { resul[10]=num[cont]*num2[cont]; printf("%i",&resul); } getch(); }
18.5
85
0.632883
ewertonpugliesi