hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
842e4a7a09162563e9e5a60f30e5147843ad4046
1,410
cpp
C++
test/unit/IR/Type.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
17
2021-03-04T01:10:22.000Z
2022-03-30T18:33:14.000Z
test/unit/IR/Type.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
320
2020-11-16T02:42:50.000Z
2022-03-31T16:43:26.000Z
test/unit/IR/Type.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
6
2020-11-10T02:37:10.000Z
2021-12-25T06:58:44.000Z
#include "caffeine/IR/Type.h" #include "caffeine/IR/Operation.h" #include "caffeine/IR/Value.h" #include <llvm/IR/DataLayout.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Type.h> #include <gtest/gtest.h> using namespace caffeine; using llvm::LLVMContext; static const char* const X86_64_LINUX = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"; TEST(ir_type, byte_size_bool) { Type type = Type::bool_ty(); llvm::DataLayout layout{X86_64_LINUX}; ASSERT_EQ(type.byte_size(layout), 1); } TEST(ir_type, byte_size_void) { Type type = Type::void_ty(); llvm::DataLayout layout{X86_64_LINUX}; ASSERT_EQ(type.byte_size(layout), 0); } TEST(ir_type, print_void) { std::stringstream output; Type type = Type::void_ty(); output << type; ASSERT_EQ(output.str(), "void"); } TEST(ir_type, print_int) { std::stringstream output; Type type = Type::int_ty(1); output << type; ASSERT_EQ(output.str(), "i1"); } TEST(ir_type, print_ptr) { std::stringstream output; Type type = Type::pointer_ty(); output << type; ASSERT_EQ(output.str(), "void*"); } TEST(ir_type, print_array) { std::stringstream output; Type type = Type::array_ty(4); output << type; ASSERT_EQ(output.str(), "array"); } TEST(ir_type, print_vector) { std::stringstream output; Type type = Type::vector_ty(); output << type; ASSERT_EQ(output.str(), "vector"); }
20.434783
77
0.684397
[ "vector" ]
842f2aa4783c3213922c93ac6566ac3aa9b3b476
15,063
cpp
C++
shell/ext/webcheck/droptrgt.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/ext/webcheck/droptrgt.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/ext/webcheck/droptrgt.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "private.h" #include "offl_cpp.h" #include "subsmgrp.h" HRESULT _GetURLData(IDataObject *pdtobj, int iDropType, TCHAR *pszUrl, UINT cchUrl, TCHAR *pszName, UINT cchName); HRESULT _ConvertHDROPData(IDataObject *, BOOL); HRESULT ScheduleDefault(LPCTSTR, LPCTSTR); #define CITBDTYPE_HDROP 1 #define CITBDTYPE_URL 2 #define CITBDTYPE_TEXT 3 // // Constructor // COfflineDropTarget::COfflineDropTarget(HWND hwndParent) { m_cRefs = 1; m_hwndParent = hwndParent; m_pDataObj = NULL; m_grfKeyStateLast = 0; m_fHasHDROP = FALSE; m_fHasSHELLURL = FALSE; m_fHasTEXT = FALSE; m_dwEffectLastReturned = 0; DllAddRef(); } // // Destructor // COfflineDropTarget::~COfflineDropTarget() { DllRelease(); } // // QueryInterface // STDMETHODIMP COfflineDropTarget::QueryInterface(REFIID riid, LPVOID *ppv) { HRESULT hr = E_NOINTERFACE; *ppv = NULL; // Any interface on this object is the object pointer if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDropTarget)) { *ppv = (LPDROPTARGET)this; AddRef(); hr = NOERROR; } return hr; } // // AddRef // STDMETHODIMP_(ULONG) COfflineDropTarget::AddRef() { return ++m_cRefs; } // // Release // STDMETHODIMP_(ULONG) COfflineDropTarget::Release() { if (0L != --m_cRefs) { return m_cRefs; } delete this; return 0L; } // // DragEnter // STDMETHODIMP COfflineDropTarget::DragEnter(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect) { // Release any old data object we might have // TraceMsg(TF_SUBSFOLDER, TEXT("odt - DragEnter")); if (m_pDataObj) { m_pDataObj->Release(); } m_grfKeyStateLast = grfKeyState; m_pDataObj = pDataObj; // // See if we will be able to get CF_HDROP from this guy // if (pDataObj) { pDataObj->AddRef(); TCHAR url[INTERNET_MAX_URL_LENGTH], name[MAX_NAME_QUICKLINK]; FORMATETC fe = {(CLIPFORMAT) RegisterClipboardFormat(CFSTR_SHELLURL), NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; m_fHasSHELLURL = m_fHasHDROP = m_fHasTEXT = FALSE; if (NOERROR == pDataObj->QueryGetData(&fe)) { TraceMsg(TF_SUBSFOLDER, "odt - DragEnter : SHELLURL!"); m_fHasSHELLURL = (NOERROR == _GetURLData(pDataObj,CITBDTYPE_URL,url,ARRAYSIZE(url),name, ARRAYSIZE(name))); } if (fe.cfFormat = CF_HDROP, NOERROR == pDataObj->QueryGetData(&fe)) { TraceMsg(TF_SUBSFOLDER, "odt - DragEnter : HDROP!"); m_fHasHDROP = (NOERROR == _ConvertHDROPData(pDataObj, FALSE)); } if (fe.cfFormat = CF_TEXT, NOERROR == pDataObj->QueryGetData(&fe)) { TraceMsg(TF_SUBSFOLDER, "odt - DragEnter : TEXT!"); m_fHasTEXT = (NOERROR == _GetURLData(pDataObj,CITBDTYPE_TEXT,url,ARRAYSIZE(url),name, ARRAYSIZE(name))); } } // Save the drop effect if (pdwEffect) { *pdwEffect = m_dwEffectLastReturned = GetDropEffect(pdwEffect); } return S_OK; } // // GetDropEffect // DWORD COfflineDropTarget::GetDropEffect(LPDWORD pdwEffect) { ASSERT(pdwEffect); if (m_fHasSHELLURL || m_fHasTEXT) { return *pdwEffect & (DROPEFFECT_COPY | DROPEFFECT_LINK); } else if (m_fHasHDROP) { return *pdwEffect & (DROPEFFECT_COPY ); } else { return DROPEFFECT_NONE; } } // // DragOver // STDMETHODIMP COfflineDropTarget::DragOver(DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect) { // TraceMsg(TF_SUBSFOLDER, TEXT("odt - DragOver")); if (m_grfKeyStateLast == grfKeyState) { // Return the effect we saved at dragenter time if (*pdwEffect) { *pdwEffect = m_dwEffectLastReturned; } } else { if (*pdwEffect) { *pdwEffect = m_dwEffectLastReturned = GetDropEffect(pdwEffect); } } m_grfKeyStateLast = grfKeyState; return S_OK; } // // DragLeave // STDMETHODIMP COfflineDropTarget::DragLeave() { // TraceMsg(TF_SUBSFOLDER, TEXT("odt - DragLeave")); if (m_pDataObj) { m_pDataObj->Release(); m_pDataObj = NULL; } return S_OK; } // // Drop // STDMETHODIMP COfflineDropTarget::Drop(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect) { // UINT idCmd; // Choice from drop popup menu HRESULT hr = S_OK; // // Take the new data object, since OLE can give us a different one than // it did in DragEnter // // TraceMsg(TF_SUBSFOLDER, TEXT("odt - Drop")); if (m_pDataObj) { m_pDataObj->Release(); } m_pDataObj = pDataObj; if (pDataObj) { pDataObj->AddRef(); } // If the dataobject doesn't have an HDROP, its not much good to us *pdwEffect &= DROPEFFECT_COPY|DROPEFFECT_LINK; if (!(*pdwEffect)) { DragLeave(); return S_OK; } hr = E_NOINTERFACE; if (m_fHasHDROP) hr = _ConvertHDROPData(pDataObj, TRUE); else { TCHAR url[INTERNET_MAX_URL_LENGTH], name[MAX_NAME_QUICKLINK]; if (m_fHasSHELLURL) hr = _GetURLData(pDataObj, CITBDTYPE_URL, url, ARRAYSIZE(url), name, ARRAYSIZE(name)); if (FAILED(hr) && m_fHasTEXT) hr = _GetURLData(pDataObj, CITBDTYPE_TEXT, url, ARRAYSIZE(url), name, ARRAYSIZE(name)); if (SUCCEEDED(hr)) { TraceMsg(TF_SUBSFOLDER, "URL: %s, Name: %s", url, name); hr = ScheduleDefault(url, name); } } if (FAILED(hr)) { TraceMsg(TF_SUBSFOLDER, "Couldn't DROP"); } DragLeave(); return hr; } HRESULT _CLSIDFromExtension( LPCTSTR pszExt, CLSID *pclsid) { TCHAR szProgID[80]; long cb = SIZEOF(szProgID); if (RegQueryValue(HKEY_CLASSES_ROOT, pszExt, szProgID, &cb) == ERROR_SUCCESS) { TCHAR szCLSID[80]; StrCatBuff(szProgID, TEXT("\\CLSID"), ARRAYSIZE(szProgID)); cb = SIZEOF(szCLSID); if (RegQueryValue(HKEY_CLASSES_ROOT, szProgID, szCLSID, &cb) == ERROR_SUCCESS) { // FEATURE (scotth): call shell32's SHCLSIDFromString once it // exports A/W versions. This would clean this // up. return CLSIDFromString(szCLSID, pclsid); } } return E_FAIL; } // get the target of a shortcut. this uses IShellLink which // Internet Shortcuts (.URL) and Shell Shortcuts (.LNK) support so // it should work generally // HRESULT _GetURLTarget(LPCTSTR pszPath, LPTSTR pszTarget, UINT cch) { IShellLink *psl; HRESULT hr = E_FAIL; CLSID clsid; if (FAILED(_CLSIDFromExtension(PathFindExtension(pszPath), &clsid))) clsid = CLSID_ShellLink; // assume it's a shell link hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl); if (SUCCEEDED(hr)) { IPersistFile *ppf; hr = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); if (SUCCEEDED(hr)) { hr = ppf->Load(pszPath, 0); ppf->Release(); } if (SUCCEEDED(hr)) { IUniformResourceLocator * purl; hr = psl->QueryInterface(IID_IUniformResourceLocator,(void**)&purl); if (SUCCEEDED(hr)) purl->Release(); } if (SUCCEEDED(hr)) hr = psl->GetPath(pszTarget, cch, NULL, SLGP_UNCPRIORITY); psl->Release(); } return hr; } HRESULT _ConvertHDROPData(IDataObject *pdtobj, BOOL bSubscribe) { HRESULT hRes = NOERROR; STGMEDIUM stgmedium; FORMATETC formatetc; TCHAR url[INTERNET_MAX_URL_LENGTH]; TCHAR name[MAX_NAME_QUICKLINK]; name[0] = 0; url[0] = 0; formatetc.cfFormat = CF_HDROP; formatetc.ptd = NULL; formatetc.dwAspect = DVASPECT_CONTENT; formatetc.lindex = -1; formatetc.tymed = TYMED_HGLOBAL; // Get the parse string hRes = pdtobj->GetData(&formatetc, &stgmedium); if (SUCCEEDED(hRes)) { LPTSTR pszURLData = (LPTSTR)GlobalLock(stgmedium.hGlobal); if (pszURLData) { TCHAR szPath[MAX_PATH]; SHFILEINFO sfi; int cFiles, i; HDROP hDrop = (HDROP)stgmedium.hGlobal; hRes = S_FALSE; cFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0); for (i = 0; i < cFiles; i ++) { DragQueryFile(hDrop, i, szPath, ARRAYSIZE(szPath)); // defaults... StrCpyN(name, szPath, ARRAYSIZE(name)); if (SHGetFileInfo(szPath, 0, &sfi, sizeof(sfi), SHGFI_DISPLAYNAME)) StrCpyN(name, sfi.szDisplayName, ARRAYSIZE(name)); if (SHGetFileInfo(szPath, 0, &sfi, sizeof(sfi),SHGFI_ATTRIBUTES) && (sfi.dwAttributes & SFGAO_LINK)) { if (SUCCEEDED(_GetURLTarget(szPath, url, INTERNET_MAX_URL_LENGTH))) { TraceMsg(TF_SUBSFOLDER, "URL: %s, Name: %s", url, name); // If we just want to see whether there is some urls // here, we can break now. if (!bSubscribe) { if ((IsHTTPPrefixed(url)) && (!SHRestricted2(REST_NoAddingSubscriptions, url, 0))) { hRes = S_OK; } break; } hRes = ScheduleDefault(url, name); } } } GlobalUnlock(stgmedium.hGlobal); if (bSubscribe) hRes = S_OK; } else hRes = S_FALSE; ReleaseStgMedium(&stgmedium); } return hRes; } // Takes a variety of inputs and returns a string for drop targets. // szUrl: the URL // szName: the name (for quicklinks and the confo dialog boxes) // returns: NOERROR if succeeded // HRESULT _GetURLData(IDataObject *pdtobj, int iDropType, TCHAR *pszUrl, UINT cchUrl, TCHAR *pszName, UINT cchName) { HRESULT hRes = NOERROR; STGMEDIUM stgmedium; FORMATETC formatetc; *pszName = 0; *pszUrl = 0; switch (iDropType) { case CITBDTYPE_URL: formatetc.cfFormat = (CLIPFORMAT) RegisterClipboardFormat(CFSTR_SHELLURL); break; case CITBDTYPE_TEXT: formatetc.cfFormat = CF_TEXT; break; default: return E_UNEXPECTED; } formatetc.ptd = NULL; formatetc.dwAspect = DVASPECT_CONTENT; formatetc.lindex = -1; formatetc.tymed = TYMED_HGLOBAL; // Get the parse string hRes = pdtobj->GetData(&formatetc, &stgmedium); if (SUCCEEDED(hRes)) { LPTSTR pszURLData = (LPTSTR)GlobalLock(stgmedium.hGlobal); if (pszURLData) { if (iDropType == CITBDTYPE_URL) { STGMEDIUM stgmediumFGD; // defaults StrCpyN(pszUrl, pszURLData, cchUrl); StrCpyN(pszName, pszURLData, cchName); formatetc.cfFormat = (CLIPFORMAT) RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR); if (SUCCEEDED(pdtobj->GetData(&formatetc, &stgmediumFGD))) { FILEGROUPDESCRIPTOR *pfgd = (FILEGROUPDESCRIPTOR *)GlobalLock(stgmediumFGD.hGlobal); if (pfgd) { TCHAR szPath[MAX_PATH]; StrCpyN(szPath, pfgd->fgd[0].cFileName, ARRAYSIZE(szPath)); PathRemoveExtension(szPath); StrCpyN(pszName, szPath, cchName); GlobalUnlock(stgmediumFGD.hGlobal); } ReleaseStgMedium(&stgmediumFGD); } } else if (iDropType == CITBDTYPE_TEXT) { if (PathIsURL(pszURLData)) { StrCpyN(pszUrl, pszURLData, cchUrl); StrCpyN(pszName, pszURLData, cchName); } else hRes = E_FAIL; } GlobalUnlock(stgmedium.hGlobal); } ReleaseStgMedium(&stgmedium); } if (SUCCEEDED(hRes)) { if (!IsHTTPPrefixed(pszUrl) || SHRestricted2(REST_NoAddingSubscriptions, pszUrl, 0)) { hRes = E_FAIL; } } return hRes; } HRESULT ScheduleDefault(LPCTSTR url, LPCTSTR name) { if (!IsHTTPPrefixed(url)) return E_INVALIDARG; ISubscriptionMgr * pSub= NULL; HRESULT hr = CoInitialize(NULL); RETURN_ON_FAILURE(hr); hr = CoCreateInstance(CLSID_SubscriptionMgr, NULL, CLSCTX_INPROC_SERVER, IID_ISubscriptionMgr, (void **)&pSub); CoUninitialize(); RETURN_ON_FAILURE(hr); ASSERT(pSub); BSTR bstrURL = NULL, bstrName = NULL; hr = CreateBSTRFromTSTR(&bstrURL, url); if (S_OK == hr) hr = CreateBSTRFromTSTR(&bstrName, name); // We need a perfectly valid structure. SUBSCRIPTIONINFO subInfo; ZeroMemory((void *)&subInfo, sizeof (subInfo)); subInfo.cbSize = sizeof(SUBSCRIPTIONINFO); if (S_OK == hr) hr = pSub->CreateSubscription(NULL, bstrURL, bstrName, CREATESUBS_NOUI, SUBSTYPE_URL, &subInfo); SAFERELEASE(pSub); SAFEFREEBSTR(bstrURL); SAFEFREEBSTR(bstrName); if (FAILED(hr)) { TraceMsg(TF_ALWAYS, "Failed to add default object."); TraceMsg(TF_ALWAYS, " hr = 0x%x\n", hr); return (FAILED(hr))?hr:E_FAIL; } else if (hr == S_FALSE) { TraceMsg(TF_SUBSFOLDER, "%s(%s) is already there.", url, name); return hr; } return S_OK; }
27.842884
115
0.534887
[ "object" ]
8439b9e557e02d18f7f09145f0f6d8453f6a7207
2,158
hpp
C++
src/hotspot/share/gc/shared/stringdedup/stringDedupStorageUse.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/gc/shared/stringdedup/stringDedupStorageUse.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/gc/shared/stringdedup/stringDedupStorageUse.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_GC_SHARED_STRINGDEDUP_STRINGDEDUPSTORAGEUSE_HPP #define SHARE_GC_SHARED_STRINGDEDUP_STRINGDEDUPSTORAGEUSE_HPP #include "gc/shared/stringdedup/stringDedup.hpp" #include "memory/allocation.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/macros.hpp" class OopStorage; // Manage access to one of the OopStorage objects used for requests. class StringDedup::StorageUse : public CHeapObj<mtStringDedup> { OopStorage* const _storage; volatile size_t _use_count; NONCOPYABLE(StorageUse); public: explicit StorageUse(OopStorage* storage); OopStorage* storage() const { return _storage; } // Return true if the storage is currently in use for registering requests. bool is_used_acquire() const; // Get the current requests object, and increment its in-use count. static StorageUse* obtain(StorageUse* volatile* ptr); // Discard a prior "obtain" request, decrementing the in-use count, and // permitting the deduplication thread to start processing if needed. void relinquish(); }; #endif // SHARE_GC_SHARED_STRINGDEDUP_STRINGDEDUPSTORAGEUSE_HPP
36.576271
77
0.769694
[ "object" ]
843cfb7b698461733b82b82c61830943dec29003
9,688
cpp
C++
arangod/Cluster/FailureOracleFeature.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
arangod/Cluster/FailureOracleFeature.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
arangod/Cluster/FailureOracleFeature.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
/// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Alex Petenchea /// @author Manuel Pöter //////////////////////////////////////////////////////////////////////////////// #include "FailureOracleFeature.h" #include "ApplicationFeatures/ApplicationFeature.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/TimeString.h" #include "Basics/application-exit.h" #include "Basics/system-compiler.h" #include "Cluster/AgencyCache.h" #include "Cluster/AgencyCallback.h" #include "Cluster/ClusterFeature.h" #include "Cluster/FailureOracle.h" #include "Scheduler/Scheduler.h" #include "Scheduler/SchedulerFeature.h" #include <atomic> #include <chrono> #include <memory> #include <shared_mutex> namespace arangodb::cluster { namespace { constexpr auto kSupervisionHealthPath = "Supervision/Health"; constexpr auto kHealthyServerKey = "Status"; [[maybe_unused]] constexpr auto kServerStatusGood = "GOOD"; [[maybe_unused]] constexpr auto kServerStatusBad = "BAD"; constexpr auto kServerStatusFailed = "FAILED"; } // namespace class FailureOracleImpl final : public IFailureOracle, public std::enable_shared_from_this<FailureOracleImpl> { public: explicit FailureOracleImpl(ClusterFeature&); auto isServerFailed(std::string_view const serverId) const noexcept -> bool override { std::shared_lock readLock(_mutex); if (auto status = _isFailed.find(std::string(serverId)); status != std::end(_isFailed)) { return status->second; } return true; } void start(); void stop(); auto getStatus() -> FailureOracleFeature::Status; void reload(VPackSlice result, consensus::index_t raftIndex); void flush(); void scheduleFlush() noexcept; template<typename Server> void createAgencyCallback(Server& server); private: mutable std::shared_mutex _mutex; FailureOracleFeature::FailureMap _isFailed; consensus::index_t _lastRaftIndex{0}; std::shared_ptr<AgencyCallback> _agencyCallback; Scheduler::WorkHandle _flushJob; ClusterFeature& _clusterFeature; std::atomic_bool _isRunning; std::chrono::system_clock::time_point _lastUpdated; }; FailureOracleImpl::FailureOracleImpl(ClusterFeature& _clusterFeature) : _clusterFeature{_clusterFeature} {}; void FailureOracleImpl::start() { _isRunning.store(true); auto agencyCallbackRegistry = _clusterFeature.agencyCallbackRegistry(); if (!agencyCallbackRegistry) { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "Expected non-null AgencyCallbackRegistry " "while starting FailureOracle."); TRI_ASSERT(false); } LOG_TOPIC("848eb", DEBUG, Logger::CLUSTER) << "Started Failure Oracle"; Result res = agencyCallbackRegistry->registerCallback(_agencyCallback, true); if (res.fail()) { THROW_ARANGO_EXCEPTION(res); TRI_ASSERT(false); } scheduleFlush(); } void FailureOracleImpl::stop() { _isRunning.store(false); LOG_TOPIC("cf940", DEBUG, Logger::CLUSTER) << "Stopping Failure Oracle"; try { auto agencyCallbackRegistry = _clusterFeature.agencyCallbackRegistry(); if (agencyCallbackRegistry) { agencyCallbackRegistry->unregisterCallback(_agencyCallback); } } catch (std::exception const& ex) { LOG_TOPIC("42bf2", WARN, Logger::CLUSTER) << "Caught unexpected exception while unregistering agency callback " "for FailureOracleImpl: " << ex.what(); } _flushJob->cancel(); } auto FailureOracleImpl::getStatus() -> FailureOracleFeature::Status { std::shared_lock readLock(_mutex); return FailureOracleFeature::Status{.isFailed = _isFailed, .lastUpdated = _lastUpdated}; } void FailureOracleImpl::reload(VPackSlice result, consensus::index_t raftIndex) { FailureOracleFeature::FailureMap isFailed; for (auto const [key, value] : VPackObjectIterator(result)) { auto const serverId = key.copyString(); auto const isServerFailed = value.get(kHealthyServerKey).isEqualString(kServerStatusFailed); isFailed[serverId] = isServerFailed; } std::unique_lock writeLock(_mutex); if (_lastRaftIndex >= raftIndex) { LOG_TOPIC("289b0", TRACE, Logger::CLUSTER) << "skipping reload with old raft index " << raftIndex << "; already at " << _lastRaftIndex; return; } std::swap(_isFailed, isFailed); _lastRaftIndex = raftIndex; _lastUpdated = std::chrono::system_clock::now(); if (ADB_UNLIKELY(Logger::isEnabled(LogLevel::TRACE, Logger::CLUSTER))) { if (isFailed != _isFailed) { LOG_TOPIC("321d2", TRACE, Logger::CLUSTER) << "reloading with " << _isFailed << " at " << timepointToString(_lastUpdated); } } } void FailureOracleImpl::flush() { if (!_isRunning.load()) { LOG_TOPIC("65a8b", TRACE, Logger::CLUSTER) << "Failure Oracle feature no longer running, ignoring flush"; return; } AgencyCache& agencyCache = _clusterFeature.agencyCache(); auto [builder, raftIndex] = agencyCache.get(kSupervisionHealthPath); if (auto result = builder->slice(); !result.isNone()) { TRI_ASSERT(result.isObject()) << " expected object in agency at " << kSupervisionHealthPath << " but got " << result.toString(); reload(result, raftIndex); } else { LOG_TOPIC("f6403", ERR, Logger::CLUSTER) << "Agency cache returned no result for " << kSupervisionHealthPath; TRI_ASSERT(false); } } void FailureOracleImpl::scheduleFlush() noexcept { using namespace std::chrono_literals; auto scheduler = SchedulerFeature::SCHEDULER; if (!scheduler) { LOG_TOPIC("6c08b", ERR, Logger::CLUSTER) << "Scheduler unavailable, aborting scheduled flushes."; return; } _flushJob = scheduler->queueDelayed( RequestLane::AGENCY_CLUSTER, 50s, [weak = weak_from_this()](bool canceled) { auto self = weak.lock(); if (self && !canceled && self->_isRunning.load()) { try { self->flush(); } catch (std::exception& ex) { LOG_TOPIC("42bf3", FATAL, Logger::CLUSTER) << "Exception while flushing the failure oracle " << ex.what(); FATAL_ERROR_EXIT(); } self->scheduleFlush(); } else { LOG_TOPIC("b5839", DEBUG, Logger::CLUSTER) << "Failure Oracle is gone, exiting scheduled flush loop."; } }); } template<typename Server> void FailureOracleImpl::createAgencyCallback(Server& server) { TRI_ASSERT(_agencyCallback == nullptr); _agencyCallback = std::make_shared<AgencyCallback>( server, kSupervisionHealthPath, [weak = weak_from_this()](VPackSlice result, consensus::index_t raftIndex) { auto self = weak.lock(); if (self) { if (!result.isNone()) { TRI_ASSERT(result.isObject()) << " expected object in agency at " << kSupervisionHealthPath << " but got " << result.toString(); self->reload(result, raftIndex); } else { LOG_TOPIC("581ba", WARN, Logger::CLUSTER) << "Failure Oracle callback got no result, skipping reload"; } } else { LOG_TOPIC("453b4", DEBUG, Logger::CLUSTER) << "Failure Oracle is gone, ignoring agency callback"; } return true; }, true, true); } FailureOracleFeature::FailureOracleFeature(Server& server) : ArangodFeature{server, *this} { setOptional(true); startsAfter<SchedulerFeature>(); startsAfter<ClusterFeature>(); onlyEnabledWith<SchedulerFeature>(); onlyEnabledWith<ClusterFeature>(); } void FailureOracleFeature::prepare() { bool const enabled = ServerState::instance()->isCoordinator() || ServerState::instance()->isDBServer(); setEnabled(enabled); } void FailureOracleFeature::start() { TRI_ASSERT(_cache == nullptr); _cache = std::make_shared<FailureOracleImpl>( server().getEnabledFeature<ClusterFeature>()); _cache->createAgencyCallback(server()); _cache->start(); LOG_TOPIC("42af3", DEBUG, Logger::CLUSTER) << "FailureOracleFeature is ready"; } void FailureOracleFeature::stop() { _cache->stop(); } auto FailureOracleFeature::status() -> Status { return _cache->getStatus(); } void FailureOracleFeature::flush() { _cache->flush(); } auto FailureOracleFeature::getFailureOracle() -> std::shared_ptr<IFailureOracle> { return std::static_pointer_cast<IFailureOracle>(_cache); } void FailureOracleFeature::Status::toVelocyPack( velocypack::Builder& builder) const { VPackObjectBuilder ob(&builder); builder.add("lastUpdated", VPackValue(timepointToString(lastUpdated))); { VPackObjectBuilder ob2(&builder, "isFailed"); for (auto const& [pid, status] : isFailed) { builder.add(pid, VPackValue(status)); } } } } // namespace arangodb::cluster
33.178082
80
0.672998
[ "object" ]
843d5752c9e616c5e20494ecf7c4995bdca6f2ea
2,810
cpp
C++
ext/stub/java/awt/font/GlyphVector-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/awt/font/GlyphVector-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/awt/font/GlyphVector-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/awt/font/GlyphVector.hpp> extern void unimplemented_(const char16_t* name); java::awt::font::GlyphVector::GlyphVector(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::awt::font::GlyphVector::GlyphVector() : GlyphVector(*static_cast< ::default_init_tag* >(0)) { ctor(); } constexpr int32_t java::awt::font::GlyphVector::FLAG_COMPLEX_GLYPHS; constexpr int32_t java::awt::font::GlyphVector::FLAG_HAS_POSITION_ADJUSTMENTS; constexpr int32_t java::awt::font::GlyphVector::FLAG_HAS_TRANSFORMS; constexpr int32_t java::awt::font::GlyphVector::FLAG_MASK; constexpr int32_t java::awt::font::GlyphVector::FLAG_RUN_RTL; void ::java::awt::font::GlyphVector::ctor() { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::awt::font::GlyphVector::ctor()"); } int32_t java::awt::font::GlyphVector::getGlyphCharIndex(int32_t glyphIndex) { /* stub */ unimplemented_(u"int32_t java::awt::font::GlyphVector::getGlyphCharIndex(int32_t glyphIndex)"); return 0; } int32_tArray* java::awt::font::GlyphVector::getGlyphCharIndices(int32_t beginGlyphIndex, int32_t numEntries, ::int32_tArray* codeReturn) { /* stub */ unimplemented_(u"int32_tArray* java::awt::font::GlyphVector::getGlyphCharIndices(int32_t beginGlyphIndex, int32_t numEntries, ::int32_tArray* codeReturn)"); return 0; } java::awt::Shape* java::awt::font::GlyphVector::getGlyphOutline(int32_t glyphIndex, float x, float y) { /* stub */ unimplemented_(u"java::awt::Shape* java::awt::font::GlyphVector::getGlyphOutline(int32_t glyphIndex, float x, float y)"); return 0; } java::awt::Rectangle* java::awt::font::GlyphVector::getGlyphPixelBounds(int32_t index, FontRenderContext* renderFRC, float x, float y) { /* stub */ unimplemented_(u"java::awt::Rectangle* java::awt::font::GlyphVector::getGlyphPixelBounds(int32_t index, FontRenderContext* renderFRC, float x, float y)"); return 0; } int32_t java::awt::font::GlyphVector::getLayoutFlags() { /* stub */ unimplemented_(u"int32_t java::awt::font::GlyphVector::getLayoutFlags()"); return 0; } java::awt::Rectangle* java::awt::font::GlyphVector::getPixelBounds(FontRenderContext* renderFRC, float x, float y) { /* stub */ unimplemented_(u"java::awt::Rectangle* java::awt::font::GlyphVector::getPixelBounds(FontRenderContext* renderFRC, float x, float y)"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::awt::font::GlyphVector::class_() { static ::java::lang::Class* c = ::class_(u"java.awt.font.GlyphVector", 25); return c; } java::lang::Class* java::awt::font::GlyphVector::getClass0() { return class_(); }
36.025641
160
0.722776
[ "shape" ]
843e83bc740538e6423bf7bdcd6ded7009352aeb
6,826
cpp
C++
Projeto/plottermatriz.cpp
asilvadev/DCA-Modelador-3D
5f3b0795be7ca589a05e209d72822862366aa589
[ "MIT" ]
null
null
null
Projeto/plottermatriz.cpp
asilvadev/DCA-Modelador-3D
5f3b0795be7ca589a05e209d72822862366aa589
[ "MIT" ]
null
null
null
Projeto/plottermatriz.cpp
asilvadev/DCA-Modelador-3D
5f3b0795be7ca589a05e209d72822862366aa589
[ "MIT" ]
null
null
null
#include <QPainter> #include <QPen> #include <QBrush> #include <QMouseEvent> #include <QtDebug> #include <vector> #include <iostream> #include "plottermatriz.h" #include "sculptor.h" PlotterMatriz::PlotterMatriz(QWidget *parent) : QWidget(parent) { scultporTamX = 25; scultporTamY = 25; scultporTamZ = 25; cubo = new Sculptor(scultporTamX, scultporTamY, scultporTamZ); cortePlano = scultporTamZ/2; plano = 1; tamX = 1; tamY = 1; tamZ = 1; raio = 1; raioX = 1; raioY = 1; raioZ = 1; corR = 0; corG = 0; corB = 0; transparencia = 255; forma = 1; } void PlotterMatriz::paintEvent(QPaintEvent *event) { QPainter pa(this); QPen pen; QBrush brush; pen.setColor(QColor(128,128,128,255)); pen.setWidth(1); pa.setPen(pen); brush.setColor(QColor(255,255,255,0)); brush.setStyle(Qt::SolidPattern); pa.setBrush(brush); mtrz.clear(); mtrz = cubo ->readMx(cortePlano, plano); int dim1 = width()/mtrz[0].size(); int dim2 = height()/mtrz.size(); if(dim1>dim2){ tamQ=dim2; } else { tamQ=dim1; } for(unsigned int i =0; i<mtrz.size(); i++){ for(unsigned int j =0; j<mtrz[0].size(); j++){ pa.drawRect(i*tamQ,j*tamQ,tamQ, tamQ); } } for(unsigned int i=0; i<mtrz.size();i++){ //trabalhar com iterators pra desenhar voxels ligados for(unsigned int j=0; j<mtrz[0].size();j++){ if(mtrz[i][j].isOn){ brush.setColor(QColor(mtrz[i][j].r,mtrz[i][j].g,mtrz[i][j].b,mtrz[i][j].a)); //Cor setada por sliders brush.setStyle(Qt::SolidPattern); pa.setBrush(brush); int xcenter =i*tamQ; int ycenter =j*tamQ; pa.drawEllipse(xcenter,ycenter,tamQ,tamQ); } } } } void PlotterMatriz::mouseMoveEvent(QMouseEvent *event){ emit moveX(event->x()); emit moveY(event->y()); mouseX = (event->x())/tamQ; mouseY = (event->y())/tamQ; switch(plano){ case 1: posX=mouseX; posY=mouseY; posZ=cortePlano; break; case 2: posX=mouseY; posY=cortePlano; posZ=mouseX; break; case 3: posX=cortePlano; posY=mouseX; posZ=mouseY; break; case 4: posX=mouseY; posY=scultporTamY-1-mouseX; posZ=cortePlano; break; case 5: posX=scultporTamX-1-mouseX; posY=cortePlano; posZ=mouseY; break; case 6: posX=cortePlano; posY=mouseY; posZ=scultporTamZ-1-mouseX; break; case 7: posX=scultporTamX-1-mouseX; posY=scultporTamY-1-mouseY; posZ=cortePlano; break; case 8: posX=scultporTamX-1-mouseY; posY=cortePlano; posZ=scultporTamZ-1-mouseX; break; } emit mouseLinha(posX); emit mouseColuna(posY); PlotterMatriz::desenharForma(forma, mousePressed); } void PlotterMatriz::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton){ emit clickX(event->x()); emit clickY(event->y()); mousePressed = true; mouseX = (event->x())/tamQ; mouseY = (event->y())/tamQ; switch(plano){ case 1: posX=mouseX; posY=mouseY; posZ=cortePlano; break; case 2: posX=mouseY; posY=cortePlano; posZ=mouseX; break; case 3: posX=cortePlano; posY=mouseX; posZ=mouseY; break; case 4: posX=mouseY; posY=scultporTamY-1-mouseX; posZ=cortePlano; break; case 5: posX=scultporTamX-1-mouseX; posY=cortePlano; posZ=mouseY; break; case 6: posX=cortePlano; posY=mouseY; posZ=scultporTamZ-1-mouseX; break; case 7: posX=scultporTamX-1-mouseX; posY=scultporTamY-1-mouseY; posZ=cortePlano; break; case 8: posX=scultporTamX-1-mouseY; posY=cortePlano; posZ=scultporTamZ-1-mouseX; break; } emit mouseLinha(posX); emit mouseColuna(posY); PlotterMatriz::desenharForma(forma,mousePressed); } } void PlotterMatriz::mouseReleaseEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton){ mousePressed = false; } } void PlotterMatriz::desenharForma(int forma, bool mousePressed){ if(mousePressed){ if(forma == 1) { cubo->setColor(corR, corG, corB, transparencia); cubo->putVoxel(posX, posY, posZ); } if(forma == 2) { cubo->cutVoxel(posX, posY, posZ); } if(forma == 3) { cubo->setColor(corR, corG, corB, transparencia); cubo->putBox(posX, (posX+tamX), posY, (posY+tamY), posZ, (posZ+tamZ)); } if(forma == 4) { cubo->cutBox(posX, (posX+tamX), posY, (posY+tamY), posZ, (posZ+tamZ)); } if(forma == 5) { cubo->setColor(corR, corG, corB, transparencia); cubo->putSphere(posX, posY, posZ, raio); } if(forma == 6) { cubo->cutSphere(posX, posY, posZ, raio); } if(forma == 7) { cubo->setColor(corR, corG, corB, transparencia); cubo->putEllipsoid(posX, posY, posZ, raioX, raioY, raioZ); } if(forma == 8) { cubo->cutEllipsoid(posX, posY, posZ, raioX, raioY, raioZ); } repaint(); } } void PlotterMatriz::mudaCorR(int red) { corR = red; } void PlotterMatriz::mudaCorG(int green) { corG = green; } void PlotterMatriz::mudaCorB(int blue) { corB = blue; } void PlotterMatriz::mudaTransparencia(int a) { transparencia = a; } void PlotterMatriz::mudaTamX(int size) { tamX = size; } void PlotterMatriz::mudaTamY(int size) { tamY = size; } void PlotterMatriz::mudaTamZ(int size) { tamZ = size; } void PlotterMatriz::mudaRaio(int rd) { raio=rd; } void PlotterMatriz::mudaRaioX(int rx) { raioX = rx; } void PlotterMatriz::mudaRaioY(int ry) { raioY = ry; } void PlotterMatriz::mudaRaioZ(int rz) { raioZ = rz; } void PlotterMatriz::mudaCorte(int pln) { cortePlano = pln; repaint(); } void PlotterMatriz::mudaScpTamX(int scpX) { scultporTamX = scpX; } void PlotterMatriz::mudaScpTamY(int scpY) { scultporTamY = scpY; } void PlotterMatriz::mudaScpTamZ(int scpZ) { scultporTamZ = scpZ; }
20.874618
119
0.541606
[ "vector" ]
4604bb9de05543e93f3d306572d01f7a8a0aac94
770
cpp
C++
LeetCode/_0064_MinimumPathSum.cpp
Restart20200301/Algorithm-Practice
2b5f42492a1ae574d7ddc7efeebdef55a82a30a5
[ "MIT" ]
2
2020-05-26T08:25:25.000Z
2020-05-27T03:53:00.000Z
LeetCode/_0064_MinimumPathSum.cpp
Restart20200301/Algorithm-Practice
2b5f42492a1ae574d7ddc7efeebdef55a82a30a5
[ "MIT" ]
null
null
null
LeetCode/_0064_MinimumPathSum.cpp
Restart20200301/Algorithm-Practice
2b5f42492a1ae574d7ddc7efeebdef55a82a30a5
[ "MIT" ]
null
null
null
/* 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明:每次只能向下或者向右移动一步。 示例: 输入: [   [1,3,1], [1,5,1], [4,2,1] ] 输出: 7 解释: 因为路径 1→3→1→1→1 的总和最小。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-path-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class Solution { public: int minPathSum(vector<vector<int>>& grid) { auto rows = grid.size(); auto cols = grid[0].size(); vector<int> dp(cols, grid[0][0]); for (int i = 1; i < cols; ++i) dp[i] = grid[0][i] + dp[i - 1]; for (int i = 1; i < rows; ++i) { dp[0] += grid[i][0]; for (int j = 1; j < cols; ++j) { dp[j] = grid[i][j] + min(dp[j], dp[j - 1]); } } return *dp.rbegin(); } };
20.263158
59
0.493506
[ "vector" ]
460a76e3c7b89f0cd8fd0f9ef9cc48dd6de25d45
10,971
cpp
C++
src/ofxOilTrace.cpp
jagracar/ofxOilPaint
095201a165d1122c1d92fe2a291b936f3de35c75
[ "MIT" ]
44
2018-04-08T05:59:10.000Z
2022-02-20T17:41:14.000Z
src/ofxOilTrace.cpp
jagracar/ofxOilPaint
095201a165d1122c1d92fe2a291b936f3de35c75
[ "MIT" ]
1
2019-04-26T10:46:22.000Z
2019-04-26T10:46:22.000Z
src/ofxOilTrace.cpp
jagracar/ofxOilPaint
095201a165d1122c1d92fe2a291b936f3de35c75
[ "MIT" ]
6
2018-04-29T19:46:01.000Z
2021-10-02T21:36:22.000Z
#include "ofxOilTrace.h" #include "ofxOilBrush.h" #include "ofMain.h" float ofxOilTrace::NOISE_FACTOR = 0.007; unsigned char ofxOilTrace::MIN_ALPHA = 20; float ofxOilTrace::BRIGHTNESS_RELATIVE_CHANGE = 0.09; unsigned int ofxOilTrace::TYPICAL_MIX_STARTING_STEP = 5; float ofxOilTrace::MIX_STRENGTH = 0.012; ofxOilTrace::ofxOilTrace(const glm::vec2& startingPosition, unsigned int nSteps, float speed) { // Check that the input makes sense if (nSteps == 0) { throw invalid_argument("The trace should have at least one step."); } // Fill the positions and alphas containers float initAng = ofRandom(TWO_PI); float noiseSeed = ofRandom(1000); float alphaDecrement = min(255.0 / nSteps, 25.0); positions.push_back(startingPosition); alphas.push_back(255); for (unsigned int i = 1; i < nSteps; ++i) { float ang = initAng + TWO_PI * (ofNoise(noiseSeed + NOISE_FACTOR * i) - 0.5); positions.emplace_back(positions[i - 1].x + speed * cos(ang), positions[i - 1].y + speed * sin(ang)); alphas.push_back(255 - alphaDecrement * i); } // Set the average color as totally transparent averageColor.set(0, 0); } ofxOilTrace::ofxOilTrace(const vector<glm::vec2>& _positions, const vector<unsigned char>& _alphas) { // Check that the input makes sense if (_positions.size() == 0) { throw invalid_argument("The trace should have at least one step."); } else if (_positions.size() != _alphas.size()) { throw invalid_argument("The _positions and _alphas vectors should have the same size."); } positions = _positions; alphas = _alphas; averageColor.set(0, 0); } void ofxOilTrace::setBrushSize(float brushSize) { // Initialize the brush brush = ofxOilBrush(positions[0], brushSize); // Reset the average color averageColor.set(0, 0); // Reset the bristle containers bPositions.clear(); bImgColors.clear(); bPaintedColors.clear(); bColors.clear(); } void ofxOilTrace::calculateBristlePositions() { // Reset the container bPositions.clear(); for (const glm::vec2& pos : positions) { // Move the brush brush.updatePosition(pos, false); // Save the bristles positions bPositions.push_back(brush.getBristlesPositions()); } // Reset the brush to the initial position brush.resetPosition(positions[0]); } void ofxOilTrace::calculateBristleImageColors(const ofImage& img) { // Extract some useful information int width = img.getWidth(); int height = img.getHeight(); // Calculate the bristle positions if necessary if (bPositions.size() == 0) { calculateBristlePositions(); } // Calculate the image colors at the bristles positions bImgColors.clear(); for (const vector<glm::vec2>& bp : bPositions) { bImgColors.emplace_back(); vector<ofColor>& bic = bImgColors.back(); for (const glm::vec2& pos : bp) { // Check that the bristle is inside the image int x = pos.x; int y = pos.y; if (x >= 0 && x < width && y >= 0 && y < height) { bic.push_back(img.getColor(x, y)); } else { bic.emplace_back(0, 0); } } } } void ofxOilTrace::calculateBristlePaintedColors(const ofPixels& paintedPixels, const ofColor& backgroundColor) { // Extract some useful information int width = paintedPixels.getWidth(); int height = paintedPixels.getHeight(); // Calculate the bristle positions if necessary if (bPositions.size() == 0) { calculateBristlePositions(); } // Calculate the painted colors at the bristles positions bPaintedColors.clear(); for (const vector<glm::vec2>& bp : bPositions) { bPaintedColors.emplace_back(); vector<ofColor>& bpc = bPaintedColors.back(); for (const glm::vec2& pos : bp) { // Check that the bristle is inside the canvas int x = pos.x; int y = pos.y; if (x >= 0 && x < width && y >= 0 && y < height) { const ofColor& color = paintedPixels.getColor(x, y); if (color != backgroundColor && color.a != 0) { bpc.push_back(color); } else { bpc.emplace_back(0, 0); } } else { bpc.emplace_back(0, 0); } } } } void ofxOilTrace::setAverageColor(const ofColor& color) { averageColor.set(color); // Reset the bristle colors since they are not valid anymore bColors.clear(); } void ofxOilTrace::calculateAverageColor(const ofImage& img) { // Calculate the bristle image colors if necessary if (bImgColors.size() == 0) { calculateBristleImageColors(img); } // Calculate the trace average color float redSum = 0; float greenSum = 0; float blueSum = 0; int counter = 0; for (unsigned int i = 0, nSteps = getNSteps(); i < nSteps; ++i) { // Check that the alpha value is high enough for the average color calculation if (alphas[i] >= MIN_ALPHA) { for (const ofColor& color : bImgColors[i]) { if (color.a != 0) { redSum += color.r; greenSum += color.g; blueSum += color.b; ++counter; } } } } if (counter > 0) { averageColor.set(redSum / counter, greenSum / counter, blueSum / counter, 255); } else { averageColor.set(0, 0); } } void ofxOilTrace::calculateBristleColors(const ofPixels& paintedPixels, const ofColor& backgroundColor) { // Get some useful information unsigned int nSteps = getNSteps(); unsigned int nBristles = getNBristles(); // Calculate the bristle painted colors if necessary if (bPaintedColors.size() == 0) { calculateBristlePaintedColors(paintedPixels, backgroundColor); } // Calculate the starting colors for each bristle vector<ofColor> startingColors = vector<ofColor>(nBristles); float noiseSeed = ofRandom(1000); float averageHue, averageSaturation, averageBrightness; averageColor.getHsb(averageHue, averageSaturation, averageBrightness); for (unsigned int bristle = 0; bristle < nBristles; ++bristle) { // Add some brightness changes to make it more realistic float deltaBrightness = BRIGHTNESS_RELATIVE_CHANGE * averageBrightness * (ofNoise(noiseSeed + 0.4 * bristle) - 0.5); startingColors[bristle].setHsb(averageHue, averageSaturation, averageBrightness + deltaBrightness); } // Use the bristle starting colors until the step where the mixing starts unsigned int mixStartingStep = ofClamp(TYPICAL_MIX_STARTING_STEP, 1, nSteps); bColors = vector<vector<ofColor>>(mixStartingStep, startingColors); // Mix the previous step colors with the already painted colors vector<float> redPrevious; vector<float> greenPrevious; vector<float> bluePrevious; for (const ofColor& color : startingColors) { redPrevious.push_back(color.r); greenPrevious.push_back(color.g); bluePrevious.push_back(color.b); } float f = 1 - MIX_STRENGTH; for (unsigned int i = mixStartingStep; i < nSteps; ++i) { // Copy the previous step colors bColors.push_back(bColors.back()); // Check that the alpha value is high enough for mixing if (alphas[i] >= MIN_ALPHA) { // Calculate the bristle colors for this step vector<ofColor>& bc = bColors.back(); const vector<ofColor>& bpc = bPaintedColors[i]; if (bpc.size() > 0) { for (unsigned int bristle = 0; bristle < nBristles; ++bristle) { const ofColor& paintedColor = bpc[bristle]; if (paintedColor.a != 0) { float redMix = f * redPrevious[bristle] + MIX_STRENGTH * paintedColor.r; float greenMix = f * greenPrevious[bristle] + MIX_STRENGTH * paintedColor.g; float blueMix = f * bluePrevious[bristle] + MIX_STRENGTH * paintedColor.b; redPrevious[bristle] = redMix; greenPrevious[bristle] = greenMix; bluePrevious[bristle] = blueMix; bc[bristle].set(redMix, greenMix, blueMix); } } } } } } void ofxOilTrace::paint() { // Check that the bristle colors have been calculated before running this method if (bColors.size() == 0) { throw logic_error("Please, run calculateBristleColors method before paint."); } for (unsigned int i = 0, nSteps = getNSteps(); i < nSteps; ++i) { // Move the brush brush.updatePosition(positions[i], true); // Paint the brush brush.paint(bColors[i], alphas[i]); } // Reset the brush to the initial position brush.resetPosition(positions[0]); } void ofxOilTrace::paint(ofFbo& canvasBuffer) { // Check that the bristle colors have been calculated before running this method if (bColors.size() == 0) { throw logic_error("Please, run calculateBristleColors method before paint."); } for (unsigned int i = 0, nSteps = getNSteps(); i < nSteps; ++i) { // Move the brush brush.updatePosition(positions[i], true); // Paint the brush brush.paint(bColors[i], alphas[i]); // Paint the trace on the canvas only if alpha is high enough if (alphas[i] >= MIN_ALPHA) { canvasBuffer.begin(); brush.paint(bColors[i], 255); canvasBuffer.end(); } } // Reset the brush to the initial position brush.resetPosition(positions[0]); } void ofxOilTrace::paintStep(unsigned int step) { // Check that the bristle colors have been calculated before running this method if (bColors.size() == 0) { throw logic_error("Please, run calculateBristleColors method before paint."); } // Check that it makes sense to paint the given step if (step < getNSteps()) { // Move the brush brush.updatePosition(positions[step], true); // Paint the brush brush.paint(bColors[step], alphas[step]); // Reset the brush to the initial position if we are at the last trajectory step if (step == getNSteps() - 1) { brush.resetPosition(positions[0]); } } } void ofxOilTrace::paintStep(unsigned int step, ofFbo& canvasBuffer) { // Check that the bristle colors have been calculated before running this method if (bColors.size() == 0) { throw logic_error("Please, run calculateBristleColors method before paint."); } // Check that it makes sense to paint the given step if (step < getNSteps()) { // Move the brush brush.updatePosition(positions[step], true); // Paint the brush brush.paint(bColors[step], alphas[step]); // Paint the trace on the canvas only if alpha is high enough if (alphas[step] >= MIN_ALPHA) { canvasBuffer.begin(); brush.paint(bColors[step], 255); canvasBuffer.end(); } // Reset the brush to the initial position if we are at the last trajectory step if (step == getNSteps() - 1) { brush.resetPosition(positions[0]); } } } unsigned int ofxOilTrace::getNSteps() const { return positions.size(); } const vector<glm::vec2>& ofxOilTrace::getTrajectoryPositions() const { return positions; } const vector<unsigned char>& ofxOilTrace::getTrajectoryAphas() const { return alphas; } const ofColor& ofxOilTrace::getAverageColor() const { return averageColor; } unsigned int ofxOilTrace::getNBristles() const { return brush.getNBristles(); } const vector<vector<glm::vec2>>& ofxOilTrace::getBristlePositions() const { return bPositions; } const vector<vector<ofColor>>& ofxOilTrace::getBristleImageColors() const { return bImgColors; } const vector<vector<ofColor>>& ofxOilTrace::getBristlePaintedColors() const { return bPaintedColors; } const vector<vector<ofColor>>& ofxOilTrace::getBristleColors() const { return bColors; }
28.496104
112
0.703673
[ "vector" ]
46208d73fcf8d2b64b1e8c81a2a83c900f106381
10,785
cc
C++
src/openzwave-driver.cc
sescandell/node-openzwave-shared
21e1516ef3c316d8a6986a44fb844345344de9fe
[ "ISC" ]
215
2015-05-21T13:49:35.000Z
2021-12-08T21:10:02.000Z
src/openzwave-driver.cc
sescandell/node-openzwave-shared
21e1516ef3c316d8a6986a44fb844345344de9fe
[ "ISC" ]
356
2015-05-24T13:27:13.000Z
2022-03-15T13:59:23.000Z
src/openzwave-driver.cc
sescandell/node-openzwave-shared
21e1516ef3c316d8a6986a44fb844345344de9fe
[ "ISC" ]
166
2015-07-07T05:04:48.000Z
2021-03-19T18:22:39.000Z
/* * Copyright (c) 2013 Jonathan Perkin <jonathan@perkin.org.uk> * Copyright (c) 2015-2017 Elias Karakoulakis <elias.karakoulakis@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "openzwave.hpp" using namespace v8; using namespace node; namespace OZW { // =================================================================== NAN_METHOD(OZW::Connect) // =================================================================== { Nan::HandleScope scope; CheckMinArgs(1, "path"); ::std::string path(*Nan::Utf8String(info[0])); uv_async_init(uv_default_loop(), &async, async_cb_handler); OZW *self = ObjectWrap::Unwrap<OZW>(info.This()); ::std::string version(""); #if OPENZWAVE_EXCEPTIONS try { #endif OpenZWave::Options::Create(self->config_path, self->userpath, self->option_overrides); OpenZWave::Options::Get()->Lock(); OpenZWave::Manager::Create(); OZWManager(AddWatcher, ozw_watcher_callback, NULL); OZWManager(AddDriver, path); version = OpenZWave::Manager::getVersionAsString(); #if OPENZWAVE_EXCEPTIONS } catch (OpenZWave::OZWException &e) { char buffer[200]; snprintf(buffer, 200, "Exception connecting in %s(%d): %s", e.GetFile().c_str(), e.GetLine(), e.GetMsg().c_str()); Nan::ThrowError(buffer); } #endif Local<v8::Value> cbinfo[16]; cbinfo[0] = Nan::New<String>("connected").ToLocalChecked(); cbinfo[1] = Nan::New<String>(version).ToLocalChecked(); emit_cb->Call(Nan::New(ctx_obj), 2, cbinfo, resource); } // =================================================================== NAN_METHOD(OZW::UpdateOptions) // =================================================================== { Nan::HandleScope scope; CheckMinArgs(1, "info"); OZW *self = ObjectWrap::Unwrap<OZW>(info.This()); ::std::string ozw_userpath = self->userpath; ::std::string ozw_config_path = self->config_path; ::std::string option_overrides; bool log_initialisation = true; // Options are global for all drivers and can only be set once. if (info.Length() > 0) { Local<Object> opts = Nan::To<Object>(info[0]).ToLocalChecked(); Local<Array> props = Nan::GetOwnPropertyNames(opts).ToLocalChecked(); for (unsigned int i = 0; i < props->Length(); ++i) { Nan::MaybeLocal<Value> keymaybe = Nan::Get(props, i); if (keymaybe.IsEmpty()) continue; Local<Value> key = keymaybe.ToLocalChecked(); ::std::string keyname = *Nan::Utf8String(key); Local<Value> argval = Nan::Get(opts, key).ToLocalChecked(); ::std::string argvalstr = *Nan::Utf8String(argval); if(argvalstr.empty()) continue; // UserPath is directly passed to Manager->Connect() // scan for OpenZWave options.xml in the nodeJS module's '/config' subdirectory if (keyname == "UserPath") { ozw_userpath.assign(argvalstr); } else if (keyname == "ConfigPath") { ozw_config_path.assign(argvalstr); } else if (keyname == "LogInitialisation") { log_initialisation = (Nan::To<bool>(argval) == Nan::Just(true)); } else { option_overrides += " --" + keyname + " " + argvalstr; } } } // Update configuration data for connect. self->config_path = ozw_config_path; self->userpath = ozw_userpath; self->option_overrides = option_overrides; self->log_initialisation = log_initialisation; if (self->log_initialisation) { ::std::ostringstream versionstream; versionstream << ozw_vers_major << "." << ozw_vers_minor << "." << ozw_vers_revision; ::std::cout << "Initialising OpenZWave " << versionstream.str() << " binary addon for Node.JS.\n"; #if OPENZWAVE_SECURITY == 1 ::std::cout << "\tOpenZWave Security API is ENABLED\n"; #else ::std::cout << "\tSecurity API not found, using legacy BeginControllerCommand() instead\n"; #endif ::std::cout << "\tZWave device db : " << ozw_config_path << "\n"; ::std::cout << "\tUser settings path : " << ozw_userpath << "\n"; if (option_overrides.length() > 0) { ::std::cout << "\tOption Overrides :" << option_overrides << "\n"; } } } // =================================================================== NAN_METHOD(OZW::Disconnect) // =================================================================== { Nan::HandleScope scope; CheckMinArgs(1, "path"); ::std::string path(*Nan::Utf8String(info[0])); OZWManager(RemoveDriver, path); OZWManager(RemoveWatcher, ozw_watcher_callback, NULL); #if OPENZWAVE_EXCEPTIONS try { #endif OpenZWave::Manager::Destroy(); OpenZWave::Options::Destroy(); #if OPENZWAVE_EXCEPTIONS } catch (OpenZWave::OZWException &e) { char buffer[200]; snprintf(buffer, 200, "Exception disconnecting in %s(%d): %s", e.GetFile().c_str(), e.GetLine(), e.GetMsg().c_str()); Nan::ThrowError(buffer); } #endif // FIXME: seems some recent innocuous change in NaN causes the context (ctx_obj) to be freed. // Therefore, deleting this V8 resource will cause V8 to crash. NOT deleting it could memleak // when you're reloading the driver. // // delete emit_cb; // } /* * Reset the ZWave controller chip. A hard reset is destructive and wipes * out all known configuration, a soft reset just restarts the chip. */ // =================================================================== NAN_METHOD(OZW::HardReset) // =================================================================== { Nan::HandleScope scope; OZWManager(ResetController, homeid); } // =================================================================== NAN_METHOD(OZW::SoftReset) // =================================================================== { Nan::HandleScope scope; OZWManager(SoftReset, homeid); } // =================================================================== NAN_METHOD(OZW::GetControllerNodeId) // =================================================================== { Nan::HandleScope scope; uint8 ctrlid = -1; OZWManagerAssign(ctrlid, GetControllerNodeId, homeid); info.GetReturnValue().Set( Nan::New<Integer>(ctrlid)); } // =================================================================== NAN_METHOD(OZW::GetSUCNodeId) // =================================================================== { Nan::HandleScope scope; uint8 sucid = -1; OZWManagerAssign(sucid, GetSUCNodeId, homeid); info.GetReturnValue().Set( Nan::New<Integer>(sucid)); } /* Query if the controller is a primary controller. The primary controller * is the main device used to configure and control a Z-Wave network. * There can only be one primary controller - all other controllers * are secondary controllers. */ // =================================================================== NAN_METHOD(OZW::IsPrimaryController) // =================================================================== { Nan::HandleScope scope; bool isprimary = false; OZWManagerAssign(isprimary, IsPrimaryController, homeid); info.GetReturnValue().Set(Nan::New<Boolean>(isprimary)); } /* Query if the controller is a static update controller. A Static * Update Controller (SUC) is a controller that must never be moved * in normal operation and which can be used by other nodes to * receive information about network changes. */ // =================================================================== NAN_METHOD(OZW::IsStaticUpdateController) // =================================================================== { Nan::HandleScope scope; bool issuc = false; OZWManagerAssign(issuc, IsStaticUpdateController, homeid); info.GetReturnValue().Set(Nan::New<Boolean>(issuc)); } /* Query if the controller is using the bridge controller library. * A bridge controller is able to create virtual nodes that can be * associated with other controllers to enable events to be passed on. */ // =================================================================== NAN_METHOD(OZW::IsBridgeController) // =================================================================== { Nan::HandleScope scope; bool isbridge = false; OZWManagerAssign(isbridge, IsBridgeController, homeid); info.GetReturnValue().Set(Nan::New<Boolean>(isbridge)); } /* Get the version of the Z-Wave API library used by a controller. */ // =================================================================== NAN_METHOD(OZW::GetLibraryVersion) // =================================================================== { Nan::HandleScope scope; ::std::string libver(""); OZWManagerAssign(libver, GetLibraryVersion, homeid); info.GetReturnValue().Set( Nan::New<String>( libver.c_str()) .ToLocalChecked()); } /* Get the version of Openzwave */ // =================================================================== NAN_METHOD(OZW::GetOzwVersion) // =================================================================== { Nan::HandleScope scope; ::std::string version(""); version = OpenZWave::Manager::getVersionAsString(); //OZWManagerAssign(version, GetVersionAsString); info.GetReturnValue().Set( Nan::New<String>( version.c_str()) .ToLocalChecked()); } /* Get a string containing the Z-Wave API library type used by a * controller. The possible library types are: * Static Controller * Controller * Enhanced Slave * Slave * Installer * Routing Slave * Bridge Controller * Device Under Test * * The controller should never return a slave library type. For a * more efficient test of whether a controller is a Bridge Controller, * use the IsBridgeController method. */ // =================================================================== NAN_METHOD(OZW::GetLibraryTypeName) // =================================================================== { Nan::HandleScope scope; ::std::string libtype(""); OZWManagerAssign(libtype, GetLibraryTypeName, homeid); info.GetReturnValue().Set( Nan::New<String>( libtype.c_str()) .ToLocalChecked()); } // =================================================================== NAN_METHOD(OZW::GetSendQueueCount) // =================================================================== { Nan::HandleScope scope; uint32 cnt = 0; OZWManagerAssign(cnt, GetSendQueueCount, homeid); info.GetReturnValue().Set(Nan::New<Integer>(cnt)); } } // namespace OZW
32.19403
101
0.580807
[ "object" ]
4623a9d374117ee117c2f8fb1f6bd6ca0a6aeb40
1,415
cpp
C++
sherlock_and_the_beast.cpp
zmechz/study-cpp
34ec5ea88139d907cbef5bf593c8715302f96117
[ "MIT" ]
1
2017-08-18T00:26:39.000Z
2017-08-18T00:26:39.000Z
sherlock_and_the_beast.cpp
zmechz/cpp-lab
34ec5ea88139d907cbef5bf593c8715302f96117
[ "MIT" ]
null
null
null
sherlock_and_the_beast.cpp
zmechz/cpp-lab
34ec5ea88139d907cbef5bf593c8715302f96117
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <memory> #include <cstring> using namespace std; int find_highest_number(int n) { char buffer[n+1]; // cout << "\nN " << n; memset(buffer, '5' , n); buffer[n+1] = '\0'; // cout << "\nBuffer " << buffer; int tmp = atoi(buffer); string s; int div_by_three; int div_by_five; // cout << " tmp = " << tmp << endl; for(size_t i = tmp; i >= 555; i--) { s = to_string(i); div_by_three = count(s.begin(), s.end(), '3'); div_by_five = count(s.begin(), s.end(), '5'); if(s.size() == div_by_three + div_by_five) { if(div_by_three == 0 || div_by_three % 5 == 0) { if (div_by_five == 0 || div_by_five % 3 == 0) { tmp = i; // cout << endl << "I = " << i << endl; // cout << "3s = " << div_by_three << endl; // cout << "5s = " << div_by_five << endl; break; } } } } return tmp; } int main(){ int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; if(n < 3){ cout << -1 << endl; } else { int div = find_highest_number(n); cout << div << endl; } } return 0; }
24.824561
63
0.428975
[ "vector" ]
462ff14e7967dd9976d96138342a803de18b71af
972
cpp
C++
Leetcode/HashMap/employeeImportance.cpp
pokemonTrainer5833/Data-Structures
10aa1a1b6975a3cd32aa5978f5e950283360dd0e
[ "MIT" ]
null
null
null
Leetcode/HashMap/employeeImportance.cpp
pokemonTrainer5833/Data-Structures
10aa1a1b6975a3cd32aa5978f5e950283360dd0e
[ "MIT" ]
null
null
null
Leetcode/HashMap/employeeImportance.cpp
pokemonTrainer5833/Data-Structures
10aa1a1b6975a3cd32aa5978f5e950283360dd0e
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<unordered_map> #include<queue> using namespace std; // Definition for Employee. class Employee { public: int id; int importance; vector<int> subordinates; }; class Solution { public: int getImportance(vector<Employee*> employees, int id) { Employee* start = nullptr; unordered_map<int, Employee*>mappah; for(auto ele:employees){ if(ele->id==id) start = ele; if(mappah.find(ele->id)==mappah.end())mappah[ele->id] = ele; } if(start == nullptr) return 0; queue<Employee*>q; q.push(start); int importance = 0; while(!q.empty()){ Employee* first = q.front(); importance+=(first->importance); q.pop(); for(int ele:first->subordinates){ q.push(mappah[ele]); } } return importance; } };
23.142857
72
0.533951
[ "vector" ]
46384f4f3962ec7ccaa798642d9cc5483fc6d18c
1,981
cpp
C++
Greedy-Algo/JobSequencingProblem.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Greedy-Algo/JobSequencingProblem.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Greedy-Algo/JobSequencingProblem.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// Given a set of N jobs where each jobi has a deadline and profit associated with it. Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit if and only if the job is completed by its deadline. The task is to find the number of jobs done and the maximum profit. // Note: Jobs will be given in the form (Jobid, Deadline, Profit) associated with that Job. // Example 1: // Input: // N = 4 // Jobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)} // Output: // 2 60 // Explanation: // Job1 and Job3 can be done with // maximum profit of 60 (20+40). // Example 2: // Input: // N = 5 // Jobs = {(1,2,100),(2,1,19),(3,2,27), // (4,1,25),(5,1,15)} // Output: // 2 127 // Explanation: // 2 jobs can be done with // maximum profit of 127 (100+27). // Your Task : // You don't need to read input or print anything. Your task is to complete the function JobScheduling() which takes an integer N and an array of Jobs(Job id, Deadline, Profit) as input and returns the count of jobs and maximum profit. // Expected Time Complexity: O(NlogN) // Expected Auxilliary Space: O(N) // Constraints: // 1 <= N <= 105 // 1 <= Deadline <= 100 // 1 <= Profit <= 500 class Solution { public: static bool compare(Job a, Job b){ return a.profit > b.profit; } vector<int> JobScheduling(Job arr[], int n) { sort(arr, arr + n, compare); int jobs = 0, total = 0, maxi = arr[0].dead; for(int i = 0; i < n; i++) maxi = max(maxi, arr[i].dead); vector<int> slots(maxi + 1, -1); for(int i = 0; i < n; i++){ for(int j = arr[i].dead; j > 0; j--){ if(slots[j] == -1){ total += arr[i].profit; slots[j] = i; jobs++; break; } } } return {jobs, total}; } };
30.015152
314
0.539122
[ "vector" ]
4640caed07b9bd3f3d33331672dec3e435bf5b06
1,382
hpp
C++
include/nodes/GeoConversionNodes.hpp
niniemann/sempr
2f3b04c031d70b9675ad441f97728a8fb839abed
[ "BSD-3-Clause" ]
8
2018-03-28T19:45:47.000Z
2022-03-23T16:53:24.000Z
include/nodes/GeoConversionNodes.hpp
niniemann/sempr
2f3b04c031d70b9675ad441f97728a8fb839abed
[ "BSD-3-Clause" ]
58
2018-01-31T11:10:04.000Z
2021-08-13T11:48:31.000Z
include/nodes/GeoConversionNodes.hpp
niniemann/sempr
2f3b04c031d70b9675ad441f97728a8fb839abed
[ "BSD-3-Clause" ]
1
2018-07-04T12:30:06.000Z
2018-07-04T12:30:06.000Z
#ifndef SEMPR_GEOCONVERSIONNODES_HPP_ #define SEMPR_GEOCONVERSIONNODES_HPP_ #include <rete-core/Builtin.hpp> #include <rete-core/Accessors.hpp> #include "../component/GeosGeometry.hpp" namespace sempr { /** Takes a geometry and a zone (int), and returns a new geometry transformed from WGS84 lon/lat to UTM<zone> x/y. */ class UTMFromWGSNode : public rete::Builtin { public: UTMFromWGSNode( rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo, rete::PersistentInterpretation<int> zone ); rete::WME::Ptr process(rete::Token::Ptr) override; bool operator == (const rete::BetaNode& other) const override; private: rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo_; rete::PersistentInterpretation<int> zone_; }; /** Converts a geometry from an UTM zone to WGS84 */ class WGSFromUTMNode : public rete::Builtin { public: WGSFromUTMNode( rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo, rete::PersistentInterpretation<int> zone ); rete::WME::Ptr process(rete::Token::Ptr) override; bool operator == (const rete::BetaNode& other) const override; private: rete::PersistentInterpretation<GeosGeometryInterface::Ptr> geo_; rete::PersistentInterpretation<int> zone_; }; } #endif /* include guard: SEMPR_GEOCONVERSIONNODES_HPP_ */
24.678571
77
0.7178
[ "geometry" ]
464b1a0a6c0e484a1a8904516fbdf532835b0fcf
42,423
cpp
C++
src/kognac/utils/utils.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
null
null
null
src/kognac/utils/utils.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
2
2018-06-26T16:41:19.000Z
2021-09-16T12:26:05.000Z
src/kognac/utils/utils.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
2
2018-09-18T11:38:18.000Z
2021-09-13T23:27:09.000Z
/* * Copyright 2016 Jacopo Urbani * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #include <kognac/utils.h> /**** MEMORY STATISTICS ****/ #if defined(_WIN32) #include <io.h> #include <fcntl.h> #include <windows.h> #include <psapi.h> #include <tchar.h> #include <direct.h> #include <filesystem> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> #include <sys/resource.h> #include <dirent.h> #if defined(__APPLE__) && defined(__MACH__) #include <mach/mach.h> #include <sys/types.h> #include <sys/sysctl.h> #include <dirent.h> #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include <fcntl.h> #include <procfs.h> #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) #include <stdio.h> #endif #else #error "I don't know which OS it is being used. Cannot optimize the code..." #endif #include <sys/stat.h> #include <kognac/lz4io.h> #include <kognac/logs.h> #include <algorithm> #include <vector> #include <string> #include <set> #include <assert.h> #include <stdio.h> using namespace std; /**** FILE UTILS ****/ //Return full path of the exec/library string Utils::getFullPathExec() { #if defined(_WIN32) char ownPth[MAX_PATH]; // When NULL is passed to GetModuleHandle, the handle of the exe itself is returned HMODULE hModule = GetModuleHandle(NULL); if (hModule != NULL) { // Use GetModuleFileName() with module handle to get the path GetModuleFileName(hModule, ownPth, (sizeof(ownPth))); return string(ownPth); } #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) char buff[FILENAME_MAX]; if (getcwd(buff, FILENAME_MAX) != NULL) { std::string current_working_dir(buff); return current_working_dir; } #endif return string(""); } //Return only the files or the entire path? vector<string> Utils::getFilesWithPrefix(string dirname, string prefix) { vector<string> files; vector<string> allfiles = Utils::getFiles(dirname); for (uint64_t i = 0; i < allfiles.size(); ++i) { string fn = filename(allfiles[i]); if (Utils::starts_with(fn, prefix)) files.push_back(allfiles[i]); } return files; } vector<string> Utils::getSubdirs(string dirname) { vector<string> files; #if defined(_WIN32) WIN32_FIND_DATA ffd; //TCHAR szDir[MAX_PATH]; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError = 0; std::string toSearch = dirname + DIR_SEP + "*"; hFind = FindFirstFile(toSearch.c_str(), &ffd); if (INVALID_HANDLE_VALUE == hFind) { return std::vector<string>(); } // List all the files in the directory with some info about them. do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (string(ffd.cFileName) == "." || string(ffd.cFileName) == "..") continue; string fileFullPath = dirname + DIR_SEP + ffd.cFileName; files.push_back(fileFullPath); } } while (FindNextFile(hFind, &ffd) != 0); #else DIR *d = opendir(dirname.c_str()); struct dirent *dir; if (d) { while ((dir = readdir(d)) != NULL) { string path = dirname + DIR_SEP + string(dir->d_name); if (isDirectory(path) && dir->d_name[0] != '.') { files.push_back(path); } } closedir(d); } #endif return files; } vector<string> Utils::getFiles(string dirname, bool ignoreExtension) { std::set<string> sfiles; #if defined(_WIN32) WIN32_FIND_DATA ffd; //TCHAR szDir[MAX_PATH]; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError = 0; std::string toSearch = dirname + DIR_SEP + "*"; hFind = FindFirstFile(toSearch.c_str(), &ffd); if (INVALID_HANDLE_VALUE == hFind) { return std::vector<string>(); } // List all the files in the directory with some info about them. do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //ignore the subdirectories } else if (ffd.cFileName[0] != '.') { string fileFullPath = dirname + DIR_SEP + ffd.cFileName; if (ignoreExtension) { sfiles.insert(Utils::removeExtension(fileFullPath)); } else { sfiles.insert(fileFullPath); } } } while (FindNextFile(hFind, &ffd) != 0); #else DIR *d = opendir(dirname.c_str()); struct dirent *dir; if (d) { while ((dir = readdir(d)) != NULL) { if (dir->d_name[0] != '.') { string fileFullPath = dirname + DIR_SEP + string(dir->d_name); if (ignoreExtension) { sfiles.insert(Utils::removeExtension(fileFullPath)); } else { sfiles.insert(fileFullPath); } } } closedir(d); } #endif std::vector<string> files; for(auto s : sfiles) { files.push_back(s); } return files; } vector<string> Utils::getFilesWithSuffix(string dirname, string suffix) { vector<string> files; vector<string> allfiles = Utils::getFiles(dirname); for (uint64_t i = 0; i < allfiles.size(); ++i) { string f = allfiles[i]; if (Utils::ends_with(f, suffix)) { files.push_back(f); } } return files; } bool Utils::hasExtension(const string &file){ string fn = filename(file); return (fn.find('.') != std::string::npos); } string Utils::extension(const string &file) { string fn = filename(file); auto pos = fn.find_last_of('.'); if (pos == std::string::npos) { return ""; } return fn.substr(pos, fn.size() - pos); //must return also '.' } string Utils::removeExtension(string file) { string fn = filename(file); auto pos = fn.find('.'); if (pos != std::string::npos) { pos += file.size() - fn.size(); return file.substr(0, pos); } else { return file; } } string Utils::removeLastExtension(string file) { string fn = filename(file); auto pos = fn.find_last_of('.'); if (pos != std::string::npos) { pos += file.size() - fn.size(); return file.substr(0, pos); } else { return file; } } bool Utils::isDirectory(string dirname) { #if defined(_WIN32) DWORD d = GetFileAttributes(dirname.c_str()); if (d == INVALID_FILE_ATTRIBUTES) { return false; } if (d &FILE_ATTRIBUTE_DIRECTORY) { return true; } else { return false; } #else struct stat st; auto resp = stat(dirname.c_str(), &st); if (resp == 0) { if ((st.st_mode & S_IFDIR) != 0) return true; } return false; #endif } bool Utils::isFile(string dirname) { #if defined(_WIN32) DWORD d = GetFileAttributes(dirname.c_str()); if (d == INVALID_FILE_ATTRIBUTES) { return false; } if (!(d & FILE_ATTRIBUTE_DIRECTORY)) { return true; } else { return false; } #else struct stat st; if (stat(dirname.c_str(), &st) == 0) if ((st.st_mode & S_IFREG) != 0) return true; return false; #endif } uint64_t Utils::fileSize(string file) { #if defined(_WIN32) LARGE_INTEGER size; HANDLE fd = CreateFile(file.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); bool res = GetFileSizeEx(fd, &size); CloseHandle(fd); if (!res) { throw 10; } return size.QuadPart; #else struct stat stat_buf; int rc = stat(file.c_str(), &stat_buf); if (rc == 0) { return stat_buf.st_size; } else { throw 10; } #endif } void Utils::create_directories(string newdir) { string pd = parentDir(newdir); if (pd != newdir && !exists(pd)) { create_directories(pd); } if (!Utils::exists(newdir)) { #if defined(_WIN32) _mkdir(newdir.c_str()); #else if (mkdir(newdir.c_str(), 0777) != 0) { LOG(ERRORL) << "Error creating dir " << newdir; throw 10; } #endif } else if (!Utils::isDirectory(newdir)) { LOG(ERRORL) << "Directory " << newdir << " is already existing but it is not a dir"; abort(); } } void Utils::remove(string file) { if (isDirectory(file)) { #if defined(_WIN32) auto resp = RemoveDirectory(file.c_str()); if (resp == 0) { DWORD errorMessageID = ::GetLastError(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); LOG(ERRORL) << "Error deleting directory " << file << " " << message; abort(); } #else if (rmdir(file.c_str()) != 0) { LOG(ERRORL) << "Error removing dir " << file; abort(); } #endif } else { #if defined(_WIN32) auto resp = DeleteFile(file.c_str()); if (resp == 0) { DWORD errorMessageID = ::GetLastError(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); LOG(ERRORL) << "Error deleting file " << file << " " << message; abort(); } #else int resp = ::remove(file.c_str()); if (resp != 0) { LOG(ERRORL) << "Error deleting file " << file; abort(); } #endif } } void Utils::remove_all(string path) { if (isDirectory(path)) { std::vector<std::string> subdirs = Utils::getSubdirs(path); for (uint64_t i = 0; i < subdirs.size(); ++i) { remove_all(subdirs[i]); } std::vector<std::string> filechildren = Utils::getFiles(path); for (uint64_t i = 0; i < filechildren.size(); ++i) { remove(filechildren[i]); } remove(path); } else { remove(path); } } void Utils::copy(string oldfile, string newfile) { std::ifstream source(oldfile, ios::binary); std::ofstream dest(newfile, ios::binary); std::istreambuf_iterator<char> begin_source(source); std::istreambuf_iterator<char> end_source; std::ostreambuf_iterator<char> begin_dest(dest); std::copy(begin_source, end_source, begin_dest); source.close(); dest.close(); } void Utils::rename(string oldfile, string newfile) { if(std::rename(oldfile.c_str(), newfile.c_str()) != 0 ) LOG(ERRORL) << "Error renaming file " << oldfile; } string Utils::parentDir(string path) { auto pos = path.rfind(CDIR_SEP); if (pos != std::string::npos) { return path.substr(0, pos); } else { return path; } } string Utils::filename(string path) { auto pos = path.rfind(CDIR_SEP); if (pos != std::string::npos) { return path.substr(pos + 1, path.size() - pos); } else { return path; } } bool Utils::exists(std::string file) { #if defined(_WIN32) return isFile(file) || isDirectory(file); #else struct stat buffer; auto resp = lstat(file.c_str(), &buffer); return resp == 0; #endif } bool Utils::isEmpty(string dir) { if (!Utils::isDirectory(dir)) { LOG(ERRORL) << dir << " is not a directory!"; throw 10; } return Utils::getFiles(dir).empty() && Utils::getSubdirs(dir).empty(); } void Utils::resizeFile(string file, uint64_t newsize) { if (!Utils::exists(file)) { LOG(ERRORL) << file << " does not exist"; throw 10; } uint64_t oldsize = Utils::fileSize(file); if (oldsize != newsize) { #if defined(_WIN32) HANDLE fd = CreateFile(file.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); LARGE_INTEGER liSize; liSize.QuadPart = newsize; int res = SetFilePointerEx(fd, liSize, NULL, FILE_BEGIN); if (res == 0) { LOG(ERRORL) << "Wronged setting the file pointer of " << file; } res = SetEndOfFile(fd); if (res == 0) { DWORD errorMessageID = ::GetLastError(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); LOG(ERRORL) << "Error truncating the file " << file << " " << message; abort(); } CloseHandle(fd); #else if (truncate(file.c_str(), newsize)) { } #endif } } string Utils::join(string dir, string filename) { return dir + CDIR_SEP + filename; } /**** END FILE UTILS ****/ /**** START STRING UTILS ****/ bool Utils::starts_with(const string s, const string prefix) { size_t m = min(s.size(), prefix.size()); return strncmp(s.c_str(), prefix.c_str(), m) == 0; } bool Utils::ends_with(const string s, const string suffix) { return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; } bool Utils::contains(const string s, const string substr) { return s.find(substr) != string::npos; } /**** END STRING UTILS ****/ int Utils::numBytes(int64_t number) { int64_t max = 32; if (number < 0) { LOG(ERRORL) << "Negative number " << number; } for (int i = 1; i <= 8; i++) { if (number < max) { return i; } max *= 256; } LOG(ERRORL) << "Number is too large: " << number; return -1; } int Utils::numBytesFixedLength(int64_t number) { uint8_t bytes = 0; do { bytes++; number = number >> 8; } while (number > 0); return bytes; } int Utils::numBytes2(int64_t number) { int nbytes = 0; do { number >>= 7; nbytes++; } while (number > 0); return nbytes; } int Utils::decode_int(char* buffer, int offset) { int n = (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; return n; } int Utils::decode_int(const char* buffer) { int n = (buffer[0] & 0xFF) << 24; n += (buffer[1] & 0xFF) << 16; n += (buffer[2] & 0xFF) << 8; n += buffer[3] & 0xFF; return n; } void Utils::encode_int(char* buffer, int offset, int n) { buffer[offset++] = (n >> 24) & 0xFF; buffer[offset++] = (n >> 16) & 0xFF; buffer[offset++] = (n >> 8) & 0xFF; buffer[offset++] = n & 0xFF; } void Utils::encode_int(char* buffer, int n) { buffer[0] = (n >> 24) & 0xFF; buffer[1] = (n >> 16) & 0xFF; buffer[2] = (n >> 8) & 0xFF; buffer[3] = n & 0xFF; } int Utils::decode_intLE(char* buffer, int offset) { int n = buffer[offset++] & 0xFF; n += (buffer[offset++] & 0xFF) << 8; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset] & 0xFF) << 24; return n; } void Utils::encode_intLE(char* buffer, int offset, int n) { buffer[offset++] = n & 0xFF; buffer[offset++] = (n >> 8) & 0xFF; buffer[offset++] = (n >> 16) & 0xFF; buffer[offset++] = (n >> 24) & 0xFF; } int64_t Utils::decode_long(char* buffer, int offset) { int64_t n = (int64_t) (buffer[offset++]) << 56; n += (int64_t) (buffer[offset++] & 0xFF) << 48; n += (int64_t) (buffer[offset++] & 0xFF) << 40; n += (int64_t) (buffer[offset++] & 0xFF) << 32; n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; return n; } int64_t Utils::decode_longFixedBytes(const char* buffer, const uint8_t nbytes) { uint8_t offset = 0; int64_t n = 0; switch (nbytes) { case 1: n += buffer[offset] & 0xFF; break; case 2: n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 3: n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 4: n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 5: n += (int64_t) (buffer[offset++] & 0xFF) << 32; n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 6: n += (int64_t) (buffer[offset++] & 0xFF) << 40; n += (int64_t) (buffer[offset++] & 0xFF) << 32; n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 7: n += (int64_t) (buffer[offset++] & 0xFF) << 48; n += (int64_t) (buffer[offset++] & 0xFF) << 40; n += (int64_t) (buffer[offset++] & 0xFF) << 32; n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; case 8: n += (int64_t) (buffer[offset++]) << 56; n += (int64_t) (buffer[offset++] & 0xFF) << 48; n += (int64_t) (buffer[offset++] & 0xFF) << 40; n += (int64_t) (buffer[offset++] & 0xFF) << 32; n += (int64_t) (buffer[offset++] & 0xFF) << 24; n += (buffer[offset++] & 0xFF) << 16; n += (buffer[offset++] & 0xFF) << 8; n += buffer[offset] & 0xFF; break; } return n; } int64_t Utils::decode_long(const char* buffer) { int64_t n = (int64_t) (buffer[0]) << 56; n += (int64_t) (buffer[1] & 0xFF) << 48; n += (int64_t) (buffer[2] & 0xFF) << 40; n += (int64_t) (buffer[3] & 0xFF) << 32; n += (int64_t) (buffer[4] & 0xFF) << 24; n += (buffer[5] & 0xFF) << 16; n += (buffer[6] & 0xFF) << 8; n += buffer[7] & 0xFF; return n; } void Utils::encode_long(char* buffer, int offset, int64_t n) { buffer[offset++] = (n >> 56) & 0xFF; buffer[offset++] = (n >> 48) & 0xFF; buffer[offset++] = (n >> 40) & 0xFF; buffer[offset++] = (n >> 32) & 0xFF; buffer[offset++] = (n >> 24) & 0xFF; buffer[offset++] = (n >> 16) & 0xFF; buffer[offset++] = (n >> 8) & 0xFF; buffer[offset++] = n & 0xFF; } void Utils::encode_long(char* buffer, int64_t n) { buffer[0] = (n >> 56) & 0xFF; buffer[1] = (n >> 48) & 0xFF; buffer[2] = (n >> 40) & 0xFF; buffer[3] = (n >> 32) & 0xFF; buffer[4] = (n >> 24) & 0xFF; buffer[5] = (n >> 16) & 0xFF; buffer[6] = (n >> 8) & 0xFF; buffer[7] = n & 0xFF; } void Utils::encode_longNBytes(char* buffer, const uint8_t nbytes, const uint64_t n) { uint8_t offset = 0; switch (nbytes) { case 1: buffer[0] = n & 0xFF; break; case 2: buffer[0] = (n >> 8) & 0xFF; buffer[1] = n & 0xFF; break; case 3: buffer[0] = (n >> 16) & 0xFF; buffer[1] = (n >> 8) & 0xFF; buffer[2] = n & 0xFF; break; case 4: buffer[0] = (n >> 24) & 0xFF; buffer[1] = (n >> 16) & 0xFF; buffer[2] = (n >> 8) & 0xFF; buffer[3] = n & 0xFF; break; case 5: buffer[0] = (n >> 32) & 0xFF; buffer[1] = (n >> 24) & 0xFF; buffer[2] = (n >> 16) & 0xFF; buffer[3] = (n >> 8) & 0xFF; buffer[4] = n & 0xFF; break; case 6: buffer[0] = (n >> 40) & 0xFF; buffer[1] = (n >> 32) & 0xFF; buffer[2] = (n >> 24) & 0xFF; buffer[3] = (n >> 16) & 0xFF; buffer[4] = (n >> 8) & 0xFF; buffer[5] = n & 0xFF; break; case 7: buffer[0] = (n >> 48) & 0xFF; buffer[1] = (n >> 40) & 0xFF; buffer[2] = (n >> 32) & 0xFF; buffer[3] = (n >> 24) & 0xFF; buffer[4] = (n >> 16) & 0xFF; buffer[5] = (n >> 8) & 0xFF; buffer[6] = n & 0xFF; break; case 8: buffer[0] = (n >> 56) & 0xFF; buffer[1] = (n >> 48) & 0xFF; buffer[2] = (n >> 40) & 0xFF; buffer[3] = (n >> 32) & 0xFF; buffer[4] = (n >> 24) & 0xFF; buffer[5] = (n >> 16) & 0xFF; buffer[6] = (n >> 8) & 0xFF; buffer[7] = n & 0xFF; break; default: throw 10; } } int64_t Utils::decode_longWithHeader(char* buffer) { int64_t n = (int64_t) (buffer[0] & 0x7F) << 49; n += (int64_t) (buffer[1] & 0x7F) << 42; n += (int64_t) (buffer[2] & 0x7F) << 35; n += (int64_t) (buffer[3] & 0x7F) << 28; n += (int64_t) (buffer[4] & 0x7F) << 21; n += (buffer[5] & 0x7F) << 14; n += (buffer[6] & 0x7F) << 7; n += buffer[7] & 0x7F; return n; } void Utils::encode_longWithHeader0(char* buffer, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative"; exit(1); } buffer[0] = (n >> 49) & 0x7F; buffer[1] = (n >> 42) & 0x7F; buffer[2] = (n >> 35) & 0x7F; buffer[3] = (n >> 28) & 0x7F; buffer[4] = (n >> 21) & 0x7F; buffer[5] = (n >> 14) & 0x7F; buffer[6] = (n >> 7) & 0x7F; buffer[7] = n & 0x7F; } void Utils::encode_longWithHeader1(char* buffer, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative"; exit(1); } buffer[0] = ((n >> 49) | 0x80) & 0xFF; buffer[1] = ((n >> 42) | 0x80) & 0xFF; buffer[2] = ((n >> 35) | 0x80) & 0xFF; buffer[3] = ((n >> 28) | 0x80) & 0xFF; buffer[4] = ((n >> 21) | 0x80) & 0xFF; buffer[5] = ((n >> 14) | 0x80) & 0xFF; buffer[6] = ((n >> 7) | 0x80) & 0xFF; buffer[7] = (n | 0x80) & 0xFF; } //long Utils::decode_long(char* buffer, int offset, const char nbytes) { // long n = 0; // for (int i = nbytes - 1; i >= 0; i--) { // n += (long) (buffer[offset++] & 0xFF) << i * 8; // } // return n; //} short Utils::decode_short(const char* buffer, int offset) { return (short) (((buffer[offset] & 0xFF) << 8) + (buffer[offset + 1] & 0xFF)); } void Utils::encode_short(char* buffer, int offset, int n) { buffer[offset++] = (n >> 8) & 0xFF; buffer[offset++] = n & 0xFF; } void Utils::encode_short(char* buffer, int n) { buffer[0] = (n >> 8) & 0xFF; buffer[1] = n & 0xFF; } int64_t Utils::decode_vlong(char* buffer, int *offset) { int pos = *offset; int first = buffer[pos++]; int nbytes = ((first & 255) >> 5) + 1; int64_t retval = (first & 31); switch (nbytes) { case 2: retval += (buffer[pos++] & 255) << 5; break; case 3: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; break; case 4: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; retval += (buffer[pos++] & 255) << 21; break; case 5: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; retval += (buffer[pos++] & 255) << 21; retval += (int64_t) (buffer[pos++] & 255) << 29; break; case 6: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; retval += (buffer[pos++] & 255) << 21; retval += (int64_t) (buffer[pos++] & 255) << 29; retval += (int64_t) (buffer[pos++] & 255) << 37; break; case 7: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; retval += (buffer[pos++] & 255) << 21; retval += (int64_t) (buffer[pos++] & 255) << 29; retval += (int64_t) (buffer[pos++] & 255) << 37; retval += (int64_t) (buffer[pos++] & 255) << 45; break; case 8: retval += (buffer[pos++] & 255) << 5; retval += (buffer[pos++] & 255) << 13; retval += (buffer[pos++] & 255) << 21; retval += (int64_t) (buffer[pos++] & 255) << 29; retval += (int64_t) (buffer[pos++] & 255) << 37; retval += (int64_t) (buffer[pos++] & 255) << 45; retval += (int64_t) (buffer[pos++] & 255) << 53; break; } *offset = pos; return retval; } int Utils::encode_vlong(char* buffer, int offset, int64_t n) { int nbytes = numBytes(n); buffer[offset++] = (((nbytes - 1) << 5) + ((int) n & 31)); n >>= 5; for (int i = 1; i < nbytes; i++) { buffer[offset++] = ((int) n & 255); n >>= 8; } return offset; } uint16_t Utils::encode_vlong(char* buffer, int64_t n) { int nbytes = numBytes(n); int offset = 0; buffer[offset++] = (((nbytes - 1) << 5) + ((int) n & 31)); n >>= 5; for (int i = 1; i < nbytes; i++) { buffer[offset++] = ((int) n & 255); n >>= 8; } return nbytes; } //short Utils::decode_vshort(char* buffer, int *offset) { // char n = buffer[(*offset)++]; // if (n < 0) { // short return_value = (short) ((n & 127) << 8); // return_value += buffer[(*offset)++] & 255; // return return_value; // } else { // return n; // } //} //int Utils::decode_vint(char* buffer, int *offset) { // int n = 0; // int pos = *offset; // int b = buffer[pos++]; // n = b & 63; // int nbytes = (b >> 6) & 3; // switch (nbytes) { // case 1: // n += (buffer[pos++] & 255) << 6; // break; // case 2: // n += (buffer[pos++] & 255) << 6; // n += (buffer[pos++] & 255) << 14; // break; // case 3: // n += (buffer[pos++] & 255) << 6; // n += (buffer[pos++] & 255) << 14; // n += (buffer[pos++] & 255) << 22; // break; // } // *offset = pos; // return n; //} int Utils::decode_vint2(char* buffer, int *offset) { int pos = *offset; int number = buffer[pos++]; if (number < 0) { int longNumber = number & 127; int shiftBytes = 7; do { number = buffer[pos++]; longNumber += ((number & 127) << shiftBytes); shiftBytes += 7; } while (number < 0); *offset = pos; return longNumber; } else { *offset = pos; return number; } } int Utils::encode_vlong2(char* buffer, int offset, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative. This is not allowed with vlong2"; throw 10; } if (n < 128) { // One byte is enough buffer[offset++] = static_cast<char>(n); return offset; } else { int bytesToStore = 64 - numberOfLeadingZeros((uint64_t)n); while (bytesToStore > 7) { buffer[offset++] = ((n & 127) + 128); n >>= 7; bytesToStore -= 7; } buffer[offset++] = n & 127; } return offset; } uint16_t Utils::encode_vlong2(char* buffer, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative. This is not allowed with vlong2"; throw 10; } if (n < 128) { // One byte is enough buffer[0] = static_cast<char>(n); return 1; } else { int bytesToStore = 64 - numberOfLeadingZeros((uint64_t)n); uint16_t offset = 0; while (bytesToStore > 7) { buffer[offset++] = ((n & 127) + 128); n >>= 7; bytesToStore -= 7; } buffer[offset++] = n & 127; return offset; } } void Utils::encode_vlong2_fixedLen(char* buffer, int64_t n, const uint8_t len) { char *beginbuffer = buffer; if (n < 128) { // One byte is enough *buffer = static_cast<char>(n); } else { int neededBits = 64 - numberOfLeadingZeros((uint64_t)n); while (neededBits > 7) { *buffer = ((n & 127) + 128); n >>= 7; buffer++; neededBits -= 7; } *buffer = n & 127; } buffer++; int64_t remBytes = len - (buffer - beginbuffer); while (--remBytes >= 0) { *buffer = (char)128; buffer++; } assert((buffer - beginbuffer) == len); } int Utils::encode_vlong2_fast(uint8_t *out, uint64_t x) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; return i; } uint64_t Utils::decode_vlong2_fast(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int64_t Utils::decode_vlong2(const char* buffer, int *offset) { int pos = *offset; int shift = 7; int64_t n = buffer[pos] & 127; while (buffer[pos++] < 0) { n += (int64_t) (buffer[pos] & 127) << shift; shift += 7; } *offset = pos; return n; } int64_t Utils::decode_vlongWithHeader0(char* buffer, const int end, int *p) { int pos = 0; int shift = 7; int64_t n = buffer[pos++] & 127; while (pos < end && ((buffer[pos] & 128) == 0)) { n += (int64_t) (buffer[pos++] & 127) << shift; shift += 7; } *p = pos; return n; } int64_t Utils::decode_vlongWithHeader1(char* buffer, const int end, int *p) { int pos = 0; int shift = 7; int64_t n = buffer[pos++] & 127; while (pos < end && buffer[pos] < 0) { n += (int64_t) (buffer[pos++] & 127) << shift; shift += 7; } *p = pos; return n; } int Utils::encode_vlongWithHeader0(char* buffer, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative"; return -1; } int i = 0; do { buffer[i++] = n & 127; n >>= 7; } while (n > 0); return i; } int Utils::encode_vlongWithHeader1(char* buffer, int64_t n) { if (n < 0) { LOG(ERRORL) << "Number is negative"; return -1; } int i = 0; do { buffer[i++] = ( n | 128 ) & 0xFF; n >>= 7; } while (n > 0); return i; } int Utils::encode_vint2(char* buffer, int offset, int n) { if (n < 128) { // One byte is enough buffer[offset++] = n; return offset; } else { int bytesToStore = 32 - numberOfLeadingZeros((unsigned int) n); while (bytesToStore > 7) { buffer[offset++] = ((n & 127) + 128); n >>= 7; bytesToStore -= 7; } buffer[offset++] = (n & 127); } return offset; } int Utils::commonPrefix(tTerm *o1, int s1, int e1, tTerm *o2, int s2, int e2) { int len = 0; for (int i = s1, j = s2; i < e1 && j < e2; i++, j++) { if (o1[i] != o2[j]) { return len; } ++len; } return len; } int Utils::compare(const char* o1, int s1, int e1, const char* o2, int s2, int e2) { for (int i = s1, j = s2; i < e1 && j < e2; i++, j++) { if (o1[i] != o2[j]) { return ((int)o1[i] & 0xff) - ((int) o2[j] & 0xff); } } return (e1 - s1) - (e2 - s2); } int Utils::prefixEquals(char* o1, int len1, char* o2, int len2) { int i = 0; for (; i < len1 && i < len2; i++) { if (o1[i] != o2[i]) { return ((int) o1[i] & 0xff) - ((int) o2[i] & 0xff); } } if (i == len1) { return 0; } else { return 1; } } int Utils::prefixEquals(char* o1, int len, char* o2) { int i = 0; for (; i < len && o2[i] != '\0'; i++) { if (o1[i] != o2[i]) { return ((int) o1[i] & 0xff) - ((int) o2[i] & 0xff); } } if (i == len) { return 0; } else { return 1; } } double Utils::get_max_mem() { double memory = 0.0; #if defined(__APPLE__) && defined(__MACH__) struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); memory = (double) rusage.ru_maxrss / 1024 / 1024; #elif defined(__unix__) || defined(__unix) || defined(unix) struct rusage rusage; getrusage(RUSAGE_SELF, &rusage); memory = (double)rusage.ru_maxrss / 1024; #endif #if defined(_WIN32) PROCESS_MEMORY_COUNTERS_EX pmc; pmc.cb = sizeof(pmc); bool result = GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(PROCESS_MEMORY_COUNTERS_EX)); if (!result) { DWORD errorMessageID = ::GetLastError(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); LOG(ERRORL) << "Error getting peak memory " << message; } memory = static_cast<double>(pmc.PeakWorkingSetSize / 1024 / 1024); #endif return memory; } uint64_t Utils::getSystemMemory() { #if defined(__APPLE__) && defined(__MACH__) int mib[2]; mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; int64_t size = 0; size_t len = sizeof(size); sysctl(mib, 2, &size, &len, NULL, 0); return size; #elif defined(__unix__) || defined(__unix) || defined(unix) uint64_t pages = sysconf(_SC_PHYS_PAGES); uint64_t page_size = sysconf(_SC_PAGE_SIZE); return pages * page_size; #elif defined(_WIN32) MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); return memInfo.ullTotalPhys; #endif } uint64_t Utils::getUsedMemory() { #if defined(_WIN32) /* Windows -------------------------------------------------- */ PROCESS_MEMORY_COUNTERS info; GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) /* OSX ------------------------------------------------------ */ struct mach_task_basic_info info; mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; if (task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, (task_info_t) &info, &infoCount) != KERN_SUCCESS) return (size_t) 0L; /* Can't access? */ return (size_t) info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) /* Linux ---------------------------------------------------- */ uint64_t rss = 0L; FILE* fp = NULL; if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) return (size_t)0L; /* Can't open? */ if ( fscanf( fp, "%*s%" SCNu64, &rss ) != 1 ) { fclose( fp ); return (size_t)0L; /* Can't read? */ } fclose( fp ); return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); #else /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ return (size_t)0L; /* Unsupported. */ #endif } uint64_t Utils::getIOReadChars() { #if defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) std::ifstream file("/proc/self/io"); std::string line; while (std::getline(file, line)) { string::size_type loc = line.find("rchar", 0); if (loc != string::npos) { string number = line.substr(7); return stol(number); } } return (size_t)0L; #else return (size_t)0L; /* Unsupported. */ #endif } uint64_t Utils::getIOReadBytes() { #if defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) std::ifstream file("/proc/self/io"); std::string line; while (std::getline(file, line)) { string::size_type loc = line.find("read_bytes", 0); if (loc != string::npos) { string number = line.substr(12); return stol(number); } } return (size_t)0L; #else return -1; /* Unsupported. */ #endif } uint64_t Utils::getCPUCounter() { #if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #ifdef __i386__ unsigned a, d; __asm__ volatile("rdtsc" : "=a" (a), "=d" (d)); return ((uint64_t)a) | (((uint64_t)d) << 32); #elif __aarch64__ return 0; //unsupported #else return 0; //unsupported #endif #else return 0; //unsupported #endif } int Utils::getNumberPhysicalCores() { #if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) return sysconf( _SC_NPROCESSORS_ONLN); #else SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #endif } int64_t Utils::quickSelect(int64_t *vector, int size, int k) { std::vector<int64_t> supportVector(vector, vector + size); std::nth_element(supportVector.begin(), supportVector.begin() + k, supportVector.end()); return supportVector[k]; // if (start == end) // return vector[start]; // int j = partition(vector, start, end); // int length = j - start + 1; // if (length == k) // return vector[j]; // else if (k < length) // return quickSelect(vector, start, j - 1, k); // else // return quickSelect(vector, j + 1, end, k - length); } uint64_t Utils::getNBytes(std::string input) { if (Utils::isDirectory(input)) { uint64_t size = 0; std::vector<std::string> files = Utils::getFiles(input); for (uint64_t i = 0; i < files.size(); ++i) { if (isFile(files[i])) size += Utils::fileSize(files[i]); } /*for (fs::directory_iterator itr(input); itr != fs::directory_iterator(); ++itr) { if (fs::is_regular(itr->path())) { size += fs::file_size(itr->path()); } }*/ return size; } else { return Utils::fileSize(input); } } bool Utils::isCompressed(std::string input) { if (Utils::isDirectory(input)) { bool isCompressed = false; std::vector<std::string> files = Utils::getFiles(input); for (uint64_t i = 0; i < files.size(); ++i) { string &f = files[i]; if (Utils::extension(f) == string(".gz")) { isCompressed = true; } } /*for (fs::directory_iterator itr(input); itr != fs::directory_iterator(); ++itr) { if (fs::is_regular(itr->path())) { if (itr->path().extension() == string(".gz")) isCompressed = true; } }*/ return isCompressed; } else { return Utils::extension(input) == string(".gz"); } } void Utils::linkdir(string source, string dest) { #if defined(_WIN32) LOG(ERRORL) << "LinkDir: Not supported"; throw 10; #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) if (symlink(source.c_str(), dest.c_str())) { throw 10; } #endif } void Utils::rmlink(string link) { #if defined(_WIN32) LOG(ERRORL) << "RmLink: Not supported"; throw 10; #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) unlink(link.c_str()); #endif } bool Utils::isAbsolutePath(string path) { if (path == "") { LOG(ERRORL) << "Cannot determine if " << path << "is absolute or not"; throw 10; } // Commented out: too new (for my Windows Visual Studio).ZZ // #if defined(_WIN32) // std::filesystem::path path(path); // return path.is_absolute(); // #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) if (path[0] == '/') { return true; } else { return false; } #else LOG(ERRORL) << "IsAbsolutePath: Not supported"; throw 10; #endif } //int partition(long* input, int start, int end) { // int pivot = input[end]; // // while (start < end) { // while (input[start] < pivot) // start++; // // while (input[end] > pivot) // end--; // // if (input[start] == input[end]) // start++; // else if (start < end) { // int tmp = input[start]; // input[start] = input[end]; // input[end] = tmp; // } // } // // return end; //}
30.002122
144
0.532471
[ "vector" ]
465716ec67e7d5c770a15821d93e045e201cf974
4,844
cpp
C++
src/gui/rendered_textures/viewport.cpp
Pritchy96/cadbase
8d3b3a4441a7889fe3510631719b341e8dc1d3f3
[ "MIT" ]
null
null
null
src/gui/rendered_textures/viewport.cpp
Pritchy96/cadbase
8d3b3a4441a7889fe3510631719b341e8dc1d3f3
[ "MIT" ]
null
null
null
src/gui/rendered_textures/viewport.cpp
Pritchy96/cadbase
8d3b3a4441a7889fe3510631719b341e8dc1d3f3
[ "MIT" ]
null
null
null
#include <algorithm> #include <spdlog/spdlog.h> #include <glm/fwd.hpp> #include <memory> #include <vector> #include "cad-base/gui/rendered_textures/viewport.hpp" #include "cad-base/geometry/viewport_grid.hpp" #include "cad-base/gui/gui_data.hpp" #include "cad-base/gui/rendered_textures/gui_render_texture.hpp" #include "cad-base/scene_data.hpp" using std::vector; using std::shared_ptr; using std::make_shared; using std::make_unique; using glm::vec3; const vector<vec3> AXIS_LINES = { vec3(0.0f, 0.0f, 0.0f), // x vec3(100.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), // y vec3(0.0f, 100.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), // z vec3(0.0f, 0.0f, 100.0f), }; const vector<vec3> AXIS_COLOURS = { vec3(1.0f, 0.0f, 0.0f), // x vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), // y vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f), // z vec3(0.0f, 0.0f, 1.0f) }; Viewport::Viewport(GLFWwindow *window, glm::vec4 background_col, int viewport_width, int viewport_height, shared_ptr<SceneData> scene_data) : GuiRenderTexture(window, background_col, viewport_width, viewport_height), scene_data(scene_data) { spdlog::info("Viewport Initialised"); render_axis = make_shared<Geometry>(AXIS_LINES, AXIS_COLOURS, "Render Axis"); viewport_geo_renderable_pairs.emplace_back(render_axis, make_unique<Renderable>(basic_shader, render_axis, GL_LINES)); grid = make_shared<ViewportGrid>(50, 50, 20, 20, glm::vec3(0.3f, 0.3f, 0.3f), basic_shader); viewport_geo_renderable_pairs.emplace_back(grid, make_unique<Renderable>(basic_shader, grid, GL_LINES)); } void Viewport::Draw() { //Call base class Draw method. GuiRenderTexture::Draw(); //Render viewport specific Geometry. auto geo_renderable = viewport_geo_renderable_pairs.begin(); while(geo_renderable != viewport_geo_renderable_pairs.end()) { // Geo is dead, nuke the map link if (geo_renderable->first->is_dead) { // iterator.erase gives the next item in the list. geo_renderable = viewport_geo_renderable_pairs.erase(geo_renderable); continue; } if (geo_renderable->second == nullptr) { // Renderable for geo doesn't exist, make one. // TODO: Some logic to choose a render type? (currently default to GL_TRIANGLES) geo_renderable->second = make_unique<Renderable>(basic_shader, geo_renderable->first, GL_TRIANGLES); } shared_ptr<Geometry> geometry = geo_renderable->first; shared_ptr<Renderable> renderable = geo_renderable->second; if (geometry->buffers_invalid) { renderable->valid_geometry_vao = false; renderable->valid_aa_bounding_box_vao = false; } renderable->Draw(camera->GetProjectionMatrix(), camera->GetViewMatrix()); ++geo_renderable; } } void Viewport::HandleIO() { GuiRenderTexture::HandleIO(); ImGuiIO& io = ImGui::GetIO(); bool image_hovered = ImGui::IsItemHovered(); //Zoom if ((image_hovered || texture_has_focus) && io.MouseWheel != 0) { arcball->Zoom(); } if (ImGui::IsMouseDragging(ImGuiMouseButton_Middle)) { //Pan if (image_hovered) { arcball->Pan(); } } else if (ImGui::IsMouseDragging(ImGuiMouseButton_Left)) { if (image_hovered) { glm::vec2 mouse_delta = glm::vec2(io.MouseDelta.x, io.MouseDelta.y); //TODO: use Persp matrix and distance from camera > selected object to make movement of object 1:1 with movement of object. glm::vec4 mouse_delta_world = camera->GetRotation() * glm::vec4(mouse_delta.x, 0.0f, -mouse_delta.y, 1.0f); mouse_delta_world /= mouse_delta_world.w; auto selected_ptr = scene_data->SelectedGeoBegin(); while (selected_ptr != scene_data->SelectedGeoEnd()) { (*selected_ptr)->MoveOrigin(mouse_delta_world); selected_ptr++; } } } } void Viewport::SelectRenderable(shared_ptr<Renderable> clicked_renderable) { bool object_already_selected = std::find(scene_data->SelectedGeoBegin(), scene_data->SelectedGeoEnd(), clicked_renderable->geometry) != scene_data->SelectedGeoEnd(); //Don't deselect all geo other than clicked object if it's already clicked //This is annoying behaviour for the user if they accidentally click a selected object if (!ImGui::GetIO().KeyShift && !object_already_selected) { scene_data->ClearSelectedGeo(); } //Not in list, add it. if (!object_already_selected) { scene_data->SelectedGeoPushBack(clicked_renderable->geometry); } } void Viewport::SelectNothing() { if (!ImGui::GetIO().KeyShift) { // Clear selection when Shift is not held scene_data->ClearSelectedGeo(); } }
34.35461
169
0.667217
[ "cad", "geometry", "render", "object", "vector" ]
465745eaa395f24e8eac45a1b4021b6ddf53c408
6,663
cpp
C++
kwm/keys.cpp
choco/kwm
5f833ef02090b86b7262db0415a64a2771addb4d
[ "MIT" ]
null
null
null
kwm/keys.cpp
choco/kwm
5f833ef02090b86b7262db0415a64a2771addb4d
[ "MIT" ]
null
null
null
kwm/keys.cpp
choco/kwm
5f833ef02090b86b7262db0415a64a2771addb4d
[ "MIT" ]
null
null
null
#include "keys.h" #include "helpers.h" #include "interpreter.h" #define internal static #define local_persist static extern modifier_keys MouseDragKey; internal const char *Shell = "/bin/bash"; internal const char *ShellArgs = "-c"; internal inline bool HasFlags(modifier_keys *Modifier, uint32_t Flag) { bool Result = Modifier->Flags & Flag; return Result; } internal inline void AddFlags(modifier_keys *Modifier, uint32_t Flag) { Modifier->Flags |= Flag; } internal inline bool CompareCmdKey(modifier_keys *A, modifier_keys *B) { if(HasFlags(A, Modifier_Flag_Cmd)) { return (HasFlags(B, Modifier_Flag_LCmd) || HasFlags(B, Modifier_Flag_RCmd) || HasFlags(B, Modifier_Flag_Cmd)); } else { return ((HasFlags(A, Modifier_Flag_LCmd) == HasFlags(B, Modifier_Flag_LCmd)) && (HasFlags(A, Modifier_Flag_RCmd) == HasFlags(B, Modifier_Flag_RCmd)) && (HasFlags(A, Modifier_Flag_Cmd) == HasFlags(B, Modifier_Flag_Cmd))); } } internal inline bool CompareShiftKey(modifier_keys *A, modifier_keys *B) { if(HasFlags(A, Modifier_Flag_Shift)) { return (HasFlags(B, Modifier_Flag_LShift) || HasFlags(B, Modifier_Flag_RShift) || HasFlags(B, Modifier_Flag_Shift)); } else { return ((HasFlags(A, Modifier_Flag_LShift) == HasFlags(B, Modifier_Flag_LShift)) && (HasFlags(A, Modifier_Flag_RShift) == HasFlags(B, Modifier_Flag_RShift)) && (HasFlags(A, Modifier_Flag_Shift) == HasFlags(B, Modifier_Flag_Shift))); } } internal inline bool CompareAltKey(modifier_keys *A, modifier_keys *B) { if(HasFlags(A, Modifier_Flag_Alt)) { return (HasFlags(B, Modifier_Flag_LAlt) || HasFlags(B, Modifier_Flag_RAlt) || HasFlags(B, Modifier_Flag_Alt)); } else { return ((HasFlags(A, Modifier_Flag_LAlt) == HasFlags(B, Modifier_Flag_LAlt)) && (HasFlags(A, Modifier_Flag_RAlt) == HasFlags(B, Modifier_Flag_RAlt)) && (HasFlags(A, Modifier_Flag_Alt) == HasFlags(B, Modifier_Flag_Alt))); } } internal inline bool CompareControlKey(modifier_keys *A, modifier_keys *B) { if(HasFlags(A, Modifier_Flag_Control)) { return (HasFlags(B, Modifier_Flag_LControl) || HasFlags(B, Modifier_Flag_RControl) || HasFlags(B, Modifier_Flag_Control)); } else { return ((HasFlags(A, Modifier_Flag_LControl) == HasFlags(B, Modifier_Flag_LControl)) && (HasFlags(A, Modifier_Flag_RControl) == HasFlags(B, Modifier_Flag_RControl)) && (HasFlags(A, Modifier_Flag_Control) == HasFlags(B, Modifier_Flag_Control))); } } internal void ParseModifiers(modifier_keys *Modifier, std::string KeySym) { std::vector<std::string> Modifiers = SplitString(KeySym, '+'); for(std::size_t ModIndex = 0; ModIndex < Modifiers.size(); ++ModIndex) { if(Modifiers[ModIndex] == "cmd") AddFlags(Modifier, Modifier_Flag_Cmd); else if(Modifiers[ModIndex] == "lcmd") AddFlags(Modifier, Modifier_Flag_LCmd); else if(Modifiers[ModIndex] == "rcmd") AddFlags(Modifier, Modifier_Flag_RCmd); else if(Modifiers[ModIndex] == "alt") AddFlags(Modifier, Modifier_Flag_Alt); else if(Modifiers[ModIndex] == "lalt") AddFlags(Modifier, Modifier_Flag_LAlt); else if(Modifiers[ModIndex] == "ralt") AddFlags(Modifier, Modifier_Flag_RAlt); else if(Modifiers[ModIndex] == "shift") AddFlags(Modifier, Modifier_Flag_Shift); else if(Modifiers[ModIndex] == "lshift") AddFlags(Modifier, Modifier_Flag_LShift); else if(Modifiers[ModIndex] == "rshift") AddFlags(Modifier, Modifier_Flag_RShift); else if(Modifiers[ModIndex] == "ctrl") AddFlags(Modifier, Modifier_Flag_Control); else if(Modifiers[ModIndex] == "lctrl") AddFlags(Modifier, Modifier_Flag_LControl); else if(Modifiers[ModIndex] == "rctrl") AddFlags(Modifier, Modifier_Flag_RControl); } } internal modifier_keys ModifierFromCGEvent(CGEventRef Event) { modifier_keys Modifier = {}; CGEventFlags Flags = CGEventGetFlags(Event); if((Flags & Event_Mask_Cmd) == Event_Mask_Cmd) { if((Flags & Event_Mask_LCmd) == Event_Mask_LCmd) AddFlags(&Modifier, Modifier_Flag_LCmd); else if((Flags & Event_Mask_RCmd) == Event_Mask_RCmd) AddFlags(&Modifier, Modifier_Flag_RCmd); else AddFlags(&Modifier, Modifier_Flag_Cmd); } if((Flags & Event_Mask_Shift) == Event_Mask_Shift) { if((Flags & Event_Mask_LShift) == Event_Mask_LShift) AddFlags(&Modifier, Modifier_Flag_LShift); else if((Flags & Event_Mask_RShift) == Event_Mask_RShift) AddFlags(&Modifier, Modifier_Flag_RShift); else AddFlags(&Modifier, Modifier_Flag_Shift); } if((Flags & Event_Mask_Alt) == Event_Mask_Alt) { if((Flags & Event_Mask_LAlt) == Event_Mask_LAlt) AddFlags(&Modifier, Modifier_Flag_LAlt); else if((Flags & Event_Mask_RAlt) == Event_Mask_RAlt) AddFlags(&Modifier, Modifier_Flag_RAlt); else AddFlags(&Modifier, Modifier_Flag_Alt); } if((Flags & Event_Mask_Control) == Event_Mask_Control) { if((Flags & Event_Mask_LControl) == Event_Mask_LControl) AddFlags(&Modifier, Modifier_Flag_LControl); else if((Flags & Event_Mask_RControl) == Event_Mask_RControl) AddFlags(&Modifier, Modifier_Flag_RControl); else AddFlags(&Modifier, Modifier_Flag_Control); } return Modifier; } void KwmSetMouseDragKey(std::string KeySym) { ParseModifiers(&MouseDragKey, KeySym); } bool MouseDragKeyMatchesCGEvent(CGEventRef Event) { modifier_keys Modifier = ModifierFromCGEvent(Event); return (CompareCmdKey(&MouseDragKey, &Modifier) && CompareShiftKey(&MouseDragKey, &Modifier) && CompareAltKey(&MouseDragKey, &Modifier) && CompareControlKey(&MouseDragKey, &Modifier)); } void KwmExecuteSystemCommand(std::string Command) { int ChildPID = fork(); if(ChildPID == 0) { DEBUG("Exec: FORK SUCCESS"); char *Exec[] = { (char *) Shell, (char *) ShellArgs, (char *) Command.c_str(), NULL}; int StatusCode = execvp(Exec[0], Exec); DEBUG("Exec failed with code: " << StatusCode); exit(StatusCode); } }
32.985149
95
0.639802
[ "vector" ]
4679d171acdca8f16bb94603f4f5ae32a1e301fa
1,656
hpp
C++
cpuemu/w65c02s/execution_wrapper.hpp
deqyra/cpuemu
b30d39e01ef03a165169d53397d117a2550c650e
[ "MIT" ]
2
2021-04-23T13:40:45.000Z
2022-03-28T13:59:30.000Z
cpuemu/w65c02s/execution_wrapper.hpp
deqyra/cpuemu
b30d39e01ef03a165169d53397d117a2550c650e
[ "MIT" ]
null
null
null
cpuemu/w65c02s/execution_wrapper.hpp
deqyra/cpuemu
b30d39e01ef03a165169d53397d117a2550c650e
[ "MIT" ]
null
null
null
#ifndef CPUEMU__W65C02S__EXECUTION_WRAPPER_HPP #define CPUEMU__W65C02S__EXECUTION_WRAPPER_HPP #include <vector> #include <common/types.hpp> #include <common/memory.hpp> #include "cpu.hpp" namespace emu::w65c02s { class ExecutionWrapper { public: ExecutionWrapper(); // Write a program to internal memory at the provided start address. The CPU // will not be reset upon calling this function. The reset vector from main // program start location will be set accordingly. void registerProgram(const std::vector<Byte>& program, const uint64_t startAddress); // Write data to the memory range at the provided start address. void registerMemory(const std::vector<Byte>& memory, const uint64_t startAddress); // Have the CPU perform a single cycle of execution void cycleStep(); // Have the CPU perform an entire instruction, return the number of cycles // it stepped through. // If the CPU is resetting, calling this function will step through the // remaining cycles in the reset sequence. // If the CPU was requested to reset amidst the execution of the current // instruction, the function will return when the CPU enters the first cycle // of its reset sequence. uint8_t instructionStep(); private: // CPU which will execute the program CPU _cpu; using Memory = Memory<CPU::MaxMemory>; // Memory linked to the CPU Memory _mem; // Program to execute std::vector<Byte> _program; public: // View on the CPU const CPU& cpu = _cpu; // View on the memory const Memory& mem = _mem; }; } #endif//CPUEMU__W65C02S__EXECUTION_WRAPPER_HPP
27.147541
88
0.716787
[ "vector" ]
468986925da4c77712962d6ac562dd417694dfce
13,383
cpp
C++
xinput.cpp
MaddTheSane/koku-xinput-wine
cc20eeaf32eaeda14c8ff7e7929bcd672026269e
[ "BSD-2-Clause" ]
null
null
null
xinput.cpp
MaddTheSane/koku-xinput-wine
cc20eeaf32eaeda14c8ff7e7929bcd672026269e
[ "BSD-2-Clause" ]
null
null
null
xinput.cpp
MaddTheSane/koku-xinput-wine
cc20eeaf32eaeda14c8ff7e7929bcd672026269e
[ "BSD-2-Clause" ]
null
null
null
#include "xinput.h" #include "config.h" #include "main.h" #ifndef USE_SDL2 #include <SDL/SDL.h> #define SDL_INIT_HAPTIC 0 #define SDL_Haptic void #else #include <SDL2/SDL.h> #include <SDL2/SDL_haptic.h> #endif #include <vector> #include <iostream> #include <fstream> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <iomanip> #include <sstream> using namespace std; bool active = true; class Sgamepad_sdl { public: Sgamepad_sdl() { joystick = nullptr; haptic = nullptr; memset(haptic_effects, 0, sizeof(haptic_effects)); } SDL_Joystick *joystick; SDL_Haptic *haptic; int haptic_effects[2]; }; static vector<Sgamepad_sdl> gamepads_sdl; const GUID GUID_NULL = {0,0,0,{0,0,0,0,0,0,0,0}}; void GamepadInitSDL() { static bool inited = false; if (inited) { return; } inited = true; //init: SDL_Init(SDL_INIT_JOYSTICK|SDL_INIT_HAPTIC); SDL_JoystickEventState(SDL_IGNORE); for(int i = 0; i < SDL_NumJoysticks(); ++i) { SDL_Joystick* joy = SDL_JoystickOpen(i); if (joy) { Sgamepad_sdl new_gamepad = Sgamepad_sdl(); new_gamepad.joystick = joy; new_gamepad.haptic = 0; //check for haptic #ifdef USE_SDL2 new_gamepad.haptic = SDL_HapticOpenFromJoystick(new_gamepad.joystick); if (new_gamepad.haptic != 0) { //start haptic effects SDL_HapticEffect effect[2]; memset(&effect, 0, sizeof(SDL_HapticEffect)*2); effect[0].type = SDL_HAPTIC_SINE; //constant somehow don't work, or I don't undestand what it does.. effect[0].periodic.direction.type = SDL_HAPTIC_CARTESIAN; effect[0].periodic.direction.dir[0] = 1; effect[0].periodic.period = 0; effect[0].periodic.magnitude = 0; effect[0].periodic.length = SDL_HAPTIC_INFINITY; effect[1] = effect[0]; effect[1].periodic.direction.dir[0] = -1; effect[1].periodic.magnitude = 0; new_gamepad.haptic_effects[0] = SDL_HapticNewEffect(new_gamepad.haptic, &(effect[0])); new_gamepad.haptic_effects[1] = SDL_HapticNewEffect(new_gamepad.haptic, &(effect[1])); SDL_HapticRunEffect(new_gamepad.haptic, new_gamepad.haptic_effects[0], 1); SDL_HapticRunEffect(new_gamepad.haptic, new_gamepad.haptic_effects[1], 1); } #endif gamepads_sdl.push_back(new_gamepad); } } XINPUT_VIBRATION welcome_vibration; welcome_vibration.wLeftMotorSpeed = 65535; welcome_vibration.wRightMotorSpeed = 0; XInputSetState(0, &welcome_vibration); SDL_Delay(250); welcome_vibration.wLeftMotorSpeed = 0; welcome_vibration.wRightMotorSpeed = 0; XInputSetState(0, &welcome_vibration); SDL_Delay(250); welcome_vibration.wLeftMotorSpeed = 0; welcome_vibration.wRightMotorSpeed = 65535; XInputSetState(0, &welcome_vibration); SDL_Delay(250); welcome_vibration.wLeftMotorSpeed = 0; welcome_vibration.wRightMotorSpeed = 0; XInputSetState(0, &welcome_vibration); //load config: string path = string(getenv("HOME"))+"/.config/koku-xinput-wine.ini"; ifstream iconfig(path.c_str(), ifstream::in); if (iconfig.is_open()) { if (debug) { clog << "koku-xinput-wine: Load config \"" << path << "\"" << endl; } //load config while (iconfig.good()) { string line; std::getline(iconfig, line); if (line.size() == 0) { //empty line continue; } if (line[0] == ';') { //comment continue; } int pos = 0; //read until not A-Z a-z 0-9 string name; while(pos < line.size()) { char c = line[pos++]; if (((c >= 'A')&&(c <= 'Z')) || ((c >= 'a')&&(c <= 'z')) || ((c >= '0')&&(c <= '9')) || (c == '_')) { name += c; } else { break; } } //search name in mapping for(int i = 0; i < 20; ++i) { if (mapping[i].name == name) { //name found if (debug) { clog << "koku-xinput-wine: Load parameter for \"" << name << "\"" << endl; } //read until "=" while(pos < line.size()) { char c = line[pos++]; if (c == '=') { break; } } //read until A-Z a-z 0-9 while(pos < line.size()) { char c = line[pos++]; if (((c >= 'A')&&(c <= 'Z')) || ((c >= 'a')&&(c <= 'z')) || ((c >= '0')&&(c <= '9'))) { --pos; break; } } if (pos >= line.size()) break; //read the type settings[i].type = line[pos++]; settings[i].mask = short(0xFFFF); settings[i].scale = 1; settings[i].id = 0; if (debug) { switch(settings[i].type) { case 'A': clog << "koku-xinput-wine: Type = Axis" << endl; break; case 'B': clog << "koku-xinput-wine: Type = Buttons" << endl; break; case 'H': clog << "koku-xinput-wine: Type = Hats" << endl; break; default: clog << "koku-xinput-wine: Type = Unknow" << endl; break; } } if (pos >= line.size()) break; //parse number { stringstream ss(string(line.c_str()+pos, line.size()-pos)); int id; ss >> id; settings[i].id = id; } if (debug) { clog << "koku-xinput-wine: Id = " << right << setw(2) << setfill('0') << int(settings[i].id) << setfill(' ') << setw(0) << left << endl; } //read until '&' while(pos < line.size()) { char c = line[pos++]; if (c == '&') { pos--; break; } if (c == '*') { pos--; break; } } if (pos >= line.size()) break; if (line[pos++] == '&') { if (pos >= line.size()) break; if (line[pos++] != '0') break; if (pos >= line.size()) break; if (line[pos++] != 'x') break; if (pos >= line.size()) break; //parse number { stringstream ss(string(line.c_str()+pos, line.size()-pos)); int mask; ss >> hex >> mask >> dec; settings[i].mask = short(mask); } if (debug) { clog << "koku-xinput-wine: Mask = 0x" << right << setw(4) << setfill('0') << hex << settings[i].mask << setfill(' ') << dec << setw(0) << left << endl; } //read until '*' while(pos < line.size()) { char c = line[pos++]; if (c == '*') { break; } } } if (pos >= line.size()) break; //parse number { stringstream ss(string(line.c_str()+pos, line.size()-pos)); ss >> settings[i].scale; } if (debug) { clog << "koku-xinput-wine: Scale = " << settings[i].scale << endl; } //exit loop break; } } } iconfig.close(); } else { if (debug) { clog << "koku-xinput-wine: Save default config \"" << path << "\"" << endl; } //write default config ofstream oconfig(path.c_str(), ifstream::out); if (oconfig.is_open()) { oconfig << ";koku-xinput-wine config, for more information see https://github.com/KoKuToru/koku-xinput-wine" << endl; for(int i = 0; i < 20; ++i) { oconfig << left << setw(30) << mapping[i].name << " = " << right << settings[i].type << setfill('0') << setw(2) << int(settings[i].id) << setfill(' ') ; if (settings[i].mask != short(0xFFFF)) { oconfig << "&0x" << setfill('0') << setw(4) << hex << settings[i].mask << setfill(' ') << dec; } if (settings[i].scale != 1) { oconfig << "*" << settings[i].scale; } oconfig << endl; } oconfig.close(); }else { clog << "koku-xinput-wine: couldn't open file" << endl; } } } void WINAPI XInputEnable(bool enable) { if (!enable) { XINPUT_VIBRATION stop_vibration; stop_vibration.wLeftMotorSpeed = 0; stop_vibration.wRightMotorSpeed = 0; for(int i = 0; i < 4; ++i) { XInputSetState(i, &stop_vibration); } } active = enable; } unsigned WINAPI XInputGetAudioDeviceIds(unsigned dwUserIndex, short* pRenderDeviceId, unsigned *pRenderCount, short* pCaptureDeviceId, unsigned *pCaptureCount) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } /* If there is no headset connected to the controller, the function will also retrieve ERROR_SUCCESS with NULL as the values for pRenderDeviceId and pCaptureDeviceId. */ *pRenderDeviceId = 0; *pCaptureDeviceId = 0; return ERROR_SUCCESS; } unsigned WINAPI XInputGetBatteryInformation(unsigned dwUserIndex, char devType, XINPUT_BATTERY_INFORMATION *pBatteryInformation) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } if (devType == BATTERY_DEVTYPE_GAMEPAD) { //sorry no real battery check pBatteryInformation->BatteryType = BATTERY_TYPE_WIRED; pBatteryInformation->BatteryLevel = BATTERY_LEVEL_FULL; } else { pBatteryInformation->BatteryType = BATTERY_TYPE_DISCONNECTED; pBatteryInformation->BatteryLevel = BATTERY_LEVEL_EMPTY; } return ERROR_SUCCESS; } unsigned WINAPI XInputGetCapabilities(unsigned dwUserIndex, unsigned dwFlags, XINPUT_CAPABILITIES *pCapabilities) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } pCapabilities->Type = XINPUT_DEVTYPE_GAMEPAD; pCapabilities->SubType = XINPUT_DEVSUBTYPE_GAMEPAD; pCapabilities->Flags = (gamepads_sdl[dwUserIndex].haptic != 0)?XINPUT_CAPS_FFB_SUPPORTED:0; pCapabilities->Gamepad.wButtons = 0xFFFF; pCapabilities->Gamepad.bLeftTrigger = 255; pCapabilities->Gamepad.bRightTrigger = 255; pCapabilities->Gamepad.sThumbLX = 32767; pCapabilities->Gamepad.sThumbLY = 32767; pCapabilities->Gamepad.xThumbRX = 32767; pCapabilities->Gamepad.xThumbRY = 32767; if (gamepads_sdl[dwUserIndex].haptic != 0) { pCapabilities->Vibration.wLeftMotorSpeed = 65535; pCapabilities->Vibration.wRightMotorSpeed = 65535; } else { pCapabilities->Vibration.wLeftMotorSpeed = 0; pCapabilities->Vibration.wRightMotorSpeed = 0; } return ERROR_SUCCESS; } unsigned WINAPI XInputGetDSoundAudioDeviceGuids(unsigned dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } /* If there is no headset connected to the controller, the function also retrieves ERROR_SUCCESS with GUID_NULL as the values for pDSoundRenderGuid and pDSoundCaptureGuid. */ *pDSoundRenderGuid = GUID_NULL; *pDSoundCaptureGuid = GUID_NULL; return ERROR_SUCCESS; } unsigned WINAPI XInputGetKeystroke(unsigned dwUserIndex, unsigned dwReserved, XINPUT_KEYSTROKE* pKeystroke) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } //If no new keys have been pressed, the return value is ERROR_EMPTY. return ERROR_EMPTY; } unsigned WINAPI XInputGetState(unsigned dwUserIndex, XINPUT_STATE *pState) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } SDL_JoystickUpdate(); //load data for(int i = 0; i < 20; ++i) { short value = 0; switch(settings[i].type) { case 'A': value = max(SDL_JoystickGetAxis(gamepads_sdl[dwUserIndex].joystick , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale; break; case 'H': value = max(SDL_JoystickGetHat(gamepads_sdl[dwUserIndex].joystick , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale; break; case 'B': value = max(SDL_JoystickGetButton(gamepads_sdl[dwUserIndex].joystick , settings[i].id-1)&settings[i].mask, -32767)*settings[i].scale; break; default: //uhm break; } if (mapping[i].mask == 0) { *(mapping[i].addr) = value; } else if (value != 0) { *(mapping[i].addr) |= mapping[i].mask; } else { *(mapping[i].addr) &= (~mapping[i].mask); } } //set data static int dwPacketNumber = 0; pState->dwPacketNumber = ++dwPacketNumber; pState->Gamepad.wButtons = *(reinterpret_cast<unsigned short*>(&gamepad.buttons)); pState->Gamepad.bLeftTrigger = gamepad.left_shoulder; pState->Gamepad.bRightTrigger = gamepad.right_shoulder; pState->Gamepad.sThumbLX = gamepad.left_thumb_x; pState->Gamepad.sThumbLY = gamepad.left_thumb_y; pState->Gamepad.xThumbRX = gamepad.right_thumb_x; pState->Gamepad.xThumbRY = gamepad.right_thumb_y; return ERROR_SUCCESS; } unsigned WINAPI XInputSetState(unsigned dwUserIndex, XINPUT_VIBRATION *pVibration) { GamepadInitSDL(); if (dwUserIndex >= gamepads_sdl.size()) { return ERROR_DEVICE_NOT_CONNECTED; } if (active) { //Sorry no vibration in SDL1.2, maybe SDL2 #ifdef USE_SDL2 if (gamepads_sdl[dwUserIndex].haptic != 0) { SDL_HapticEffect effect[2]; memset(&effect, 0, sizeof(SDL_HapticEffect)*2); effect[0].type = SDL_HAPTIC_SINE; effect[0].periodic.direction.type = SDL_HAPTIC_CARTESIAN; effect[0].periodic.direction.dir[0] = 1; effect[0].periodic.period = 0; effect[0].periodic.magnitude = pVibration->wLeftMotorSpeed>>1; effect[0].periodic.length = SDL_HAPTIC_INFINITY; effect[1] = effect[0]; effect[1].periodic.direction.dir[0] = -1; effect[1].periodic.magnitude = pVibration->wRightMotorSpeed>>1; SDL_HapticUpdateEffect(gamepads_sdl[dwUserIndex].haptic, gamepads_sdl[dwUserIndex].haptic_effects[0], &(effect[0])); SDL_HapticUpdateEffect(gamepads_sdl[dwUserIndex].haptic, gamepads_sdl[dwUserIndex].haptic_effects[1], &(effect[1])); } #endif } return ERROR_SUCCESS; }
24.875465
159
0.63491
[ "vector" ]
468d2503b9d06d230d6b6f2d8f68cafa0e99fdc8
8,101
cpp
C++
config.cpp
BlackHawkPL/checkLOS
dfdca8c3c1ede1572de0b4bf49f81ab977cdbd2f
[ "MIT" ]
null
null
null
config.cpp
BlackHawkPL/checkLOS
dfdca8c3c1ede1572de0b4bf49f81ab977cdbd2f
[ "MIT" ]
1
2017-10-21T21:37:04.000Z
2017-10-22T02:24:20.000Z
config.cpp
BlackHawkPL/checkLOS
dfdca8c3c1ede1572de0b4bf49f81ab977cdbd2f
[ "MIT" ]
1
2020-04-08T19:32:16.000Z
2020-04-08T19:32:16.000Z
class CfgPatches { class los_check { units[] = { "" }; weapons[] = {}; requiredVersion = 0.1; requiredAddons[] = {"A3_Ui_F"}; version = 1; }; }; class Extended_PostInit_EventHandlers { class checkLOS { clientinit="call compile preprocessFileLineNumbers '\checkLOS\init.sqf'"; }; }; class CfgMarkerColors { class ColorBlack; class BH_checkLOS_colorNotVisible { color[] = {0.1,0.1,0.1,1}; name = "No LOS"; scope = 1; }; class BH_checkLOS_colorObstructed { color[] = {1,0,0.1,1}; name = "LOS obstruced by object"; scope = 1; }; class BH_checkLOS_colorVisible { color[] = {0,0,1,1}; name = "clear LOS"; scope = 1; }; class BH_checkLOS_orange { color[] = {255/255,165/255,0/255, 1}; name = "Orange"; scope = 2; }; class BH_checkLOS_brown { color[] = {165/255,42/255,42/255, 1}; name = "Brown"; scope = 2; }; class BH_checkLOS_dark_green { color[] = {0/255,100/255,0/255, 1}; name = "Dark green"; scope = 2; }; class BH_checkLOS_purple { color[] = {128/255,0/255,128/255, 1}; name = "Purple"; scope = 2; }; class BH_checkLOS_pink { color[] = {255/255,192/255,203/255, 1}; name = "Pink"; scope = 2; }; class BH_checkLOS_gray { color[] = {169/255,169/255,169/255, 1}; name = "Gray"; scope = 2; }; class BH_checkLOS_khaki { color[] = {240/255,230/255,140/255, 1}; name = "Khaki"; scope = 2; }; class BH_checkLOS_olive { color[] = {128/255,128/255,0/255, 1}; name = "Olive"; scope = 2; }; class BH_checkLOS_uo_brown { color[] = {177/255,158/255,113/255, 1}; name = "UO Brown™"; scope = 2; }; class BH_checkLOS_heatmap1 { color[] = {0/255,100/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap2 { color[] = {0/255,110/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap3 { color[] = {0/255,120/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap4 { color[] = {0/255,130/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap5 { color[] = {0/255,140/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap6 { color[] = {0/255,150/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap7 { color[] = {0/255,160/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap8 { color[] = {0/255,170/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap9 { color[] = {0/255,180/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap10 { color[] = {0/255,190/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap11 { color[] = {40/255,200/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap12 { color[] = {60/255,210/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap13 { color[] = {80/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap14 { color[] = {100/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap15 { color[] = {110/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap16 { color[] = {120/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap17 { color[] = {130/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap18 { color[] = {140/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap19 { color[] = {150/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap20 { color[] = {160/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap21 { color[] = {170/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap22 { color[] = {180/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap23 { color[] = {190/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap24 { color[] = {200/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap25 { color[] = {210/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap26 { color[] = {220/255,220/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap27 { color[] = {220/255,210/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap28 { color[] = {220/255,200/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap29 { color[] = {220/255,190/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap30 { color[] = {220/255,180/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap31 { color[] = {220/255,170/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap32 { color[] = {220/255,160/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap33 { color[] = {220/255,150/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap34 { color[] = {220/255,140/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap35 { color[] = {220/255,130/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap36 { color[] = {220/255,120/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap37 { color[] = {220/255,110/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap38 { color[] = {220/255,100/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap39 { color[] = {220/255,90/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap40 { color[] = {220/255,80/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap41 { color[] = {220/255,70/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap42 { color[] = {220/255,60/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap43 { color[] = {215/255,55/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap44 { color[] = {210/255,50/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap45 { color[] = {205/255,45/255,0/255, 1}; name = "heatmap"; scope = 0; }; class BH_checkLOS_heatmap46 { color[] = {200/255,40/255,0/255, 1}; name = "heatmap"; scope = 0; }; };
21.776882
75
0.483891
[ "object" ]
469b89a4fd03aea639fae846b7a384b748d40e6c
2,952
cpp
C++
PIN64/Game.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
1
2019-05-22T23:22:14.000Z
2019-05-22T23:22:14.000Z
PIN64/Game.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
1
2019-07-04T10:12:06.000Z
2019-07-04T10:12:06.000Z
PIN64/Game.cpp
MooglyGuy/pin64
aa411cbabbc400f752411d2c0a0711209d7f4826
[ "BSD-3-Clause" ]
null
null
null
#include <SDL.h> #include "Logger.h" #include "Game.h" Game::Game() : mInitialized(false) , mRunning(false) , mPaused(false) , mCurrTime(0) , mLastTime(0) , mWindow(nullptr) , mRenderer(nullptr) , mFramebuffer(nullptr) , mFB(nullptr) , mEventDispatcher(nullptr) , mRDRAM(nullptr) , mHiddenRAM(nullptr) , mCapture(nullptr) , mRDP(nullptr) { } Game::~Game() { if (mInitialized) { SDL_DestroyRenderer(mRenderer); SDL_DestroyWindow(mWindow); delete mEventDispatcher; delete mCapture; } } bool Game::Initialize() { mWindow = SDL_CreateWindow("PIN64 v0.00", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (!mWindow) { Logger::Log("Call to SDL_CreateWindow failed: %s\n", SDL_GetError()); SDL_Quit(); return false; } mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!mRenderer) { SDL_DestroyWindow(mWindow); Logger::Log("Call to SDL_CreateRenderer failed: %s\n", SDL_GetError()); SDL_Quit(); return false; } mEventDispatcher = new EventDispatcher(); mEventDispatcher->RegisterListener(this); mInitialized = true; mFramebuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 640, 480); mFB = std::make_unique<uint8_t[]>(8 * 1024 * 1024); mRDRAM = std::make_unique<uint8_t[]>(8 * 1024 * 1024); mHiddenRAM = std::make_unique<uint8_t[]>(8 * 1024 * 1024); mCapture = new pin64_t(); mCapture->play(0); mRDP = new n64_rdp((uint32_t*)mRDRAM.get()); mRDP->init_internal_state(mCapture); return true; } static double mix(double a, double b, double factor) { return a + (b - a) * factor; } void Game::Render(double delta) { if (!mPaused) { if (!mCapture->playing()) { mCapture->play(0); } else { if (mRDP->commands_available()) { mRDP->process_command(); mCapture->next_command(); } else { mCapture->mark_frame(running_machine()); mRDP->screen_update(reinterpret_cast<uint32_t*>(mFB.get())); SDL_UpdateTexture(mFramebuffer, nullptr, mFB.get(), 640 * 4); SDL_SetRenderDrawColor(mRenderer, 0, 0, 0, 0xff); SDL_RenderClear(mRenderer); SDL_RenderCopy(mRenderer, mFramebuffer, nullptr, nullptr); SDL_RenderPresent(mRenderer); } } } } void Game::Run() { mRunning = true; while (mRunning) { mLastTime = mCurrTime; mCurrTime = SDL_GetPerformanceCounter(); uint64_t timeDelta = mCurrTime - mLastTime; double secondsDelta = double(timeDelta * 1000) / SDL_GetPerformanceFrequency(); Render(secondsDelta); mEventDispatcher->PollEvents(); } } bool Game::HandleEvent(InputEvent event) { switch (event.GetType()) { case EventType_Quit: mRunning = false; return true; case EventType_KeyDown: { KeyDownEvent& keyEvent = reinterpret_cast<KeyDownEvent&>(event); if (keyEvent.key().sym == SDLK_p) { mEventDispatcher->DispatchEvent(PauseEvent()); } } case EventType_Pause: mPaused = !mPaused; return true; } return false; }
22.883721
107
0.697832
[ "render" ]
46a3e1ae55cf4b16a891cc93706ade6d7c5cccd5
2,418
hpp
C++
common/autoware_lanelet2_ros_interface/include/autoware_lanelet2_ros2_interface/utility/utilities.hpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
common/autoware_lanelet2_ros_interface/include/autoware_lanelet2_ros2_interface/utility/utilities.hpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
common/autoware_lanelet2_ros_interface/include/autoware_lanelet2_ros2_interface/utility/utilities.hpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015-2019 Autoware Foundation. 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. * * Authors: Kenji Miyake, Ryohsuke Mitsudome */ #ifndef AUTOWARE_LANELET2_ROS_INTERFACE_UTILITY_UTILITIES_H #define AUTOWARE_LANELET2_ROS_INTERFACE_UTILITY_UTILITIES_H #include <geometry_msgs/msg/point.hpp> #include <lanelet2_routing/Route.h> #include <lanelet2_routing/RoutingGraph.h> #include <autoware_msgs/msg/lane_array.hpp> #include <map> namespace lanelet { namespace utils { /** * [matchWaypointAndLanelet Matches waypoints and lanelets] * @param lanelet_map [pointer to lanelet2 map] * @param routing_graph [roughting graph of the map] * @param lane_array [lane array containing waypoints] * @param waypointid2laneletid [object with key:"gid(gobal_id) of waypoints" * value:"lanelet id"] */ void matchWaypointAndLanelet(const lanelet::LaneletMapPtr lanelet_map, const lanelet::routing::RoutingGraphPtr routing_graph, const autoware_msgs::msg::LaneArray& lane_array, std::map<int, lanelet::Id>* waypointid2laneletid); /** * @brief Apply a patch for centerline because the original implementation * doesn't have enough quality */ void overwriteLaneletsCenterline(lanelet::LaneletMapPtr lanelet_map, const bool force_overite = false); /** * @brief [Removes the list of regulatory elements from the given map in * such a way that the resulting map is valid and self-contained] * @param regem_list [list of regulatory element ptrs to be removed] * @param lanelet_map [pointer to lanelet2 map] */ void removeRegulatoryElements(std::vector<lanelet::RegulatoryElementPtr> regem_list, const lanelet::LaneletMapPtr lanelet_map); } // namespace utils } // namespace lanelet #endif // AUTOWARE_LANELET2_ROS_INTERFACE_UTILITY_UTILITIES_H
37.2
127
0.7378
[ "object", "vector" ]
46a6386f86232e5d34d5e1297bf6d7fd9a0e4738
8,145
cxx
C++
src/main.cxx
fermi-lat/detModel
fd8348a10adb75a669f0e4977448afc5e877f057
[ "BSD-3-Clause" ]
null
null
null
src/main.cxx
fermi-lat/detModel
fd8348a10adb75a669f0e4977448afc5e877f057
[ "BSD-3-Clause" ]
null
null
null
src/main.cxx
fermi-lat/detModel
fd8348a10adb75a669f0e4977448afc5e877f057
[ "BSD-3-Clause" ]
null
null
null
/// Test program for the generic model #include <string> #include <iostream> #include <fstream> #include <list> #include <vector> #include "detModel/Management/Manager.h" #include "detModel/Management/VrmlSectionsVisitor.h" #include "detModel/Management/CountMaterial.h" #include "detModel/Management/IDmapBuilder.h" #include "detModel/Management/PrinterSectionsVisitor.h" #include "detModel/Management/HtmlConstantsVisitor.h" #include "detModel/Management/PrinterMaterialsVisitor.h" #include "detModel/Management/XercesBuilder.h" #include "detModel/Materials/MatCollection.h" #include "detModel/Materials/Material.h" #include "detModel/Utilities/Color.h" #include "detModel/Utilities/PositionedVolume.h" #include "detModel/Sections/Volume.h" #include "detModel/Sections/Shape.h" #include "detModel/Sections/Box.h" #include "detModel/Gdd.h" #include "idents/VolumeIdentifier.h" #include "idents/AcdId.h" #include "xmlUtil/id/IdDict.h" /* This basic test needs two argument; the xml file to use and the volume name to use as the mother volume (for example oneCAL). If only the filename is specified, the topVolume specified in the section is used as the mother volume. Ex. ./test.exe ../../../xmlUtil/v2r1/xml/flight.xml oneTKR The test program produce a sections.wrl file with the VRML representation of the geometry (be careful, if you have a big geometry the file can be huge) and a file constants.html with the constants tables in html format. */ // void orderSegments(std::vector<idents::VolumeIdentifier>& segs, short face, short ribNum, bool xOrient, bool increasing, detModel::IDmapBuilder& idMap, detModel::Manager* man); int main(int argc, char* argv[]) { // We need the XML flight as input to the test executable if (argc == 1) return 0; // We retrive the manager pointer (it is a singleton, so it is not possible // to create it in the usual way) detModel::Manager* manager = detModel::Manager::getPointer(); // Set the builder and the file name manager->setBuilder(new detModel::XercesBuilder); manager->setNameFile(argv[1]); // We set the mode for the choice elements in the XML file //manager->setMode("digi"); // We build the hierarchy; in that case we build all, i.e. both the constants // the sections and the materials manager->build(detModel::Manager::all); // We start the VRMLSectionsVisitor to build the vrml file // If we don't specify a string in the constructor, it will build the // vrml file for all the volumes placed in the topVolume, otherwise it // will build the vrml file for the specified volume. The output is // placed in sections.vrml detModel::VrmlSectionsVisitor* visitor; std::string volName(""); if (argc > 2) volName = std::string(argv[2]); visitor = new detModel::VrmlSectionsVisitor(volName); visitor->setMode("digi"); // We retrieve the hierarchy entry point, i.e. the GDD object. It // contains all the relevant information detModel::Gdd* g = manager->getGdd(); // An example; we retrieve some info from the xml file std::cout << "XML file contains " << g->getVolumesNumber() << " volumes." << std::endl; std::cout << "XML file contains " << g->getMaterialsNumber() << " materials." << std::endl; std::cout << "XML file contains " << g->getConstantsNumber() << " constants." << std::endl; double maxLogVal; manager->getNumericConstByName("maxLog", &maxLogVal); std::cout << "value for maxLog is " << maxLogVal << std::endl; // Retrieve the materials, generate the colors and set some // transparency values /* detModel::MatCollection* mats = g->getMaterials(); mats->generateColor(); mats->setMaterialTransparency("Vacuum",0.7); */ // We start the HTMLConstantsVisitor to build the html file with the // constants tables. Colors and layout are stolen from Joanne ones. manager->startVisitor(new detModel::HtmlConstantsVisitor()); // We set a mode for choices // manager->setMode("propagate"); // We start the vrml visitor /* Comment out for now manager->startVisitor(visitor); */ /* manager->startVisitor(new detModel::CountMaterial(volName)); */ detModel::IDmapBuilder idMap(volName); manager->startVisitor(&idMap); idMap.summary(std::cout); std::vector<idents::VolumeIdentifier> segments; orderSegments(segments, 1, 1, true, true, idMap, manager); segments.clear(); orderSegments(segments, 1, 3, false, true, idMap, manager); segments.clear(); orderSegments(segments, 1, 1, true, false, idMap, manager); segments.clear(); orderSegments(segments, 2, 1, true, true, idMap, manager); segments.clear(); orderSegments(segments, 2, 1, false, true, idMap, manager); segments.clear(); orderSegments(segments, 0, 1, true, true, idMap, manager); segments.clear(); orderSegments(segments, 0, 1, false, true, idMap, manager); segments.clear(); /* Diagnostic */ // for( detModel::IDmapBuilder::PVmap::const_iterator id = idMap.begin(); // id!=idMap.end(); ++id){ // const detModel::PositionedVolume * pv = (*id).second; // const detModel::Volume* vol = pv->getVolume(); // const detModel::Box* b = // dynamic_cast<const detModel::Box*>(pv->getVolume()); // if (b !=0) { // std::cout << "Got box with id "; // std::cout << ((*id).first).name() << " named " // << vol->getName() << std::endl; // } // } delete visitor; delete manager; return(0); } // Something like this will be added to GlastSvc void orderSegments(std::vector<idents::VolumeIdentifier>& segs, short face, short ribNum, bool xOrient, bool increasing, detModel::IDmapBuilder& idMap, detModel::Manager* man) { using detModel::IDmapBuilder; static bool init = false; static int eLATACD; // static int eACDRibbon; static int eMeasureX; static int eMeasureY; if (!init) { bool ok = man->getNumericConstByName("eLATACD", &eLATACD); if (ok) ok = man->getNumericConstByName("eACDRibbon", &eACDRibbon); if (ok) ok = man->getNumericConstByName("eMeasureX", &eMeasureX); if (ok) ok = man->getNumericConstByName("eMeasureY", &eMeasureY); if (!ok) { std::cerr << "FATAL: Ribbon volume identifier field values not found" << std::endl; exit(1); } // Check that fields are what we think they should be xmlUtil::IdDict* dict = man->getGdd()->getIdDictionary(); xmlUtil::NamedId ribId(6); ribId.addField("fLATObjects", eLATACD); ribId.addField("fACDFace", 0); ribId.addField("fACDCmp", 41); ribId.addField("fMeasure", eMeasureX); ribId.addField("fRibbon", 1); ribId.addField("fRibbonSegment", 1); if (!dict->idOk(ribId)) { std::cerr << "FATAL: Ribbon volume identifier structure not as expected!" << std::endl; exit(1); } } // Make a volume identifier for a ribbon idents::VolumeIdentifier sample; IDmapBuilder::axisDir dir = IDmapBuilder::zDir; // except for face=0 sample.append(1); // ACD sample.append(face); sample.append(41); // ribbon if (xOrient) { sample.append(1); // measures Y if (face==0) dir = IDmapBuilder::xDir; } else { sample.append(0); // measures X if (face==0) dir = IDmapBuilder::yDir; } sample.append(ribNum); sample.append(0); // segment # doesn't matter; will be masked off std::vector<bool> wild; wild.reserve(6); wild.push_back(false); wild.push_back(false); wild.push_back(false); wild.push_back(false); wild.push_back(false); wild.push_back(true); idMap.orderSensitive(segs, sample, wild, dir, increasing); std::cout << "For inputs face = " << face << " ribNum = " << ribNum << " xOrient = " << xOrient << " and increasing = " << increasing << std::endl << "output vol ids are: " << std::endl; for (unsigned ix = 0; ix < segs.size(); ix++) { std::cout << segs[ix].name() << std::endl; } std::cout << std::endl; }
32.321429
93
0.662738
[ "geometry", "object", "shape", "vector", "model" ]
9e5cb241c0be083d4f7380c018879427a6c5bf10
1,411
cpp
C++
TASM_Compiler/MacroHandle.cpp
darthhater101/TASM-Compiler
e26e8d7e6b2ac268832e740dd3d6b19986eb98ea
[ "MIT" ]
null
null
null
TASM_Compiler/MacroHandle.cpp
darthhater101/TASM-Compiler
e26e8d7e6b2ac268832e740dd3d6b19986eb98ea
[ "MIT" ]
null
null
null
TASM_Compiler/MacroHandle.cpp
darthhater101/TASM-Compiler
e26e8d7e6b2ac268832e740dd3d6b19986eb98ea
[ "MIT" ]
null
null
null
#include "MacroHandle.h" #include <vector> #include <fstream> #include <string> void fileChanger(std::string _file) { std::ifstream file(_file); std::ofstream out("test.txt"); out.clear(); std::string macroName = ""; std::vector<std::string> macro_lines; std::string macroParam = ""; std::string existParam = ""; bool isMacro = false; std::string line; while (getline(file, line)) { if (line.empty()) { continue; } out << line << std::endl; if (line.find("ENDM") != std::string::npos) { isMacro = false; } if (isMacro) { macro_lines.push_back(line); } if (line.find("MACRO") != std::string::npos) { for (auto x : line) { if (x == ' ') { break; } macroName.push_back(x); } for (int i = line.size() - 1; line[i] != ' '; i--) { macroParam.push_back(line[i]); } reverse(macroParam.begin(), macroParam.end()); isMacro = true; } if (line.find(macroName) != std::string::npos) { for (int i = line.size() - 1; line[i] != ' '; i--) { existParam.push_back(line[i]); } reverse(existParam.begin(), existParam.end()); for (auto x : macro_lines) { if (x.find(macroParam) != std::string::npos) { x.erase(x.find(macroParam), macroName.size()); x += existParam; } out << x << std::endl; } existParam.clear(); } } }
19.597222
56
0.544295
[ "vector" ]
9e607e7ead657b88310482a6abc858444bee85eb
15,576
cpp
C++
src/VK/VKPass.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
6
2019-07-16T05:39:18.000Z
2022-02-17T10:10:18.000Z
src/VK/VKPass.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
null
null
null
src/VK/VKPass.cpp
nicovanbentum/Raekor
131e68490aa119213467ef295d3bfb94e5dd7046
[ "MIT" ]
null
null
null
#include "pch.h" #include "VKPass.h" #include "VKUtil.h" #include "VKDevice.h" #include "VKSwapchain.h" #include "VKExtensions.h" #include "VKAccelerationStructure.h" #include "camera.h" #include "async.h" namespace Raekor::VK { void PathTracePass::initialize(Device& device, const Swapchain& swapchain, const AccelerationStructure& accelStruct, const Buffer& instanceBuffer, const Buffer& materialBuffer, const BindlessDescriptorSet& bindlessTextures) { createRenderTextures(device, glm::uvec2(swapchain.getExtent().width, swapchain.getExtent().height)); createDescriptorSet(device, bindlessTextures); updateDescriptorSet(device, accelStruct, instanceBuffer, materialBuffer); createPipeline(device, 8); createShaderBindingTable(device); } void PathTracePass::destroy(Device& device) { device.destroyShader(rgenShader); device.destroyShader(rmissShader); device.destroyShader(rchitShader); device.destroyShader(rmissShadowShader); destroyRenderTextures(device); vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); device.destroyBuffer(shaderBindingTable); } void PathTracePass::createRenderTextures(Device& device, const glm::uvec2& size) { { Texture::Desc desc; desc.width = size.x; desc.height = size.y; desc.shaderAccess = true; desc.format = VK_FORMAT_R32G32B32A32_SFLOAT; finalTexture = device.createTexture(desc); accumTexture = device.createTexture(desc); device.setDebugName(finalTexture, "finalTexture"); device.setDebugName(accumTexture, "accumTexture"); } } void PathTracePass::createPipeline(Device& device, uint32_t maxRecursionDepth) { const auto vulkanSDK = getenv("VULKAN_SDK"); assert(vulkanSDK); if (!fs::exists("shaders/Vulkan/bin")) { fs::create_directory("shaders/Vulkan/bin"); } fs::file_time_type timeOfMostRecentlyUpdatedIncludeFile; for (const auto& file : fs::directory_iterator("shaders/Vulkan/include")) { const auto updateTime = fs::last_write_time(file); if (updateTime > timeOfMostRecentlyUpdatedIncludeFile) { timeOfMostRecentlyUpdatedIncludeFile = updateTime; } } for (const auto& file : fs::directory_iterator("shaders/Vulkan")) { if (file.is_directory()) continue; Async::dispatch([=]() { auto outfile = file.path().parent_path() / "bin" / file.path().filename(); outfile.replace_extension(outfile.extension().string() + ".spv"); const auto textFileWriteTime = file.last_write_time(); if (!fs::exists(outfile) || fs::last_write_time(outfile) < textFileWriteTime || timeOfMostRecentlyUpdatedIncludeFile > fs::last_write_time(outfile)) { bool success = false; if (file.path().extension() == ".hlsl") { success = Shader::DXC(file); } else { success = Shader::glslangValidator(vulkanSDK, file); } Async::lock([&]() { if (!success) { std::cout << "Compilation " << COUT_RED("failed") << " for shader: " << file.path().string() << '\n'; } else { std::cout << "Compilation " << COUT_GREEN("finished") << " for shader: " << file.path().string() << '\n'; } }); } }); } Async::wait(); rgenShader = device.createShader("shaders/Vulkan/bin/pathtrace.rgen.spv"); rmissShader = device.createShader("shaders/Vulkan/bin/pathtrace.rmiss.spv"); rchitShader = device.createShader("shaders/Vulkan/bin/pathtrace.rchit.spv"); rmissShadowShader = device.createShader("shaders/Vulkan/bin/shadow.rmiss.spv"); std::array shaderStages = { rgenShader.getPipelineCreateInfo(), rmissShader.getPipelineCreateInfo(), rmissShadowShader.getPipelineCreateInfo(), rchitShader.getPipelineCreateInfo() }; VkRayTracingShaderGroupCreateInfoKHR group = {}; group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR; group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR; group.intersectionShader = VK_SHADER_UNUSED_KHR; group.closestHitShader = VK_SHADER_UNUSED_KHR; group.generalShader = VK_SHADER_UNUSED_KHR; group.anyHitShader = VK_SHADER_UNUSED_KHR; // raygen shaderGroups.emplace_back(group).generalShader = 0; shaderGroups.back().type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR; // miss shaderGroups.emplace_back(group).generalShader = 1; shaderGroups.back().type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR; // miss shadow shaderGroups.emplace_back(group).generalShader = 2; shaderGroups.back().type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR; // closest hit shaderGroups.emplace_back(group).closestHitShader = 3; shaderGroups.back().type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR; VkRayTracingPipelineCreateInfoKHR pipelineInfo = {}; pipelineInfo.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR; pipelineInfo.layout = pipelineLayout; pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pGroups = shaderGroups.data(); pipelineInfo.groupCount = uint32_t(shaderGroups.size()); pipelineInfo.stageCount = uint32_t(shaderStages.size()); pipelineInfo.maxPipelineRayRecursionDepth = maxRecursionDepth; ThrowIfFailed(EXT::vkCreateRayTracingPipelinesKHR(device, VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline)); } void PathTracePass::createDescriptorSet(Device& device, const BindlessDescriptorSet& bindlessTextures) { VkDescriptorSetLayoutBinding binding0 = {}; binding0.binding = 0; binding0.descriptorCount = 1; binding0.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; binding0.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR; VkDescriptorSetLayoutBinding binding1 = {}; binding1.binding = 1; binding1.descriptorCount = 1; binding1.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; binding1.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; VkDescriptorSetLayoutBinding binding2 = {}; binding2.binding = 2; binding2.descriptorCount = 1; binding2.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; binding2.stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; VkDescriptorSetLayoutBinding binding3 = {}; binding3.binding = 3; binding3.descriptorCount = 1; binding3.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; binding3.stageFlags = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; VkDescriptorSetLayoutBinding binding4 = {}; binding4.binding = 4; binding4.descriptorCount = 1; binding4.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; binding4.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR; std::array bindings = { binding0, binding1, binding2, binding3, binding4 }; VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo = {}; descriptorSetLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutInfo.bindingCount = uint32_t(bindings.size()); descriptorSetLayoutInfo.pBindings = bindings.data(); ThrowIfFailed(vkCreateDescriptorSetLayout(device, &descriptorSetLayoutInfo, nullptr, &descriptorSetLayout)); device.allocateDescriptorSet(1, &descriptorSetLayout, &descriptorSet); VkPushConstantRange pushConstantRange = {}; pushConstantRange.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_MISS_BIT_KHR; pushConstantRange.size = sizeof(PushConstants); // TODO: query size from physical device std::array layouts = { descriptorSetLayout, bindlessTextures.getLayout() }; VkPipelineLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; layoutInfo.pSetLayouts = layouts.data(); layoutInfo.setLayoutCount = uint32_t(layouts.size()); layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &pushConstantRange; ThrowIfFailed(vkCreatePipelineLayout(device, &layoutInfo, nullptr, &pipelineLayout)); } void PathTracePass::updateDescriptorSet(Device& device, const AccelerationStructure& accelStruct, const Buffer& instanceBuffer, const Buffer& materialBuffer) { VkDescriptorImageInfo imageInfo = {}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; imageInfo.imageView = device.createView(finalTexture); VkWriteDescriptorSet write0 = {}; write0.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write0.descriptorCount = 1; write0.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write0.dstBinding = 0; write0.dstSet = descriptorSet; write0.pImageInfo = &imageInfo; VkWriteDescriptorSetAccelerationStructureKHR accelStructInfo = {}; accelStructInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; accelStructInfo.pAccelerationStructures = &accelStruct.accelerationStructure; accelStructInfo.accelerationStructureCount = 1; VkWriteDescriptorSet write1 = {}; write1.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write1.descriptorCount = 1; write1.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; write1.dstBinding = 1; write1.dstSet = descriptorSet; write1.pNext = &accelStructInfo; VkDescriptorBufferInfo bufferInfo2 = {}; bufferInfo2.range = VK_WHOLE_SIZE; bufferInfo2.buffer = instanceBuffer.buffer; VkWriteDescriptorSet write2 = {}; write2.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write2.descriptorCount = 1; write2.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write2.dstBinding = 2; write2.dstSet = descriptorSet; write2.pBufferInfo = &bufferInfo2; VkDescriptorBufferInfo bufferInfo3 = {}; bufferInfo3.range = VK_WHOLE_SIZE; bufferInfo3.buffer = materialBuffer.buffer; VkWriteDescriptorSet write3 = {}; write3.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write3.descriptorCount = 1; write3.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write3.dstBinding = 3; write3.dstSet = descriptorSet; write3.pBufferInfo = &bufferInfo3; VkDescriptorImageInfo imageInfo2 = {}; imageInfo2.imageLayout = VK_IMAGE_LAYOUT_GENERAL; imageInfo2.imageView = device.createView(accumTexture); VkWriteDescriptorSet write4 = {}; write4.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write4.descriptorCount = 1; write4.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; write4.dstBinding = 4; write4.dstSet = descriptorSet; write4.pImageInfo = &imageInfo2; std::array writes = { write0, write1, write2, write3, write4 }; vkUpdateDescriptorSets(device, uint32_t(writes.size()), writes.data(), 0, nullptr); } void PathTracePass::createShaderBindingTable(Device& device) { const auto& rayTracingProperties = device.getPhysicalProperties().rayTracingPipelineProperties; const uint32_t groupCount = uint32_t(shaderGroups.size()); const uint32_t alignedGroupSize = uint32_t(align_up( rayTracingProperties.shaderGroupHandleSize, rayTracingProperties.shaderGroupBaseAlignment )); const uint32_t sbtSize = groupCount * alignedGroupSize; shaderBindingTable = device.createBuffer( sbtSize, VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_ONLY ); std::vector<uint8_t> shaderHandleStorage(sbtSize); ThrowIfFailed(EXT::vkGetRayTracingShaderGroupHandlesKHR(device, pipeline, 0, groupCount, sbtSize, shaderHandleStorage.data())); auto mappedPtr = static_cast<uint8_t*>(device.getMappedPointer(shaderBindingTable)); for (uint32_t group = 0; group < groupCount; group++) { const auto dataPtr = shaderHandleStorage.data() + group * rayTracingProperties.shaderGroupHandleSize; memcpy(mappedPtr, dataPtr, rayTracingProperties.shaderGroupHandleSize); mappedPtr += alignedGroupSize; } } void PathTracePass::recordCommands(const Device& device, const Viewport& viewport, VkCommandBuffer commandBuffer, const BindlessDescriptorSet& bindlessTextures) { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); std::array descriptorSets = { /* set = 0 */ descriptorSet, /* set = 1 */ bindlessTextures.getDescriptorSet() }; vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipelineLayout, 0, uint32_t(descriptorSets.size()), descriptorSets.data(), 0, nullptr ); pushConstants.invViewProj = glm::inverse(viewport.getCamera().getProjection() * viewport.getCamera().getView()); pushConstants.cameraPosition = glm::vec4(viewport.getCamera().getPosition(), 1.0); constexpr VkShaderStageFlags stages = VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_MISS_BIT_KHR; vkCmdPushConstants(commandBuffer, pipelineLayout, stages, 0, sizeof(pushConstants), &pushConstants); pushConstants.frameCounter++; const auto& rayTracingProperties = device.getPhysicalProperties().rayTracingPipelineProperties; const uint32_t alignedGroupSize = uint32_t(align_up( rayTracingProperties.shaderGroupHandleSize, rayTracingProperties.shaderGroupBaseAlignment )); const auto SBTBufferDeviceAddress = device.getDeviceAddress(shaderBindingTable); VkStridedDeviceAddressRegionKHR raygenRegion = {}; raygenRegion.deviceAddress = SBTBufferDeviceAddress; raygenRegion.size = alignedGroupSize; raygenRegion.stride = alignedGroupSize; VkStridedDeviceAddressRegionKHR missRegion = {}; missRegion.deviceAddress = raygenRegion.deviceAddress + raygenRegion.size; missRegion.size = alignedGroupSize * 2; missRegion.stride = alignedGroupSize; VkStridedDeviceAddressRegionKHR hitRegion = {}; hitRegion.deviceAddress = missRegion.deviceAddress + missRegion.size; hitRegion.size = alignedGroupSize; hitRegion.stride = alignedGroupSize; VkStridedDeviceAddressRegionKHR callableRegion = {}; EXT::vkCmdTraceRaysKHR(commandBuffer, &raygenRegion, &missRegion, &hitRegion, &callableRegion, viewport.size.x, viewport.size.y, 1); } void PathTracePass::reloadShadersFromDisk(Device& device) { vkQueueWaitIdle(device.queue); vkDestroyPipeline(device, pipeline, nullptr); device.destroyShader(rgenShader); device.destroyShader(rmissShader); device.destroyShader(rchitShader); device.destroyShader(rmissShadowShader); createPipeline(device, 8); } void PathTracePass::destroyRenderTextures(Device& device) { device.destroyTexture(finalTexture); device.destroyTexture(accumTexture); } }
39.234257
225
0.717065
[ "vector" ]
9e675377278f97f01d0defdbf3d95903d8bc9438
2,174
cpp
C++
Samples/Win32/ThunderRumble/Common/ShipInput.cpp
yazhenchua/PlayFab-Samples
85d1d252bd21d050575c382628caa6d0c9785ff7
[ "MIT" ]
160
2016-05-26T09:30:20.000Z
2022-03-31T08:05:56.000Z
Samples/Win32/ThunderRumble/Common/ShipInput.cpp
srivers8424/PlayFab-Samples
9fe465858e7f9bae3250dfe77d4500bb57d9e7fd
[ "MIT" ]
17
2016-03-22T17:37:16.000Z
2021-11-20T23:20:07.000Z
Samples/Win32/ThunderRumble/Common/ShipInput.cpp
srivers8424/PlayFab-Samples
9fe465858e7f9bae3250dfe77d4500bb57d9e7fd
[ "MIT" ]
204
2016-05-14T22:46:51.000Z
2022-03-04T00:45:56.000Z
//-------------------------------------------------------------------------------------- // ShipInput.h // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "ShipInput.h" using namespace ThunderRumble; using namespace DirectX; ShipInput::ShipInput(const GamePad::State& gamePadState) : LeftStick(SimpleMath::Vector2(gamePadState.thumbSticks.leftX, gamePadState.thumbSticks.leftY)), RightStick(SimpleMath::Vector2(gamePadState.thumbSticks.rightX, gamePadState.thumbSticks.rightY)), MineFired(gamePadState.triggers.right >= 0.9f) { } ShipInput::ShipInput(const DirectX::Keyboard::State& keyboardState) : LeftStick(SimpleMath::Vector2(0, 0)), RightStick(SimpleMath::Vector2(0, 0)), MineFired(keyboardState.Space) { if (keyboardState.W) { LeftStick.y += 1.f; } if (keyboardState.A) { LeftStick.x -= 1.f; } if (keyboardState.S) { LeftStick.y -= 1.f; } if (keyboardState.D) { LeftStick.x += 1.f; } LeftStick.Normalize(); if (keyboardState.Up) { RightStick.y += 1.f; } if (keyboardState.Left) { RightStick.x -= 1.f; } if (keyboardState.Down) { RightStick.y -= 1.f; } if (keyboardState.Right) { RightStick.x += 1.f; } } ShipInput::~ShipInput() { } void ShipInput::Add(const ShipInput & moreInput) { LeftStick += moreInput.LeftStick; RightStick += moreInput.RightStick; if (!MineFired) { MineFired = moreInput.MineFired; } } std::vector<uint8_t> ShipInput::Serialize() { auto bufferLen = sizeof(ShipInput); auto buffer = new uint8_t[bufferLen]; if (!buffer) { return std::vector<uint8_t>(); } CopyMemory(buffer, this, bufferLen); std::vector<uint8_t> serialized(buffer, buffer + bufferLen); delete[] buffer; return serialized; } void ShipInput::Deserialize(const std::vector<uint8_t> &data) { CopyMemory(this, data.data(), sizeof(ShipInput)); }
22.183673
102
0.583717
[ "vector" ]
9e7025638d725dbe5f837f9523a59413aa699611
6,228
cpp
C++
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/distances.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/distances.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/perception/point_cloud_mapping/src/cloud_geometry/distances.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/* * Copyright (c) 2008 Radu Bogdan Rusu <rusu -=- cs.tum.edu> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. * * $Id: distances.cpp 20633 2009-08-04 07:19:09Z tfoote $ * */ /** \author Radu Bogdan Rusu */ #include <point_cloud_mapping/geometry/point.h> #include <point_cloud_mapping/geometry/distances.h> namespace cloud_geometry { namespace distances { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Get the distance from a point to a line (represented by a point and a direction) * \param p a point * \param q the point on the line * \param dir the direction of the line */ double pointToLineDistance (const geometry_msgs::Point32 &p, const geometry_msgs::Point32 &q, const geometry_msgs::Point32 &dir) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) geometry_msgs::Point32 r, p_t; r.x = q.x + dir.x; r.y = q.y + dir.y; r.z = q.z + dir.z; p_t.x = r.x - p.x; p_t.y = r.y - p.y; p_t.z = r.z - p.z; geometry_msgs::Point32 c = cross (p_t, dir); double sqr_distance = (c.x * c.x + c.y * c.y + c.z * c.z) / (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); return (sqrt (sqr_distance)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Get the distance from a point to a line (represented by a point and a direction) * \param p a point * \param line_coefficients the line coefficients (point.x point.y point.z direction.x direction.y direction.z) */ double pointToLineDistance (const geometry_msgs::Point32 &p, const std::vector<double> &line_coefficients) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) std::vector<double> dir (3), r (3), p_t (3), c; dir[0] = line_coefficients[3]; dir[1] = line_coefficients[4]; dir[2] = line_coefficients[5]; r[0] = line_coefficients[0] + dir[0]; r[1] = line_coefficients[1] + dir[1]; r[2] = line_coefficients[2] + dir[2]; p_t[0] = r[0] - p.x; p_t[1] = r[1] - p.y; p_t[2] = r[2] - p.z; cross (p_t, dir, c); double sqr_distance = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]) / (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]); return (sqrt (sqr_distance)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** \brief Get the shortest 3D segment between two 3D lines * \param line_a the coefficients of the first line (point, direction) * \param line_b the coefficients of the second line (point, direction) * \param segment the resulting two 3D points that mark the beginning and the end of the segment */ void lineToLineSegment (const std::vector<double> &line_a, const std::vector<double> &line_b, std::vector<double> &segment) { segment.resize (6); geometry_msgs::Point32 p2, q2; p2.x = line_a.at (0) + line_a.at (3); // point + direction = 2nd point p2.y = line_a.at (1) + line_a.at (4); p2.z = line_a.at (2) + line_a.at (5); q2.x = line_b.at (0) + line_b.at (3); // point + direction = 2nd point q2.y = line_b.at (1) + line_b.at (4); q2.z = line_b.at (2) + line_b.at (5); geometry_msgs::Point32 u, v, w; // a = x2 - x1 = line_a[1] - line_a[0] u.x = p2.x - line_a.at (0); u.y = p2.y - line_a.at (1); u.z = p2.z - line_a.at (2); // b = x4 - x3 = line_b[1] - line_b[0] v.x = q2.x - line_b.at (0); v.y = q2.y - line_b.at (1); v.z = q2.z - line_b.at (2); // c = x2 - x3 = line_a[1] - line_b[0] w.x = p2.x - line_b.at (0); w.y = p2.y - line_b.at (1); w.z = p2.z - line_b.at (2); double a = dot (u, u); double b = dot (u, v); double c = dot (v, v); double d = dot (u, w); double e = dot (v, w); double denominator = a*c - b*b; double sc, tc; // Compute the line parameters of the two closest points if (denominator < 1e-5) // The lines are almost parallel { sc = 0.0; tc = (b > c ? d / b : e / c); // Use the largest denominator } else { sc = (b*e - c*d) / denominator; tc = (a*e - b*d) / denominator; } // Get the closest points segment[0] = p2.x + (sc * u.x); segment[1] = p2.y + (sc * u.y); segment[2] = p2.z + (sc * u.z); segment[3] = line_b.at (0) + (tc * v.x); segment[4] = line_b.at (1) + (tc * v.y); segment[5] = line_b.at (2) + (tc * v.z); } } }
39.923077
127
0.558446
[ "geometry", "vector", "3d" ]
9e7d2bb0910a2dc2a8eeb85cb72bf47f1d4b846e
85,470
cpp
C++
code/tools/gtkradiant/radiant/surfacedialog.cpp
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
11
2016-06-03T07:46:15.000Z
2021-09-09T19:35:32.000Z
code/tools/gtkradiant/radiant/surfacedialog.cpp
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
1
2016-10-14T23:06:19.000Z
2016-10-14T23:06:19.000Z
code/tools/gtkradiant/radiant/surfacedialog.cpp
raynorpat/xreal
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
[ "BSD-3-Clause" ]
5
2016-10-13T04:43:58.000Z
2019-08-24T14:03:35.000Z
/* Copyright (C) 1999-2006 Id Software, Inc. and contributors. For a list of contributors, see the accompanying CONTRIBUTORS file. This file is part of GtkRadiant. GtkRadiant is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GtkRadiant 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 GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ // // Surface Dialog // // Leonardo Zide (leo@lokigames.com) // #include "surfacedialog.h" #include "debugging/debugging.h" #include "warnings.h" #include "iscenegraph.h" #include "itexdef.h" #include "iundo.h" #include "iselection.h" #include <gtk/gtkhbox.h> #include <gtk/gtkvbox.h> #include <gtk/gtkframe.h> #include <gtk/gtklabel.h> #include <gtk/gtktable.h> #include <gtk/gtkbutton.h> #include <gtk/gtkspinbutton.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtkcheckbutton.h> //Shamus: For Textool #include "signal/isignal.h" #include "generic/object.h" #include "math/vector.h" #include "texturelib.h" #include "shaderlib.h" #include "stringio.h" #include "gtkutil/idledraw.h" #include "gtkutil/dialog.h" #include "gtkutil/entry.h" #include "gtkutil/nonmodal.h" #include "gtkutil/pointer.h" #include "gtkutil/glwidget.h" //Shamus: For Textool #include "gtkutil/button.h" #include "map.h" #include "select.h" #include "patchmanip.h" #include "brushmanip.h" #include "patchdialog.h" #include "preferences.h" #include "brush_primit.h" #include "xywindow.h" #include "mainframe.h" #include "gtkdlgs.h" #include "dialog.h" #include "brush.h" //Shamus: for Textool #include "patch.h" #include "commands.h" #include "stream/stringstream.h" #include "grid.h" #include "textureentry.h" //NOTE: Proper functioning of Textool currently requires that the "#if 1" lines in // brush_primit.h be changed to "#if 0". add/removeScale screws this up ATM. :-) // Plus, Radiant seems to work just fine without that stuff. ;-) #define TEXTOOL_ENABLED 0 #if TEXTOOL_ENABLED namespace TexTool { //Shamus: Textool function prototypes gboolean size_allocate( GtkWidget *, GtkAllocation *, gpointer ); gboolean expose( GtkWidget *, GdkEventExpose *, gpointer ); gboolean button_press( GtkWidget *, GdkEventButton *, gpointer ); gboolean button_release( GtkWidget *, GdkEventButton *, gpointer ); gboolean motion( GtkWidget *, GdkEventMotion *, gpointer ); void flipX( GtkToggleButton *, gpointer ); void flipY( GtkToggleButton *, gpointer ); //End Textool function prototypes //Shamus: Textool globals GtkWidget * g_textoolWin; //End Textool globals void queueDraw(){ gtk_widget_queue_draw( g_textoolWin ); } } #endif inline void spin_button_set_step( GtkSpinButton* spin, gfloat step ){ #if 1 gtk_spin_button_get_adjustment( spin )->step_increment = step; #else GValue gvalue = GValue_default(); g_value_init( &gvalue, G_TYPE_DOUBLE ); g_value_set_double( &gvalue, step ); g_object_set( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), "step-increment", &gvalue, NULL ); #endif } class Increment { float& m_f; public: GtkSpinButton* m_spin; GtkEntry* m_entry; Increment( float& f ) : m_f( f ), m_spin( 0 ), m_entry( 0 ) { } void cancel(){ entry_set_float( m_entry, m_f ); } typedef MemberCaller<Increment, &Increment::cancel> CancelCaller; void apply(){ m_f = static_cast<float>( entry_get_float( m_entry ) ); spin_button_set_step( m_spin, m_f ); } typedef MemberCaller<Increment, &Increment::apply> ApplyCaller; }; void SurfaceInspector_GridChange(); class SurfaceInspector : public Dialog { GtkWindow* BuildDialog(); NonModalEntry m_textureEntry; NonModalSpinner m_hshiftSpinner; NonModalEntry m_hshiftEntry; NonModalSpinner m_vshiftSpinner; NonModalEntry m_vshiftEntry; NonModalSpinner m_hscaleSpinner; NonModalEntry m_hscaleEntry; NonModalSpinner m_vscaleSpinner; NonModalEntry m_vscaleEntry; NonModalSpinner m_rotateSpinner; NonModalEntry m_rotateEntry; IdleDraw m_idleDraw; GtkCheckButton* m_surfaceFlags[32]; GtkCheckButton* m_contentFlags[32]; NonModalEntry m_valueEntry; GtkEntry* m_valueEntryWidget; public: WindowPositionTracker m_positionTracker; WindowPositionTrackerImportStringCaller m_importPosition; WindowPositionTrackerExportStringCaller m_exportPosition; // Dialog Data float m_fitHorizontal; float m_fitVertical; Increment m_hshiftIncrement; Increment m_vshiftIncrement; Increment m_hscaleIncrement; Increment m_vscaleIncrement; Increment m_rotateIncrement; GtkEntry* m_texture; SurfaceInspector() : m_textureEntry( ApplyShaderCaller( *this ), UpdateCaller( *this ) ), m_hshiftSpinner( ApplyTexdefCaller( *this ), UpdateCaller( *this ) ), m_hshiftEntry( Increment::ApplyCaller( m_hshiftIncrement ), Increment::CancelCaller( m_hshiftIncrement ) ), m_vshiftSpinner( ApplyTexdefCaller( *this ), UpdateCaller( *this ) ), m_vshiftEntry( Increment::ApplyCaller( m_vshiftIncrement ), Increment::CancelCaller( m_vshiftIncrement ) ), m_hscaleSpinner( ApplyTexdefCaller( *this ), UpdateCaller( *this ) ), m_hscaleEntry( Increment::ApplyCaller( m_hscaleIncrement ), Increment::CancelCaller( m_hscaleIncrement ) ), m_vscaleSpinner( ApplyTexdefCaller( *this ), UpdateCaller( *this ) ), m_vscaleEntry( Increment::ApplyCaller( m_vscaleIncrement ), Increment::CancelCaller( m_vscaleIncrement ) ), m_rotateSpinner( ApplyTexdefCaller( *this ), UpdateCaller( *this ) ), m_rotateEntry( Increment::ApplyCaller( m_rotateIncrement ), Increment::CancelCaller( m_rotateIncrement ) ), m_idleDraw( UpdateCaller( *this ) ), m_valueEntry( ApplyFlagsCaller( *this ), UpdateCaller( *this ) ), m_importPosition( m_positionTracker ), m_exportPosition( m_positionTracker ), m_hshiftIncrement( g_si_globals.shift[0] ), m_vshiftIncrement( g_si_globals.shift[1] ), m_hscaleIncrement( g_si_globals.scale[0] ), m_vscaleIncrement( g_si_globals.scale[1] ), m_rotateIncrement( g_si_globals.rotate ) { m_fitVertical = 1; m_fitHorizontal = 1; m_positionTracker.setPosition( c_default_window_pos ); } void constructWindow( GtkWindow* main_window ){ m_parent = main_window; Create(); AddGridChangeCallback( FreeCaller<SurfaceInspector_GridChange>() ); } void destroyWindow(){ Destroy(); } bool visible() const { return GTK_WIDGET_VISIBLE( const_cast<GtkWindow*>( GetWidget() ) ); } void queueDraw(){ if ( visible() ) { m_idleDraw.queueDraw(); } } void Update(); typedef MemberCaller<SurfaceInspector, &SurfaceInspector::Update> UpdateCaller; void ApplyShader(); typedef MemberCaller<SurfaceInspector, &SurfaceInspector::ApplyShader> ApplyShaderCaller; void ApplyTexdef(); typedef MemberCaller<SurfaceInspector, &SurfaceInspector::ApplyTexdef> ApplyTexdefCaller; void ApplyFlags(); typedef MemberCaller<SurfaceInspector, &SurfaceInspector::ApplyFlags> ApplyFlagsCaller; }; namespace { SurfaceInspector* g_SurfaceInspector; inline SurfaceInspector& getSurfaceInspector(){ ASSERT_NOTNULL( g_SurfaceInspector ); return *g_SurfaceInspector; } } void SurfaceInspector_constructWindow( GtkWindow* main_window ){ getSurfaceInspector().constructWindow( main_window ); } void SurfaceInspector_destroyWindow(){ getSurfaceInspector().destroyWindow(); } void SurfaceInspector_queueDraw(){ getSurfaceInspector().queueDraw(); } namespace { CopiedString g_selectedShader; TextureProjection g_selectedTexdef; ContentsFlagsValue g_selectedFlags; size_t g_selectedShaderSize[2]; } void SurfaceInspector_SetSelectedShader( const char* shader ){ g_selectedShader = shader; SurfaceInspector_queueDraw(); } void SurfaceInspector_SetSelectedTexdef( const TextureProjection& projection ){ g_selectedTexdef = projection; SurfaceInspector_queueDraw(); } void SurfaceInspector_SetSelectedFlags( const ContentsFlagsValue& flags ){ g_selectedFlags = flags; SurfaceInspector_queueDraw(); } static bool s_texture_selection_dirty = false; void SurfaceInspector_updateSelection(){ s_texture_selection_dirty = true; SurfaceInspector_queueDraw(); #if TEXTOOL_ENABLED if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) { TexTool::queueDraw(); //globalOutputStream() << "textool texture changed..\n"; } #endif } void SurfaceInspector_SelectionChanged( const Selectable& selectable ){ SurfaceInspector_updateSelection(); } void SurfaceInspector_SetCurrent_FromSelected(){ if ( s_texture_selection_dirty == true ) { s_texture_selection_dirty = false; if ( !g_SelectedFaceInstances.empty() ) { TextureProjection projection; //This *may* be the point before it fucks up... Let's see! //Yep, there was a call to removeScale in there... Scene_BrushGetTexdef_Component_Selected( GlobalSceneGraph(), projection ); SurfaceInspector_SetSelectedTexdef( projection ); Scene_BrushGetShaderSize_Component_Selected( GlobalSceneGraph(), g_selectedShaderSize[0], g_selectedShaderSize[1] ); g_selectedTexdef.m_brushprimit_texdef.coords[0][2] = float_mod( g_selectedTexdef.m_brushprimit_texdef.coords[0][2], (float)g_selectedShaderSize[0] ); g_selectedTexdef.m_brushprimit_texdef.coords[1][2] = float_mod( g_selectedTexdef.m_brushprimit_texdef.coords[1][2], (float)g_selectedShaderSize[1] ); CopiedString name; Scene_BrushGetShader_Component_Selected( GlobalSceneGraph(), name ); if ( string_not_empty( name.c_str() ) ) { SurfaceInspector_SetSelectedShader( name.c_str() ); } ContentsFlagsValue flags; Scene_BrushGetFlags_Component_Selected( GlobalSceneGraph(), flags ); SurfaceInspector_SetSelectedFlags( flags ); } else { TextureProjection projection; Scene_BrushGetTexdef_Selected( GlobalSceneGraph(), projection ); SurfaceInspector_SetSelectedTexdef( projection ); CopiedString name; Scene_BrushGetShader_Selected( GlobalSceneGraph(), name ); if ( string_empty( name.c_str() ) ) { Scene_PatchGetShader_Selected( GlobalSceneGraph(), name ); } if ( string_not_empty( name.c_str() ) ) { SurfaceInspector_SetSelectedShader( name.c_str() ); } ContentsFlagsValue flags( 0, 0, 0, false ); Scene_BrushGetFlags_Selected( GlobalSceneGraph(), flags ); SurfaceInspector_SetSelectedFlags( flags ); } } } const char* SurfaceInspector_GetSelectedShader(){ SurfaceInspector_SetCurrent_FromSelected(); return g_selectedShader.c_str(); } const TextureProjection& SurfaceInspector_GetSelectedTexdef(){ SurfaceInspector_SetCurrent_FromSelected(); return g_selectedTexdef; } const ContentsFlagsValue& SurfaceInspector_GetSelectedFlags(){ SurfaceInspector_SetCurrent_FromSelected(); return g_selectedFlags; } /* =================================================== SURFACE INSPECTOR =================================================== */ si_globals_t g_si_globals; // make the shift increments match the grid settings // the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size // this depends on a scale value if you have selected a particular texture on which you want it to work: // we move the textures in pixels, not world units. (i.e. increment values are in pixel) // depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() // increment * scale = gridsize // hscale and vscale are optional parameters, if they are zero they will be set to the default scale // NOTE: the default scale depends if you are using BP mode or regular. // For regular it's 0.5f (128 pixels cover 64 world units), for BP it's simply 1.0f // see fenris #2810 void DoSnapTToGrid( float hscale, float vscale ){ g_si_globals.shift[0] = static_cast<float>( float_to_integer( static_cast<float>( GetGridSize() ) / hscale ) ); g_si_globals.shift[1] = static_cast<float>( float_to_integer( static_cast<float>( GetGridSize() ) / vscale ) ); getSurfaceInspector().queueDraw(); } void SurfaceInspector_GridChange(){ if ( g_si_globals.m_bSnapTToGrid ) { DoSnapTToGrid( Texdef_getDefaultTextureScale(), Texdef_getDefaultTextureScale() ); } } // make the shift increments match the grid settings // the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size // this depends on the current texture scale used? // we move the textures in pixels, not world units. (i.e. increment values are in pixel) // depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() // increment * scale = gridsize static void OnBtnMatchGrid( GtkWidget *widget, gpointer data ){ float hscale, vscale; hscale = static_cast<float>( gtk_spin_button_get_value_as_float( getSurfaceInspector().m_hscaleIncrement.m_spin ) ); vscale = static_cast<float>( gtk_spin_button_get_value_as_float( getSurfaceInspector().m_vscaleIncrement.m_spin ) ); if ( hscale == 0.0f || vscale == 0.0f ) { globalOutputStream() << "ERROR: unexpected scale == 0.0f\n"; return; } DoSnapTToGrid( hscale, vscale ); } // DoSurface will always try to show the surface inspector // or update it because something new has been selected // Shamus: It does get called when the SI is hidden, but not when you select something new. ;-) void DoSurface( void ){ if ( getSurfaceInspector().GetWidget() == 0 ) { getSurfaceInspector().Create(); } getSurfaceInspector().Update(); getSurfaceInspector().importData(); getSurfaceInspector().ShowDlg(); } void SurfaceInspector_toggleShown(){ if ( getSurfaceInspector().visible() ) { getSurfaceInspector().HideDlg(); } else { DoSurface(); } } void SurfaceInspector_FitTexture(){ UndoableCommand undo( "textureAutoFit" ); Select_FitTexture( getSurfaceInspector().m_fitHorizontal, getSurfaceInspector().m_fitVertical ); } static void OnBtnPatchdetails( GtkWidget *widget, gpointer data ){ Scene_PatchCapTexture_Selected( GlobalSceneGraph() ); } static void OnBtnPatchnatural( GtkWidget *widget, gpointer data ){ Scene_PatchNaturalTexture_Selected( GlobalSceneGraph() ); } static void OnBtnPatchreset( GtkWidget *widget, gpointer data ){ float fx, fy; if ( DoTextureLayout( &fx, &fy ) == eIDOK ) { Scene_PatchTileTexture_Selected( GlobalSceneGraph(), fx, fy ); } } static void OnBtnPatchFit( GtkWidget *widget, gpointer data ){ Scene_PatchTileTexture_Selected( GlobalSceneGraph(), 1, 1 ); } static void OnBtnAxial( GtkWidget *widget, gpointer data ){ //globalOutputStream() << "--> [OnBtnAxial]...\n"; UndoableCommand undo( "textureDefault" ); TextureProjection projection; //globalOutputStream() << " TexDef_Construct_Default()...\n"; TexDef_Construct_Default( projection ); //globalOutputStream() << " Select_SetTexdef()...\n"; #if TEXTOOL_ENABLED //Shamus: if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) { // Scale up texture width/height if in BP mode... //NOTE: This may not be correct any more! :-P if ( !g_SelectedFaceInstances.empty() ) { Face & face = g_SelectedFaceInstances.last().getFace(); float x = face.getShader().m_state->getTexture().width; float y = face.getShader().m_state->getTexture().height; projection.m_brushprimit_texdef.coords[0][0] /= x; projection.m_brushprimit_texdef.coords[0][1] /= y; projection.m_brushprimit_texdef.coords[1][0] /= x; projection.m_brushprimit_texdef.coords[1][1] /= y; } } #endif Select_SetTexdef( projection ); } static void OnBtnFaceFit( GtkWidget *widget, gpointer data ){ getSurfaceInspector().exportData(); SurfaceInspector_FitTexture(); } typedef const char* FlagName; const FlagName surfaceflagNamesDefault[32] = { "surf1", "surf2", "surf3", "surf4", "surf5", "surf6", "surf7", "surf8", "surf9", "surf10", "surf11", "surf12", "surf13", "surf14", "surf15", "surf16", "surf17", "surf18", "surf19", "surf20", "surf21", "surf22", "surf23", "surf24", "surf25", "surf26", "surf27", "surf28", "surf29", "surf30", "surf31", "surf32" }; const FlagName contentflagNamesDefault[32] = { "cont1", "cont2", "cont3", "cont4", "cont5", "cont6", "cont7", "cont8", "cont9", "cont10", "cont11", "cont12", "cont13", "cont14", "cont15", "cont16", "cont17", "cont18", "cont19", "cont20", "cont21", "cont22", "cont23", "cont24", "cont25", "cont26", "cont27", "cont28", "cont29", "cont30", "cont31", "cont32" }; const char* getSurfaceFlagName( std::size_t bit ){ const char* value = g_pGameDescription->getKeyValue( surfaceflagNamesDefault[bit] ); if ( string_empty( value ) ) { return surfaceflagNamesDefault[bit]; } return value; } const char* getContentFlagName( std::size_t bit ){ const char* value = g_pGameDescription->getKeyValue( contentflagNamesDefault[bit] ); if ( string_empty( value ) ) { return contentflagNamesDefault[bit]; } return value; } // ============================================================================= // SurfaceInspector class guint togglebutton_connect_toggled( GtkToggleButton* button, const Callback& callback ){ return g_signal_connect_swapped( G_OBJECT( button ), "toggled", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); } GtkWindow* SurfaceInspector::BuildDialog(){ GtkWindow* window = create_floating_window( "Surface Inspector", m_parent ); m_positionTracker.connect( window ); global_accel_connect_window( window ); window_connect_focus_in_clear_focus_widget( window ); { // replaced by only the vbox: GtkWidget* vbox = gtk_vbox_new( FALSE, 5 ); gtk_widget_show( vbox ); gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox ) ); gtk_container_set_border_width( GTK_CONTAINER( vbox ), 5 ); { GtkWidget* hbox2 = gtk_hbox_new( FALSE, 5 ); gtk_widget_show( hbox2 ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hbox2 ), FALSE, FALSE, 0 ); { GtkWidget* label = gtk_label_new( "Texture" ); gtk_widget_show( label ); gtk_box_pack_start( GTK_BOX( hbox2 ), label, FALSE, TRUE, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_box_pack_start( GTK_BOX( hbox2 ), GTK_WIDGET( entry ), TRUE, TRUE, 0 ); m_texture = entry; m_textureEntry.connect( entry ); GlobalTextureEntryCompletion::instance().connect( entry ); } } { GtkWidget* table = gtk_table_new( 6, 4, FALSE ); gtk_widget_show( table ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( table ), FALSE, FALSE, 0 ); gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); { GtkWidget* label = gtk_label_new( "Horizontal shift" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 2 ) ); m_hshiftIncrement.m_spin = spin; m_hshiftSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 0, 1, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( spin ), 60, -2 ); } { GtkWidget* label = gtk_label_new( "Step" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 0, 1, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( entry ), 50, -2 ); m_hshiftIncrement.m_entry = entry; m_hshiftEntry.connect( entry ); } { GtkWidget* label = gtk_label_new( "Vertical shift" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 2 ) ); m_vshiftIncrement.m_spin = spin; m_vshiftSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 1, 2, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( spin ), 60, -2 ); } { GtkWidget* label = gtk_label_new( "Step" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 1, 2, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 1, 2, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( entry ), 50, -2 ); m_vshiftIncrement.m_entry = entry; m_vshiftEntry.connect( entry ); } { GtkWidget* label = gtk_label_new( "Horizontal stretch" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 5 ) ); m_hscaleIncrement.m_spin = spin; m_hscaleSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 2, 3, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( spin ), 60, -2 ); } { GtkWidget* label = gtk_label_new( "Step" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 2, 3, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 2, 3 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 2, 3, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 2, 3 ); gtk_widget_set_usize( GTK_WIDGET( entry ), 50, -2 ); m_hscaleIncrement.m_entry = entry; m_hscaleEntry.connect( entry ); } { GtkWidget* label = gtk_label_new( "Vertical stretch" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 3, 4, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 5 ) ); m_vscaleIncrement.m_spin = spin; m_vscaleSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 3, 4, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( spin ), 60, -2 ); } { GtkWidget* label = gtk_label_new( "Step" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 3, 4, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 3, 4, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( entry ), 50, -2 ); m_vscaleIncrement.m_entry = entry; m_vscaleEntry.connect( entry ); } { GtkWidget* label = gtk_label_new( "Rotate" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 4, 5, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkSpinButton* spin = GTK_SPIN_BUTTON( gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0, -8192, 8192, 2, 8, 0 ) ), 0, 2 ) ); m_rotateIncrement.m_spin = spin; m_rotateSpinner.connect( spin ); gtk_widget_show( GTK_WIDGET( spin ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( spin ), 1, 2, 4, 5, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( spin ), 60, -2 ); gtk_spin_button_set_wrap( spin, TRUE ); } { GtkWidget* label = gtk_label_new( "Step" ); gtk_widget_show( label ); gtk_misc_set_alignment( GTK_MISC( label ), 0, 0 ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 4, 5, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_table_attach( GTK_TABLE( table ), GTK_WIDGET( entry ), 3, 4, 4, 5, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( GTK_WIDGET( entry ), 50, -2 ); m_rotateIncrement.m_entry = entry; m_rotateEntry.connect( entry ); } { // match grid button GtkWidget* button = gtk_button_new_with_label( "Match Grid" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 4, 5, 6, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnMatchGrid ), 0 ); } } { GtkWidget* frame = gtk_frame_new( "Texturing" ); gtk_widget_show( frame ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( frame ), FALSE, FALSE, 0 ); { GtkWidget* table = gtk_table_new( 4, 4, FALSE ); gtk_widget_show( table ); gtk_container_add( GTK_CONTAINER( frame ), table ); gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); { GtkWidget* label = gtk_label_new( "Brush" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( "Patch" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 2, 3, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( "Width" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 2, 3, 0, 1, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* label = gtk_label_new( "Height" ); gtk_widget_show( label ); gtk_table_attach( GTK_TABLE( table ), label, 3, 4, 0, 1, (GtkAttachOptions) ( GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); } { GtkWidget* button = gtk_button_new_with_label( "Axial" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 1, 2, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnAxial ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* button = gtk_button_new_with_label( "Fit" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 1, 2, 1, 2, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnFaceFit ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* button = gtk_button_new_with_label( "CAP" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 0, 1, 3, 4, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchdetails ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* button = gtk_button_new_with_label( "Set..." ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 1, 2, 3, 4, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchreset ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* button = gtk_button_new_with_label( "Natural" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 2, 3, 3, 4, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchnatural ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* button = gtk_button_new_with_label( "Fit" ); gtk_widget_show( button ); gtk_table_attach( GTK_TABLE( table ), button, 3, 4, 3, 4, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( OnBtnPatchFit ), 0 ); gtk_widget_set_usize( button, 60, -2 ); } { GtkWidget* spin = gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 1, 0, 1 << 16, 1, 10, 0 ) ), 0, 6 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 2, 3, 1, 2, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( spin, 60, -2 ); AddDialogData( *GTK_SPIN_BUTTON( spin ), m_fitHorizontal ); } { GtkWidget* spin = gtk_spin_button_new( GTK_ADJUSTMENT( gtk_adjustment_new( 1, 0, 1 << 16, 1, 10, 0 ) ), 0, 6 ); gtk_widget_show( spin ); gtk_table_attach( GTK_TABLE( table ), spin, 3, 4, 1, 2, (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions) ( 0 ), 0, 0 ); gtk_widget_set_usize( spin, 60, -2 ); AddDialogData( *GTK_SPIN_BUTTON( spin ), m_fitVertical ); } } } if ( !string_empty( g_pGameDescription->getKeyValue( "si_flags" ) ) ) { { GtkFrame* frame = GTK_FRAME( gtk_frame_new( "Surface Flags" ) ); gtk_widget_show( GTK_WIDGET( frame ) ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( frame ), TRUE, TRUE, 0 ); { GtkVBox* vbox3 = GTK_VBOX( gtk_vbox_new( FALSE, 4 ) ); //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); gtk_widget_show( GTK_WIDGET( vbox3 ) ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox3 ) ); { GtkTable* table = GTK_TABLE( gtk_table_new( 8, 4, FALSE ) ); gtk_widget_show( GTK_WIDGET( table ) ); gtk_box_pack_start( GTK_BOX( vbox3 ), GTK_WIDGET( table ), TRUE, TRUE, 0 ); gtk_table_set_row_spacings( table, 0 ); gtk_table_set_col_spacings( table, 0 ); GtkCheckButton** p = m_surfaceFlags; for ( int c = 0; c != 4; ++c ) { for ( int r = 0; r != 8; ++r ) { GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new_with_label( getSurfaceFlagName( c * 8 + r ) ) ); gtk_widget_show( GTK_WIDGET( check ) ); gtk_table_attach( table, GTK_WIDGET( check ), c, c + 1, r, r + 1, (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions)( 0 ), 0, 0 ); *p++ = check; guint handler_id = togglebutton_connect_toggled( GTK_TOGGLE_BUTTON( check ), ApplyFlagsCaller( *this ) ); g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler_id ) ); } } } } } { GtkFrame* frame = GTK_FRAME( gtk_frame_new( "Content Flags" ) ); gtk_widget_show( GTK_WIDGET( frame ) ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( frame ), TRUE, TRUE, 0 ); { GtkVBox* vbox3 = GTK_VBOX( gtk_vbox_new( FALSE, 4 ) ); //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); gtk_widget_show( GTK_WIDGET( vbox3 ) ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox3 ) ); { GtkTable* table = GTK_TABLE( gtk_table_new( 8, 4, FALSE ) ); gtk_widget_show( GTK_WIDGET( table ) ); gtk_box_pack_start( GTK_BOX( vbox3 ), GTK_WIDGET( table ), TRUE, TRUE, 0 ); gtk_table_set_row_spacings( table, 0 ); gtk_table_set_col_spacings( table, 0 ); GtkCheckButton** p = m_contentFlags; for ( int c = 0; c != 4; ++c ) { for ( int r = 0; r != 8; ++r ) { GtkCheckButton* check = GTK_CHECK_BUTTON( gtk_check_button_new_with_label( getContentFlagName( c * 8 + r ) ) ); gtk_widget_show( GTK_WIDGET( check ) ); gtk_table_attach( table, GTK_WIDGET( check ), c, c + 1, r, r + 1, (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ), (GtkAttachOptions)( 0 ), 0, 0 ); *p++ = check; guint handler_id = togglebutton_connect_toggled( GTK_TOGGLE_BUTTON( check ), ApplyFlagsCaller( *this ) ); g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler_id ) ); } } // not allowed to modify detail flag using Surface Inspector gtk_widget_set_sensitive( GTK_WIDGET( m_contentFlags[BRUSH_DETAIL_FLAG] ), FALSE ); } } } { GtkFrame* frame = GTK_FRAME( gtk_frame_new( "Value" ) ); gtk_widget_show( GTK_WIDGET( frame ) ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( frame ), TRUE, TRUE, 0 ); { GtkVBox* vbox3 = GTK_VBOX( gtk_vbox_new( FALSE, 4 ) ); gtk_container_set_border_width( GTK_CONTAINER( vbox3 ), 4 ); gtk_widget_show( GTK_WIDGET( vbox3 ) ); gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox3 ) ); { GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); gtk_widget_show( GTK_WIDGET( entry ) ); gtk_box_pack_start( GTK_BOX( vbox3 ), GTK_WIDGET( entry ), TRUE, TRUE, 0 ); m_valueEntryWidget = entry; m_valueEntry.connect( entry ); } } } } #if TEXTOOL_ENABLED if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) { // Shamus: Textool goodies... GtkWidget * frame = gtk_frame_new( "Textool" ); gtk_widget_show( frame ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( frame ), FALSE, FALSE, 0 ); { //Prolly should make this a member or global var, so the SI can draw on it... TexTool::g_textoolWin = glwidget_new( FALSE ); // --> Dunno, but this stuff may be necessary... (Looks like it!) gtk_widget_ref( TexTool::g_textoolWin ); gtk_widget_set_events( TexTool::g_textoolWin, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK ); GTK_WIDGET_SET_FLAGS( TexTool::g_textoolWin, GTK_CAN_FOCUS ); // <-- end stuff... gtk_widget_show( TexTool::g_textoolWin ); gtk_widget_set_usize( TexTool::g_textoolWin, -1, 240 ); //Yeah! gtk_container_add( GTK_CONTAINER( frame ), TexTool::g_textoolWin ); g_signal_connect( G_OBJECT( TexTool::g_textoolWin ), "size_allocate", G_CALLBACK( TexTool::size_allocate ), NULL ); g_signal_connect( G_OBJECT( TexTool::g_textoolWin ), "expose_event", G_CALLBACK( TexTool::expose ), NULL ); g_signal_connect( G_OBJECT( TexTool::g_textoolWin ), "button_press_event", G_CALLBACK( TexTool::button_press ), NULL ); g_signal_connect( G_OBJECT( TexTool::g_textoolWin ), "button_release_event", G_CALLBACK( TexTool::button_release ), NULL ); g_signal_connect( G_OBJECT( TexTool::g_textoolWin ), "motion_notify_event", G_CALLBACK( TexTool::motion ), NULL ); } { GtkWidget * hbox = gtk_hbox_new( FALSE, 5 ); gtk_widget_show( hbox ); gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hbox ), FALSE, FALSE, 0 ); // Checkboxes go here... (Flip X/Y) GtkWidget * flipX = gtk_check_button_new_with_label( "Flip X axis" ); GtkWidget * flipY = gtk_check_button_new_with_label( "Flip Y axis" ); gtk_widget_show( flipX ); gtk_widget_show( flipY ); gtk_box_pack_start( GTK_BOX( hbox ), flipX, FALSE, FALSE, 0 ); gtk_box_pack_start( GTK_BOX( hbox ), flipY, FALSE, FALSE, 0 ); //Instead of this, we probably need to create a vbox to put into the frame, then the //window, then the hbox. !!! FIX !!! // gtk_container_add(GTK_CONTAINER(frame), hbox); //Hmm. Do we really need g_object_set_data? Mebbe not... And we don't! :-) // g_object_set_data(G_OBJECT(flipX), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipX), "toggled", G_CALLBACK(TexTool::flipX), 0))); // g_object_set_data(G_OBJECT(flipY), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipY), "toggled", G_CALLBACK(TexTool::flipY), 0))); //Instead, just do: g_signal_connect( G_OBJECT( flipX ), "toggled", G_CALLBACK( TexTool::flipX ), NULL ); g_signal_connect( G_OBJECT( flipY ), "toggled", G_CALLBACK( TexTool::flipY ), NULL ); } } #endif } return window; } /* ============== Update Set the fields to the current texdef (i.e. map/texdef -> dialog widgets) if faces selected (instead of brushes) -> will read this face texdef, else current texdef if only patches selected, will read the patch texdef =============== */ void spin_button_set_value_no_signal( GtkSpinButton* spin, gdouble value ){ guint handler_id = gpointer_to_int( g_object_get_data( G_OBJECT( spin ), "handler" ) ); g_signal_handler_block( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), handler_id ); gtk_spin_button_set_value( spin, value ); g_signal_handler_unblock( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), handler_id ); } void spin_button_set_step_increment( GtkSpinButton* spin, gdouble value ){ GtkAdjustment* adjust = gtk_spin_button_get_adjustment( spin ); adjust->step_increment = value; } void SurfaceInspector::Update(){ const char * name = SurfaceInspector_GetSelectedShader(); if ( shader_is_texture( name ) ) { gtk_entry_set_text( m_texture, shader_get_textureName( name ) ); } else { gtk_entry_set_text( m_texture, "" ); } texdef_t shiftScaleRotate; //Shamus: This is where we get into trouble--the BP code tries to convert to a "faked" //shift, rotate & scale values from the brush face, which seems to screw up for some reason. //!!! FIX !!! /*globalOutputStream() << "--> SI::Update. About to do ShiftScaleRotate_fromFace()...\n"; SurfaceInspector_GetSelectedBPTexdef(); globalOutputStream() << "BP: (" << g_selectedBrushPrimitTexdef.coords[0][0] << ", " << g_selectedBrushPrimitTexdef.coords[0][1] << ")(" << g_selectedBrushPrimitTexdef.coords[1][0] << ", " << g_selectedBrushPrimitTexdef.coords[1][1] << ")(" << g_selectedBrushPrimitTexdef.coords[0][2] << ", " << g_selectedBrushPrimitTexdef.coords[1][2] << ") SurfaceInspector::Update\n";//*/ //Ok, it's screwed up *before* we get here... ShiftScaleRotate_fromFace( shiftScaleRotate, SurfaceInspector_GetSelectedTexdef() ); // normalize again to hide the ridiculously high scale values that get created when using texlock shiftScaleRotate.shift[0] = float_mod( shiftScaleRotate.shift[0], (float)g_selectedShaderSize[0] ); shiftScaleRotate.shift[1] = float_mod( shiftScaleRotate.shift[1], (float)g_selectedShaderSize[1] ); { spin_button_set_value_no_signal( m_hshiftIncrement.m_spin, shiftScaleRotate.shift[0] ); spin_button_set_step_increment( m_hshiftIncrement.m_spin, g_si_globals.shift[0] ); entry_set_float( m_hshiftIncrement.m_entry, g_si_globals.shift[0] ); } { spin_button_set_value_no_signal( m_vshiftIncrement.m_spin, shiftScaleRotate.shift[1] ); spin_button_set_step_increment( m_vshiftIncrement.m_spin, g_si_globals.shift[1] ); entry_set_float( m_vshiftIncrement.m_entry, g_si_globals.shift[1] ); } { spin_button_set_value_no_signal( m_hscaleIncrement.m_spin, shiftScaleRotate.scale[0] ); spin_button_set_step_increment( m_hscaleIncrement.m_spin, g_si_globals.scale[0] ); entry_set_float( m_hscaleIncrement.m_entry, g_si_globals.scale[0] ); } { spin_button_set_value_no_signal( m_vscaleIncrement.m_spin, shiftScaleRotate.scale[1] ); spin_button_set_step_increment( m_vscaleIncrement.m_spin, g_si_globals.scale[1] ); entry_set_float( m_vscaleIncrement.m_entry, g_si_globals.scale[1] ); } { spin_button_set_value_no_signal( m_rotateIncrement.m_spin, shiftScaleRotate.rotate ); spin_button_set_step_increment( m_rotateIncrement.m_spin, g_si_globals.rotate ); entry_set_float( m_rotateIncrement.m_entry, g_si_globals.rotate ); } if ( !string_empty( g_pGameDescription->getKeyValue( "si_flags" ) ) ) { ContentsFlagsValue flags( SurfaceInspector_GetSelectedFlags() ); entry_set_int( m_valueEntryWidget, flags.m_value ); for ( GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p ) { toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( *p ), flags.m_surfaceFlags & ( 1 << ( p - m_surfaceFlags ) ) ); } for ( GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p ) { toggle_button_set_active_no_signal( GTK_TOGGLE_BUTTON( *p ), flags.m_contentFlags & ( 1 << ( p - m_contentFlags ) ) ); } } } /* ============== Apply Reads the fields to get the current texdef (i.e. widgets -> MAP) in brush primitive mode, grab the fake shift scale rot and compute a new texture matrix =============== */ void SurfaceInspector::ApplyShader(){ StringOutputStream name( 256 ); name << GlobalTexturePrefix_get() << gtk_entry_get_text( m_texture ); // TTimo: detect and refuse invalid texture names (at least the ones with spaces) if ( !texdef_name_valid( name.c_str() ) ) { globalErrorStream() << "invalid texture name '" << name.c_str() << "'\n"; SurfaceInspector_queueDraw(); return; } UndoableCommand undo( "textureNameSetSelected" ); Select_SetShader( name.c_str() ); } void SurfaceInspector::ApplyTexdef(){ texdef_t shiftScaleRotate; shiftScaleRotate.shift[0] = static_cast<float>( gtk_spin_button_get_value_as_float( m_hshiftIncrement.m_spin ) ); shiftScaleRotate.shift[1] = static_cast<float>( gtk_spin_button_get_value_as_float( m_vshiftIncrement.m_spin ) ); shiftScaleRotate.scale[0] = static_cast<float>( gtk_spin_button_get_value_as_float( m_hscaleIncrement.m_spin ) ); shiftScaleRotate.scale[1] = static_cast<float>( gtk_spin_button_get_value_as_float( m_vscaleIncrement.m_spin ) ); shiftScaleRotate.rotate = static_cast<float>( gtk_spin_button_get_value_as_float( m_rotateIncrement.m_spin ) ); TextureProjection projection; //Shamus: This is the other place that screws up, it seems, since it doesn't seem to do the //conversion from the face (I think) and so bogus values end up in the thing... !!! FIX !!! //This is actually OK. :-P ShiftScaleRotate_toFace( shiftScaleRotate, projection ); UndoableCommand undo( "textureProjectionSetSelected" ); Select_SetTexdef( projection ); } void SurfaceInspector::ApplyFlags(){ unsigned int surfaceflags = 0; for ( GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p ) { if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( *p ) ) ) { surfaceflags |= ( 1 << ( p - m_surfaceFlags ) ); } } unsigned int contentflags = 0; for ( GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p ) { if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( *p ) ) ) { contentflags |= ( 1 << ( p - m_contentFlags ) ); } } int value = entry_get_int( m_valueEntryWidget ); UndoableCommand undo( "flagsSetSelected" ); Select_SetFlags( ContentsFlagsValue( surfaceflags, contentflags, value, true ) ); } void Face_getTexture( Face& face, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags ){ shader = face.GetShader(); face.GetTexdef( projection ); flags = face.getShader().m_flags; } typedef Function4<Face&, CopiedString&, TextureProjection&, ContentsFlagsValue&, void, Face_getTexture> FaceGetTexture; void Face_setTexture( Face& face, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags ){ face.SetShader( shader ); face.SetTexdef( projection ); face.SetFlags( flags ); } typedef Function4<Face&, const char*, const TextureProjection&, const ContentsFlagsValue&, void, Face_setTexture> FaceSetTexture; void Patch_getTexture( Patch& patch, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags ){ shader = patch.GetShader(); projection = TextureProjection( texdef_t(), brushprimit_texdef_t(), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) ); flags = ContentsFlagsValue( 0, 0, 0, false ); } typedef Function4<Patch&, CopiedString&, TextureProjection&, ContentsFlagsValue&, void, Patch_getTexture> PatchGetTexture; void Patch_setTexture( Patch& patch, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags ){ patch.SetShader( shader ); } typedef Function4<Patch&, const char*, const TextureProjection&, const ContentsFlagsValue&, void, Patch_setTexture> PatchSetTexture; typedef Callback3<CopiedString&, TextureProjection&, ContentsFlagsValue&> GetTextureCallback; typedef Callback3<const char*, const TextureProjection&, const ContentsFlagsValue&> SetTextureCallback; struct Texturable { GetTextureCallback getTexture; SetTextureCallback setTexture; }; void Face_getClosest( Face& face, SelectionTest& test, SelectionIntersection& bestIntersection, Texturable& texturable ){ SelectionIntersection intersection; face.testSelect( test, intersection ); if ( intersection.valid() && SelectionIntersection_closer( intersection, bestIntersection ) ) { bestIntersection = intersection; texturable.setTexture = makeCallback3( FaceSetTexture(), face ); texturable.getTexture = makeCallback3( FaceGetTexture(), face ); } } class OccludeSelector : public Selector { SelectionIntersection& m_bestIntersection; bool& m_occluded; public: OccludeSelector( SelectionIntersection & bestIntersection, bool & occluded ) : m_bestIntersection( bestIntersection ), m_occluded( occluded ) { m_occluded = false; } void pushSelectable( Selectable& selectable ){ } void popSelectable(){ } void addIntersection( const SelectionIntersection& intersection ){ if ( SelectionIntersection_closer( intersection, m_bestIntersection ) ) { m_bestIntersection = intersection; m_occluded = true; } } }; class BrushGetClosestFaceVisibleWalker : public scene::Graph::Walker { SelectionTest& m_test; Texturable& m_texturable; mutable SelectionIntersection m_bestIntersection; public: BrushGetClosestFaceVisibleWalker( SelectionTest & test, Texturable & texturable ) : m_test( test ), m_texturable( texturable ) { } bool pre( const scene::Path& path, scene::Instance& instance ) const { if ( path.top().get().visible() ) { BrushInstance* brush = Instance_getBrush( instance ); if ( brush != 0 ) { m_test.BeginMesh( brush->localToWorld() ); for ( Brush::const_iterator i = brush->getBrush().begin(); i != brush->getBrush().end(); ++i ) { Face_getClosest( *( *i ), m_test, m_bestIntersection, m_texturable ); } } else { SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance ); if ( selectionTestable ) { bool occluded; OccludeSelector selector( m_bestIntersection, occluded ); selectionTestable->testSelect( selector, m_test ); if ( occluded ) { Patch* patch = Node_getPatch( path.top() ); if ( patch != 0 ) { m_texturable.setTexture = makeCallback3( PatchSetTexture(), *patch ); m_texturable.getTexture = makeCallback3( PatchGetTexture(), *patch ); } else { m_texturable = Texturable(); } } } } } return true; } }; Texturable Scene_getClosestTexturable( scene::Graph& graph, SelectionTest& test ){ Texturable texturable; graph.traverse( BrushGetClosestFaceVisibleWalker( test, texturable ) ); return texturable; } bool Scene_getClosestTexture( scene::Graph& graph, SelectionTest& test, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags ){ Texturable texturable = Scene_getClosestTexturable( graph, test ); if ( texturable.getTexture != GetTextureCallback() ) { texturable.getTexture( shader, projection, flags ); return true; } return false; } void Scene_setClosestTexture( scene::Graph& graph, SelectionTest& test, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags ){ Texturable texturable = Scene_getClosestTexturable( graph, test ); if ( texturable.setTexture != SetTextureCallback() ) { texturable.setTexture( shader, projection, flags ); } } class FaceTexture { public: TextureProjection m_projection; ContentsFlagsValue m_flags; }; FaceTexture g_faceTextureClipboard; void FaceTextureClipboard_setDefault(){ g_faceTextureClipboard.m_flags = ContentsFlagsValue( 0, 0, 0, false ); TexDef_Construct_Default( g_faceTextureClipboard.m_projection ); } void TextureClipboard_textureSelected( const char* shader ){ FaceTextureClipboard_setDefault(); } class TextureBrowser; extern TextureBrowser g_TextureBrowser; void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ); const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ); void Scene_copyClosestTexture( SelectionTest& test ){ CopiedString shader; if ( Scene_getClosestTexture( GlobalSceneGraph(), test, shader, g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags ) ) { TextureBrowser_SetSelectedShader( g_TextureBrowser, shader.c_str() ); } } void Scene_applyClosestTexture( SelectionTest& test ){ UndoableCommand command( "facePaintTexture" ); Scene_setClosestTexture( GlobalSceneGraph(), test, TextureBrowser_GetSelectedShader( g_TextureBrowser ), g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags ); SceneChangeNotify(); } void SelectedFaces_copyTexture(){ if ( !g_SelectedFaceInstances.empty() ) { Face& face = g_SelectedFaceInstances.last().getFace(); face.GetTexdef( g_faceTextureClipboard.m_projection ); g_faceTextureClipboard.m_flags = face.getShader().m_flags; TextureBrowser_SetSelectedShader( g_TextureBrowser, face.getShader().getShader() ); } } void FaceInstance_pasteTexture( FaceInstance& faceInstance ){ faceInstance.getFace().SetTexdef( g_faceTextureClipboard.m_projection ); faceInstance.getFace().SetShader( TextureBrowser_GetSelectedShader( g_TextureBrowser ) ); faceInstance.getFace().SetFlags( g_faceTextureClipboard.m_flags ); SceneChangeNotify(); } bool SelectedFaces_empty(){ return g_SelectedFaceInstances.empty(); } void SelectedFaces_pasteTexture(){ UndoableCommand command( "facePasteTexture" ); g_SelectedFaceInstances.foreach( FaceInstance_pasteTexture ); } void SurfaceInspector_constructPreferences( PreferencesPage& page ){ page.appendCheckBox( "", "Surface Inspector Increments Match Grid", g_si_globals.m_bSnapTToGrid ); } void SurfaceInspector_constructPage( PreferenceGroup& group ){ PreferencesPage page( group.createPage( "Surface Inspector", "Surface Inspector Preferences" ) ); SurfaceInspector_constructPreferences( page ); } void SurfaceInspector_registerPreferencesPage(){ PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, SurfaceInspector_constructPage>() ); } void SurfaceInspector_registerCommands(){ GlobalCommands_insert( "FitTexture", FreeCaller<SurfaceInspector_FitTexture>(), Accelerator( 'B', (GdkModifierType)GDK_SHIFT_MASK ) ); GlobalCommands_insert( "SurfaceInspector", FreeCaller<SurfaceInspector_toggleShown>(), Accelerator( 'S' ) ); GlobalCommands_insert( "FaceCopyTexture", FreeCaller<SelectedFaces_copyTexture>() ); GlobalCommands_insert( "FacePasteTexture", FreeCaller<SelectedFaces_pasteTexture>() ); } #include "preferencesystem.h" void SurfaceInspector_Construct(){ g_SurfaceInspector = new SurfaceInspector; SurfaceInspector_registerCommands(); FaceTextureClipboard_setDefault(); GlobalPreferenceSystem().registerPreference( "SurfaceWnd", getSurfaceInspector().m_importPosition, getSurfaceInspector().m_exportPosition ); GlobalPreferenceSystem().registerPreference( "SI_SurfaceTexdef_Scale1", FloatImportStringCaller( g_si_globals.scale[0] ), FloatExportStringCaller( g_si_globals.scale[0] ) ); GlobalPreferenceSystem().registerPreference( "SI_SurfaceTexdef_Scale2", FloatImportStringCaller( g_si_globals.scale[1] ), FloatExportStringCaller( g_si_globals.scale[1] ) ); GlobalPreferenceSystem().registerPreference( "SI_SurfaceTexdef_Shift1", FloatImportStringCaller( g_si_globals.shift[0] ), FloatExportStringCaller( g_si_globals.shift[0] ) ); GlobalPreferenceSystem().registerPreference( "SI_SurfaceTexdef_Shift2", FloatImportStringCaller( g_si_globals.shift[1] ), FloatExportStringCaller( g_si_globals.shift[1] ) ); GlobalPreferenceSystem().registerPreference( "SI_SurfaceTexdef_Rotate", FloatImportStringCaller( g_si_globals.rotate ), FloatExportStringCaller( g_si_globals.rotate ) ); GlobalPreferenceSystem().registerPreference( "SnapTToGrid", BoolImportStringCaller( g_si_globals.m_bSnapTToGrid ), BoolExportStringCaller( g_si_globals.m_bSnapTToGrid ) ); typedef FreeCaller1<const Selectable&, SurfaceInspector_SelectionChanged> SurfaceInspectorSelectionChangedCaller; GlobalSelectionSystem().addSelectionChangeCallback( SurfaceInspectorSelectionChangedCaller() ); typedef FreeCaller<SurfaceInspector_updateSelection> SurfaceInspectorUpdateSelectionCaller; Brush_addTextureChangedCallback( SurfaceInspectorUpdateSelectionCaller() ); Patch_addTextureChangedCallback( SurfaceInspectorUpdateSelectionCaller() ); SurfaceInspector_registerPreferencesPage(); } void SurfaceInspector_Destroy(){ delete g_SurfaceInspector; } #if TEXTOOL_ENABLED namespace TexTool { // namespace hides these symbols from other object-files // //Shamus: Textool functions, including GTK+ callbacks // //NOTE: Black screen when TT first comes up is caused by an uninitialized Extent... !!! FIX !!! // But... You can see down below that it *is* initialized! WTF? struct Extent { float minX, minY, maxX, maxY; float width( void ) { return fabs( maxX - minX ); } float height( void ) { return fabs( maxY - minY ); } }; //This seems to control the texture scale... (Yep! ;-) Extent extents = { -2.0f, -2.0f, +2.0f, +2.0f }; brushprimit_texdef_t tm; // Texture transform matrix Vector2 pts[c_brush_maxFaces]; Vector2 center; int numPts; int textureNum; Vector2 textureSize; Vector2 windowSize; #define VP_PADDING 1.2 #define PI 3.14159265358979 bool lButtonDown = false; bool rButtonDown = false; //int dragPoint; //int anchorPoint; bool haveAnchor = false; brushprimit_texdef_t currentBP; brushprimit_texdef_t origBP; // Original brush primitive (before we muck it up) float controlRadius = 5.0f; float rotationAngle = 0.0f; float rotationAngle2 = 0.0f; float oldRotationAngle; Vector2 rotationPoint; bool translatingX = false; // Widget state variables bool translatingY = false; bool scalingX = false; bool scalingY = false; bool rotating = false; bool resizingX = false; // Not sure what this means... :-/ bool resizingY = false; float origAngle, origScaleX, origScaleY; Vector2 oldCenter; // Function prototypes (move up to top later...) void DrawCircularArc( Vector2 ctr, float startAngle, float endAngle, float radius ); void CopyPointsFromSelectedFace( void ){ // Make sure that there's a face and winding to get! if ( g_SelectedFaceInstances.empty() ) { numPts = 0; return; } Face & face = g_SelectedFaceInstances.last().getFace(); textureNum = face.getShader().m_state->getTexture().texture_number; textureSize.x() = face.getShader().m_state->getTexture().width; textureSize.y() = face.getShader().m_state->getTexture().height; //globalOutputStream() << "--> Texture #" << textureNum << ": " << textureSize.x() << " x " << textureSize.y() << "...\n"; currentBP = SurfaceInspector_GetSelectedTexdef().m_brushprimit_texdef; face.EmitTextureCoordinates(); Winding & w = face.getWinding(); int count = 0; for ( Winding::const_iterator i = w.begin(); i != w.end(); i++ ) { //globalOutputStream() << (*i).texcoord.x() << " " << (*i).texcoord.y() << ", "; pts[count].x() = ( *i ).texcoord.x(); pts[count].y() = ( *i ).texcoord.y(); count++; } numPts = count; //globalOutputStream() << " ..copied points\n"; } brushprimit_texdef_t bp; //This approach is probably wrongheaded and just not right anyway. So, !!! FIX !!! [DONE] void CommitChanges( void ){ texdef_t t; // Throwaway, since this is BP only bp.coords[0][0] = tm.coords[0][0] * origBP.coords[0][0] + tm.coords[0][1] * origBP.coords[1][0]; bp.coords[0][1] = tm.coords[0][0] * origBP.coords[0][1] + tm.coords[0][1] * origBP.coords[1][1]; bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2]; //Ok, this works for translation... // bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2] * textureSize.x(); bp.coords[1][0] = tm.coords[1][0] * origBP.coords[0][0] + tm.coords[1][1] * origBP.coords[1][0]; bp.coords[1][1] = tm.coords[1][0] * origBP.coords[0][1] + tm.coords[1][1] * origBP.coords[1][1]; bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2]; // bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2] * textureSize.y(); //This doesn't work: g_brush_texture_changed(); // Let's try this: //Note: We should only set an undo *after* the button has been released... !!! FIX !!! //Definitely *should* have an undo, though! // UndoableCommand undo("textureProjectionSetSelected"); Select_SetTexdef( TextureProjection( t, bp, Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) ) ); //This is working, but for some reason the translate is causing the rest of the SI //widgets to yield bad readings... !!! FIX !!! //I.e., click on textool window, translate face wireframe, then controls go crazy. Dunno why. //It's because there were some uncommented out add/removeScale functions in brush.h and a //removeScale in brushmanip.cpp... :-/ //Translate isn't working at all now... :-( //It's because we need to multiply in some scaling factor (prolly the texture width/height) //Yep. :-P } void UpdateControlPoints( void ){ CommitChanges(); // Init texture transform matrix tm.coords[0][0] = 1.0f; tm.coords[0][1] = 0.0f; tm.coords[0][2] = 0.0f; tm.coords[1][0] = 0.0f; tm.coords[1][1] = 1.0f; tm.coords[1][2] = 0.0f; } /* For shifting we have: */ /* The code that should provide reasonable defaults, but doesn't for some reason: It's scaling the BP by 128 for some reason, between the time it's created and the time we get back to the SI widgets: static void OnBtnAxial(GtkWidget *widget, gpointer data) { UndoableCommand undo("textureDefault"); TextureProjection projection; TexDef_Construct_Default(projection); Select_SetTexdef(projection); } Select_SetTexdef() calls Scene_BrushSetTexdef_Component_Selected(GlobalSceneGraph(), projection) which is in brushmanip.h: This eventually calls Texdef_Assign(m_texdef, texdef, m_brushprimit_texdef, brushprimit_texdef) in class Face... which just copies from brushpr to m_brushpr... */ //Small problem with this thing: It's scaled to the texture which is all screwed up... !!! FIX !!! [DONE] //Prolly should separate out the grid drawing so that we can draw it behind the polygon. const float gridWidth = 1.3f; // Let's try an absolute height... WORKS!!! // NOTE that 2.0 is the height of the viewport. Dunno why... Should make collision // detection easier... const float gridRadius = gridWidth * 0.5f; typedef const float WidgetColor[3]; const WidgetColor widgetColor[10] = { { 1.0000f, 0.2000f, 0.0000f }, // Red { 0.9137f, 0.9765f, 0.4980f }, // Yellow { 0.0000f, 0.6000f, 0.3216f }, // Green { 0.6157f, 0.7726f, 0.8196f }, // Cyan { 0.4980f, 0.5000f, 0.4716f }, // Grey // Highlight colors { 1.0000f, 0.6000f, 0.4000f }, // Light Red { 1.0000f, 1.0000f, 0.8980f }, // Light Yellow { 0.4000f, 1.0000f, 0.7216f }, // Light Green { 1.0000f, 1.0000f, 1.0000f }, // Light Cyan { 0.8980f, 0.9000f, 0.8716f } // Light Grey }; #define COLOR_RED 0 #define COLOR_YELLOW 1 #define COLOR_GREEN 2 #define COLOR_CYAN 3 #define COLOR_GREY 4 #define COLOR_LT_RED 5 #define COLOR_LT_YELLOW 6 #define COLOR_LT_GREEN 7 #define COLOR_LT_CYAN 8 #define COLOR_LT_GREY 9 void DrawControlWidgets( void ){ //Note that the grid should go *behind* the face outline... !!! FIX !!! // Grid float xStart = center.x() - ( gridWidth / 2.0f ); float yStart = center.y() - ( gridWidth / 2.0f ); float xScale = ( extents.height() / extents.width() ) * ( textureSize.y() / textureSize.x() ); glPushMatrix(); //Small problem with this approach: Changing the center point in the TX code doesn't seem to //change anything here--prolly because we load a new identity matrix. A couple of ways to fix //this would be to get rid of that code, or change the center to a new point by taking into //account the transforms that we toss with the new identity matrix. Dunno which is better. glLoadIdentity(); glScalef( xScale, 1.0, 1.0 ); // Will that square it up? Yup. glRotatef( static_cast<float>( radians_to_degrees( atan2( -currentBP.coords[0][1], currentBP.coords[0][0] ) ) ), 0.0, 0.0, -1.0 ); glTranslatef( -center.x(), -center.y(), 0.0 ); // Circle glColor3fv( translatingX && translatingY ? widgetColor[COLOR_LT_YELLOW] : widgetColor[COLOR_YELLOW] ); glBegin( GL_LINE_LOOP ); DrawCircularArc( center, 0, 2.0f * PI, gridRadius * 0.16 ); glEnd(); // Axes glBegin( GL_LINES ); glColor3fv( translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN] ); glVertex2f( center.x(), center.y() + ( gridRadius * 0.16 ) ); glVertex2f( center.x(), center.y() + ( gridRadius * 1.00 ) ); glColor3fv( translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED] ); glVertex2f( center.x() + ( gridRadius * 0.16 ), center.y() ); glVertex2f( center.x() + ( gridRadius * 1.00 ), center.y() ); glEnd(); // Arrowheads glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glBegin( GL_TRIANGLES ); glColor3fv( translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN] ); glVertex2f( center.x(), center.y() + ( gridRadius * 1.10 ) ); glVertex2f( center.x() + ( gridRadius * 0.06 ), center.y() + ( gridRadius * 0.94 ) ); glVertex2f( center.x() - ( gridRadius * 0.06 ), center.y() + ( gridRadius * 0.94 ) ); glColor3fv( translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED] ); glVertex2f( center.x() + ( gridRadius * 1.10 ), center.y() ); glVertex2f( center.x() + ( gridRadius * 0.94 ), center.y() + ( gridRadius * 0.06 ) ); glVertex2f( center.x() + ( gridRadius * 0.94 ), center.y() - ( gridRadius * 0.06 ) ); glEnd(); // Arc glBegin( GL_LINE_STRIP ); glColor3fv( rotating ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN] ); DrawCircularArc( center, 0.03f * PI, 0.47f * PI, gridRadius * 0.90 ); glEnd(); // Boxes glColor3fv( scalingY && !scalingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN] ); glBegin( GL_LINES ); glVertex2f( center.x() + ( gridRadius * 0.20 ), center.y() + ( gridRadius * 1.50 ) ); glVertex2f( center.x() - ( gridRadius * 0.20 ), center.y() + ( gridRadius * 1.50 ) ); glEnd(); glBegin( GL_LINE_LOOP ); glVertex2f( center.x() + ( gridRadius * 0.10 ), center.y() + ( gridRadius * 1.40 ) ); glVertex2f( center.x() - ( gridRadius * 0.10 ), center.y() + ( gridRadius * 1.40 ) ); glVertex2f( center.x() - ( gridRadius * 0.10 ), center.y() + ( gridRadius * 1.20 ) ); glVertex2f( center.x() + ( gridRadius * 0.10 ), center.y() + ( gridRadius * 1.20 ) ); glEnd(); glColor3fv( scalingX && !scalingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED] ); glBegin( GL_LINES ); glVertex2f( center.x() + ( gridRadius * 1.50 ), center.y() + ( gridRadius * 0.20 ) ); glVertex2f( center.x() + ( gridRadius * 1.50 ), center.y() - ( gridRadius * 0.20 ) ); glEnd(); glBegin( GL_LINE_LOOP ); glVertex2f( center.x() + ( gridRadius * 1.40 ), center.y() + ( gridRadius * 0.10 ) ); glVertex2f( center.x() + ( gridRadius * 1.40 ), center.y() - ( gridRadius * 0.10 ) ); glVertex2f( center.x() + ( gridRadius * 1.20 ), center.y() - ( gridRadius * 0.10 ) ); glVertex2f( center.x() + ( gridRadius * 1.20 ), center.y() + ( gridRadius * 0.10 ) ); glEnd(); glColor3fv( scalingX && scalingY ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN] ); glBegin( GL_LINE_STRIP ); glVertex2f( center.x() + ( gridRadius * 1.50 ), center.y() + ( gridRadius * 1.10 ) ); glVertex2f( center.x() + ( gridRadius * 1.50 ), center.y() + ( gridRadius * 1.50 ) ); glVertex2f( center.x() + ( gridRadius * 1.10 ), center.y() + ( gridRadius * 1.50 ) ); glEnd(); glBegin( GL_LINE_LOOP ); glVertex2f( center.x() + ( gridRadius * 1.40 ), center.y() + ( gridRadius * 1.40 ) ); glVertex2f( center.x() + ( gridRadius * 1.40 ), center.y() + ( gridRadius * 1.20 ) ); glVertex2f( center.x() + ( gridRadius * 1.20 ), center.y() + ( gridRadius * 1.20 ) ); glVertex2f( center.x() + ( gridRadius * 1.20 ), center.y() + ( gridRadius * 1.40 ) ); glEnd(); glPopMatrix(); } void DrawControlPoints( void ){ glColor3f( 1, 1, 1 ); glBegin( GL_LINE_LOOP ); for ( int i = 0; i < numPts; i++ ) glVertex2f( pts[i].x(), pts[i].y() ); glEnd(); } // Note: Setup and all that jazz must be done by the caller! void DrawCircularArc( Vector2 ctr, float startAngle, float endAngle, float radius ){ float stepSize = ( 2.0f * PI ) / 200.0f; for ( float angle = startAngle; angle <= endAngle; angle += stepSize ) glVertex2f( ctr.x() + radius * cos( angle ), ctr.y() + radius * sin( angle ) ); } void focus(){ if ( numPts == 0 ) { return; } // Find selected texture's extents... extents.minX = extents.maxX = pts[0].x(), extents.minY = extents.maxY = pts[0].y(); for ( int i = 1; i < numPts; i++ ) { if ( pts[i].x() < extents.minX ) { extents.minX = pts[i].x(); } if ( pts[i].x() > extents.maxX ) { extents.maxX = pts[i].x(); } if ( pts[i].y() < extents.minY ) { extents.minY = pts[i].y(); } if ( pts[i].y() > extents.maxY ) { extents.maxY = pts[i].y(); } } // Do some viewport fitting stuff... //globalOutputStream() << "--> Center: " << center.x() << ", " << center.y() << "\n"; //globalOutputStream() << "--> Extents (stage 1): " << extents.minX << ", " // << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; // TTimo: Apply a ratio to get the area we'll draw. center.x() = 0.5f * ( extents.minX + extents.maxX ), center.y() = 0.5f * ( extents.minY + extents.maxY ); extents.minX = center.x() + VP_PADDING * ( extents.minX - center.x() ), extents.minY = center.y() + VP_PADDING * ( extents.minY - center.y() ), extents.maxX = center.x() + VP_PADDING * ( extents.maxX - center.x() ), extents.maxY = center.y() + VP_PADDING * ( extents.maxY - center.y() ); //globalOutputStream() << "--> Extents (stage 2): " << extents.minX << ", " // << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; // TTimo: We want a texture with the same X / Y ratio. // TTimo: Compute XY space / window size ratio. float SSize = extents.width(), TSize = extents.height(); float ratioX = textureSize.x() * extents.width() / windowSize.x(), ratioY = textureSize.y() * extents.height() / windowSize.y(); //globalOutputStream() << "--> Texture size: " << textureSize.x() << ", " << textureSize.y() << "\n"; //globalOutputStream() << "--> Window size: " << windowSize.x() << ", " << windowSize.y() << "\n"; if ( ratioX > ratioY ) { TSize = ( windowSize.y() * ratioX ) / textureSize.y(); // TSize = extents.width() * (windowSize.y() / windowSize.x()) * (textureSize.x() / textureSize.y()); } else { SSize = ( windowSize.x() * ratioY ) / textureSize.x(); // SSize = extents.height() * (windowSize.x() / windowSize.y()) * (textureSize.y() / textureSize.x()); } extents.minX = center.x() - 0.5f * SSize, extents.maxX = center.x() + 0.5f * SSize, extents.minY = center.y() - 0.5f * TSize, extents.maxY = center.y() + 0.5f * TSize; //globalOutputStream() << "--> Extents (stage 3): " << extents.minX << ", " // << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; } gboolean size_allocate( GtkWidget * win, GtkAllocation * a, gpointer ){ windowSize.x() = a->width; windowSize.y() = a->height; queueDraw(); return false; } gboolean expose( GtkWidget * win, GdkEventExpose * e, gpointer ){ // globalOutputStream() << "--> Textool Window was exposed!\n"; // globalOutputStream() << " (window width/height: " << cc << "/" << e->area.height << ")\n"; // windowSize.x() = e->area.width, windowSize.y() = e->area.height; //This needs to go elsewhere... // InitTextool(); if ( glwidget_make_current( win ) == FALSE ) { globalOutputStream() << " FAILED to make current! Oh, the agony! :-(\n"; return true; } CopyPointsFromSelectedFace(); if ( !lButtonDown ) { focus(); } // Probably should init button/anchor states here as well... // rotationAngle = 0.0f; glClearColor( 0, 0, 0, 0 ); glViewport( 0, 0, e->area.width, e->area.height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); //??? glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glDisable( GL_DEPTH_TEST ); glDisable( GL_BLEND ); glOrtho( extents.minX, extents.maxX, extents.maxY, extents.minY, -1, 1 ); glColor3f( 1, 1, 1 ); // draw the texture background glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glBindTexture( GL_TEXTURE_2D, textureNum ); glEnable( GL_TEXTURE_2D ); glBegin( GL_QUADS ); glTexCoord2f( extents.minX, extents.minY ); glVertex2f( extents.minX, extents.minY ); glTexCoord2f( extents.maxX, extents.minY ); glVertex2f( extents.maxX, extents.minY ); glTexCoord2f( extents.maxX, extents.maxY ); glVertex2f( extents.maxX, extents.maxY ); glTexCoord2f( extents.minX, extents.maxY ); glVertex2f( extents.minX, extents.maxY ); glEnd(); glDisable( GL_TEXTURE_2D ); // draw the texture-space grid glColor3fv( widgetColor[COLOR_GREY] ); glBegin( GL_LINES ); const int gridSubdivisions = 8; const float gridExtents = 4.0f; for ( int i = 0; i < gridSubdivisions + 1; ++i ) { float y = i * ( gridExtents / float(gridSubdivisions) ); float x = i * ( gridExtents / float(gridSubdivisions) ); glVertex2f( 0, y ); glVertex2f( gridExtents, y ); glVertex2f( x, 0 ); glVertex2f( x, gridExtents ); } glEnd(); DrawControlPoints(); DrawControlWidgets(); //??? // reset the current texture // glBindTexture(GL_TEXTURE_2D, 0); // glFinish(); glwidget_swap_buffers( win ); return false; } /*int FindSelectedPoint(int x, int y) { for(int i=0; i<numPts; i++) { int nx = (int)(windowSize.x() * (pts[i].x() - extents.minX) / extents.width()); int ny = (int)(windowSize.y() * (pts[i].y() - extents.minY) / extents.height()); if (abs(nx - x) <= 3 && abs(ny - y) <= 3) return i; } return -1; }//*/ Vector2 trans; Vector2 trans2; Vector2 dragPoint; // Defined in terms of window space (+x/-y) Vector2 oldTrans; gboolean button_press( GtkWidget * win, GdkEventButton * e, gpointer ){ // globalOutputStream() << "--> Textool button press...\n"; if ( e->button == 1 ) { lButtonDown = true; GlobalUndoSystem().start(); origBP = currentBP; //globalOutputStream() << "--> Original BP: [" << origBP.coords[0][0] << "][" << origBP.coords[0][1] << "][" << origBP.coords[0][2] << "]\n"; //globalOutputStream() << " [" << origBP.coords[1][0] << "][" << origBP.coords[1][1] << "][" << origBP.coords[1][2] << "]\n"; //float angle = atan2(origBP.coords[0][1], origBP.coords[0][0]) * 180.0f / 3.141592653589f; origAngle = ( origBP.coords[0][1] > 0 ? PI : -PI ); // Could also be -PI... !!! FIX !!! [DONE] if ( origBP.coords[0][0] != 0.0f ) { origAngle = atan( origBP.coords[0][1] / origBP.coords[0][0] ); } origScaleX = origBP.coords[0][0] / cos( origAngle ); origScaleY = origBP.coords[1][1] / cos( origAngle ); rotationAngle = origAngle; oldCenter[0] = oldCenter[1] = 0; //globalOutputStream() << "--> BP stats: ang=" << origAngle * RAD_TO_DEG << ", scale=" << origScaleX << "/" << origScaleY << "\n"; //Should also set the Flip X/Y checkboxes here as well... !!! FIX !!! //Also: should reverse texture left/right up/down instead of flipping the points... //disnowok //float nx = windowSize.x() * (e->x - extents.minX) / (extents.maxX - extents.minX); //float ny = windowSize.y() * (e->y - extents.minY) / (extents.maxY - extents.minY); //disdoes... //But I want it to scroll the texture window, not the points... !!! FIX !!! //Actually, should scroll the texture window only when mouse is down on no widgets... float nx = e->x / windowSize.x() * extents.width() + extents.minX; float ny = e->y / windowSize.y() * extents.height() + extents.minY; trans.x() = -tm.coords[0][0] * nx - tm.coords[0][1] * ny; trans.y() = -tm.coords[1][0] * nx - tm.coords[1][1] * ny; dragPoint.x() = e->x, dragPoint.y() = e->y; trans2.x() = nx, trans2.y() = ny; oldRotationAngle = rotationAngle; // oldTrans.x() = tm.coords[0][2] - nx * textureSize.x(); // oldTrans.y() = tm.coords[1][2] - ny * textureSize.y(); oldTrans.x() = tm.coords[0][2]; oldTrans.y() = tm.coords[1][2]; oldCenter.x() = center.x(); oldCenter.y() = center.y(); queueDraw(); return true; } /* else if (e->button == 3) { rButtonDown = true; }//*/ //globalOutputStream() << "(" << (haveAnchor ? "anchor" : "released") << ")\n"; return false; } gboolean button_release( GtkWidget * win, GdkEventButton * e, gpointer ){ // globalOutputStream() << "--> Textool button release...\n"; if ( e->button == 1 ) { /* float ptx = e->x / windowSize.x() * extents.width() + extents.minX; float pty = e->y / windowSize.y() * extents.height() + extents.minY; //This prolly should go into the mouse move code... //Doesn't work correctly anyway... if (translatingX || translatingY) center.x() = ptx, center.y() = pty;//*/ lButtonDown = false; if ( translatingX || translatingY ) { GlobalUndoSystem().finish( "translateTexture" ); } else if ( rotating ) { GlobalUndoSystem().finish( "rotateTexture" ); } else if ( scalingX || scalingY ) { GlobalUndoSystem().finish( "scaleTexture" ); } else if ( resizingX || resizingY ) { GlobalUndoSystem().finish( "resizeTexture" ); } else { GlobalUndoSystem().finish( "textoolUnknown" ); } rotating = translatingX = translatingY = scalingX = scalingY = resizingX = resizingY = false; queueDraw(); } else if ( e->button == 3 ) { rButtonDown = false; } return true; } /* void C2DView::GridForWindow( float c[2], int x, int y) { SpaceForWindow( c, x, y ); if ( !m_bDoGrid ) return; c[0] /= m_GridStep[0]; c[1] /= m_GridStep[1]; c[0] = (float)floor( c[0] + 0.5f ); c[1] = (float)floor( c[1] + 0.5f ); c[0] *= m_GridStep[0]; c[1] *= m_GridStep[1]; } void C2DView::SpaceForWindow( float c[2], int x, int y) { c[0] = ((float)(x))/((float)(m_rect.right-m_rect.left))*(m_Maxs[0]-m_Mins[0])+m_Mins[0]; c[1] = ((float)(y))/((float)(m_rect.bottom-m_rect.top))*(m_Maxs[1]-m_Mins[1])+m_Mins[1]; } */ gboolean motion( GtkWidget * win, GdkEventMotion * e, gpointer ){ // globalOutputStream() << "--> Textool motion...\n"; if ( lButtonDown ) { if ( translatingX || translatingY ) { float ptx = e->x / windowSize.x() * extents.width() + extents.minX; float pty = e->y / windowSize.y() * extents.height() + extents.minY; //Need to fix this to take the rotation angle into account, so that it moves along //the rotated X/Y axis... if ( translatingX ) { // tm.coords[0][2] = (trans.x() + ptx) * textureSize.x(); //This works, but only when the angle is zero. !!! FIX !!! [DONE] // tm.coords[0][2] = oldCenter.x() + (ptx * textureSize.x()); tm.coords[0][2] = oldTrans.x() + ( ptx - trans2.x() ) * textureSize.x(); // center.x() = oldCenter.x() + (ptx - trans2.x()); } if ( translatingY ) { // tm.coords[1][2] = (trans.y() + pty) * textureSize.y(); // tm.coords[1][2] = oldCenter.y() + (pty * textureSize.y()); tm.coords[1][2] = oldTrans.y() + ( pty - trans2.y() ) * textureSize.y(); // center.y() = oldCenter.y() + (pty - trans2.y()); } //Need to update center.x/y() so that the widget translates as well. Also, oldCenter //is badly named... Should be oldTrans or something like that... !!! FIX !!! //Changing center.x/y() here doesn't seem to change anything... :-/ UpdateControlPoints(); } else if ( rotating ) { // Shamus: New rotate code int cx = (int)( windowSize.x() * ( center.x() - extents.minX ) / extents.width() ); int cy = (int)( windowSize.y() * ( center.y() - extents.minY ) / extents.height() ); Vector3 v1( dragPoint.x() - cx, dragPoint.y() - cy, 0 ), v2( e->x - cx, e->y - cy, 0 ); vector3_normalise( v1 ); vector3_normalise( v2 ); float c = vector3_dot( v1, v2 ); Vector3 cross = vector3_cross( v1, v2 ); float s = vector3_length( cross ); if ( cross[2] > 0 ) { s = -s; } // Problem with this: arcsin/cos seems to only return -90 to 90 and 0 to 180... // Can't derive angle from that! //rotationAngle = asin(s);// * 180.0f / 3.141592653589f; rotationAngle = acos( c ); //rotationAngle2 = asin(s); if ( cross[2] < 0 ) { rotationAngle = -rotationAngle; } //NO! DOESN'T WORK! rotationAngle -= 45.0f * DEG_TO_RAD; //Let's try this: //No wok. /*c = cos(rotationAngle - oldRotationAngle); s = sin(rotationAngle - oldRotationAngle); rotationAngle += oldRotationAngle; //c += cos(oldRotationAngle); //s += sin(oldRotationAngle); //rotationAngle += oldRotationAngle; //c %= 2.0 * PI; //s %= 2.0 * PI; //rotationAngle %= 2.0 * PI;//*/ //This is wrong... Hmm... //It seems to shear the texture instead of rotating it... !!! FIX !!! // Now it rotates correctly. Seems TTimo was overcomplicating things here... ;-) // Seems like what needs to happen here is multiplying these rotations by tm... !!! FIX !!! // See brush_primit.cpp line 244 (Texdef_EmitTextureCoordinates()) for where texcoords come from... tm.coords[0][0] = c; tm.coords[0][1] = s; tm.coords[1][0] = -s; tm.coords[1][1] = c; //It doesn't work anymore... Dunno why... //tm.coords[0][2] = -trans.x(); // This works!!! Yeah!!! //tm.coords[1][2] = -trans.y(); //nope. //tm.coords[0][2] = rotationPoint.x(); // This works, but strangely... //tm.coords[1][2] = rotationPoint.y(); //tm.coords[0][2] = 0;// center.x() / 2.0f; //tm.coords[1][2] = 0;// center.y() / 2.0f; //No. //tm.coords[0][2] = -(center.x() * textureSize.x()); //tm.coords[1][2] = -(center.y() * textureSize.y()); //Eh? No, but seems to be getting closer... /*float ptx = e->x / windowSize.x() * extents.width() + extents.minX; float pty = e->y / windowSize.y() * extents.height() + extents.minY; tm.coords[0][2] = -c * center.x() - s * center.y() + ptx; tm.coords[1][2] = s * center.x() - c * center.x() + pty;//*/ //Kinda works, but center drifts around on non-square textures... /*tm.coords[0][2] = (-c * center.x() - s * center.y()) * textureSize.x(); tm.coords[1][2] = ( s * center.x() - c * center.y()) * textureSize.y();//*/ //Rotates correctly, but not around the actual center of the face's points... /*tm.coords[0][2] = -c * center.x() * textureSize.x() - s * center.y() * textureSize.y(); tm.coords[1][2] = s * center.x() * textureSize.x() - c * center.y() * textureSize.y();//*/ //Yes!!! tm.coords[0][2] = ( -c * center.x() * textureSize.x() - s * center.y() * textureSize.y() ) + center.x() * textureSize.x(); tm.coords[1][2] = ( s * center.x() * textureSize.x() - c * center.y() * textureSize.y() ) + center.y() * textureSize.y(); //*/ //This doesn't work... //And this is the wrong place for this anyway (I'm pretty sure). /*tm.coords[0][2] += oldCenter.x(); tm.coords[1][2] += oldCenter.y();//*/ UpdateControlPoints(); // will cause a redraw } return true; } else // Check for widget mouseovers { Vector2 tran; float nx = e->x / windowSize.x() * extents.width() + extents.minX; float ny = e->y / windowSize.y() * extents.height() + extents.minY; // Translate nx/y to the "center" point... nx -= center.x(); ny -= center.y(); ny = -ny; // Flip Y-axis so that increasing numbers move up tran.x() = tm.coords[0][0] * nx + tm.coords[0][1] * ny; tran.y() = tm.coords[1][0] * nx + tm.coords[1][1] * ny; //This doesn't seem to generate a valid distance from the center--for some reason it //calculates a fixed number every time //Look at nx/y above: they're getting fixed there! !!! FIX !!! [DONE] float dist = sqrt( ( nx * nx ) + ( ny * ny ) ); // Normalize to the 2.0 = height standard (for now) //globalOutputStream() << "--> Distance before: " << dist; dist = dist * 2.0f / extents.height(); //globalOutputStream() << ". After: " << dist; tran.x() = tran.x() * 2.0f / extents.height(); tran.y() = tran.y() * 2.0f / extents.height(); //globalOutputStream() << ". Trans: " << tran.x() << ", " << tran.y() << "\n"; //Let's try this instead... //Interesting! It seems that e->x/y are rotated //(no, they're not--the TM above is what's doing it...) nx = ( ( e->x / windowSize.y() ) * 2.0f ) - ( windowSize.x() / windowSize.y() ); ny = ( ( e->y / windowSize.y() ) * 2.0f ) - ( windowSize.y() / windowSize.y() ); ny = -ny; //Cool! It works! Now just need to do rotation... rotating = translatingX = translatingY = scalingX = scalingY = resizingX = resizingY = false; if ( dist < ( gridRadius * 0.16f ) ) { translatingX = translatingY = true; } else if ( dist > ( gridRadius * 0.16f ) && dist < ( gridRadius * 1.10f ) && fabs( ny ) < ( gridRadius * 0.05f ) && nx > 0 ) { translatingX = true; } else if ( dist > ( gridRadius * 0.16f ) && dist < ( gridRadius * 1.10f ) && fabs( nx ) < ( gridRadius * 0.05f ) && ny > 0 ) { translatingY = true; } // Should tighten up the angle on this, or put this test after the axis tests... else if ( tran.x() > 0 && tran.y() > 0 && ( dist > ( gridRadius * 0.82f ) && dist < ( gridRadius * 0.98f ) ) ) { rotating = true; } queueDraw(); return true; } return false; } //It seems the fake tex coords conversion is screwing this stuff up... !!! FIX !!! //This is still wrong... Prolly need to do something with the oldScaleX/Y stuff... void flipX( GtkToggleButton *, gpointer ){ // globalOutputStream() << "--> Flip X...\n"; //Shamus: // SurfaceInspector_GetSelectedBPTexdef(); // Refresh g_selectedBrushPrimitTexdef... // tm.coords[0][0] = -tm.coords[0][0]; // tm.coords[1][0] = -tm.coords[1][0]; // tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now...Nope. // tm.coords[1][1] = -tm.coords[1][1]; tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now... tm.coords[1][0] = -tm.coords[1][0]; // tm.coords[2][0] = -tm.coords[2][0];//wil wok? no. UpdateControlPoints(); } void flipY( GtkToggleButton *, gpointer ){ // globalOutputStream() << "--> Flip Y...\n"; // tm.coords[0][1] = -tm.coords[0][1]; // tm.coords[1][1] = -tm.coords[1][1]; // tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now...Nope. // tm.coords[1][0] = -tm.coords[1][0]; tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now... tm.coords[1][1] = -tm.coords[1][1]; // tm.coords[2][1] = -tm.coords[2][1];//wil wok? no. UpdateControlPoints(); } } // end namespace TexTool #endif
36.777108
176
0.676015
[ "object", "vector", "transform" ]
9e7d4f52926eeb370170e722959d0a275eb68191
16,453
cpp
C++
source/Load_main.cpp
PhanSangTheAlerianLord/OpenGL-Object-Loading
4efb653e83cd0a858921416f99c5b6a75e1c84db
[ "MIT" ]
3
2021-11-03T09:38:09.000Z
2022-01-25T14:56:27.000Z
source/Load_main.cpp
PhanSangTheAlerianLord/OpenGL-Object-Loading
4efb653e83cd0a858921416f99c5b6a75e1c84db
[ "MIT" ]
null
null
null
source/Load_main.cpp
PhanSangTheAlerianLord/OpenGL-Object-Loading
4efb653e83cd0a858921416f99c5b6a75e1c84db
[ "MIT" ]
1
2021-11-04T05:07:38.000Z
2021-11-04T05:07:38.000Z
#include <gl\glew.h> #include <gl\freeglut.h> #include <iostream> #include <stdio.h> #include <string> #include <glm\gtc\type_ptr.hpp> #include <glm\gtc\matrix_transform.hpp> #include "Utility.h" #include "Load_Model.h" #include "Controls.h" using namespace std; using namespace glm; int width = 1920;//1024 int height = 1080;//768 vec3 lookFrom(7.0f, 10.0f, -5.0f); vec3 direction(0.0f, 0.0f, -1.0f); vec3 Up(0, 1, 0); float rotation_angle = 0.0f; float increase = 0.015; //vbo[0] : vertex + texture //vbo[1] : normal GLuint program; //GLuint vao; //GLuint vbo_vertices; //GLuint vbo_texcoords; //GLuint vbo_normals; //GLuint ibo; GLuint mvLoc; GLuint pLoc; GLuint mvpLoc; GLuint nLoc; //material base GLuint useTextureLoc; //GLuint useBumpMappingLoc; GLuint useMaskLoc; GLuint DiffuseLoc; GLuint KsLoc; //Num Mesh int num_mesh; //Light Loc GLuint globalAmbLoc; GLuint ambLoc; GLuint diffLoc; GLuint specLoc; GLuint posLoc; //Light Properties float a = 0.2f; float globalAmbient[4] = { a, a, a, 1.0f }; float lightAmbient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; float lightDiffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; float lightSpecular[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; void init_light(GLuint program, vec3 light_position) { float light_pos[3]; light_pos[0] = light_position.x; light_pos[1] = light_position.y; light_pos[2] = light_position.z; globalAmbLoc = glGetUniformLocation(program, "globalAmbient"); ambLoc = glGetUniformLocation(program, "light.ambient"); diffLoc = glGetUniformLocation(program, "light.diffuse"); specLoc = glGetUniformLocation(program, "light.specular"); posLoc = glGetUniformLocation(program, "light.position"); glProgramUniform4fv(program, globalAmbLoc, 1, globalAmbient); glProgramUniform4fv(program, ambLoc, 1, lightAmbient); glProgramUniform4fv(program, diffLoc, 1, lightDiffuse); glProgramUniform4fv(program, specLoc, 1, lightSpecular); glProgramUniform3fv(program, posLoc, 1, light_pos); } void init_data(Model& model) { mvLoc = glGetUniformLocation(program, "mv_matrix"); pLoc = glGetUniformLocation(program, "proj_matrix"); mvpLoc = glGetUniformLocation(program, "mvp_matrix"); nLoc = glGetUniformLocation(program, "normal_matrix"); useTextureLoc = glGetUniformLocation(program, "useTexture"); useMaskLoc = glGetUniformLocation(program, "useMask"); //useBumpMappingLoc = glGetUniformLocation(program, "useBumpMapping"); DiffuseLoc = glGetUniformLocation(program, "Kd"); KsLoc = glGetUniformLocation(program, "Ks"); for (int i = 0; i < model.indices.size(); ++i) { glGenVertexArrays(1, &model.indices[i].vao); glBindVertexArray(model.indices[i].vao); if (model.mats[i].useTexture) { glGenBuffers(1, &model.indices[i].vbo_vertices); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices); glBufferData(GL_ARRAY_BUFFER, model.indices[i].vertices.size() * sizeof(vec3), &model.indices[i].vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &model.indices[i].vbo_texcoords); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords); glBufferData(GL_ARRAY_BUFFER, model.indices[i].texcoords.size() * sizeof(vec2), &model.indices[i].texcoords[0], GL_STATIC_DRAW); glGenBuffers(1, &model.indices[i].vbo_normals); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals); glBufferData(GL_ARRAY_BUFFER, model.indices[i].normals.size() * sizeof(vec3), &model.indices[i].normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); } else { glGenBuffers(1, &model.indices[i].vbo_vertices); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices); glBufferData(GL_ARRAY_BUFFER, model.indices[i].vertices.size() * sizeof(vec3), &model.indices[i].vertices[0], GL_STATIC_DRAW); //glGenBuffers(1, &model.indices[i].vbo_texcoords); //glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords); //glBufferData(GL_ARRAY_BUFFER, model.indices[i].texcoords.size() * sizeof(vec2), &model.indices[i].texcoords[0], GL_STATIC_DRAW); glGenBuffers(1, &model.indices[i].vbo_normals); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals); glBufferData(GL_ARRAY_BUFFER, model.indices[i].normals.size() * sizeof(vec3), &model.indices[i].normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //glEnableVertexAttribArray(1); //glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords); //glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); } glGenBuffers(1, &model.indices[i].IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].index.size() * 4, &model.indices[i].index[0], GL_STATIC_DRAW); glUniform1i(useMaskLoc, model.mats[i].useMask); } //diffuseLoc = glGetUniformLocation(program, "DiffuseTexture"); num_mesh = model.indices.size(); } static void Draw_Model(GLFWwindow*& window, Model& model, Camera& cam) { cam.Compute_Matrix(window); mat4 mvMat = cam.vMat * cam.mMat; mat4 pMat = cam.pMat; mat4 mvpMat = pMat * mvMat;//pMat * mvpMat; mat4 nMat = transpose(inverse(mvMat)); //mat4 nMat = transpose(inverse(cam.vMat)); glUniformMatrix4fv(mvLoc, 1, GL_FALSE, value_ptr(mvMat)); glUniformMatrix4fv(pLoc, 1, GL_FALSE, value_ptr(pMat)); glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, value_ptr(mvpMat)); glUniformMatrix4fv(nLoc, 1, GL_FALSE, value_ptr(nMat)); for (int i = 0; i < model.indices.size(); ++i) { glBindVertexArray(model.indices[i].vao); /*glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_vertices); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_texcoords); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, model.indices[i].vbo_normals); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);*/ if (model.mats[i].useTexture) { glUniform1i(useTextureLoc, 1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, model.mats[i].Texture_Kd_Id); } else { glUniform1i(useTextureLoc, 0); vec3 Kd = model.mats[i].Kd; glUniform4f(DiffuseLoc, Kd.x, Kd.y, Kd.z, 1.0f); } float Ns = model.mats[i].Ns; glUniform1f(KsLoc, Ns); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, model.indices[i].IBO); glDrawElements(GL_TRIANGLES, model.indices[i].index.size(), GL_UNSIGNED_INT, 0); //int size = model.indices[i].ind.size(); //glDrawArrays(GL_TRIANGLES, start, size / 2); //start += size / 2; } //glBindVertexArray(0); } void main() { if (!glfwInit()) { exit(EXIT_FAILURE); } glewExperimental = GL_TRUE; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow* window = glfwCreateWindow(width, height, "SanMiguel", NULL, NULL); glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { exit(EXIT_FAILURE); } glfwSwapInterval(1); glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); Model model("E:\\Models_For_Rendering\\textures\\san-miguel.obj"); //Model model("E:\\a_a_Final_Model_Rendering\\bathroom_one_tube\\contemporary_bathroom.obj"); //Model model("E:\\Models\\Storm_Trooper\\helmet.obj"); //Model model("E:\\Models\\stair_case\\final_model\\StairCase_no_Carpet2.obj"); //Model model("E:\\Models\\Stanford_Bunny\\Bunny_Plane.obj"); //Model model("E:\\Models\\Material_Test_Ball\\Painter\\painter_with_light.obj"); //Model model("E:\\Models\\kitchen\\blender\\Country_Kitchen.obj"); //Model model("E:\\Models\\salle_de_bin_bath_room\\salle_de_bin\\textures\\salle_de_bain_stainless_full_wall.obj"); //Model model("E:\\Models\\Victorian_House\\blender\\Victorian_House.obj"); //Model model("E:\\Models\\BedRoom\\pbrt\\pbrt_to_obj\\pbr_to_blend_floor_texture.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom_slykdrako\\bedroom.obj"); //Model model("E:\\Models\\stair_case\\final_model\\StairCase_no_Carpet2.obj"); //Model model("E:\\Models\\blender_to_obj\\wooden_staircase\\StairCase_with_mtl.obj"); //Model model("E:\\Models\\stair_case\\original\\The Wooden Staircase BS.obj"); //Model model("E:\\Models\\coffe_maker\\coffer\\copy_coffe_maker\\final_good\\coffe_maker_modify_final_good_braun.obj"); //Model model("E:\\Models\\coffe_maker\\coffer\\coffe_maker.obj"); //Model model("E:\\Models\\blender_to_obj\\bathroom\\blender\\textures\\contemporary_bathroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bathroom\\blender\\textures\\contemporary_bathroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom_slykdrako\\bedroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom\\blender_bedroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom_interior\\slykdrako_quarto01_blender.obj"); //Model model("E:\\Models\\blender_to_obj\\wooden_staircase\\The Wooden Staircase BS.obj"); //Model model("E:\\Models\\blender_to_obj\\victorian_house\\Victorian House Blendswap.obj"); //Model model("E:\\Models\\blender_to_obj\\country_kitchen\\Country-Kitchen.obj"); //Model model("E:\\Models\\Modern_Hall\\Modern_Hall_Obj\\Hall10.obj"); //Model model("E:\\Models\\blender_to_obj\\bathroom\\blender\\textures\\contemporary_bathroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom\\bedroom.obj"); //Model model("E:\\Models\\Stanford_Dragon\\dragon.obj"); //Model model("E:\\Models\\gallery\\textures\\gallery.obj"); //Model model("E:\\Models\\blender\\coffer\\coffer.obj"); //Model model("E:\\Models\\blender\\SpaceShip\\obj\\SpaceShip.obj"); //Model model("E:\\Models\\blender\\modern_hall\\obj\\Modern_Hall.obj"); //Model model("E:\\Models_For_Rendering\\textures\\san-miguel.obj"); //Model model("E:\\Models\\RungHolt\\rungholt.obj"); //Model model("E:\\Models\\RungHolt\\house.obj"); //Model model("E:\\Models\\crytek_sponza\\textures\\crytek_sponza.obj"); //Model model("E:\\Models\\fireplace_room\\FireRoom\\fireplace_room.obj"); //Model model("E:\\Models\\fireplace_room\\fireplace_room.obj"); //Model model("E:\\Models\\salle_de_bin\\textures\\salle_de_bain.obj"); //Model model("E:\\Models\\Glass\\glass-of-water\\models\\Cup_of_Water_light.obj"); //Model model("E:\\Models\\Cornell_Box\\cornell-box.obj"); //Model model("E:\\Models\\dining_room\\blender\\The_Breakfast_Room.obj"); //Model model("E:\\Models\\sibenik\\sibenik.obj"); //Model model("E:\\Models\\dabrovic_sponza\\sponza.obj"); //Model model("E:\\Models\\Cube\\cube.obj"); //Model model("E:\\Models\\Living_Room\\living_room\\textures\\living_room.obj"); //Model model("E:\\Models\\Power_Plant\\powerplant.obj"); //Model model("E:\\Models\\SexRoom\\iscv2.obj"); //Model model("E:\\Models\\Conference_Hall\\conference.obj"); //Model model("E:\\Models\\mori_knob\\testObj.obj"); //Model model("E:\\Models\\Mitsuba\\mitsuba.obj");//pos: -0.136471, 3.496326, 2.057827 dir: 0.018116 -0.819192 -0.573234 //Model model("E:\\Models\\Mitsuba\\mitsuba-sphere.obj"); //Model model("E:\\Models\\holodeck\\holodeck.obj"); //Model model("E:\\Models\\z_blender_dom\\blender\\SpaceShip\\obj\\SpaceShip.obj"); //Model model("E:\\Models\\z_blender_dom\\blender\\coffer\\coffer.obj"); //Model model("E:\\Models\\z_blender_dom\\blender\\bedroom\\textures\\BedRoom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom_slykdrako\\bedroom.obj"); //Model model("E:\\Models\\blender_to_obj\\bedroom_slykdrako\\textures\\quarto01-cycles_2.63.obj"); //Model model("E:\\test_model\\contemporary_bathroom.obj"); //Model model("E:\\z_final_model_export\\contemporary_bathroom.obj"); //Model model("E:\\a_a_Final_Model_Rendering\\good_bath_room\\contemporary_bathroom.obj"); //Model model("E:\\a_a_Final_Model_Rendering\\bath_room\\contemporary_bathroom.obj"); //Model model("E:\\a_a_Final_Model_Rendering\\bathroom_one_tube\\contemporary_bathroom.obj"); Utility utils; //if (model.use_texture) program = utils.CreateProgram("vs.glsl", "fs.glsl"); //else // program = utils.CreateProgram("vs2.glsl", "fs2.glsl"); Camera cam(width, height); init_data(model); vec3 max_vector = model.max_vector; vec3 min_vector = model.min_vector; vec3 center = (max_vector + min_vector) * 0.5f; vec3 light_position = center;//vec3(center.x, max_vector.y + 20.0f, center.z); glUseProgram(program); init_light(program, light_position); glClearColor(0.0, 0.0, 0.0, 1.0); //cout << model.fs.size() << "\n"; //for (int i = 0; i < model.mats.size(); ++i) //cout << model.mats[i].Kd.x << " " << model.mats[i].Kd.y << " " << model.mats[i].Kd.z << "\n"; model.Clear_Before_Render(); float px, py, pz; float dx, dy, dz; while (!glfwWindowShouldClose(window)) { glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); //string str = "Pos: " + std::to_string(cam.p.x) + "," + std::to_string(cam.p.y) + "," + std::to_string(cam.p.z) // + " direction: " + to_string(cam.d.x) + " " + to_string(cam.d.y) + " " + to_string(cam.d.z); px = cam.p.x; py = cam.p.y; pz = cam.p.z; dx = cam.d.x; dy = cam.d.y; dz = cam.d.z; //glfwSetWindowTitle(window, str.c_str()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw_Model(window, model, cam); glfwSwapBuffers(window); glfwPollEvents(); } ofstream ofs("coordinate2.txt"); //ofs << "pos: " << cam.p.x << " " << cam.p.y << " " << cam.p.z << "\n"; //ofs << "direction: " << cam.d.x << " " << cam.d.y << " " << cam.d.z << "\n"; ofs << "pos: " << px << " " << py << " " << pz << "\n"; ofs << "direction: " << dx << " " << dy << " " << dz << "\n"; getchar(); model.ClearMemory(); for (int i = 0; i < model.mats.size(); ++i) { glBindVertexArray(0); glDeleteVertexArrays(1, &model.indices[i].vao); glBindBuffer(model.indices[i].vbo_vertices, 0); glDeleteBuffers(1, &model.indices[i].vbo_vertices); glBindBuffer(model.indices[i].vbo_texcoords, 0); glDeleteBuffers(1, &model.indices[i].vbo_texcoords); glBindBuffer(model.indices[i].vbo_normals, 0); glDeleteBuffers(1, &model.indices[i].vbo_normals); } for (int i = 0; i < model.indices.size(); ++i) { glBindBuffer(model.indices[i].IBO, 0); } for (int i = 0; i < model.mats.size(); ++i) { glDeleteTextures(1, &model.mats[i].Texture_Kd_Id); } //glBindBuffer(ibo, 0); } /* void main() { Model model; model.Read_Material("E:\\a_Sang_Ray_Tracing\\Models\\bathroom\\bathroom_obj\\textures\\bathroom.mtl"); for (auto& v : model.material_map) { cout << v.first << " " << v.second << "\n"; } model.Read_Model("E:\\a_Sang_Ray_Tracing\\Models\\bathroom\\bathroom_obj\\textures\\bathroom.obj"); int mtl_size = model.mats.size(); for (int i = 0; i < mtl_size; ++i) { cout << " mtl " << i << " " << model.mats[i].name << " "; cout << model.indices[i].ind.size() << "\n"; } getchar(); } */ /* void main() { //Model model("E:\\Models\\crytek_sponza\\textures\\crytek_sponza.obj"); Model model("E:\\Models\\sibenik\\sibenik.obj"); //cout << model.vertices.size() << "\n"; //getchar(); } */
31.579655
134
0.68328
[ "mesh", "model" ]
9e88727ef55b7ad916e56ab6578afbbccbaf7e70
1,241
cpp
C++
ch11/ex11_21.cpp
forevermzm/Cpp-Primer
0f149707451d50738677d9194cb701af53e99934
[ "CC0-1.0" ]
2
2015-06-11T17:50:41.000Z
2017-01-23T09:37:56.000Z
ch11/ex11_21.cpp
forevermzm/Cpp-Primer
0f149707451d50738677d9194cb701af53e99934
[ "CC0-1.0" ]
null
null
null
ch11/ex11_21.cpp
forevermzm/Cpp-Primer
0f149707451d50738677d9194cb701af53e99934
[ "CC0-1.0" ]
1
2018-10-23T09:43:12.000Z
2018-10-23T09:43:12.000Z
//! @Alan //! //! Exercise 11.21: //! Assuming word_count is a map from string to size_t and word is a string, //! explain the following loop: //! while (cin >> word) //! ++word_count.insert({word, 0}).first->second; //! #include <iostream> #include <map> #include <string> #include <algorithm> #include <set> #include <vector> #include <iterator> int main() { std::map<std::string, size_t> word_count; std::string word; while(std::cin >> word) { /* //! insert the pair {word,0} into the map and get the iterator. auto it = word_count.insert({word,0}); //! check if the pair is inserted //! if not, increment the value of the key-value of the pair if(!it.second) ++it.first->second; */ ++word_count.insert({word, 0}).first->second; //! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //! similiar to the codes above it, but more accurate and efficient //! the increment operator "++" is excuted as ++ (word_count.insert({word, 0}).first->second) //! print the content of the map. for(auto e : word_count) std::cout << e.first << " " << e.second << "\n"; } return 0; }
26.978261
97
0.546334
[ "vector" ]
9e8bdbc5f13be921939cf01e305332811ff659e7
1,580
cpp
C++
src/engine/render_debug_system.cpp
hxhieu/32blit-hello
a44aa10291b54d9b0211f41e9a314b2f11235ac2
[ "MIT" ]
null
null
null
src/engine/render_debug_system.cpp
hxhieu/32blit-hello
a44aa10291b54d9b0211f41e9a314b2f11235ac2
[ "MIT" ]
null
null
null
src/engine/render_debug_system.cpp
hxhieu/32blit-hello
a44aa10291b54d9b0211f41e9a314b2f11235ac2
[ "MIT" ]
null
null
null
#include "render_debug_system.h" namespace mitmeo { namespace engine { RenderDebugSystem::RenderDebugSystem() {} void RenderDebugSystem::run(entt::registry &world, uint32_t time_ms) { // Debug pen blit::screen.pen = blit::Pen(0, 255, 0, 200); auto debug = world.view<components::Collider, components::Position>(); std::vector<blit::Rect> colliders = std::vector<blit::Rect>{}; for (auto e : debug) { auto &c = debug.get<components::Collider>(e); auto &p = debug.get<components::Position>(e); auto r = blit::Rect{ p.x + (int32_t)c.x, p.y + (int32_t)c.y, (int32_t)c.w, (int32_t)c.h}; // Draw origins blit::screen.line(blit::Point(p.x - 2, p.y), blit::Point(p.x + 2, p.y)); blit::screen.line(blit::Point(p.x, p.y - 2), blit::Point(p.x, p.y + 2)); // Draw colliders blit::screen.line(blit::Point(r.x - r.w / 2, r.y - r.h / 2), blit::Point(r.x + r.w / 2, r.y - r.h / 2)); blit::screen.line(blit::Point(r.x - r.w / 2, r.y + r.h / 2), blit::Point(r.x + r.w / 2, r.y + r.h / 2)); blit::screen.line(blit::Point(r.x - r.w / 2, r.y - r.h / 2), blit::Point(r.x - r.w / 2, r.y + r.h / 2)); blit::screen.line(blit::Point(r.x + r.w / 2, r.y - r.h / 2), blit::Point(r.x + r.w / 2, r.y + r.h / 2)); } } }; }
40.512821
120
0.459494
[ "vector" ]
9e904be7b22b400847a493dbffec1c0b083b023f
651
hpp
C++
kernel/driver/input/InputHandler.hpp
boulangg/phoenix
d14928ebaf8b2546e00d407c239f28c3e929181e
[ "MIT" ]
3
2016-04-22T13:29:08.000Z
2016-04-25T15:56:23.000Z
kernel/driver/input/InputHandler.hpp
boulangg/phoenix
d14928ebaf8b2546e00d407c239f28c3e929181e
[ "MIT" ]
null
null
null
kernel/driver/input/InputHandler.hpp
boulangg/phoenix
d14928ebaf8b2546e00d407c239f28c3e929181e
[ "MIT" ]
null
null
null
#pragma once #include <list> #include <vector> #include "InputEventCode.hpp" class InputDevice; class InputHandler { public: InputHandler() : _devices() { } virtual ~InputHandler() { } virtual void handleEvents(const std::vector<InputValue>& vals) = 0; //bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value); //bool (*match)(struct input_handler *handler, struct input_dev *dev); virtual int connect(InputDevice *dev, const struct input_device_id *id); virtual void disconnect(InputDevice *handle); //virtual void (*start)(struct input_handle *handle); std::list<InputDevice*> _devices; };
21.7
96
0.731183
[ "vector" ]
9e96ed7185150d90ba2fd0e4e498c98e5b63bad6
4,881
cpp
C++
tools/code_snippets/Measurement/realtimemultisamplearray.cpp
fjpolo/mne-cpp
fe5ce28680dbcfc3cd2e24954e31a5bf0531f28d
[ "BSD-3-Clause" ]
1
2021-05-18T08:33:44.000Z
2021-05-18T08:33:44.000Z
tools/code_snippets/Measurement/realtimemultisamplearray.cpp
yvnxs/mne-cpp
29c90a86f49c843b5f0ca8f9180cb38e0e774176
[ "BSD-3-Clause" ]
null
null
null
tools/code_snippets/Measurement/realtimemultisamplearray.cpp
yvnxs/mne-cpp
29c90a86f49c843b5f0ca8f9180cb38e0e774176
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file realtimemultisamplearray.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date February, 2013 * * @section LICENSE * * Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Contains the implementation of the RealTimeMultiSampleArray class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "realtimemultisamplearray.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace XMEASLIB; //using namespace IOBuffer; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RealTimeMultiSampleArray::RealTimeMultiSampleArray(unsigned int uiNumChannels) : SngChnMeasurement() , m_dMinValue(0) , m_dMaxValue(65535) , m_dSamplingRate(0) , m_qString_Unit("") , m_uiNumChannels(uiNumChannels) , m_ucMultiArraySize(10) { } //************************************************************************************************************* RealTimeMultiSampleArray::~RealTimeMultiSampleArray() { } //************************************************************************************************************* QVector<double> RealTimeMultiSampleArray::getVector() const { return m_vecValue; } //************************************************************************************************************* void RealTimeMultiSampleArray::setVector(QVector<double> v) { if(v.size() != int(m_uiNumChannels)) qDebug() << "Error Occured in RealTimeMultiSampleArray::setVector: Vector size does not matche the number of channels! "; for(QVector<double>::iterator it = v.begin(); it != v.end(); ++it) { if(*it < m_dMinValue) *it = m_dMinValue; else if(*it > m_dMaxValue) *it = m_dMaxValue; } m_vecValue = v; m_matSamples.push_back(m_vecValue); if(m_matSamples.size() >= m_ucMultiArraySize && notifyEnabled) { notify(); m_matSamples.clear(); } }
41.717949
129
0.467527
[ "vector" ]
9e98e2b890a3178fbaa2c56840c7be68b8516c67
590
cpp
C++
Lectura.cpp
Apih97/NominaH
6b7febf8b9fcbf1961ffe7a27cc5b41372c7d99a
[ "PostgreSQL", "MIT" ]
null
null
null
Lectura.cpp
Apih97/NominaH
6b7febf8b9fcbf1961ffe7a27cc5b41372c7d99a
[ "PostgreSQL", "MIT" ]
null
null
null
Lectura.cpp
Apih97/NominaH
6b7febf8b9fcbf1961ffe7a27cc5b41372c7d99a
[ "PostgreSQL", "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <fstream> #include <direct.h> #include <ctime> #include <windows.h> using namespace std; int main (){ HWND consoleWindow = GetConsoleWindow(); SetWindowPos( consoleWindow, 0, 10, 10, 0, 0, SWP_NOSIZE | SWP_NOZORDER ); system("color B"); system("mode con: cols=40 lines=30"); string lectura; ifstream lista; cout<<"Lista de archivos"<<endl; lista.open("ArchivosTotal.txt",ios::in); while(!lista.eof()){ getline(lista,lectura); cout<<endl; cout<<" + "<<lectura; } lista.close(); system("pause"); return 0; }
16.388889
75
0.661017
[ "vector" ]
9eaa7aa63d4e524136fd4fcade1443711b7b5bf5
16,860
cpp
C++
yoloconvertor/src/main_fusion.cpp
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
1
2022-03-07T06:24:27.000Z
2022-03-07T06:24:27.000Z
yoloconvertor/src/main_fusion.cpp
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
null
null
null
yoloconvertor/src/main_fusion.cpp
VisualComputingInstitute/CROWDBOT_perception
df98f3f658c39fb3fa4ac0456f1214f7918009f6
[ "MIT" ]
null
null
null
// ROS includes. #include <ros/ros.h> #include <ros/time.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <string.h> #include <cmath> #include <algorithm> // std::min_element, std::max_element #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <rwth_perception_people_msgs/GroundPlane.h> #include <frame_msgs/DetectedPersons.h> #include "Matrix.h" #include "Vector.h" using namespace std; using namespace message_filters; using namespace rwth_perception_people_msgs; using namespace frame_msgs; tf::TransformListener* listener; ros::Publisher pub_detected_persons; double worldScale; // for computing 3D positions from BBoxes int detection_id_increment, detection_id_offset, current_detection_id; // added for multi-sensor use in SPENCER double pose_variance; // used in output frame_msgs::DetectedPerson.pose.covariance double overlap_thresh; // used in detecting overlapping, default value is 0.5 string world_frame; /* subscrible: tf: 3 detected person: publish: 1 detection person */ void transfer_detected_persons_to_world_cord(const DetectedPersonsConstPtr &sub_dp, DetectedPersons &pub_dp, string camera_frame) { ros::Time detection_time(sub_dp->header.stamp); tf::StampedTransform transform; try { listener->waitForTransform(world_frame, camera_frame, detection_time, ros::Duration(1.0)); listener->lookupTransform(world_frame,camera_frame,detection_time, transform); //from camera_frame to world_frame // it may cannot find the tf in exact the same time as the input image.. so, maybe someway, lets see } catch (tf::TransformException ex){ ROS_WARN_THROTTLE(20.0, "Failed transform lookup in camera frame to world frame", ex.what()); } for(unsigned int i=0;i<(sub_dp->detections.size());i++) { // only process the 3d pose. // get its tf, and do transformation // other things are the same with the dp_left // questions. about the detection id... DetectedPerson detected_person(sub_dp->detections[i]); tf::Vector3 pos_vector_in_camera(detected_person.pose.pose.position.x, detected_person.pose.pose.position.y, detected_person.pose.pose.position.z); tf::Vector3 pos_vector_in_world = transform*pos_vector_in_camera; // may need from world to camera, lets see. Vector<double> pos3D; pos3D.setSize(3); pos3D[0] = pos_vector_in_world.getX(); pos3D[1] = pos_vector_in_world.getY(); pos3D[2] = pos_vector_in_world.getZ(); detected_person.pose.pose.position.x = pos3D(0); detected_person.pose.pose.position.y = pos3D(1); detected_person.pose.pose.position.z = pos3D(2); Matrix<double> rotation; Matrix<double> covariance; covariance.set_size(3,3,0.0); rotation.set_size(3,3,0.0); covariance(0,0) = detected_person.pose.covariance[0]; //0.05; covariance(1,1) = detected_person.pose.covariance[7];//0.05; covariance(2,2) = detected_person.pose.covariance[14];//0.05; covariance(0,1) = detected_person.pose.covariance[6];//0; covariance(0,2) = detected_person.pose.covariance[12];//0; covariance(1,0) = detected_person.pose.covariance[1];//0; covariance(1,2) = detected_person.pose.covariance[13];//0; covariance(2,0) = detected_person.pose.covariance[2];//0; covariance(2,1) = detected_person.pose.covariance[8];//0; tf::Quaternion rot_q = transform.getRotation(); tf::Matrix3x3 rot(rot_q); rotation(0,0) = rot.getColumn(0).getX(); rotation(0,1) = rot.getColumn(0).getY(); rotation(0,2) = rot.getColumn(0).getZ(); rotation(1,0) = rot.getColumn(1).getX(); rotation(1,1) = rot.getColumn(1).getY(); rotation(1,2) = rot.getColumn(1).getZ(); rotation(2,0) = rot.getColumn(2).getX(); rotation(2,1) = rot.getColumn(2).getY(); rotation(2,2) = rot.getColumn(2).getZ(); //std::cout << "cov before:" << std::endl; //covariance.Show(); covariance = rotation*covariance; rotation.Transpose(); covariance = covariance*rotation; //std::cout << "cov after:" << std::endl; //covariance.Show(); detected_person.pose.covariance[0] = covariance(0,0); //0.05; detected_person.pose.covariance[7] = covariance(1,1);//0.05; detected_person.pose.covariance[14] = covariance(2,2);//0.05; detected_person.pose.covariance[6] = covariance(0,1);//0; detected_person.pose.covariance[12] = covariance(0,2);//0; detected_person.pose.covariance[1] = covariance(1,0);//0; detected_person.pose.covariance[13] = covariance(1,2);//0; detected_person.pose.covariance[2] = covariance(2,0);//0; detected_person.pose.covariance[8] = covariance(2,1);//0; // additional nan check if(!std::isnan(detected_person.pose.pose.position.x) && !std::isnan(detected_person.pose.pose.position.y) && !std::isnan(detected_person.pose.pose.position.z)){ pub_dp.detections.push_back(detected_person); }else{ ROS_DEBUG("A detection has been discarded because of nan values during fusion!"); } } } bool is_overlaping(const DetectedPerson& dp1,const DetectedPerson& dp2) { Vector<double> pos1; Vector<double> pos2; pos1.setSize(3); pos2.setSize(3); pos1[0] = dp1.pose.pose.position.x; pos1[1] = dp1.pose.pose.position.y; pos1[2] = dp1.pose.pose.position.z; pos2[0] = dp2.pose.pose.position.x; pos2[1] = dp2.pose.pose.position.y; pos2[2] = dp2.pose.pose.position.z; bool flag = false; if((pos1 - pos2).norm() < overlap_thresh ) // set 0.05, if two people is closer than 5 cm, we say they should be exactly the same person flag = true; else flag = false; return flag; } bool compare_stamp(ros::Time & i, ros::Time& j) { return i.toSec()<j.toSec(); } void add_new_camera_detection(DetectedPersons& dps_new, DetectedPersons& dps_dst) { // it should only compare with the first k dps_dst's elements, which means all detection from the original camera size_t k = dps_dst.detections.size(); // a k size index vector, to indicate if this index's detection in dps_dst has been replaced, // if it has been raplaced, which means now the detection in dps_dst is from the new camera. // since we don't want to replace detetions from the same camera. // so In this case we will simply push_back the new detection into dps_dst, but not replace the one in dps_dst. // true: can replace // false: don't replace std::vector<bool> index(k,true); for(int i=0;i<dps_new.detections.size();++i) { DetectedPerson new_det(dps_new.detections[i]); // we have actually 3 cases for each detection from dps_new: // 1. the new det overlapping and better and can replace the det in dps_dst -> replace // 2. the new det overlapping and better but cannot replace the det in dps_dst-> push_back // 3. the new det not overlapping -> push_back // 4. throw away this detetction. bool overlaping_flag(false); bool better_det_flag(false); bool replace_flag(false); // it should only compare with the first k dps_dst's elements, which are come from the first camera for(int j=0;j<k;++j) { if(is_overlaping(new_det,dps_dst.detections[j])) { overlaping_flag = true; // if this new detection from this camera is better, replace the original one by this new_det if(new_det.confidence > dps_dst.detections[j].confidence) { better_det_flag = true; // see if we can replace it if(index[j]) { dps_dst.detections[j] = new_det; // if we have replaced, we should simply go to the next detection in new camera( go to the next iteration in out loop) replace_flag = true; break; } } } } if(replace_flag) // case 1 { continue; } else if(overlaping_flag && better_det_flag) //case 2 { dps_dst.detections.push_back(new_det); } else if(!overlaping_flag) //case 3 { dps_dst.detections.push_back(new_det); } } } void combine_three_camera_detection(DetectedPersons& dps0, DetectedPersons& dps1, DetectedPersons& dps2, DetectedPersons& dps_dst) { // again use greedy method // we first deal with the camera 0 for(int i = 0;i<dps0.detections.size();++i) { // since there is no detection from other camera, we see every detection here as best detection and push_back. dps_dst.detections.push_back(dps0.detections[i]); } //camera 1 add_new_camera_detection(dps1,dps_dst); //camera 2 add_new_camera_detection(dps2,dps_dst); // now re assign detection ID for(int i=0;i<dps_dst.detections.size();++i) { dps_dst.detections[i].detection_id = current_detection_id; current_detection_id += detection_id_increment; } } void yolofusioncallback(const DetectedPersonsConstPtr &dp_left, const DetectedPersonsConstPtr &dp_right, const DetectedPersonsConstPtr &dp_rear ) { // debug output, to show latency from yolo_v3 //ROS_DEBUG_STREAM("current time:" << ros::Time::now()); if(pub_detected_persons.getNumSubscribers()) { // these three DetectedPersons are in world frame frame_msgs::DetectedPersons left_detected_persons; frame_msgs::DetectedPersons right_detected_persons; frame_msgs::DetectedPersons rear_detected_persons; transfer_detected_persons_to_world_cord(dp_left, left_detected_persons, dp_left->header.frame_id); transfer_detected_persons_to_world_cord(dp_right, right_detected_persons, dp_right->header.frame_id); transfer_detected_persons_to_world_cord(dp_rear, rear_detected_persons, dp_rear->header.frame_id); // three modification // 1. only do this remove overlapping between camera and camera // 2. when overlapping happen, take the highest confidence detection // 3. use an arg, not a constant value as overlap_thresh. // remove the overlaping detection frame_msgs::DetectedPersons detected_persons; // reserve enough memory for this final detected_persons msg. detected_persons.detections.reserve(left_detected_persons.detections.size()+right_detected_persons.detections.size()+rear_detected_persons.detections.size()); combine_three_camera_detection(left_detected_persons,right_detected_persons,rear_detected_persons, detected_persons); // this is for using std::max_element to get the latest time stamp std::vector<ros::Time> stamp_vec; stamp_vec.push_back(dp_left->header.stamp); stamp_vec.push_back(dp_right->header.stamp); stamp_vec.push_back(dp_rear->header.stamp); detected_persons.header.stamp = *std::max_element(stamp_vec.begin(),stamp_vec.end(),compare_stamp); detected_persons.header.frame_id = world_frame; // Publish pub_detected_persons.publish(detected_persons); } } // Connection callback that unsubscribes from the tracker if no one is subscribed. void connectCallback(ros::Subscriber &sub_msg, ros::NodeHandle &n, Subscriber<DetectedPersons> &sub_dp_left, Subscriber<DetectedPersons> &sub_dp_right, Subscriber<DetectedPersons> &sub_dp_rear){ if(!pub_detected_persons.getNumSubscribers()) { ROS_DEBUG("yoloconvertor: No subscribers. Unsubscribing."); sub_msg.shutdown(); sub_dp_left.unsubscribe(); sub_dp_rear.unsubscribe(); sub_dp_right.unsubscribe(); } else { ROS_DEBUG("yoloconvertor: New subscribers. Subscribing."); sub_dp_left.subscribe(); sub_dp_right.subscribe(); sub_dp_rear.subscribe(); } } int main(int argc, char **argv) { // Set up ROS. ros::init(argc, argv, "fuse_yolo"); ros::NodeHandle n; // create a tf listener listener = new tf::TransformListener(); // Declare variables that can be modified by launch file or command line. int queue_size; string detected_persons_left; string detected_persons_right; string detected_persons_rear; string pub_topic_detected_persons; // Initialize node parameters from launch file or command line. // Use a private node handle so that multiple instances of the node can be run simultaneously // while using different parameters. ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("queue_size", queue_size, int(10)); private_node_handle_.param("detected_persons_left", detected_persons_left, string("oops!need param for left")); private_node_handle_.param("detected_persons_right", detected_persons_right, string("oops!need param for right")); private_node_handle_.param("detected_persons_rear", detected_persons_rear, string("oops!need param for rear")); // For SPENCER DetectedPersons message private_node_handle_.param("world_scale", worldScale, 1.0); // default for ASUS sensors private_node_handle_.param("detection_id_increment", detection_id_increment, 1); private_node_handle_.param("detection_id_offset", detection_id_offset, 0); private_node_handle_.param("pose_variance", pose_variance, 0.05); private_node_handle_.param("overlap_thresh", overlap_thresh, 0.50); //this overlap_thresh is for overlapping detection private_node_handle_.param("world_frame", world_frame, string("/robot/OdometryFrame")); current_detection_id = detection_id_offset; // Create a subscriber. // Name the topic, message queue, callback function with class name, and object containing callback function. // Set queue size to 1 because generating a queue here will only pile up images and delay the output by the amount of queued images ros::Subscriber sub_message; //Subscribers have to be defined out of the if scope to have affect. Subscriber<DetectedPersons> subscriber_detected_persons_left(n, detected_persons_left.c_str(), 1); subscriber_detected_persons_left.unsubscribe(); Subscriber<DetectedPersons> subscriber_detected_persons_right(n, detected_persons_right.c_str(),1); subscriber_detected_persons_right.unsubscribe(); Subscriber<DetectedPersons> subscriber_detected_persons_rear(n, detected_persons_rear.c_str(),1); subscriber_detected_persons_rear.unsubscribe(); ros::SubscriberStatusCallback con_cb = boost::bind(&connectCallback, boost::ref(sub_message), boost::ref(n), boost::ref(subscriber_detected_persons_left), boost::ref(subscriber_detected_persons_right), boost::ref(subscriber_detected_persons_rear)); //The real queue size for synchronisation is set here. sync_policies::ApproximateTime<DetectedPersons,DetectedPersons, DetectedPersons> MySyncPolicy(queue_size); MySyncPolicy.setAgePenalty(1000); //set high age penalty to publish older data faster even if it might not be correctly synchronized. const sync_policies::ApproximateTime<DetectedPersons, DetectedPersons, DetectedPersons> MyConstSyncPolicy = MySyncPolicy; Synchronizer< sync_policies::ApproximateTime<DetectedPersons, DetectedPersons, DetectedPersons> > sync(MyConstSyncPolicy, subscriber_detected_persons_left, subscriber_detected_persons_right, subscriber_detected_persons_rear); sync.registerCallback(boost::bind(&yolofusioncallback, _1, _2, _3)); // Create publishers private_node_handle_.param("total_detected_persons", pub_topic_detected_persons, string("/total_detected_persons")); pub_detected_persons = n.advertise<frame_msgs::DetectedPersons>(pub_topic_detected_persons, 10, con_cb, con_cb); ros::spin(); return 0; }
42.683544
168
0.667734
[ "object", "vector", "transform", "3d" ]
9eabfbd6612302f42dd8489652b4489502a7827a
8,574
cpp
C++
Blizzlike/ArcEmu/C++/SpellHandlers/RogueSpells.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/SpellHandlers/RogueSpells.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/SpellHandlers/RogueSpells.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcScript Scripts for Arcemu MMORPG Server * Copyright (C) 2008-2011 Arcemu Team * Copyright (C) 2007 Moon++ <http://www.moonplusplus.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" //Alice : Correct formula for Rogue - Preparation bool Preparation(uint32 i, Spell* pSpell) { if(!pSpell->p_caster) return true; pSpell->p_caster->ClearCooldownForSpell(5277); // Evasion Rank 1 pSpell->p_caster->ClearCooldownForSpell(26669); // Evasion Rank 2 pSpell->p_caster->ClearCooldownForSpell(2983); // Sprint Rank 1 pSpell->p_caster->ClearCooldownForSpell(8696); // Sprint Rank 2 pSpell->p_caster->ClearCooldownForSpell(11305); // Sprint Rank 3 pSpell->p_caster->ClearCooldownForSpell(1856); // Vanish Rank 1 pSpell->p_caster->ClearCooldownForSpell(1857); // Vanish Rank 2 pSpell->p_caster->ClearCooldownForSpell(26889); // Vanish Rank 3 pSpell->p_caster->ClearCooldownForSpell(14177); // Cold Blood pSpell->p_caster->ClearCooldownForSpell(36554); // Shadowstep if(pSpell->p_caster->HasAura(56819)) // Glyph of Preparation item = 42968 casts 57127 that apply aura 56819. { pSpell->p_caster->ClearCooldownForSpell(13877); // Blade Flurry pSpell->p_caster->ClearCooldownForSpell(51722); // Dismantle pSpell->p_caster->ClearCooldownForSpell(1766); // Kick } return true; } bool Shiv(uint32 i, Spell* pSpell) { Unit* pTarget = pSpell->GetUnitTarget(); if(!pSpell->p_caster || !pTarget) return true; pSpell->p_caster->CastSpell(pTarget->GetGUID(), 5940, true); Item* it = pSpell->p_caster->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_OFFHAND); if(!it) return true; EnchantmentInstance* ench = it->GetEnchantment(TEMP_ENCHANTMENT_SLOT); if(ench) { EnchantEntry* Entry = ench->Enchantment; for(uint32 c = 0; c < 3; c++) { if(Entry->type[c] && Entry->spell[c]) { SpellEntry* sp = dbcSpell.LookupEntry(Entry->spell[c]); if(!sp) return true; if(sp->c_is_flags & SPELL_FLAG_IS_POISON) { pSpell->p_caster->CastSpell(pTarget->GetGUID(), Entry->spell[c], true); } } } } return true; } bool ImprovedSprint(uint32 i, Spell* pSpell) { if(i == 0) { Unit* target = pSpell->GetUnitTarget(); if(target == NULL) return true; target->RemoveAllAurasByMechanic(MECHANIC_ENSNARED, -1, true); target->RemoveAllAurasByMechanic(MECHANIC_ROOTED, -1, true); } return true; } bool CutToTheChase(uint32 i, Aura* pAura, bool apply) { Unit* target = pAura->GetTarget(); if(apply) { static uint32 classMask[3] = { 0x20000, 0x8, 0 }; target->AddProcTriggerSpell(pAura->GetSpellProto(), pAura->GetSpellProto(), pAura->m_casterGuid, pAura->GetSpellProto()->procChance, PROC_ON_CAST_SPELL | PROC_TARGET_SELF, 0, NULL, classMask); } else target->RemoveProcTriggerSpell(pAura->GetSpellId(), pAura->m_casterGuid); return true; } bool DeadlyBrew(uint32 i, Aura* pAura, bool apply) { Unit* target = pAura->GetTarget(); if(apply) { static uint32 classMask[3] = { 0x1000A000, 0, 0 }; target->AddProcTriggerSpell(pAura->GetSpellProto(), pAura->GetSpellProto(), pAura->m_casterGuid, pAura->GetSpellProto()->procChance, PROC_ON_CAST_SPELL , 0, NULL, classMask); } else target->RemoveProcTriggerSpell(pAura->GetSpellId(), pAura->m_casterGuid); return true; } bool CloakOfShadows(uint32 i, Spell* s) { Unit* unitTarget = s->GetUnitTarget(); if(!unitTarget || !unitTarget->isAlive()) return false; Aura* pAura; for(uint32 j = MAX_NEGATIVE_AURAS_EXTEDED_START; j < MAX_NEGATIVE_AURAS_EXTEDED_END; ++j) { pAura = unitTarget->m_auras[j]; if(pAura != NULL && !pAura->IsPassive() && !pAura->IsPositive() && !(pAura->GetSpellProto()->Attributes & ATTRIBUTES_IGNORE_INVULNERABILITY) && pAura->GetSpellProto()->School != 0 ) pAura->Remove(); } return true; } bool CheatDeath(uint32 i, Aura* a, bool apply) { Unit* u_target = a->GetTarget(); Player* p_target = NULL; if(u_target->IsPlayer()) p_target = TO_PLAYER(u_target); if(p_target != NULL) { int32 m = (int32)(8.0f * p_target->CalcRating(PLAYER_RATING_MODIFIER_MELEE_CRIT_RESILIENCE)); if(m > 90) m = 90; float val; if(apply) { a->SetPositive(); val = - m / 100.0f; } else { val = m / 100.0f; } for(uint32 x = 0; x < 7; x++) p_target->DamageTakenPctMod[x] += val; } return true; } bool MasterOfSubtlety(uint32 i, Aura* a, bool apply) { Unit* u_target = a->GetTarget(); if(!u_target->IsPlayer()) return true; Player* p_target = TO_PLAYER(u_target); int32 amount = a->GetModAmount(i); if(apply) { p_target->m_outStealthDamageBonusPct += amount; p_target->m_outStealthDamageBonusPeriod = 6; // 6 seconds p_target->m_outStealthDamageBonusTimer = 0; // reset it } else { p_target->m_outStealthDamageBonusPct -= amount; p_target->m_outStealthDamageBonusPeriod = 6; // 6 seconds p_target->m_outStealthDamageBonusTimer = 0; // reset it } return true; } bool PreyOnTheWeakPeriodicDummy(uint32 i, Aura* a, bool apply) { Unit* m_target = a->GetTarget(); Player* p_target = NULL; if(!apply) return true; if(m_target->IsPlayer()) p_target = TO_PLAYER(m_target); if(p_target != NULL && p_target->getClass() == ROGUE) { Unit* target = p_target->GetMapMgr()->GetUnit(p_target->GetTarget()); if(target == NULL) return true; uint32 plrHP = p_target->GetHealth(); uint32 targetHP = target->GetHealth(); if(plrHP > targetHP) p_target->CastSpell(p_target, 58670, true); } return true; } bool KillingSpreePeriodicDummy(uint32 i, Aura* a, bool apply) { Unit* m_target = a->GetTarget(); if(!m_target->IsPlayer()) return true; Player* p_target = TO_PLAYER(m_target); //Find targets around aura's target in range of 10 yards. //It can hit same target multiple times. for(std::set<Object*>::iterator itr = p_target->GetInRangeSetBegin(); itr != p_target->GetInRangeSetEnd(); ++itr) { //Get the range of 10 yards from Effect 1 float r = static_cast< float >( a->m_spellProto->EffectRadiusIndex[1] ); //float r = ::GetRadius(dbcSpellRadius.LookupEntryForced(a->m_spellProto->EffectRadiusIndex[1])); LocationVector source = p_target->GetPosition(); float dist = (*itr)->CalcDistance(source); //Radius check if(dist <= r) { //Avoid targeting anything that is not unit and not alive if(!(*itr)->IsUnit() || !TO_UNIT((*itr))->isAlive()) continue; uint64 spellTarget = (*itr)->GetGUID(); //SPELL_EFFECT_TELEPORT p_target->CastSpell(spellTarget, 57840, true); //SPELL_EFFECT_NORMALIZED_WEAPON_DMG and triggering 57842 with the same effect p_target->CastSpell(spellTarget, 57841, true); } } return true; } bool KillingSpreeEffectDummy(uint32 i, Spell* s) { Player* p_caster = s->p_caster; if(p_caster == NULL) return true; //SPELL_EFFECT_BREAK_PLAYER_TARGETING //and applying 20% SPELL_AURA_MOD_DAMAGE_PERCENT_DONE p_caster->CastSpell(p_caster, 61851, true); return true; } void SetupRogueSpells(ScriptMgr* mgr) { mgr->register_dummy_spell(5938, &Shiv); mgr->register_dummy_spell(14185, &Preparation); mgr->register_dummy_spell(30918, &ImprovedSprint); uint32 CutToTheChaseIds[] = { 51664, 51665, 51667, 51668, 51669, 0 }; mgr->register_dummy_aura(CutToTheChaseIds, &CutToTheChase); mgr->register_dummy_aura(51625, &DeadlyBrew); mgr->register_dummy_aura(51626, &DeadlyBrew); mgr->register_dummy_spell(35729, &CloakOfShadows); mgr->register_dummy_aura(45182, &CheatDeath); uint32 masterofsubtletyids[] = { 31223, 31222, 31221, 0 }; mgr->register_dummy_aura(masterofsubtletyids, &MasterOfSubtlety); uint32 preyontheweakids[] = { 51685, 51686, 51687, 51688, 51689, 0 }; mgr->register_dummy_aura(preyontheweakids, &PreyOnTheWeakPeriodicDummy); mgr->register_dummy_aura(51690, &KillingSpreePeriodicDummy); mgr->register_dummy_spell(51690, &KillingSpreeEffectDummy); }
26.381538
194
0.700373
[ "object" ]
9eb34cb7c2ed3de9d0e7dc22029838272d260954
10,642
cpp
C++
OCLApp3/GaussianFilter/Program.cpp
zzyzy/OCLPlayground
e62ecddf4873df262238463980dede16ca4bc399
[ "MIT" ]
2
2017-10-22T07:05:20.000Z
2022-03-10T20:28:13.000Z
OCLApp3/GaussianFilter/Program.cpp
zzyzy/OCLPlayground
e62ecddf4873df262238463980dede16ca4bc399
[ "MIT" ]
null
null
null
OCLApp3/GaussianFilter/Program.cpp
zzyzy/OCLPlayground
e62ecddf4873df262238463980dede16ca4bc399
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <unordered_map> #include <CL/cl.hpp> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #include "OCLUtils.h" #include "Filters.h" #define CL_FILENAME "Convolution.cl" #define INPUT_IMAGE_FILENAME "Input/bunnycity1.bmp" #define SIMPLE_CONVOLUTION_KERNEL "SimpleConvolution" #define ONE_PASS_CONVOLUTION_KERNEL "OnePassConvolution" #define VENDOR_INTEL "Intel" #define VENDOR_AMD "Advanced Micro Devices" #define VENDOR_NVIDIA "NVIDIA" #define SELECTED_VENDOR VENDOR_INTEL int main() { cl_int err; // ============================================================== // // Setup OCL Context // // ============================================================== cl::Device device = GetDevice(SELECTED_VENDOR); cl::Context context = MakeContext(device); cl::CommandQueue queue = MakeCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE); std::vector<const char*> sourceFileNames; sourceFileNames.push_back(CL_FILENAME); cl::Program program = MakeAndBuildProgram(sourceFileNames, context, device); std::unordered_map<std::string, cl::Kernel> kernels = MakeKernels(program); // ============================================================== // // Handle user input // // ============================================================== int filterSize = 7; std::cout << "Gaussian filter window size? (3/5/7)" << std::endl; std::cin >> filterSize; while (filterSize != 3 && filterSize != 5 && filterSize != 7) { std::cout << "Invalid input. Try again." << std::endl; std::cout << "Gaussian filter window size? (3/5/7)" << std::endl; std::cin >> filterSize; } // ============================================================== // // Create buffers for image data // // ============================================================== int w, h, n; unsigned char* inputImage = stbi_load(INPUT_IMAGE_FILENAME, &w, &h, &n, 4); unsigned char* outputImage = new unsigned char[w * h * 4]; cl::size_t<3> origin; cl::size_t<3> region; region[0] = w; region[1] = h; region[2] = 1; cl::ImageFormat imageFormat(CL_RGBA, CL_UNORM_INT8); cl::Sampler sampler = MakeSampler(context, CL_FALSE, CL_ADDRESS_CLAMP, CL_FILTER_NEAREST); cl::Image2D imageBufferA = MakeImage2D(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, imageFormat, w, h, 0, inputImage); //TODO: For some reason Intel doesn't allow not using host ptr, but NVIDIA does // Maybe something wrong with C++ interface cl::Image2D imageBufferB = MakeImage2D(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, imageFormat, w, h, 0, inputImage); // ============================================================== // // Create buffer for filter data // // ============================================================== std::unordered_map<int, const float*> filters; filters.insert(std::make_pair(3, GaussianFilter3)); filters.insert(std::make_pair(5, GaussianFilter5)); filters.insert(std::make_pair(7, GaussianFilter7)); filters.insert(std::make_pair(9, GaussianFilter3x3)); filters.insert(std::make_pair(25, GaussianFilter5x5)); filters.insert(std::make_pair(49, GaussianFilter7x7)); // ============================================================== // // Simple gaussian blur // // ============================================================== float* filter = const_cast<float*>(filters[filterSize * filterSize]); cl::Buffer filterBuffer = MakeBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * filterSize * filterSize, filter); err = kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(0, imageBufferA); err |= kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(1, imageBufferB); err |= kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(2, sampler); err |= kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(3, filterBuffer); err |= kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(4, filterSize); CheckErrorCode(err, "Unable to set simple convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[SIMPLE_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h)); CheckErrorCode(err, "Unable to enqueue simple convolution kernel"); err = queue.enqueueReadImage(imageBufferB, CL_TRUE, origin, region, 0, 0, outputImage); CheckErrorCode(err, "Unable to read output image buffer"); stbi_write_bmp("Output/SimpleBlurImage.bmp", w, h, 4, outputImage); // ============================================================== // // Two pass gaussian blur // // ============================================================== filter = const_cast<float*>(filters[filterSize]); filterBuffer = MakeBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * filterSize, filter); err = kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(0, imageBufferA); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(1, imageBufferB); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(2, sampler); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(3, filterBuffer); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(4, filterSize); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(5, 1); CheckErrorCode(err, "Unable to set one pass convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[ONE_PASS_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h)); CheckErrorCode(err, "Unable to enqueue one pass convolution kernel"); err = queue.enqueueReadImage(imageBufferB, CL_TRUE, origin, region, 0, 0, outputImage); CheckErrorCode(err, "Unable to read discarded pixels output image"); stbi_write_bmp("Output/OnePassBlurredImage.bmp", w, h, 4, outputImage); err = kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(0, imageBufferB); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(1, imageBufferA); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(5, 0); CheckErrorCode(err, "Unable to set one pass convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[ONE_PASS_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h)); CheckErrorCode(err, "Unable to enqueue one pass convolution kernel"); err = queue.enqueueReadImage(imageBufferA, CL_TRUE, origin, region, 0, 0, outputImage); CheckErrorCode(err, "Unable to read output image buffer"); stbi_write_bmp("Output/TwoPassBlurredImage.bmp", w, h, 4, outputImage); err = queue.enqueueWriteImage(imageBufferA, CL_TRUE, origin, region, 0, 0, inputImage); CheckErrorCode(err, "Unable to write image buffer A"); // ============================================================== // // Perform profiling // // ============================================================== cl::Event startEvent, finishEvent; int filterSizes[3] = {3, 5, 7}; std::ofstream outfile; for (auto i = 0; i < 3; ++i) { std::string name = "Simple" + std::to_string(filterSizes[i]) + "x" + std::to_string(filterSizes[i]); outfile.open("Profiling/" + name + ".txt"); outfile << name << std::endl; cl_ulong totalTime = 0; for (auto u = 0; u < 1000; ++u) { filter = const_cast<float*>(filters[filterSizes[i] * filterSizes[i]]); filterBuffer = MakeBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * filterSizes[i] * filterSizes[i], filter); err = kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(3, filterBuffer); err |= kernels[SIMPLE_CONVOLUTION_KERNEL].setArg(4, filterSizes[i]); CheckErrorCode(err, "Unable to set simple convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[SIMPLE_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h), cl::NullRange, nullptr, &finishEvent); CheckErrorCode(err, "Unable to enqueue simple convolution kernel"); err = queue.finish(); CheckErrorCode(err, "Unable to finish queue"); auto start = finishEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>(); auto end = finishEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>(); totalTime += end - start; outfile << (end - start) / 1000000.0f << std::endl; } std::cout << "Average time for " << name << ": " << totalTime / 1000000.0f / 1000.0f << std::endl; outfile.close(); } for (auto i = 0; i < 3; ++i) { std::string name = "TwoPass" + std::to_string(filterSizes[i]) + "x" + std::to_string(filterSizes[i]); outfile.open("Profiling/" + name + ".txt"); outfile << name << std::endl; cl_ulong totalTime = 0; for (auto u = 0; u < 1000; ++u) { filter = const_cast<float*>(filters[filterSizes[i]]); filterBuffer = MakeBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float) * filterSizes[i], filter); err = kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(0, imageBufferA); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(1, imageBufferB); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(3, filterBuffer); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(4, filterSizes[i]); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(5, 1); CheckErrorCode(err, "Unable to set one pass convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[ONE_PASS_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h), cl::NullRange, nullptr, &startEvent); CheckErrorCode(err, "Unable to enqueue one pass convolution kernel"); err = kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(0, imageBufferB); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(1, imageBufferA); err |= kernels[ONE_PASS_CONVOLUTION_KERNEL].setArg(5, 0); CheckErrorCode(err, "Unable to set one pass convolution kernel arguments"); err = queue.enqueueNDRangeKernel(kernels[ONE_PASS_CONVOLUTION_KERNEL], cl::NullRange, cl::NDRange(w, h), cl::NullRange, nullptr, &finishEvent); CheckErrorCode(err, "Unable to enqueue one pass convolution kernel"); err = queue.finish(); CheckErrorCode(err, "Unable to finish queue"); auto start = startEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>(); auto end = finishEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>(); totalTime += end - start; outfile << (end - start) / 1000000.0f << std::endl; err = queue.enqueueWriteImage(imageBufferA, CL_TRUE, origin, region, 0, 0, inputImage); CheckErrorCode(err, "Unable to write image buffer A"); } std::cout << "Average time for " << name << ": " << totalTime / 1000000.0f / 1000.0f << std::endl; outfile.close(); } delete[] outputImage; stbi_image_free(inputImage); return 0; }
41.248062
107
0.649126
[ "vector" ]
9eb771823d8724142ff49f5afb018de1adfb8348
18,318
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/dae/daeRGeometry.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/dae/daeRGeometry.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/dae/daeRGeometry.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html * * 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 "daeReader.h" #include "domSourceReader.h" #include <dae.h> #include <dom/domCOLLADA.h> #include <dom/domInstance_geometry.h> #include <dom/domInstance_controller.h> #include <dom/domController.h> #include <osg/StateSet> #include <osg/Geometry> using namespace osgdae; osg::Geode* daeReader::processInstanceGeometry( domInstance_geometry *ig ) { daeElement *el = getElementFromURI( ig->getUrl() ); domGeometry *geom = daeSafeCast< domGeometry >( el ); if ( geom == NULL ) { osg::notify( osg::WARN ) << "Failed to locate geometry " << ig->getUrl().getURI() << std::endl; return NULL; } // Check cache if geometry already exists osg::Geode* cachedGeode; domGeometryGeodeMap::iterator iter = geometryMap.find( geom ); if ( iter != geometryMap.end() ) { cachedGeode = iter->second.get(); } else { cachedGeode = processGeometry( geom ); geometryMap.insert( std::make_pair( geom, cachedGeode ) ); } // Create a copy of the cached Geode with a copy of the drawables, // because we may be using a different material or texture unit bindings. osg::Geode *geode = static_cast<osg::Geode*>(cachedGeode->clone(osg::CopyOp::DEEP_COPY_DRAWABLES)); if ( geode == NULL ) { osg::notify( osg::WARN ) << "Failed to load geometry " << ig->getUrl().getURI() << std::endl; return NULL; } // process material bindings if ( ig->getBind_material() != NULL ) { processBindMaterial( ig->getBind_material(), geom, geode, cachedGeode ); } return geode; } // <controller> // attributes: // id, name // elements: // 0..1 <asset> // 1 <skin>, <morph> // 0..* <extra> osg::Geode* daeReader::processInstanceController( domInstance_controller *ictrl ) { //TODO: support skinning daeElement *el = getElementFromURI( ictrl->getUrl()); domController *ctrl = daeSafeCast< domController >( el ); if ( ctrl == NULL ) { osg::notify( osg::WARN ) << "Failed to locate conroller " << ictrl->getUrl().getURI() << std::endl; return NULL; } osg::notify( osg::WARN ) << "Processing <controller>. There is not skinning support but will display the base mesh." << std::endl; el = NULL; //## non init daeURI *src=NULL; if ( ctrl->getSkin() != NULL ) { src = &ctrl->getSkin()->getSource(); el = getElementFromURI( ctrl->getSkin()->getSource() ); } else if ( ctrl->getMorph() != NULL ) { src = &ctrl->getSkin()->getSource(); el = getElementFromURI( ctrl->getMorph()->getSource() ); } //non init case if ( !src ) { osg::notify( osg::WARN ) << "Failed to locate geometry : URI is NULL" << std::endl; return NULL; } domGeometry *geom = daeSafeCast< domGeometry >( el ); if ( geom == NULL ) { osg::notify( osg::WARN ) << "Failed to locate geometry " << src->getURI() << std::endl; return NULL; } // Check cache if geometry already exists osg::Geode* cachedGeode; domGeometryGeodeMap::iterator iter = geometryMap.find( geom ); if ( iter != geometryMap.end() ) { cachedGeode = iter->second.get(); } else { cachedGeode = processGeometry( geom ); geometryMap.insert( std::make_pair( geom, cachedGeode ) ); } // Create a copy of the cached Geode with a copy of the drawables, // because we may be using a different material or texture unit bindings. osg::Geode *geode = static_cast<osg::Geode*>(cachedGeode->clone(osg::CopyOp::DEEP_COPY_DRAWABLES)); if ( geode == NULL ) { osg::notify( osg::WARN ) << "Failed to load geometry " << src->getURI() << std::endl; return NULL; } //process material bindings if ( ictrl->getBind_material() != NULL ) { processBindMaterial( ictrl->getBind_material(), geom, geode, cachedGeode ); } return geode; } // <geometry> // attributes: // id, name // elements: // 0..1 <asset> // 1 <convex_mesh>, <mesh>, <spline> // 0..* <extra> osg::Geode *daeReader::processGeometry( domGeometry *geo ) { domMesh *mesh = geo->getMesh(); if ( mesh == NULL ) { osg::notify( osg::WARN ) << "Unsupported Geometry type loading " << geo->getId() << std::endl; return NULL; } osg::Geode* geode = new osg::Geode; if (geo->getId() != NULL ) { geode->setName( geo->getId() ); } // <mesh> // elements: // 1..* <source> // 1 <vertices> // 0..* <lines>, <linestrips>, <polygons>, <polylist>, <triangles>, <trifans>, <tristrips> // 0..* <extra> // size_t count = mesh->getContents().getCount(); // 1..* <source> SourceMap sources; domSource_Array sourceArray = mesh->getSource_array(); for ( size_t i = 0; i < sourceArray.getCount(); i++) { sources.insert( std::make_pair((daeElement*)sourceArray[i], domSourceReader( sourceArray[i] ) ) ); } // 0..* <lines> domLines_Array linesArray = mesh->getLines_array(); for ( size_t i = 0; i < linesArray.getCount(); i++) { processSinglePPrimitive<domLines>(geode, linesArray[i], sources, GL_LINES ); } // 0..* <linestrips> domLinestrips_Array linestripsArray = mesh->getLinestrips_array(); for ( size_t i = 0; i < linestripsArray.getCount(); i++) { processMultiPPrimitive<domLinestrips>(geode, linestripsArray[i], sources, GL_LINE_STRIP ); } // 0..* <polygons> domPolygons_Array polygonsArray = mesh->getPolygons_array(); for ( size_t i = 0; i < polygonsArray.getCount(); i++) { processMultiPPrimitive<domPolygons>(geode, polygonsArray[i], sources, GL_POLYGON ); } // 0..* <polylist> domPolylist_Array polylistArray = mesh->getPolylist_array(); for ( size_t i = 0; i < polylistArray.getCount(); i++) { processPolylist(geode, polylistArray[i], sources ); } // 0..* <triangles> domTriangles_Array trianglesArray = mesh->getTriangles_array(); for ( size_t i = 0; i < trianglesArray.getCount(); i++) { processSinglePPrimitive<domTriangles>(geode, trianglesArray[i], sources, GL_TRIANGLES ); } // 0..* <trifans> domTrifans_Array trifansArray = mesh->getTrifans_array(); for ( size_t i = 0; i < trifansArray.getCount(); i++) { processMultiPPrimitive<domTrifans>(geode, trifansArray[i], sources, GL_TRIANGLE_FAN ); } // 0..* <tristrips> domTristrips_Array tristripsArray = mesh->getTristrips_array(); for ( size_t i = 0; i < tristripsArray.getCount(); i++) { processMultiPPrimitive<domTristrips>(geode, tristripsArray[i], sources, GL_TRIANGLE_STRIP ); } return geode; } template< typename T > void daeReader::processSinglePPrimitive(osg::Geode* geode, T *group, SourceMap &sources, GLenum mode ) { osg::Geometry *geometry = new ReaderGeometry(); geometry->setName(group->getMaterial()); IndexMap index_map; resolveArrays( group->getInput_array(), geometry, sources, index_map ); osg::DrawArrayLengths* dal = new osg::DrawArrayLengths( mode ); processP( group->getP(), geometry, index_map, dal/*mode*/ ); geometry->addPrimitiveSet( dal ); geode->addDrawable( geometry ); } template< typename T > void daeReader::processMultiPPrimitive(osg::Geode* geode, T *group, SourceMap &sources, GLenum mode ) { osg::Geometry *geometry = new ReaderGeometry(); geometry->setName(group->getMaterial()); IndexMap index_map; resolveArrays( group->getInput_array(), geometry, sources, index_map ); osg::DrawArrayLengths* dal = new osg::DrawArrayLengths( mode ); for ( size_t i = 0; i < group->getP_array().getCount(); i++ ) { processP( group->getP_array()[i], geometry, index_map, dal/*mode*/ ); } geometry->addPrimitiveSet( dal ); geode->addDrawable( geometry ); } void daeReader::processPolylist(osg::Geode* geode, domPolylist *group, SourceMap &sources ) { osg::Geometry *geometry = new ReaderGeometry(); geometry->setName(group->getMaterial()); IndexMap index_map; resolveArrays( group->getInput_array(), geometry, sources, index_map ); osg::DrawArrayLengths* dal = new osg::DrawArrayLengths( GL_POLYGON ); //domPRef p = (domP*)(daeElement*)domP::_Meta->create(); //I don't condone creating elements like this but I don't care domPRef p = (domP*)domP::registerElement(*dae)->create().cast(); //if it created properly because I never want it as part of the document. Its just a temporary //element to trick the importer into loading polylists easier. unsigned int maxOffset = 0; for ( unsigned int i = 0; i < group->getInput_array().getCount(); i++ ) { if ( group->getInput_array()[i]->getOffset() > maxOffset ) { maxOffset = group->getInput_array()[i]->getOffset(); } } maxOffset++; unsigned int pOffset = 0; for ( unsigned int i = 0; i < group->getCount(); i++ ) { p->getValue().clear(); for ( unsigned int x = 0; x < group->getVcount()->getValue()[i]; x++ ) { for ( unsigned int y = 0; y < maxOffset; y++ ) { p->getValue().append( group->getP()->getValue()[ pOffset + x*maxOffset + y ] ); } } pOffset += group->getVcount()->getValue()[i] * maxOffset; processP( p, geometry, index_map, dal/*mode*/ ); } geometry->addPrimitiveSet( dal ); geode->addDrawable( geometry ); } void daeReader::processP( domP *p, osg::Geometry *&/*geom*/, IndexMap &index_map, osg::DrawArrayLengths* dal /*GLenum mode*/ ) { int idxcount = index_map.size(); int count = p->getValue().getCount(); count = (count/idxcount)*idxcount; dal->push_back(count/idxcount); int j = 0; while ( j < count ) { for ( IndexMap::iterator k = index_map.begin(); k != index_map.end(); k++,j++ ) { int tmp = p->getValue()[j]; k->second->push_back(tmp); } } } void daeReader::resolveArrays( domInputLocalOffset_Array &inputs, osg::Geometry *geom, SourceMap &sources, IndexMap &index_map ) { domVertices* vertices = NULL; daeElement* position_source = NULL; daeElement* color_source = NULL; daeElement* normal_source = NULL; daeElement* texcoord_source = NULL; daeElement *tmp_el; domInputLocalOffset *tmp_input; ReaderGeometry* GeometryWrapper = dynamic_cast<ReaderGeometry*>(geom); int TexCoordSetsUsed = 0; if ( findInputSourceBySemantic( inputs, "VERTEX", tmp_el, &tmp_input ) ) { vertices = daeSafeCast< domVertices >( tmp_el ); if ( vertices == NULL ) { osg::notify( osg::WARN )<<"Could not get vertices"<<std::endl; return; } // Process mandatory offset attribute int offset = tmp_input->getOffset(); if ( index_map[offset] == NULL ) index_map[offset] = new osg::IntArray(); geom->setVertexIndices( index_map[offset] ); // Process input elements within the vertices element. These are of the unshared type // and therefore cannot have set and offset attributes // The vertices POSITION semantic input element is mandatory domInputLocal *tmp; findInputSourceBySemantic( vertices->getInput_array(), "POSITION", position_source, &tmp ); if ( position_source != NULL ) { geom->setVertexArray( sources[position_source].getVec3Array() ); } else { osg::notify( osg::FATAL )<<"Mandatory POSITION semantic missing"<<std::endl; return; } // Process additional vertices input elements findInputSourceBySemantic( vertices->getInput_array(), "COLOR", color_source, &tmp ); findInputSourceBySemantic( vertices->getInput_array(), "NORMAL", normal_source, &tmp ); findInputSourceBySemantic( vertices->getInput_array(), "TEXCOORD", texcoord_source, &tmp ); int VertexCount = sources[position_source].getCount(); if ( color_source != NULL ) { // Check matching arrays if ( sources[color_source].getCount() >= VertexCount ) { geom->setColorArray( sources[color_source].getVec4Array() ); geom->setColorBinding( osg::Geometry::BIND_PER_VERTEX ); geom->setColorIndices( index_map[offset] ); // Use the vertex indices } else { osg::notify( osg::WARN )<<"Not enough entries in color array"<<std::endl; } } if ( normal_source != NULL ) { // Check matching arrays if ( sources[normal_source].getCount() >= VertexCount ) { geom->setNormalArray( sources[normal_source].getVec3Array() ); geom->setNormalBinding( osg::Geometry::BIND_PER_VERTEX ); geom->setNormalIndices( index_map[offset] ); // Use the vertex indices } else { osg::notify( osg::WARN )<<"Not enough entries in normal array"<<std::endl; } } // It seems sensible to only process the first input found here with a TEXCOORD semantic. // as offsets are not allowed here. // I assume that this belongs to set zero as the DOM returns 0 for the set attribute on shared // input elements even if the attribute is absent. if ( texcoord_source != NULL ) { domSourceReader *sc = &sources[texcoord_source]; if ( sc->getCount() >= VertexCount ) { if (NULL != GeometryWrapper) GeometryWrapper->_TexcoordSetMap[0] = TexCoordSetsUsed; switch( sc->getArrayType() ) { case domSourceReader::Vec2: geom->setTexCoordArray( TexCoordSetsUsed, sc->getVec2Array() ); break; case domSourceReader::Vec3: geom->setTexCoordArray( TexCoordSetsUsed, sc->getVec3Array() ); break; default: osg::notify( osg::WARN )<<"Unsupported array type: "<< sc->getArrayType() <<std::endl; break; } TexCoordSetsUsed++; } else { osg::notify( osg::WARN )<<"Not enough entries in texcoord array"<<std::endl; } } if ( findInputSourceBySemantic( inputs, "TEXCOORD", texcoord_source, &tmp_input, 1 ) ) { osg::notify( osg::WARN )<<"More than one input element with TEXCOORD semantic found in vertices element"<<std::endl; } } else { osg::notify( osg::WARN )<<"Vertex data not found"<<std::endl; return; } if ( findInputSourceBySemantic( inputs, "COLOR", tmp_el, &tmp_input )) { if (color_source != NULL) osg::notify( osg::WARN )<<"Overwriting vertices input(COLOR) with input from primitive"<<std::endl; else geom->setColorBinding( osg::Geometry::BIND_PER_VERTEX ); int offset = tmp_input->getOffset(); if ( index_map[offset] == NULL ) index_map[offset] = new osg::IntArray(); geom->setColorIndices( index_map[offset] ); geom->setColorArray( sources[tmp_el].getVec4Array() ); } if ( findInputSourceBySemantic( inputs, "NORMAL", tmp_el, &tmp_input ) ) { if (normal_source != NULL) osg::notify( osg::WARN )<<"Overwriting vertices input(NORMAL) with input from primitive"<<std::endl; else geom->setNormalBinding( osg::Geometry::BIND_PER_VERTEX ); int offset = tmp_input->getOffset(); if ( index_map[offset] == NULL ) index_map[offset] = new osg::IntArray(); geom->setNormalIndices( index_map[offset] ); geom->setNormalArray( sources[tmp_el].getVec3Array() ); } int inputNumber = 0; while ( findInputSourceBySemantic( inputs, "TEXCOORD", texcoord_source, &tmp_input, inputNumber ) ) { int offset = tmp_input->getOffset(); int set = tmp_input->getSet(); if (NULL != GeometryWrapper) { if (GeometryWrapper->_TexcoordSetMap.find(set) != GeometryWrapper->_TexcoordSetMap.end()) osg::notify( osg::WARN )<<"Duplicate texcoord set: "<< set <<std::endl; GeometryWrapper->_TexcoordSetMap[set] = TexCoordSetsUsed; } if ( index_map[offset] == NULL ) { index_map[offset] = new osg::IntArray(); } geom->setTexCoordIndices( TexCoordSetsUsed, index_map[offset] ); if ( texcoord_source != NULL ) { domSourceReader &sc = sources[texcoord_source]; switch( sc.getArrayType() ) { case domSourceReader::Vec2: geom->setTexCoordArray( TexCoordSetsUsed, sc.getVec2Array() ); break; case domSourceReader::Vec3: geom->setTexCoordArray( TexCoordSetsUsed, sc.getVec3Array() ); break; default: osg::notify( osg::WARN )<<"Unsupported array type: "<< sc.getArrayType() <<std::endl; break; } } TexCoordSetsUsed++; inputNumber++; } }
35.159309
134
0.596899
[ "mesh", "geometry" ]
9ec1dca39bee7b237750bd99d7f39dbf15b141d6
763
hpp
C++
libs/core/render/include/bksge/core/render/dxgi/dxgi_format.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/include/bksge/core/render/dxgi/dxgi_format.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/include/bksge/core/render/dxgi/dxgi_format.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file dxgi_format.hpp * * @brief DXGIFormat クラスの定義 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_DXGI_DXGI_FORMAT_HPP #define BKSGE_CORE_RENDER_DXGI_DXGI_FORMAT_HPP #include <bksge/core/render/d3d_common/dxgiformat.hpp> #include <bksge/core/render/texture_format.hpp> namespace bksge { namespace render { /** * @brief */ class DXGIFormat { public: explicit DXGIFormat(bksge::TextureFormat format); operator ::DXGI_FORMAT() const; private: ::DXGI_FORMAT m_format; }; } // namespace render } // namespace bksge #include <bksge/fnd/config.hpp> #if defined(BKSGE_HEADER_ONLY) #include <bksge/core/render/dxgi/inl/dxgi_format_inl.hpp> #endif #endif // BKSGE_CORE_RENDER_DXGI_DXGI_FORMAT_HPP
16.955556
58
0.715596
[ "render" ]
9eccd8a19e8ce13637dc7bd4e21f99cb34d56473
49,580
cpp
C++
sounddev/SoundDeviceASIO.cpp
extrowerk/openmpt
99cb32168f6500dfbb238f305fef6b5e58fbac1d
[ "BSD-3-Clause" ]
null
null
null
sounddev/SoundDeviceASIO.cpp
extrowerk/openmpt
99cb32168f6500dfbb238f305fef6b5e58fbac1d
[ "BSD-3-Clause" ]
null
null
null
sounddev/SoundDeviceASIO.cpp
extrowerk/openmpt
99cb32168f6500dfbb238f305fef6b5e58fbac1d
[ "BSD-3-Clause" ]
null
null
null
/* * SoundDeviceASIO.cpp * ------------------- * Purpose: ASIO sound device driver class. * Notes : (currently none) * Authors: Olivier Lapicque * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "SoundDevice.h" #include "SoundDeviceASIO.h" #include "../common/misc_util.h" #include "../common/mptUUID.h" #include "../common/mptStringBuffer.h" #include "../common/mptOSException.h" #include "../soundbase/SampleFormatConverters.h" #include "../soundbase/SampleFormatCopy.h" #include <algorithm> OPENMPT_NAMESPACE_BEGIN namespace SoundDevice { #ifdef MPT_WITH_ASIO MPT_REGISTERED_COMPONENT(ComponentASIO, "ASIO") static const double AsioSampleRateTolerance = 0.05; // Helper class to temporarily open a driver for a query. class TemporaryASIODriverOpener { protected: CASIODevice &device; const bool wasOpen; public: TemporaryASIODriverOpener(CASIODevice &d) : device(d) , wasOpen(d.IsDriverOpen()) { if(!wasOpen) { device.OpenDriver(); } } ~TemporaryASIODriverOpener() { if(!wasOpen) { device.CloseDriver(); } } }; class ASIOCallError : public ASIOException { public: ASIOCallError(const std::string &call, ASIOError err) : ASIOException(call + std::string(" failed: ") + mpt::fmt::val(err)) { return; } }; class ASIOCallBoolResult : public ASIOException { public: ASIOCallBoolResult(const std::string &call, ASIOBool err) : ASIOException(call + std::string(" failed: ") + mpt::fmt::val(err)) { return; } }; static void AsioCheckResultASIOError(ASIOError e, const char * funcName) { if(e != ASE_OK) { throw ASIOCallError(funcName, e); } } static void AsioCheckResultASIOBool(ASIOBool b, const char * funcName) { if(b != ASIOTrue) { throw ASIOCallBoolResult(funcName, b); } } template <typename Tfn> auto CASIODevice::CallDriverImpl(Tfn fn, const char * /* funcName */ ) -> decltype(fn()) { return fn(); } template <typename Tfn> auto CASIODevice::CallDriverAndMaskCrashesImpl(Tfn fn, const char * funcName) -> decltype(fn()) { try { return Windows::ThrowOnStructuredException(fn); } catch(const Windows::StructuredException &) { // nothing } ReportASIOException(std::string(funcName) + std::string("() crashed!")); throw ASIOException(std::string("Exception in '") + std::string(funcName) + std::string("'!")); } template <typename Tfn> auto CASIODevice::CallDriver(Tfn fn, const char * funcName) -> decltype(fn()) { if(GetAppInfo().MaskDriverCrashes) { return CallDriverAndMaskCrashesImpl(fn, funcName); } else { return CallDriverImpl(fn, funcName); } } #define AsioCallUnchecked(asio, call) CallDriver([&]() { return asio . call ; }, #call ) #define AsioCallBool(asio, call) AsioCheckResultASIOBool(CallDriver([&]() { return asio . call ; }, #call ), #call ) #define AsioCall(asio, call) AsioCheckResultASIOError(CallDriver([&]() { return asio . call ; }, #call ), #call ) #define ASIO_MAXDRVNAMELEN 1024 CASIODevice *CASIODevice::g_CallbacksInstance = nullptr; std::vector<SoundDevice::Info> CASIODevice::EnumerateDevices(SoundDevice::SysInfo sysInfo) { MPT_TRACE_SCOPE(); std::vector<SoundDevice::Info> devices; LONG cr; HKEY hkEnum = NULL; cr = RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\ASIO"), &hkEnum); for(DWORD index = 0; ; ++index) { TCHAR keynameBuf[ASIO_MAXDRVNAMELEN]; if((cr = RegEnumKey(hkEnum, index, keynameBuf, ASIO_MAXDRVNAMELEN)) != ERROR_SUCCESS) { break; } const mpt::winstring keyname = mpt::String::ReadWinBuf(keynameBuf); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: Found '%1':"))(mpt::ToUnicode(keyname))); HKEY hksub = NULL; if(RegOpenKeyEx(hkEnum, keyname.c_str(), 0, KEY_READ, &hksub) != ERROR_SUCCESS) { continue; } TCHAR descriptionBuf[ASIO_MAXDRVNAMELEN]; DWORD datatype = REG_SZ; DWORD datasize = sizeof(descriptionBuf); mpt::ustring description; if(ERROR_SUCCESS == RegQueryValueEx(hksub, TEXT("Description"), 0, &datatype, (LPBYTE)descriptionBuf, &datasize)) { description = mpt::ToUnicode(mpt::String::ReadWinBuf(descriptionBuf)); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: description='%1'"))(description)); } else { description = mpt::ToUnicode(keyname); } TCHAR idBuf[256]; datatype = REG_SZ; datasize = sizeof(idBuf); if(ERROR_SUCCESS == RegQueryValueEx(hksub, TEXT("CLSID"), 0, &datatype, (LPBYTE)idBuf, &datasize)) { const mpt::ustring internalID = mpt::ToUnicode(mpt::String::ReadWinBuf(idBuf)); if(Util::IsCLSID(mpt::ToWin(internalID))) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: clsid=%1"))(internalID)); SoundDevice::Info info; info.type = TypeASIO; info.internalID = internalID; info.apiName = U_("ASIO"); info.name = description; info.useNameAsIdentifier = false; info.isDefault = false; info.flags = { sysInfo.SystemClass == mpt::OS::Class::Windows ? sysInfo.IsWindowsOriginal() ? Info::Usability::Usable : Info::Usability::Experimental : Info::Usability::NotAvailable, Info::Level::Primary, Info::Compatible::No, sysInfo.SystemClass == mpt::OS::Class::Windows && sysInfo.IsWindowsOriginal() ? Info::Api::Native : Info::Api::Emulated, Info::Io::FullDuplex, Info::Mixing::Hardware, Info::Implementor::OpenMPT }; info.extraData[U_("Key")] = mpt::ToUnicode(keyname); info.extraData[U_("Description")] = description; info.extraData[U_("CLSID")] = mpt::ToUnicode(internalID); devices.push_back(info); } } RegCloseKey(hksub); hksub = NULL; } if(hkEnum) { RegCloseKey(hkEnum); hkEnum = NULL; } return devices; } CASIODevice::CASIODevice(SoundDevice::Info info, SoundDevice::SysInfo sysInfo) : SoundDevice::Base(info, sysInfo) , m_RenderSilence(0) , m_RenderingSilence(0) , m_AsioRequestFlags(0) , m_DebugRealtimeThreadID(0) { MPT_TRACE_SCOPE(); InitMembers(); m_QueriedFeatures.reset(); m_UsedFeatures.reset(); } void CASIODevice::InitMembers() { MPT_TRACE_SCOPE(); m_pAsioDrv = nullptr; m_BufferLatency = 0.0; m_nAsioBufferLen = 0; m_BufferInfo.clear(); MemsetZero(m_Callbacks); m_BuffersCreated = false; m_ChannelInfo.clear(); m_SampleBufferFloat.clear(); m_SampleBufferInt16.clear(); m_SampleBufferInt24.clear(); m_SampleBufferInt32.clear(); m_SampleInputBufferFloat.clear(); m_SampleInputBufferInt16.clear(); m_SampleInputBufferInt24.clear(); m_SampleInputBufferInt32.clear(); m_CanOutputReady = false; m_DeviceRunning = false; m_TotalFramesWritten = 0; m_BufferIndex = 0; m_RenderSilence = 0; m_RenderingSilence = 0; m_AsioRequestFlags = 0; m_DebugRealtimeThreadID.store(0); } bool CASIODevice::HandleRequests() { MPT_TRACE_SCOPE(); bool result = false; uint32 flags = m_AsioRequestFlags.exchange(0); if(flags & AsioRequestFlagLatenciesChanged) { UpdateLatency(); result = true; } return result; } CASIODevice::~CASIODevice() { MPT_TRACE_SCOPE(); Close(); } bool CASIODevice::InternalOpen() { MPT_TRACE_SCOPE(); MPT_ASSERT(!IsDriverOpen()); InitMembers(); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: Open('%1'): %2-bit, (%3,%4) channels, %5Hz, hw-timing=%6")) ( GetDeviceInternalID() , m_Settings.sampleFormat.GetBitsPerSample() , m_Settings.InputChannels , m_Settings.Channels , m_Settings.Samplerate , m_Settings.UseHardwareTiming )); SoundDevice::ChannelMapping inputChannelMapping = SoundDevice::ChannelMapping::BaseChannel(m_Settings.InputChannels, m_Settings.InputSourceID); try { OpenDriver(); if(!IsDriverOpen()) { throw ASIOException("Initializing driver failed."); } long inputChannels = 0; long outputChannels = 0; AsioCall(AsioDriver(), getChannels(&inputChannels, &outputChannels)); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getChannels() => inputChannels=%1 outputChannel=%2"))(inputChannels, outputChannels)); if(inputChannels <= 0 && outputChannels <= 0) { m_DeviceUnavailableOnOpen = true; throw ASIOException("Device unavailble."); } if(m_Settings.Channels > outputChannels) { throw ASIOException("Not enough output channels."); } if(m_Settings.Channels.GetRequiredDeviceChannels() > outputChannels) { throw ASIOException("Channel mapping requires more channels than available."); } if(m_Settings.InputChannels > inputChannels) { throw ASIOException("Not enough input channels."); } if(inputChannelMapping.GetRequiredDeviceChannels() > inputChannels) { throw ASIOException("Channel mapping requires more channels than available."); } MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: setSampleRate(sampleRate=%1)"))(m_Settings.Samplerate)); AsioCall(AsioDriver(), setSampleRate(m_Settings.Samplerate)); long minSize = 0; long maxSize = 0; long preferredSize = 0; long granularity = 0; AsioCall(AsioDriver(), getBufferSize(&minSize, &maxSize, &preferredSize, &granularity)); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getBufferSize() => minSize=%1 maxSize=%2 preferredSize=%3 granularity=%4"))( minSize, maxSize, preferredSize, granularity)); m_nAsioBufferLen = mpt::saturate_round<int32>(m_Settings.Latency * m_Settings.Samplerate / 2.0); if(minSize <= 0 || maxSize <= 0 || minSize > maxSize) { // limits make no sense if(preferredSize > 0) { m_nAsioBufferLen = preferredSize; } else { // just leave the user value, perhaps it works } } else if(granularity < -1) { // granularity value not allowed, just clamp value m_nAsioBufferLen = mpt::clamp(m_nAsioBufferLen, minSize, maxSize); } else if(granularity == -1 && (mpt::weight(minSize) != 1 || mpt::weight(maxSize) != 1)) { // granularity tells us we need power-of-2 sizes, but min or max sizes are no power-of-2 m_nAsioBufferLen = mpt::clamp(m_nAsioBufferLen, minSize, maxSize); // just start at 1 and find a matching power-of-2 in range const long bufTarget = m_nAsioBufferLen; for(long bufSize = 1; bufSize <= maxSize && bufSize <= bufTarget; bufSize *= 2) { if(bufSize >= minSize) { m_nAsioBufferLen = bufSize; } } // if no power-of-2 in range is found, just leave the clamped value alone, perhaps it works } else if(granularity == -1) { // sane values, power-of-2 size required between min and max m_nAsioBufferLen = mpt::clamp(m_nAsioBufferLen, minSize, maxSize); // get the largest allowed buffer size that is smaller or equal to the target size const long bufTarget = m_nAsioBufferLen; for(long bufSize = minSize; bufSize <= maxSize && bufSize <= bufTarget; bufSize *= 2) { m_nAsioBufferLen = bufSize; } } else if(granularity > 0) { // buffer size in granularity steps from min to max allowed m_nAsioBufferLen = mpt::clamp(m_nAsioBufferLen, minSize, maxSize); // get the largest allowed buffer size that is smaller or equal to the target size const long bufTarget = m_nAsioBufferLen; for(long bufSize = minSize; bufSize <= maxSize && bufSize <= bufTarget; bufSize += granularity) { m_nAsioBufferLen = bufSize; } } else if(granularity == 0) { // no granularity given, we should use preferredSize if possible if(preferredSize > 0) { m_nAsioBufferLen = preferredSize; } else if(m_nAsioBufferLen >= maxSize) { // a large latency was requested, use maxSize m_nAsioBufferLen = maxSize; } else { // use minSize otherwise m_nAsioBufferLen = minSize; } } else { // should not happen MPT_ASSERT_NOTREACHED(); } m_BufferInfo.resize(m_Settings.GetTotalChannels()); for(uint32 channel = 0; channel < m_Settings.GetTotalChannels(); ++channel) { MemsetZero(m_BufferInfo[channel]); if(channel < m_Settings.InputChannels) { m_BufferInfo[channel].isInput = ASIOTrue; m_BufferInfo[channel].channelNum = inputChannelMapping.ToDevice(channel); } else { m_BufferInfo[channel].isInput = ASIOFalse; m_BufferInfo[channel].channelNum = m_Settings.Channels.ToDevice(channel - m_Settings.InputChannels); } } m_Callbacks.bufferSwitch = CallbackBufferSwitch; m_Callbacks.sampleRateDidChange = CallbackSampleRateDidChange; m_Callbacks.asioMessage = CallbackAsioMessage; m_Callbacks.bufferSwitchTimeInfo = CallbackBufferSwitchTimeInfo; MPT_ASSERT_ALWAYS(g_CallbacksInstance == nullptr); g_CallbacksInstance = this; MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: createBuffers(numChannels=%1, bufferSize=%2)"))(m_Settings.Channels.GetNumHostChannels(), m_nAsioBufferLen)); AsioCall(AsioDriver(), createBuffers(m_BufferInfo.data(), m_Settings.GetTotalChannels(), m_nAsioBufferLen, &m_Callbacks)); m_BuffersCreated = true; m_ChannelInfo.resize(m_Settings.GetTotalChannels()); for(uint32 channel = 0; channel < m_Settings.GetTotalChannels(); ++channel) { MemsetZero(m_ChannelInfo[channel]); if(channel < m_Settings.InputChannels) { m_ChannelInfo[channel].isInput = ASIOTrue; m_ChannelInfo[channel].channel = inputChannelMapping.ToDevice(channel); } else { m_ChannelInfo[channel].isInput = ASIOFalse; m_ChannelInfo[channel].channel = m_Settings.Channels.ToDevice(channel - m_Settings.InputChannels); } AsioCall(AsioDriver(), getChannelInfo(&m_ChannelInfo[channel])); MPT_ASSERT(m_ChannelInfo[channel].isActive); mpt::String::SetNullTerminator(m_ChannelInfo[channel].name); MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getChannelInfo(isInput=%1 channel=%2) => isActive=%3 channelGroup=%4 type=%5 name='%6'")) ( (channel < m_Settings.InputChannels) ? ASIOTrue : ASIOFalse , m_Settings.Channels.ToDevice(channel) , m_ChannelInfo[channel].isActive , m_ChannelInfo[channel].channelGroup , m_ChannelInfo[channel].type , mpt::ToUnicode(mpt::CharsetLocale, m_ChannelInfo[channel].name) )); } bool allChannelsAreFloat = true; bool allChannelsAreInt16 = true; bool allChannelsAreInt24 = true; for(std::size_t channel = 0; channel < m_Settings.GetTotalChannels(); ++channel) { if(!IsSampleTypeFloat(m_ChannelInfo[channel].type)) { allChannelsAreFloat = false; } if(!IsSampleTypeInt16(m_ChannelInfo[channel].type)) { allChannelsAreInt16 = false; } if(!IsSampleTypeInt24(m_ChannelInfo[channel].type)) { allChannelsAreInt24 = false; } } if(allChannelsAreFloat) { m_Settings.sampleFormat = SampleFormatFloat32; m_SampleBufferFloat.resize(m_nAsioBufferLen * m_Settings.Channels); m_SampleInputBufferFloat.resize(m_nAsioBufferLen * m_Settings.InputChannels); } else if(allChannelsAreInt16) { m_Settings.sampleFormat = SampleFormatInt16; m_SampleBufferInt16.resize(m_nAsioBufferLen * m_Settings.Channels); m_SampleInputBufferInt16.resize(m_nAsioBufferLen * m_Settings.InputChannels); } else if(allChannelsAreInt24) { m_Settings.sampleFormat = SampleFormatInt24; m_SampleBufferInt24.resize(m_nAsioBufferLen * m_Settings.Channels); m_SampleInputBufferInt24.resize(m_nAsioBufferLen * m_Settings.InputChannels); } else { m_Settings.sampleFormat = SampleFormatInt32; m_SampleBufferInt32.resize(m_nAsioBufferLen * m_Settings.Channels); m_SampleInputBufferInt32.resize(m_nAsioBufferLen * m_Settings.InputChannels); } for(std::size_t channel = 0; channel < m_Settings.GetTotalChannels(); ++channel) { if(m_BufferInfo[channel].buffers[0]) { std::memset(m_BufferInfo[channel].buffers[0], 0, m_nAsioBufferLen * GetSampleSize(m_ChannelInfo[channel].type)); } if(m_BufferInfo[channel].buffers[1]) { std::memset(m_BufferInfo[channel].buffers[1], 0, m_nAsioBufferLen * GetSampleSize(m_ChannelInfo[channel].type)); } } m_CanOutputReady = false; try { ASIOError asioresult = AsioCallUnchecked(AsioDriver(), outputReady()); m_CanOutputReady = (asioresult == ASE_OK); } catch(...) { // continue, failure is not fatal here m_CanOutputReady = false; } m_StreamPositionOffset = m_nAsioBufferLen; UpdateLatency(); return true; } catch(const std::exception &e) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: Error opening device: %1!"))(mpt::get_exception_text<mpt::ustring>(e))); } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: Unknown error opening device!"))()); } InternalClose(); return false; } void CASIODevice::UpdateLatency() { MPT_TRACE_SCOPE(); long inputLatency = 0; long outputLatency = 0; try { AsioCall(AsioDriver(), getLatencies(&inputLatency, &outputLatency)); } catch(...) { // continue, failure is not fatal here inputLatency = 0; outputLatency = 0; } if(outputLatency >= static_cast<long>(m_nAsioBufferLen)) { m_BufferLatency = static_cast<double>(outputLatency + m_nAsioBufferLen) / static_cast<double>(m_Settings.Samplerate); // ASIO and OpenMPT semantics of 'latency' differ by one chunk/buffer } else { // pointless value returned from asio driver, use a sane estimate m_BufferLatency = 2.0 * static_cast<double>(m_nAsioBufferLen) / static_cast<double>(m_Settings.Samplerate); } } void CASIODevice::SetRenderSilence(bool silence, bool wait) { MPT_TRACE_SCOPE(); m_RenderSilence = (silence ? 1 : 0); if(!wait) { return; } DWORD pollingstart = GetTickCount(); while(m_RenderingSilence != (silence ? 1u : 0u)) { if(GetTickCount() - pollingstart > 250) { if(silence) { if(SourceIsLockedByCurrentThread()) { MPT_ASSERT_MSG(false, "AudioCriticalSection locked while stopping ASIO"); } else { MPT_ASSERT_MSG(false, "waiting for asio failed in Stop()"); } } else { if(SourceIsLockedByCurrentThread()) { MPT_ASSERT_MSG(false, "AudioCriticalSection locked while starting ASIO"); } else { MPT_ASSERT_MSG(false, "waiting for asio failed in Start()"); } } break; } Sleep(1); } } bool CASIODevice::InternalStart() { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS_MSG(!SourceIsLockedByCurrentThread(), "AudioCriticalSection locked while starting ASIO"); if(m_Settings.KeepDeviceRunning) { if(m_DeviceRunning) { SetRenderSilence(false, true); return true; } } SetRenderSilence(false); try { m_TotalFramesWritten = 0; AsioCall(AsioDriver(), start()); m_DeviceRunning = true; } catch(...) { return false; } return true; } bool CASIODevice::InternalIsPlayingSilence() const { MPT_TRACE_SCOPE(); return m_Settings.KeepDeviceRunning && m_DeviceRunning && m_RenderSilence.load(); } void CASIODevice::InternalEndPlayingSilence() { MPT_TRACE_SCOPE(); if(!InternalIsPlayingSilence()) { return; } m_DeviceRunning = false; try { AsioCall(AsioDriver(), stop()); } catch(...) { // continue } m_TotalFramesWritten = 0; SetRenderSilence(false); } void CASIODevice::InternalStopAndAvoidPlayingSilence() { MPT_TRACE_SCOPE(); InternalStopImpl(true); } void CASIODevice::InternalStop() { MPT_TRACE_SCOPE(); InternalStopImpl(false); } void CASIODevice::InternalStopImpl(bool force) { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS_MSG(!SourceIsLockedByCurrentThread(), "AudioCriticalSection locked while stopping ASIO"); if(m_Settings.KeepDeviceRunning && !force) { SetRenderSilence(true, true); return; } m_DeviceRunning = false; try { AsioCall(AsioDriver(), stop()); } catch(...) { // continue } m_TotalFramesWritten = 0; SetRenderSilence(false); } bool CASIODevice::InternalClose() { MPT_TRACE_SCOPE(); if(m_DeviceRunning) { m_DeviceRunning = false; try { AsioCall(AsioDriver(), stop()); } catch(...) { // continue } m_TotalFramesWritten = 0; } SetRenderSilence(false); m_CanOutputReady = false; m_SampleBufferFloat.clear(); m_SampleBufferInt16.clear(); m_SampleBufferInt24.clear(); m_SampleBufferInt32.clear(); m_SampleInputBufferFloat.clear(); m_SampleInputBufferInt16.clear(); m_SampleInputBufferInt24.clear(); m_SampleInputBufferInt32.clear(); m_ChannelInfo.clear(); if(m_BuffersCreated) { try { AsioCall(AsioDriver(), disposeBuffers()); } catch(...) { // continue } m_BuffersCreated = false; } if(g_CallbacksInstance) { MPT_ASSERT_ALWAYS(g_CallbacksInstance == this); g_CallbacksInstance = nullptr; } MemsetZero(m_Callbacks); m_BufferInfo.clear(); m_nAsioBufferLen = 0; m_BufferLatency = 0.0; CloseDriver(); return true; } void CASIODevice::OpenDriver() { MPT_TRACE_SCOPE(); if(IsDriverOpen()) { return; } CLSID clsid = Util::StringToCLSID(mpt::ToWin(GetDeviceInternalID())); try { if(CoCreateInstance(clsid,0,CLSCTX_INPROC_SERVER, clsid, (void **)&m_pAsioDrv) != S_OK) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: CoCreateInstance failed!"))()); m_pAsioDrv = nullptr; return; } } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: CoCreateInstance crashed!"))()); m_pAsioDrv = nullptr; return; } try { AsioCallBool(AsioDriver(), init(reinterpret_cast<void *>(m_AppInfo.GetHWND()))); } catch(const ASIOException &) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: init() failed!"))()); CloseDriver(); return; } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: init() crashed!"))()); CloseDriver(); return; } char driverNameBuffer[32]; Clear(driverNameBuffer); try { AsioCallUnchecked(AsioDriver(), getDriverName(driverNameBuffer)); } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getDriverName() crashed!"))()); CloseDriver(); return; } std::string driverName = mpt::String::ReadAutoBuf(driverNameBuffer); long driverVersion = 0; try { driverVersion = AsioCallUnchecked(AsioDriver(), getDriverVersion()); } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getDriverVersion() crashed!"))()); CloseDriver(); return; } char driverErrorMessageBuffer[124]; Clear(driverErrorMessageBuffer); try { AsioCallUnchecked(AsioDriver(), getErrorMessage(driverErrorMessageBuffer)); } catch(...) { MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: getErrorMessage() crashed!"))()); CloseDriver(); return; } std::string driverErrorMessage = mpt::String::ReadAutoBuf(driverErrorMessageBuffer); MPT_LOG(LogInformation, "sounddev", mpt::format(U_("ASIO: Opened driver %1 Version 0x%2: %3"))(mpt::ToUnicode(mpt::CharsetLocale, driverName), mpt::ufmt::HEX0<8>(driverVersion), mpt::ToUnicode(mpt::CharsetLocale, driverErrorMessage))); } void CASIODevice::CloseDriver() { MPT_TRACE_SCOPE(); if(!IsDriverOpen()) { return; } try { m_pAsioDrv->Release(); } catch(...) { CASIODevice::ReportASIOException("ASIO crash in Release()\n"); } m_pAsioDrv = nullptr; } static void SwapEndian(uint8 *buf, std::size_t itemCount, std::size_t itemSize) { for(std::size_t i = 0; i < itemCount; ++i) { std::reverse(buf, buf + itemSize); buf += itemSize; } } bool CASIODevice::IsSampleTypeFloat(ASIOSampleType sampleType) { switch(sampleType) { case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: return true; break; default: return false; break; } } bool CASIODevice::IsSampleTypeInt16(ASIOSampleType sampleType) { switch(sampleType) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: return true; break; default: return false; break; } } bool CASIODevice::IsSampleTypeInt24(ASIOSampleType sampleType) { switch(sampleType) { case ASIOSTInt24MSB: case ASIOSTInt24LSB: return true; break; default: return false; break; } } std::size_t CASIODevice::GetSampleSize(ASIOSampleType sampleType) { switch(sampleType) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: return 2; break; case ASIOSTInt24MSB: case ASIOSTInt24LSB: return 3; break; case ASIOSTInt32MSB: case ASIOSTInt32LSB: return 4; break; case ASIOSTInt32MSB16: case ASIOSTInt32MSB18: case ASIOSTInt32MSB20: case ASIOSTInt32MSB24: case ASIOSTInt32LSB16: case ASIOSTInt32LSB18: case ASIOSTInt32LSB20: case ASIOSTInt32LSB24: return 4; break; case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: return 4; break; case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: return 8; break; default: return 0; break; } } bool CASIODevice::IsSampleTypeBigEndian(ASIOSampleType sampleType) { switch(sampleType) { case ASIOSTInt16MSB: case ASIOSTInt24MSB: case ASIOSTInt32MSB: case ASIOSTFloat32MSB: case ASIOSTFloat64MSB: case ASIOSTInt32MSB16: case ASIOSTInt32MSB18: case ASIOSTInt32MSB20: case ASIOSTInt32MSB24: return true; break; default: return false; break; } } void CASIODevice::InternalFillAudioBuffer() { MPT_TRACE_SCOPE(); FillAsioBuffer(); } void CASIODevice::FillAsioBuffer(bool useSource) { MPT_TRACE_SCOPE(); const bool rendersilence = !useSource; const std::size_t countChunk = m_nAsioBufferLen; const std::size_t inputChannels = m_Settings.InputChannels; const std::size_t outputChannels = m_Settings.Channels; for(std::size_t inputChannel = 0; inputChannel < inputChannels; ++inputChannel) { std::size_t channel = inputChannel; void *src = m_BufferInfo[channel].buffers[static_cast<unsigned long>(m_BufferIndex) & 1]; if(IsSampleTypeBigEndian(m_ChannelInfo[channel].type)) { if(src) { SwapEndian(reinterpret_cast<uint8*>(src), countChunk, GetSampleSize(m_ChannelInfo[channel].type)); } } if(m_Settings.sampleFormat == SampleFormatFloat32) { float *const dstFloat = m_SampleInputBufferFloat.data(); if(!src) { // Skip if we did get no buffer for this channel, // Fill with zeroes. std::fill(dstFloat, dstFloat + countChunk, 0.0f); continue; } switch(m_ChannelInfo[channel].type) { case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: CopyChannelToInterleaved<SC::Convert<float, float> >(dstFloat, reinterpret_cast<float*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: CopyChannelToInterleaved<SC::Convert<float, double> >(dstFloat, reinterpret_cast<double*>(src), inputChannels, countChunk, inputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt16) { int16 *const dstInt16 = m_SampleInputBufferInt16.data(); if(!src) { // Skip if we did get no buffer for this channel, // Fill with zeroes. std::fill(dstInt16, dstInt16 + countChunk, int16(0)); continue; } switch(m_ChannelInfo[channel].type) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: CopyChannelToInterleaved<SC::Convert<int16, int16> >(dstInt16, reinterpret_cast<int16*>(src), inputChannels, countChunk, inputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt24) { int24 *const dstInt24 = m_SampleInputBufferInt24.data(); if(!src) { // Skip if we did get no buffer for this channel, // Fill with zeroes. std::fill(dstInt24, dstInt24 + countChunk, int24(0)); continue; } switch(m_ChannelInfo[channel].type) { case ASIOSTInt24MSB: case ASIOSTInt24LSB: CopyChannelToInterleaved<SC::Convert<int24, int24> >(dstInt24, reinterpret_cast<int24*>(src), inputChannels, countChunk, inputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt32) { int32 *const dstInt32 = m_SampleInputBufferInt32.data(); if(!src) { // Skip if we did get no buffer for this channel, // Fill with zeroes. std::fill(dstInt32, dstInt32 + countChunk, int32(0)); continue; } switch(m_ChannelInfo[channel].type) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: CopyChannelToInterleaved<SC::Convert<int32, int16> >(dstInt32, reinterpret_cast<int16*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt24MSB: case ASIOSTInt24LSB: CopyChannelToInterleaved<SC::Convert<int32, int24> >(dstInt32, reinterpret_cast<int24*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt32MSB: case ASIOSTInt32LSB: CopyChannelToInterleaved<SC::Convert<int32, int32> >(dstInt32, reinterpret_cast<int32*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: CopyChannelToInterleaved<SC::Convert<int32, float> >(dstInt32, reinterpret_cast<float*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: CopyChannelToInterleaved<SC::Convert<int32, double> >(dstInt32, reinterpret_cast<double*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt32MSB16: case ASIOSTInt32LSB16: CopyChannelToInterleaved<SC::ConvertShiftUp<int32, int32, 16> >(dstInt32, reinterpret_cast<int32*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt32MSB18: case ASIOSTInt32LSB18: CopyChannelToInterleaved<SC::ConvertShiftUp<int32, int32, 14> >(dstInt32, reinterpret_cast<int32*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt32MSB20: case ASIOSTInt32LSB20: CopyChannelToInterleaved<SC::ConvertShiftUp<int32, int32, 12> >(dstInt32, reinterpret_cast<int32*>(src), inputChannels, countChunk, inputChannel); break; case ASIOSTInt32MSB24: case ASIOSTInt32LSB24: CopyChannelToInterleaved<SC::ConvertShiftUp<int32, int32, 8> >(dstInt32, reinterpret_cast<int32*>(src), inputChannels, countChunk, inputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else { MPT_ASSERT_NOTREACHED(); } } if(rendersilence) { if(m_Settings.sampleFormat == SampleFormatFloat32) { std::memset(m_SampleBufferFloat.data(), 0, countChunk * outputChannels * sizeof(float)); } else if(m_Settings.sampleFormat == SampleFormatInt16) { std::memset(m_SampleBufferInt16.data(), 0, countChunk * outputChannels * sizeof(int16)); } else if(m_Settings.sampleFormat == SampleFormatInt24) { std::memset(m_SampleBufferInt24.data(), 0, countChunk * outputChannels * sizeof(int24)); } else if(m_Settings.sampleFormat == SampleFormatInt32) { std::memset(m_SampleBufferInt32.data(), 0, countChunk * outputChannels * sizeof(int32)); } else { MPT_ASSERT_NOTREACHED(); } } else { SourceLockedAudioReadPrepare(countChunk, m_nAsioBufferLen); if(m_Settings.sampleFormat == SampleFormatFloat32) { SourceLockedAudioRead(m_SampleBufferFloat.data(), (m_SampleInputBufferFloat.size() > 0) ? m_SampleInputBufferFloat.data() : nullptr, countChunk); } else if(m_Settings.sampleFormat == SampleFormatInt16) { SourceLockedAudioRead(m_SampleBufferInt16.data(), (m_SampleInputBufferInt16.size() > 0) ? m_SampleInputBufferInt16.data() : nullptr, countChunk); } else if(m_Settings.sampleFormat == SampleFormatInt24) { SourceLockedAudioRead(m_SampleBufferInt24.data(), (m_SampleInputBufferInt24.size() > 0) ? m_SampleInputBufferInt24.data() : nullptr, countChunk); } else if(m_Settings.sampleFormat == SampleFormatInt32) { SourceLockedAudioRead(m_SampleBufferInt32.data(), (m_SampleInputBufferInt32.size() > 0) ? m_SampleInputBufferInt32.data() : nullptr, countChunk); } else { MPT_ASSERT_NOTREACHED(); } } for(std::size_t outputChannel = 0; outputChannel < outputChannels; ++outputChannel) { std::size_t channel = outputChannel + m_Settings.InputChannels; void *dst = m_BufferInfo[channel].buffers[static_cast<unsigned long>(m_BufferIndex) & 1]; if(!dst) { // Skip if we did get no buffer for this channel continue; } if(m_Settings.sampleFormat == SampleFormatFloat32) { const float *const srcFloat = m_SampleBufferFloat.data(); switch(m_ChannelInfo[channel].type) { case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: CopyInterleavedToChannel<SC::Convert<float, float> >(reinterpret_cast<float*>(dst), srcFloat, outputChannels, countChunk, outputChannel); break; case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: CopyInterleavedToChannel<SC::Convert<double, float> >(reinterpret_cast<double*>(dst), srcFloat, outputChannels, countChunk, outputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt16) { const int16 *const srcInt16 = m_SampleBufferInt16.data(); switch(m_ChannelInfo[channel].type) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: CopyInterleavedToChannel<SC::Convert<int16, int16> >(reinterpret_cast<int16*>(dst), srcInt16, outputChannels, countChunk, outputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt24) { const int24 *const srcInt24 = m_SampleBufferInt24.data(); switch(m_ChannelInfo[channel].type) { case ASIOSTInt24MSB: case ASIOSTInt24LSB: CopyInterleavedToChannel<SC::Convert<int24, int24> >(reinterpret_cast<int24*>(dst), srcInt24, outputChannels, countChunk, outputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else if(m_Settings.sampleFormat == SampleFormatInt32) { const int32 *const srcInt32 = m_SampleBufferInt32.data(); switch(m_ChannelInfo[channel].type) { case ASIOSTInt16MSB: case ASIOSTInt16LSB: CopyInterleavedToChannel<SC::Convert<int16, int32> >(reinterpret_cast<int16*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt24MSB: case ASIOSTInt24LSB: CopyInterleavedToChannel<SC::Convert<int24, int32> >(reinterpret_cast<int24*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt32MSB: case ASIOSTInt32LSB: CopyInterleavedToChannel<SC::Convert<int32, int32> >(reinterpret_cast<int32*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTFloat32MSB: case ASIOSTFloat32LSB: CopyInterleavedToChannel<SC::Convert<float, int32> >(reinterpret_cast<float*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTFloat64MSB: case ASIOSTFloat64LSB: CopyInterleavedToChannel<SC::Convert<double, int32> >(reinterpret_cast<double*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt32MSB16: case ASIOSTInt32LSB16: CopyInterleavedToChannel<SC::ConvertShift<int32, int32, 16> >(reinterpret_cast<int32*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt32MSB18: case ASIOSTInt32LSB18: CopyInterleavedToChannel<SC::ConvertShift<int32, int32, 14> >(reinterpret_cast<int32*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt32MSB20: case ASIOSTInt32LSB20: CopyInterleavedToChannel<SC::ConvertShift<int32, int32, 12> >(reinterpret_cast<int32*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; case ASIOSTInt32MSB24: case ASIOSTInt32LSB24: CopyInterleavedToChannel<SC::ConvertShift<int32, int32, 8> >(reinterpret_cast<int32*>(dst), srcInt32, outputChannels, countChunk, outputChannel); break; default: MPT_ASSERT_NOTREACHED(); break; } } else { MPT_ASSERT_NOTREACHED(); } if(IsSampleTypeBigEndian(m_ChannelInfo[channel].type)) { SwapEndian(reinterpret_cast<uint8*>(dst), countChunk, GetSampleSize(m_ChannelInfo[channel].type)); } } if(m_CanOutputReady) { m_pAsioDrv->outputReady(); // do not handle errors, there is nothing we could do about them } if(!rendersilence) { SourceLockedAudioReadDone(); } } bool CASIODevice::InternalHasTimeInfo() const { MPT_TRACE_SCOPE(); return m_Settings.UseHardwareTiming; } SoundDevice::BufferAttributes CASIODevice::InternalGetEffectiveBufferAttributes() const { SoundDevice::BufferAttributes bufferAttributes; bufferAttributes.Latency = m_BufferLatency; bufferAttributes.UpdateInterval = static_cast<double>(m_nAsioBufferLen) / static_cast<double>(m_Settings.Samplerate); bufferAttributes.NumBuffers = 2; return bufferAttributes; } void CASIODevice::ApplyAsioTimeInfo(AsioTimeInfo asioTimeInfo) { MPT_TRACE_SCOPE(); if(m_Settings.UseHardwareTiming) { SoundDevice::TimeInfo timeInfo; if((asioTimeInfo.flags & kSamplePositionValid) && (asioTimeInfo.flags & kSystemTimeValid)) { double speed = 1.0; if((asioTimeInfo.flags & kSpeedValid) && (asioTimeInfo.speed > 0.0)) { speed = asioTimeInfo.speed; } else if((asioTimeInfo.flags & kSampleRateValid) && (asioTimeInfo.sampleRate > 0.0)) { speed *= asioTimeInfo.sampleRate / m_Settings.Samplerate; } timeInfo.SyncPointStreamFrames = ((((uint64)asioTimeInfo.samplePosition.hi) << 32) | asioTimeInfo.samplePosition.lo) - m_StreamPositionOffset; timeInfo.SyncPointSystemTimestamp = (((uint64)asioTimeInfo.systemTime.hi) << 32) | asioTimeInfo.systemTime.lo; timeInfo.Speed = speed; } else { // spec violation or nothing provided at all, better to estimate this stuff ourselves const uint64 asioNow = SourceLockedGetReferenceClockNowNanoseconds(); timeInfo.SyncPointStreamFrames = m_TotalFramesWritten + m_nAsioBufferLen - m_StreamPositionOffset; timeInfo.SyncPointSystemTimestamp = asioNow + mpt::saturate_round<int64>(m_BufferLatency * 1000.0 * 1000.0 * 1000.0); timeInfo.Speed = 1.0; } timeInfo.RenderStreamPositionBefore = StreamPositionFromFrames(m_TotalFramesWritten - m_StreamPositionOffset); timeInfo.RenderStreamPositionAfter = StreamPositionFromFrames(m_TotalFramesWritten - m_StreamPositionOffset + m_nAsioBufferLen); timeInfo.Latency = GetEffectiveBufferAttributes().Latency; SetTimeInfo(timeInfo); } } void CASIODevice::BufferSwitch(long doubleBufferIndex, ASIOBool directProcess) { MPT_TRACE_SCOPE(); BufferSwitchTimeInfo(nullptr, doubleBufferIndex, directProcess); // delegate } ASIOTime* CASIODevice::BufferSwitchTimeInfo(ASIOTime* params, long doubleBufferIndex, ASIOBool directProcess) { MPT_TRACE_SCOPE(); ASIOError asioresult = ASE_InvalidParameter; struct DebugRealtimeThreadIdGuard { std::atomic<uint32> & ThreadID; DebugRealtimeThreadIdGuard(std::atomic<uint32> & ThreadID) : ThreadID(ThreadID) { ThreadID.store(GetCurrentThreadId()); } ~DebugRealtimeThreadIdGuard() { ThreadID.store(0); } }; DebugRealtimeThreadIdGuard debugThreadIdGuard(m_DebugRealtimeThreadID); MPT_ASSERT(directProcess); // !directProcess is not handled correctly in OpenMPT, would require a separate thread and potentially additional buffering if(!directProcess) { m_UsedFeatures.set(AsioFeatureNoDirectProcess); } if(m_Settings.UseHardwareTiming) { AsioTimeInfo asioTimeInfo; MemsetZero(asioTimeInfo); if(params) { asioTimeInfo = params->timeInfo; } else { try { ASIOSamples samplePosition; ASIOTimeStamp systemTime; MemsetZero(samplePosition); MemsetZero(systemTime); asioresult = AsioCallUnchecked(AsioDriver(), getSamplePosition(&samplePosition, &systemTime)); if(asioresult == ASE_OK) { AsioTimeInfo asioTimeInfoQueried; MemsetZero(asioTimeInfoQueried); asioTimeInfoQueried.flags = kSamplePositionValid | kSystemTimeValid; asioTimeInfoQueried.samplePosition = samplePosition; asioTimeInfoQueried.systemTime = systemTime; asioTimeInfoQueried.speed = 1.0; ASIOSampleRate sampleRate; MemsetZero(sampleRate); asioresult = AsioCallUnchecked(AsioDriver(), getSampleRate(&sampleRate)); if(asioresult == ASE_OK) { if(sampleRate >= 0.0) { asioTimeInfoQueried.flags |= kSampleRateValid; asioTimeInfoQueried.sampleRate = sampleRate; } } asioTimeInfo = asioTimeInfoQueried; } } catch(...) { // continue } } ApplyAsioTimeInfo(asioTimeInfo); } m_BufferIndex = doubleBufferIndex; bool rendersilence = (m_RenderSilence == 1); m_RenderingSilence = (rendersilence ? 1 : 0); if(rendersilence) { m_StreamPositionOffset += m_nAsioBufferLen; FillAsioBuffer(false); } else { SourceFillAudioBufferLocked(); } m_TotalFramesWritten += m_nAsioBufferLen; return params; } void CASIODevice::SampleRateDidChange(ASIOSampleRate sRate) { MPT_TRACE_SCOPE(); if(mpt::saturate_round<uint32>(sRate) == m_Settings.Samplerate) { // not different, ignore it return; } m_UsedFeatures.set(AsioFeatureSampleRateChange); if(static_cast<double>(m_Settings.Samplerate) * (1.0 - AsioSampleRateTolerance) <= sRate && sRate <= static_cast<double>(m_Settings.Samplerate) * (1.0 + AsioSampleRateTolerance)) { // ignore slight differences which might be due to a unstable external ASIO clock source return; } // play safe and close the device RequestClose(); } static mpt::ustring AsioFeaturesToString(FlagSet<AsioFeatures> features) { mpt::ustring result; bool first = true; if(features[AsioFeatureResetRequest]) { if(!first) { result += U_(","); } first = false; result += U_("reset"); } if(features[AsioFeatureResyncRequest]) { if(!first) { result += U_(","); } first = false; result += U_("resync"); } if(features[AsioFeatureLatenciesChanged]) { if(!first) { result += U_(","); } first = false; result += U_("latency"); } if(features[AsioFeatureBufferSizeChange]) { if(!first) { result += U_(","); } first = false; result += U_("buffer"); } if(features[AsioFeatureOverload]) { if(!first) { result += U_(","); } first = false; result += U_("load"); } if(features[AsioFeatureNoDirectProcess]) { if(!first) { result += U_(","); } first = false; result += U_("nodirect"); } if(features[AsioFeatureSampleRateChange]) { if(!first) { result += U_(","); } first = false; result += U_("srate"); } return result; } bool CASIODevice::DebugIsFragileDevice() const { return true; } bool CASIODevice::DebugInRealtimeCallback() const { return GetCurrentThreadId() == m_DebugRealtimeThreadID.load(); } SoundDevice::Statistics CASIODevice::GetStatistics() const { MPT_TRACE_SCOPE(); SoundDevice::Statistics result; result.InstantaneousLatency = m_BufferLatency; result.LastUpdateInterval = static_cast<double>(m_nAsioBufferLen) / static_cast<double>(m_Settings.Samplerate); result.text = mpt::ustring(); const FlagSet<AsioFeatures> unsupported(AsioFeatureNoDirectProcess | AsioFeatureOverload | AsioFeatureBufferSizeChange | AsioFeatureSampleRateChange); FlagSet<AsioFeatures> unsupportedFeatues = m_UsedFeatures; unsupportedFeatues &= unsupported; if(unsupportedFeatues.any()) { result.text = mpt::format(U_("WARNING: unsupported features: %1"))(AsioFeaturesToString(unsupportedFeatues)); } else if(m_UsedFeatures.any()) { result.text = mpt::format(U_("OK, features used: %1"))(AsioFeaturesToString(m_UsedFeatures)); } else if(m_QueriedFeatures.any()) { result.text = mpt::format(U_("OK, features queried: %1"))(AsioFeaturesToString(m_QueriedFeatures)); } else { result.text = U_("OK."); } return result; } long CASIODevice::AsioMessage(long selector, long value, void* message, double* opt) { MPT_TRACE_SCOPE(); long result = 0; switch(selector) { case kAsioSelectorSupported: switch(value) { case kAsioSelectorSupported: case kAsioEngineVersion: result = 1; break; case kAsioSupportsTimeInfo: result = m_Settings.UseHardwareTiming ? 1 : 0; break; case kAsioResetRequest: m_QueriedFeatures.set(AsioFeatureResetRequest); result = 1; break; case kAsioBufferSizeChange: m_QueriedFeatures.set(AsioFeatureBufferSizeChange); result = 0; break; case kAsioResyncRequest: m_QueriedFeatures.set(AsioFeatureResyncRequest); result = 1; break; case kAsioLatenciesChanged: m_QueriedFeatures.set(AsioFeatureLatenciesChanged); result = 1; break; case kAsioOverload: m_QueriedFeatures.set(AsioFeatureOverload); // unsupported result = 0; break; default: // unsupported result = 0; break; } break; case kAsioEngineVersion: result = 2; break; case kAsioSupportsTimeInfo: result = m_Settings.UseHardwareTiming ? 1 : 0; break; case kAsioResetRequest: m_UsedFeatures.set(AsioFeatureResetRequest); RequestReset(); result = 1; break; case kAsioBufferSizeChange: m_UsedFeatures.set(AsioFeatureBufferSizeChange); // We do not support kAsioBufferSizeChange. // This should cause a driver to send a kAsioResetRequest. result = 0; break; case kAsioResyncRequest: m_UsedFeatures.set(AsioFeatureResyncRequest); RequestRestart(); result = 1; break; case kAsioLatenciesChanged: m_AsioRequestFlags.fetch_or(AsioRequestFlagLatenciesChanged); result = 1; break; case kAsioOverload: m_UsedFeatures.set(AsioFeatureOverload); // unsupported result = 0; break; default: // unsupported result = 0; break; } MPT_LOG(LogDebug, "sounddev", mpt::format(U_("ASIO: AsioMessage(selector=%1, value=%2, message=%3, opt=%4) => result=%5")) ( selector , value , reinterpret_cast<std::size_t>(message) , opt ? mpt::ufmt::val(*opt) : U_("NULL") , result )); return result; } long CASIODevice::CallbackAsioMessage(long selector, long value, void* message, double* opt) { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS(g_CallbacksInstance); if(!g_CallbacksInstance) return 0; return g_CallbacksInstance->AsioMessage(selector, value, message, opt); } void CASIODevice::CallbackSampleRateDidChange(ASIOSampleRate sRate) { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS(g_CallbacksInstance); if(!g_CallbacksInstance) return; g_CallbacksInstance->SampleRateDidChange(sRate); } void CASIODevice::CallbackBufferSwitch(long doubleBufferIndex, ASIOBool directProcess) { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS(g_CallbacksInstance); if(!g_CallbacksInstance) return; g_CallbacksInstance->BufferSwitch(doubleBufferIndex, directProcess); } ASIOTime* CASIODevice::CallbackBufferSwitchTimeInfo(ASIOTime* params, long doubleBufferIndex, ASIOBool directProcess) { MPT_TRACE_SCOPE(); MPT_ASSERT_ALWAYS(g_CallbacksInstance); if(!g_CallbacksInstance) return params; return g_CallbacksInstance->BufferSwitchTimeInfo(params, doubleBufferIndex, directProcess); } void CASIODevice::ReportASIOException(const std::string &str) { MPT_TRACE_SCOPE(); SendDeviceMessage(LogError, mpt::ToUnicode(mpt::CharsetLocale, str)); } SoundDevice::Caps CASIODevice::InternalGetDeviceCaps() { MPT_TRACE_SCOPE(); SoundDevice::Caps caps; caps.Available = true; caps.CanUpdateInterval = false; caps.CanSampleFormat = false; caps.CanExclusiveMode = false; caps.CanBoostThreadPriority = false; caps.CanKeepDeviceRunning = true; caps.CanUseHardwareTiming = true; caps.CanChannelMapping = true; caps.CanInput = true; caps.HasNamedInputSources = true; caps.CanDriverPanel = true; caps.LatencyMin = 0.000001; // 1 us caps.LatencyMax = 0.5; // 500 ms caps.UpdateIntervalMin = 0.0; // disabled caps.UpdateIntervalMax = 0.0; // disabled caps.DefaultSettings.sampleFormat = SampleFormatFloat32; return caps; } SoundDevice::DynamicCaps CASIODevice::GetDeviceDynamicCaps(const std::vector<uint32> &baseSampleRates) { MPT_TRACE_SCOPE(); SoundDevice::DynamicCaps caps; TemporaryASIODriverOpener opener(*this); if(!IsDriverOpen()) { m_DeviceUnavailableOnOpen = true; return caps; } try { ASIOSampleRate samplerate = 0.0; AsioCall(AsioDriver(), getSampleRate(&samplerate)); if(samplerate > 0.0) { caps.currentSampleRate = mpt::saturate_round<uint32>(samplerate); } } catch(...) { // continue } for(size_t i = 0; i < baseSampleRates.size(); i++) { try { ASIOError asioresult = AsioCallUnchecked(AsioDriver(), canSampleRate((ASIOSampleRate)baseSampleRates[i])); if(asioresult == ASE_OK) { caps.supportedSampleRates.push_back(baseSampleRates[i]); caps.supportedExclusiveSampleRates.push_back(baseSampleRates[i]); } } catch(...) { // continue } } try { long inputChannels = 0; long outputChannels = 0; AsioCall(AsioDriver(), getChannels(&inputChannels, &outputChannels)); if(!((inputChannels > 0) || (outputChannels > 0))) { m_DeviceUnavailableOnOpen = true; } for(long i = 0; i < outputChannels; ++i) { ASIOChannelInfo channelInfo; MemsetZero(channelInfo); channelInfo.channel = i; channelInfo.isInput = ASIOFalse; mpt::ustring name = mpt::ufmt::dec(i); try { AsioCall(AsioDriver(), getChannelInfo(&channelInfo)); mpt::String::SetNullTerminator(channelInfo.name); name = mpt::ToUnicode(mpt::CharsetLocale, channelInfo.name); } catch(...) { // continue } caps.channelNames.push_back(name); } for(long i = 0; i < inputChannels; ++i) { ASIOChannelInfo channelInfo; MemsetZero(channelInfo); channelInfo.channel = i; channelInfo.isInput = ASIOTrue; mpt::ustring name = mpt::ufmt::dec(i); try { AsioCall(AsioDriver(), getChannelInfo(&channelInfo)); mpt::String::SetNullTerminator(channelInfo.name); name = mpt::ToUnicode(mpt::CharsetLocale, channelInfo.name); } catch(...) { // continue } caps.inputSourceNames.push_back(std::make_pair(static_cast<uint32>(i), name)); } } catch(...) { // continue } return caps; } bool CASIODevice::OpenDriverSettings() { MPT_TRACE_SCOPE(); TemporaryASIODriverOpener opener(*this); if(!IsDriverOpen()) { return false; } try { AsioCall(AsioDriver(), controlPanel()); } catch(...) { return false; } return true; } #endif // MPT_WITH_ASIO } // namespace SoundDevice OPENMPT_NAMESPACE_END
27.744824
236
0.720775
[ "vector" ]
19b781cd068d4a68ec8ca2fbc9c006662aa10f12
3,647
cc
C++
granary/cfg/trace.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
41
2015-10-15T19:56:58.000Z
2022-02-03T19:35:10.000Z
granary/cfg/trace.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
null
null
null
granary/cfg/trace.cc
Granary/granary2
66f60e0a9d94c9e9bf9df78587871b981c9e3bed
[ "MIT" ]
7
2015-10-16T21:16:20.000Z
2022-01-15T02:02:20.000Z
/* Copyright 2014 Peter Goodman, all rights reserved. */ #define GRANARY_INTERNAL #include "arch/base.h" #include "granary/base/cstring.h" #include "granary/base/pc.h" #include "granary/cfg/block.h" #include "granary/cfg/trace.h" #include "granary/context.h" #include "granary/breakpoint.h" namespace granary { Trace::Trace(Context *context_) : context(context_), entry_block(nullptr), blocks(), first_new_block(nullptr), num_temporary_regs(kMinTemporaryVirtualRegister), num_virtual_regs(kMinTraceVirtualRegister), num_basic_blocks(0), generation(0) {} // Destroy the CFG and all basic blocks in the CFG. Trace::~Trace(void) { for (Block *block(blocks.First()), *next(nullptr); block; block = next) { next = block->list.Next(); delete block; } } // Return the entry basic block of this control-flow graph. DecodedBlock *Trace::EntryBlock(void) const { return DynamicCast<DecodedBlock *>(entry_block); } // Returns an object that can be used inside of a range-based for loop. BlockIterator Trace::Blocks(void) const { return BlockIterator(blocks.First()); } // Returns an object that can be used inside of a range-based for loop. ReverseBlockIterator Trace::ReverseBlocks(void) const { return ReverseBlockIterator(blocks.Last()); } // Returns an object that can be used inside of a range-based for loop. BlockIterator Trace::NewBlocks(void) const { return BlockIterator(first_new_block); } // Add a block to the CFG. If the block has successors that haven't yet been // added, then add those too. void Trace::AddBlock(Block *block) { if (block->list.IsLinked()) { GRANARY_ASSERT(-1 != block->Id()); } else { // We might already have a block id if this block inherits the id of the // `DirectBlock` that led to its materialization. if (-1 == block->id) block->id = num_basic_blocks++; // Distinguishes old from new blocks across iterations of // `InstrumentControlFlow`. block->generation = generation; blocks.Append(block); for (auto succ : block->Successors()) { // Add the successors. AddBlock(succ.block); } } } // Add a block to the trace as the entry block. void Trace::AddEntryBlock(Block *block) { entry_block = block; AddBlock(block); if (blocks.First() != block) { blocks.Remove(block); blocks.Prepend(block); } first_new_block = block; ++generation; } // Allocate a new virtual register that is local to the trace. VirtualRegister Trace::AllocateVirtualRegister(size_t num_bytes) { GRANARY_ASSERT(0 < num_bytes && arch::GPR_WIDTH_BYTES >= num_bytes); auto reg_num = num_virtual_regs++; GRANARY_ASSERT(kMinTraceVirtualRegister <= num_virtual_regs); GRANARY_ASSERT(kMinGlobalVirtualRegister > num_virtual_regs); return VirtualRegister(kVirtualRegisterKindVirtualGpr, static_cast<uint8_t>(num_bytes), reg_num); } // Allocate a new "temporary" virtual register. These VRs are meant for use // in instruction mangling/processing, and are re-used across instructions. VirtualRegister Trace::AllocateTemporaryRegister(size_t num_bytes) { GRANARY_ASSERT(0 < num_bytes && arch::GPR_WIDTH_BYTES >= num_bytes); auto reg_num = num_temporary_regs++; GRANARY_ASSERT(kMinTemporaryVirtualRegister <= reg_num); GRANARY_ASSERT(kMinTraceVirtualRegister > reg_num); return VirtualRegister(kVirtualRegisterKindVirtualGpr, static_cast<uint8_t>(num_bytes), reg_num); } // Free all temporary virtual registers. void Trace::FreeTemporaryRegisters(void) { num_temporary_regs = kMinTemporaryVirtualRegister; } } // namespace granary
31.713043
76
0.722237
[ "object" ]
19b8a9610d6a786b38b0ebc5f0ba65a464886e8b
1,461
cpp
C++
lsd/examples/lsd_opencv_cmd.cpp
huihui891/groundLineDetection
7306e05dad202d6bfa71d4b72d6a9716005df39b
[ "Apache-2.0" ]
null
null
null
lsd/examples/lsd_opencv_cmd.cpp
huihui891/groundLineDetection
7306e05dad202d6bfa71d4b72d6a9716005df39b
[ "Apache-2.0" ]
null
null
null
lsd/examples/lsd_opencv_cmd.cpp
huihui891/groundLineDetection
7306e05dad202d6bfa71d4b72d6a9716005df39b
[ "Apache-2.0" ]
1
2018-11-25T02:34:18.000Z
2018-11-25T02:34:18.000Z
#include <iostream> #include <fstream> #include <string> #include <opencv2/opencv.hpp> #include "lsd_opencv.hpp" using namespace std; using namespace cv; int main(int argc, char** argv) { if (argc != 3) { std::cout << "lsd_opencv_cmd [in] [out]" << std::endl << "\tin - input image" << std::endl << "\tout - output containing a line segment at each line [x1, y1, x2, y2, width, p, -log10(NFA)]" << std::endl; return false; } std::string in = argv[1]; std::string out = argv[2]; Mat image = imread(in, CV_LOAD_IMAGE_GRAYSCALE); // LSD call std::vector<Vec4i> lines; std::vector<double> width, prec; Ptr<LineSegmentDetector> lsd = createLineSegmentDetectorPtr(); double start = double(getTickCount()); lsd->detect(image, lines, width, prec); double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency(); std::cout << lines.size() <<" line segments found. For " << duration_ms << " ms." << std::endl; //Save to file ofstream segfile; segfile.open(out.c_str()); for (unsigned int i = 0; i < lines.size(); ++i) { cout << '\t' << "B: " << lines[i][0] << " " << lines[i][1] << " E: " << lines[i][2] << " " << lines[i][3] << " W: " << width[i] << " P:" << prec[i] << endl; segfile << '\t' << "B: " << lines[i][0] << " " << lines[i][1] << " E: " << lines[i][2] << " " << lines[i][3] << " W: " << width[i] << " P:" << prec[i] << endl; } segfile.close(); return 0; }
26.563636
115
0.566051
[ "vector" ]
19ba6a1266b44f0f2ef552080b61f78d08d967a4
7,371
hh
C++
packages/SPn/mesh/Mesh.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/SPn/mesh/Mesh.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/SPn/mesh/Mesh.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file SPn/mesh/Mesh.hh * \author Tom Evans * \date Wednesday February 12 0:15:45 2014 * \brief Declaration of Mesh * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #ifndef SPn_mesh_Mesh_hh #define SPn_mesh_Mesh_hh #include <vector> #include "harness/DBC.hh" #include "utils/Definitions.hh" #include "utils/Vector_Lite.hh" namespace profugus { //===========================================================================// /*! * \class Mesh * \brief Orthogonal mesh class. * * The mesh is partitioned in (I,J) blocks where I has range [0,Np_I) and J * has range [0,Np_J) and the \f$ N_p = (N_p)_I\times(N_p)_J\f$. The * processor id for this mesh is calculated using * \f[ * \mbox{proc\_id} = * \mbox{I\_block} + \mbox{J\_block}\times(N_p)_I\:. * \f] * * There are no separate domains in K; however, the user can define effective * blocks in K for added parallel efficiency. The number of cells in each * "effective" parallel block is thus \f$ N_x\times N_y\times\mbox{int}(N_z / * \mbox{num\_K\_blocks})\f$. All meshes in the decomposition must have the * same number of K blocks and \f$ N_z \f$ defined. A current restriction is * that \f$ N_z\, \mbox{mod}\,\mbox{num\_K\_blocks} = 0 \f$. * */ /*! * \example spn/test/tstMesh.cc * * Test of Mesh. */ //===========================================================================// class Mesh { public: //@{ //! Useful typedefs for classes that use mesh. typedef def::size_type size_type; typedef def::tiny_int dim_type; typedef profugus::Vector_Lite<int, 3> Dim_Vector; typedef profugus::Vector_Lite<double, 3> Space_Vector; typedef profugus::Vector_Lite<def::Vec_Dbl, 3> Cell_Edges; typedef profugus::Vector_Lite<def::Vec_Dbl, 3> Cell_Widths; //@} public: // Build a 3D mesh (or, if z_edges is empty, a 2-D mesh). Mesh(const def::Vec_Dbl &x_edges, const def::Vec_Dbl &y_edges, const def::Vec_Dbl &z_edges, size_type I_block, size_type J_block, size_type num_K_blocks); // Build a 2D mesh Mesh(const def::Vec_Dbl &x_edges, const def::Vec_Dbl &y_edges, size_type I_block, size_type J_block); // >>> PUBLIC INTERFACE // Convert cardinal index to (i,j) or (i,j,k). inline Dim_Vector cardinal(size_type cell) const; // Cell volume. inline double volume(size_type cell) const; // Block width. inline Space_Vector block_widths() const; // Query to see if a point is in a mesh. bool find_cell(const Space_Vector &r, Dim_Vector &ijk) const; // Label of mesh std::string label() const { if (dimension() == 3) return "xyz_3d"; return "xy_2d"; } // >>> NON-VIRTUAL FUNCTIONS //! Dimension of mesh. size_type dimension() const { return d_dimension; } //! Get number of cells. size_type num_cells() const { return d_num_cells; } //! Get number of vertices. size_type num_vertices() const { REQUIRE(d_num_vertices != 0); return d_num_vertices; } // Returns the width of a cell in a given direction inline double width(size_type ijk, int dim) const; // Return inverse of cell width along \e (i,j) or \e (i,j,k). inline double inv_width(size_type ijk, int dim) const; // convert (i,j,k) to cardinal index inline size_type convert(size_type i, size_type j, size_type k) const; // Convert (i,j) to cardinal index assumes k=0 (if 3D) inline size_type convert(size_type i, size_type j) const; // Cell center along \e (i,j) or \e(i,j,k). inline double center(size_type ijk, int dim) const; //! Low corner of mesh in \e (i,j,k) direction. double low_corner(int d) const { REQUIRE(d < static_cast<int>(d_dimension) ); return d_edges[d].front(); } //! High corner of mesh in \e (i,j,k) direction. double high_corner(int d) const { REQUIRE(d < static_cast<int>(d_dimension) ); return d_edges[d].back(); } //! Return all cell edges. const Cell_Edges& edges() const { return d_edges; } //! Return cell edges along a given direction. const def::Vec_Dbl& edges(int d) const { REQUIRE(d < static_cast<int>(d_dimension) ); return d_edges[d]; } //! Return cell edge coordinate along \e d. double edges(int vertices, int d) const { REQUIRE(d < static_cast<int>(d_dimension) && vertices < static_cast<int>(d_edges[d].size())); return d_edges[d][vertices]; } //! Return block width in a particular direction. double block_width(int d) const { REQUIRE(d < 3); return d_edges[d].back() - d_edges[d].front(); } //! Return number of cells in each dimension in this mesh. const Dim_Vector& num_cells_dims() const { return d_N; } //! Return number of cells in a given dimension \e ijk in this mesh. inline int num_cells_dim(size_type ijk) const { REQUIRE(ijk < 3); return d_N[ijk]; } //! Get block description (block index on i/j; num blocks along z). const Dim_Vector& get_blocks() const { return d_blocks; } //! Get block index along dimension (or number of blocks if 3) size_type block(size_type ijk) const { REQUIRE(ijk < d_dimension); return d_blocks[ijk]; } //! Get number of cells in each dimension in each block in this mesh. const Dim_Vector& num_cells_block_dims() const { return d_Nb; } //! Get number of cells in a given block along dimension \e (i,j,k). size_type num_cells_block_dim(size_type ijk) const { REQUIRE(ijk < d_dimension); return d_Nb[ijk]; } protected: // >>> protected interfaces used in the derived mesh classes // builds cell widths and inverse cell widths void build_mesh(); private: // >>> DATA // dimension of mesh const size_type d_dimension; // Number of cells in mesh. size_type d_num_cells; // Number of vertices in mesh. size_type d_num_vertices; //! Number of cells in each dimension in this mesh. Dim_Vector d_N; //@{ //! Block description either IxJ if 2D or IxJxK in 3D, I J are block IDs, //! K is the number of blocks in the Z direction Dim_Vector d_blocks; //@} //! Number of cells in each dimension in each block of this mesh. Dim_Vector d_Nb; // Cell edges. Cell_Edges d_edges; // Cell widths. Cell_Widths d_width; // Inverse cell widths. Cell_Widths d_inv_width; }; //---------------------------------------------------------------------------// } // end namespace profugus //---------------------------------------------------------------------------// // INLINE FUNCTIONS //---------------------------------------------------------------------------// #include "Mesh.i.hh" #endif // SPn_mesh_Mesh_hh //---------------------------------------------------------------------------// // end of spn/Mesh.hh //---------------------------------------------------------------------------//
29.366534
79
0.572921
[ "mesh", "vector", "3d" ]
19bc19a6ed8f4df401581521ecfdd4aca9c47b81
735
hpp
C++
include/mgard-x/MDR-X/SizeInterpreter/SizeInterpreterInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
include/mgard-x/MDR-X/SizeInterpreter/SizeInterpreterInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
include/mgard-x/MDR-X/SizeInterpreter/SizeInterpreterInterface.hpp
JieyangChen7/MGARD
acec8facae1e2767a3adff2bb3c30f3477e69bdb
[ "Apache-2.0" ]
null
null
null
#ifndef _MDR_SIZE_INTERPRETER_INTERFACE_HPP #define _MDR_SIZE_INTERPRETER_INTERFACE_HPP namespace mgard_x { namespace MDR { namespace concepts { // level bit-plane reorganizer: EBCOT-like algorithm for multilevel bit-plane // truncation class SizeInterpreterInterface { public: virtual ~SizeInterpreterInterface() = default; virtual std::vector<SIZE> interpret_retrieve_size(const std::vector<std::vector<SIZE>> &level_sizes, const std::vector<std::vector<double>> &level_errors, double tolerance, std::vector<uint8_t> &index) const = 0; virtual void print() const = 0; }; } // namespace concepts } // namespace MDR } // namespace mgard_x #endif
29.4
79
0.692517
[ "vector" ]
19c0fae73c19734ebf2997d41f2e53a462c51cd1
1,162
cpp
C++
fix_csv/src/delete_non_bosch_sensors.cpp
CppPhil/fix_mogasens_csv
eedfe3037c1bd626f81a40073bd616b58d6ba677
[ "Unlicense" ]
null
null
null
fix_csv/src/delete_non_bosch_sensors.cpp
CppPhil/fix_mogasens_csv
eedfe3037c1bd626f81a40073bd616b58d6ba677
[ "Unlicense" ]
null
null
null
fix_csv/src/delete_non_bosch_sensors.cpp
CppPhil/fix_mogasens_csv
eedfe3037c1bd626f81a40073bd616b58d6ba677
[ "Unlicense" ]
null
null
null
#include <tl/casts.hpp> #include <pl/algo/erase.hpp> #include <pl/string_view.hpp> #include <pl/stringify.hpp> #include <pl/unreachable.hpp> #include "cl/column.hpp" #include "cl/sensor.hpp" #include "delete_non_bosch_sensors.hpp" namespace fmc { namespace { constexpr pl::string_view extractIdString(cl::Sensor sensor) noexcept { using namespace pl::string_view_literals; switch (sensor) { #define CL_SENSOR_X(enm, value) \ case cl::Sensor::enm: return PL_STRINGIFY(value); CL_SENSOR #undef CL_SENSOR_X } PL_UNREACHABLE(); } } // namespace void deleteNonBoschSensors(std::vector<std::vector<std::string>>* data) { pl::algo::erase_if(*data, [](const std::vector<std::string>& row) { constexpr std::size_t index{cl::column_index<cl::Column::ExtractId>}; if (row.size() <= index) { return false; } const std::string& extractId{row[index]}; return (extractId != extractIdString(cl::Sensor::LeftArm)) && (extractId != extractIdString(cl::Sensor::Belly)) && (extractId != extractIdString(cl::Sensor::RightArm)) && (extractId != extractIdString(cl::Sensor::Chest)); }); } } // namespace fmc
25.26087
73
0.684165
[ "vector" ]
19c8ef1b18435a339990eb796ae8a236bd1601dc
4,938
cc
C++
src/core/rpc_recv_context.cc
dlintw/smf
7ad8b388ef1c051ca6e5f11e0d4c2415c8c3fda3
[ "Apache-2.0" ]
null
null
null
src/core/rpc_recv_context.cc
dlintw/smf
7ad8b388ef1c051ca6e5f11e0d4c2415c8c3fda3
[ "Apache-2.0" ]
null
null
null
src/core/rpc_recv_context.cc
dlintw/smf
7ad8b388ef1c051ca6e5f11e0d4c2415c8c3fda3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2016 Alexander Gallego. All rights reserved. // #include <smf/rpc_recv_context.h> #include <flatbuffers/minireflect.h> #include <smf/log.h> #include <smf/rpc_generated.h> #include "smf/rpc_header_utils.h" namespace std { ostream & operator<<(ostream &o, const smf::rpc::header &h) { o << "rpc::header=" << flatbuffers::FlatBufferToString(reinterpret_cast<const uint8_t *>(&h), smf::rpc::headerTypeTable()); return o; } } // namespace std namespace smf { rpc_recv_context::rpc_recv_context(seastar::socket_address address, rpc::header hdr, seastar::temporary_buffer<char> body) : remote_address(address), header(hdr), payload(std::move(body)) { assert(header.size() == payload.size()); } rpc_recv_context::rpc_recv_context(rpc_recv_context &&o) noexcept : remote_address(o.remote_address), header(o.header), payload(std::move(o.payload)) {} rpc_recv_context::~rpc_recv_context() {} seastar::future<seastar::temporary_buffer<char>> read_payload(rpc_connection *conn, size_t payload_size) { auto timeout = conn->limits->max_body_parsing_duration; seastar::timer<> body_timeout; body_timeout.set_callback([timeout, conn] { LOG_ERROR( "Parsing the body of the connnection exceeded max_timeout: {}ms", std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()); conn->set_error("Connection body parsing exceeded timeout"); conn->socket.shutdown_input(); }); body_timeout.arm(conn->limits->max_body_parsing_duration); return conn->istream.read_exactly(payload_size) .then([body_timeout = std::move(body_timeout)](auto payload) mutable { body_timeout.cancel(); return seastar::make_ready_future<decltype(payload)>(std::move(payload)); }); } constexpr uint32_t max_flatbuffers_size() { // 2GB - 1 is the max a flatbuffers::vector<uint8_t> can hold // // needed so that we have access to the internal typedefs using namespace flatbuffers; // NOLINT return static_cast<uint32_t>(FLATBUFFERS_MAX_BUFFER_SIZE); } seastar::future<stdx::optional<rpc_recv_context>> rpc_recv_context::parse_payload(rpc_connection *conn, rpc::header hdr) { using ret_type = stdx::optional<rpc_recv_context>; return read_payload(conn, hdr.size()) .then([conn, hdr](seastar::temporary_buffer<char> body) mutable { if (hdr.size() != body.size()) { LOG_ERROR("Read incorrect number of bytes `{}`, expected header: `{}`", body.size(), hdr); return seastar::make_ready_future<ret_type>(stdx::nullopt); } if (hdr.size() > max_flatbuffers_size()) { LOG_ERROR("Bad payload. Body is > FLATBUFFERS_MAX_BUFFER_SIZE"); return seastar::make_ready_future<ret_type>(stdx::nullopt); } if (hdr.bitflags() & rpc::header_bit_flags::header_bit_flags_has_payload_headers) { LOG_ERROR("Reading payload headers is not yet implemented"); return seastar::make_ready_future<ret_type>(stdx::nullopt); } const uint32_t xx = rpc_checksum_payload(body.get(), body.size()); if (xx != hdr.checksum()) { LOG_ERROR("Payload checksum `{}` does not match header checksum `{}`", xx, hdr.checksum()); return seastar::make_ready_future<ret_type>(stdx::nullopt); } rpc_recv_context ctx(conn->remote_address, hdr, std::move(body)); return seastar::make_ready_future<ret_type>( stdx::optional<rpc_recv_context>(std::move(ctx))); }); } seastar::future<stdx::optional<rpc::header>> rpc_recv_context::parse_header(rpc_connection *conn) { using ret_type = stdx::optional<rpc::header>; static constexpr size_t kRPCHeaderSize = sizeof(rpc::header); DLOG_THROW_IF( conn->istream_active_parser != 0, "without this line you can have interleaved reads on the buffer"); conn->istream_active_parser++; return conn->istream.read_exactly(kRPCHeaderSize) .then([conn](seastar::temporary_buffer<char> header) { if (kRPCHeaderSize != header.size()) { LOG_ERROR_IF(conn->is_valid(), "Invalid header size `{}`, expected `{}`, skipping req", header.size(), kRPCHeaderSize); return seastar::make_ready_future<ret_type>(stdx::nullopt); } rpc::header hdr; std::memcpy(&hdr, header.get(), header.size()); if (hdr.size() == 0) { LOG_ERROR("Emty body to parse. skipping"); return seastar::make_ready_future<ret_type>(stdx::nullopt); } if (hdr.compression() == rpc::compression_flags::compression_flags_disabled) { hdr.mutate_compression(rpc::compression_flags::compression_flags_none); } return seastar::make_ready_future<ret_type>(std::move(hdr)); }) .finally([conn] { conn->istream_active_parser--; }); } } // namespace smf
37.694656
79
0.669704
[ "vector" ]
19ca2e0348da487194d7e6a59d3aa50ece72bb02
2,190
cpp
C++
C++/188.best-time-to-buy-and-sell-stock-iv.cpp
WilliamZhaoz/github
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
[ "MIT" ]
1
2018-03-06T05:07:22.000Z
2018-03-06T05:07:22.000Z
C++/188.best-time-to-buy-and-sell-stock-iv.cpp
WilliamZhaoz/github
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
[ "MIT" ]
1
2021-12-24T16:41:02.000Z
2021-12-24T16:41:02.000Z
C++/188.best-time-to-buy-and-sell-stock-iv.cpp
WilliamZhaoz/github
2aa0eb17e272249fc225cf2e9861c4c44bd0e265
[ "MIT" ]
null
null
null
class Solution { public: int maxProfit(int k, vector<int>& prices) { // version 1: dp // buy[i][k], the max profit at the ith day when is buy in state after kth transactions, the max profit at the ith day when is sell out states after kth transactions // buy[i][k] = max(buy[i - 1][k], sell[i - 1][k - 1] - prices[i]) // sell[i][k] = max(sell[i - 1][k], buy[i - 1][k - 1] + preices[i]) // space optimization: sell[i][k] -> sell[k] // return sell[k] /* if (k > prices.size() / 2) { return helper(prices); } vector<int> buys(k + 1, INT_MIN); vector<int> sells(k + 1, 0); for (int i = 0; i < prices.size(); i++) { for (int j = 1; j <= k; j++) { buys[j] = max(buys[j], sells[j - 1] - prices[i]); sells[j] = max(sells[j], buys[j] + prices[i]); } } return sells[k]; */ // version 2: dp // global[i][k], the max profit until the ith day after kth transactions // local[i][k], the max profit until the ith day after kth transactions when the last transaction is sell at ith day. // global[i][k] = max(global[i - 1][k], local[i][k]) // local[i][k] = max(local[i - 1][k], global[i - 1][k - 1]) + diff // space optimization: global[i][k] -> global[k] // return global[k] if (k > prices.size() / 2) { return helper(prices); } vector<int> global(k + 1, 0); vector<int> local(k + 1, 0); for (int i = 1; i < prices.size(); i++) { int diff = prices[i] - prices[i - 1]; for (int j = k; j >= 1; j--) { local[j] = max(local[j], global[j - 1] ) + diff; global[j] = max(global[j], local[j]); } } return global[k]; } int helper(vector<int> & prices) { int res = 0; if (prices.size() <= 2) { return res; } for (int i = 1; i < prices.size(); i++) { res += prices[i] > prices[i - 1] ? (prices[i] - prices[i - 1]) : 0; } return res; } };
39.107143
173
0.460731
[ "vector" ]
19cc9a77263da62a368c26a5616e7134b65bf687
9,052
cpp
C++
src/utils/input_reads_profiler.cpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
1
2018-08-21T23:34:28.000Z
2018-08-21T23:34:28.000Z
src/utils/input_reads_profiler.cpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
src/utils/input_reads_profiler.cpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2018 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include "input_reads_profiler.hpp" #include <random> #include <deque> #include <iterator> #include <algorithm> #include <utility> #include <cassert> #include "mappable_algorithms.hpp" #include "maths.hpp" #include "append.hpp" namespace octopus { namespace { template <typename ForwardIt, typename RandomGenerator> ForwardIt random_select(ForwardIt first, ForwardIt last, RandomGenerator& g) { if (first == last) return first; const auto max = static_cast<std::size_t>(std::distance(first, last)); std::uniform_int_distribution<std::size_t> dist {0, max - 1}; std::advance(first, dist(g)); return first; } template <typename ForwardIt> ForwardIt random_select(ForwardIt first, ForwardIt last) { static std::default_random_engine gen {}; return random_select(first, last, gen); } auto estimate_dynamic_size(const AlignedRead& read) noexcept { return read.name().size() * sizeof(char) + read.read_group().size() * sizeof(char) + sequence_size(read) * sizeof(char) + sequence_size(read) * sizeof(AlignedRead::BaseQuality) + read.cigar().size() * sizeof(CigarOperation) + contig_name(read).size() * sizeof(char) + (read.has_other_segment() ? sizeof(AlignedRead::Segment) : 0); } auto estimate_read_size(const AlignedRead& read) noexcept { return sizeof(AlignedRead) + estimate_dynamic_size(read); } auto get_covered_sample_regions(const std::vector<SampleName>& samples, const InputRegionMap& input_regions, const ReadManager& read_manager) { InputRegionMap result {}; result.reserve(input_regions.size()); for (const auto& p : input_regions) { InputRegionMap::mapped_type contig_regions {}; std::copy_if(std::cbegin(p.second), std::cend(p.second), std::inserter(contig_regions, std::begin(contig_regions)), [&] (const auto& region) { return read_manager.has_reads(samples, region); }); if (!contig_regions.empty()) { result.emplace(p.first, std::move(contig_regions)); } } return result; } auto choose_sample_region(const GenomicRegion& from, GenomicRegion::Size max_size) { if (size(from) <= max_size) return from; const auto max_begin = from.end() - max_size; static std::default_random_engine gen {}; std::uniform_int_distribution<GenomicRegion::Position> dist {from.begin(), max_begin}; return GenomicRegion {from.contig_name(), dist(gen), from.end()}; } auto draw_sample(const SampleName& sample, const InputRegionMap& regions, const ReadManager& source, const ReadSetProfileConfig& config) { const auto contig_itr = random_select(std::cbegin(regions), std::cend(regions)); assert(!contig_itr->second.empty()); const auto region_itr = random_select(std::cbegin(contig_itr->second), std::cend(contig_itr->second)); const auto sample_region = choose_sample_region(*region_itr, config.max_sample_size); auto test_region = source.find_covered_subregion(sample, sample_region, config.max_sample_size); if (is_empty(test_region)) { test_region = expand_rhs(test_region, 1); } return source.fetch_reads(sample, test_region); } auto draw_sample_from_begin(const SampleName& sample, const InputRegionMap& regions, const ReadManager& source, const ReadSetProfileConfig& config) { const auto contig_itr = random_select(std::cbegin(regions), std::cend(regions)); assert(!contig_itr->second.empty()); const auto region_itr = random_select(std::cbegin(contig_itr->second), std::cend(contig_itr->second)); auto test_region = source.find_covered_subregion(sample, *region_itr, config.max_sample_size); if (is_empty(test_region)) { test_region = expand_rhs(test_region, 1); } return source.fetch_reads(sample, test_region); } using ReadSetSamples = std::vector<ReadManager::ReadContainer>; bool all_empty(const ReadSetSamples& samples) { return std::all_of(std::cbegin(samples), std::cend(samples), [] (const auto& reads) { return reads.empty(); }); } auto draw_samples(const SampleName& sample, const InputRegionMap& regions, const ReadManager& source, const ReadSetProfileConfig& config) { ReadSetSamples result {}; result.reserve(config.max_samples_per_sample); std::generate_n(std::back_inserter(result), config.max_samples_per_sample, [&] () { return draw_sample(sample, regions, source, config); }); if (all_empty(result)) { result.back() = draw_sample_from_begin(sample, regions, source, config); } return result; } auto draw_samples(const std::vector<SampleName>& samples, const InputRegionMap& regions, const ReadManager& source, const ReadSetProfileConfig& config) { std::vector<ReadSetSamples> result {}; result.reserve(samples.size()); for (const auto& sample : samples) { result.push_back(draw_samples(sample, regions, source, config)); } return result; } auto get_read_bytes(const std::vector<ReadSetSamples>& read_sets) { std::deque<std::size_t> result {}; for (const auto& set : read_sets) { for (const auto& reads : set) { std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(result), estimate_read_size); } } return result; } } // namespace boost::optional<ReadSetProfile> profile_reads(const std::vector<SampleName>& samples, const InputRegionMap& input_regions, const ReadManager& source, ReadSetProfileConfig config) { if (input_regions.empty()) return boost::none; const auto sampling_regions = get_covered_sample_regions(samples, input_regions, source); if (sampling_regions.empty()) return boost::none; const auto read_sets = draw_samples(samples, sampling_regions, source, config); if (read_sets.empty()) return boost::none; const auto bytes = get_read_bytes(read_sets); if (bytes.empty()) return boost::none; ReadSetProfile result {}; result.mean_read_bytes = maths::mean(bytes); result.read_bytes_stdev = maths::stdev(bytes); result.sample_mean_depth.resize(samples.size()); result.sample_depth_stdev.resize(samples.size()); std::deque<unsigned> depths {}; for (std::size_t s {0}; s < samples.size(); ++s) { std::deque<unsigned> sample_depths {}; for (const auto& reads : read_sets[s]) { if (!reads.empty()) { utils::append(calculate_positional_coverage(reads), sample_depths); } } if (!sample_depths.empty()) { result.sample_mean_depth[s] = maths::mean(sample_depths); result.sample_depth_stdev[s] = maths::stdev(sample_depths); } else { result.sample_mean_depth[s] = 0; result.sample_depth_stdev[s] = 0; } utils::append(std::move(sample_depths), depths); } assert(!depths.empty()); result.mean_depth = maths::mean(depths); result.depth_stdev = maths::stdev(depths); return result; } boost::optional<std::size_t> estimate_mean_read_size(const std::vector<SampleName>& samples, const InputRegionMap& input_regions, ReadManager& read_manager, const unsigned max_sample_size) { if (input_regions.empty()) return boost::none; const auto sample_regions = get_covered_sample_regions(samples, input_regions, read_manager); if (sample_regions.empty()) return boost::none; const auto num_samples_per_sample = max_sample_size / samples.size(); std::deque<std::size_t> read_size_samples {}; // take read samples from each sample seperatly to ensure we cover each for (const auto& sample : samples) { const auto it = random_select(std::cbegin(sample_regions), std::cend(sample_regions)); assert(!it->second.empty()); const auto it2 = random_select(std::cbegin(it->second), std::cend(it->second)); auto test_region = read_manager.find_covered_subregion(sample, *it2, num_samples_per_sample); if (is_empty(test_region)) { test_region = expand_rhs(test_region, 1); } const auto reads = read_manager.fetch_reads(sample, test_region); std::transform(std::cbegin(reads), std::cend(reads), std::back_inserter(read_size_samples), estimate_read_size); } if (read_size_samples.empty()) return boost::none; return static_cast<std::size_t>(maths::mean(read_size_samples) + maths::stdev(read_size_samples)); } std::size_t default_read_size_estimate() noexcept { return sizeof(AlignedRead) + 300; } } // namespace octopus
40.410714
115
0.670128
[ "vector", "transform" ]
19d1cc523c63dd4378b974fb801d87f80e5b5ea9
2,410
cpp
C++
ROS_WS/site_ws/src/site_model/src/data_output/radar_listener.cpp
OrangeSodahub/ROS-WS
5b3c56ea1b46025298360eed9c06f25f7c5f7fe6
[ "MIT" ]
1
2022-03-20T19:16:06.000Z
2022-03-20T19:16:06.000Z
ROS_WS/site_ws/src/site_model/src/data_output/radar_listener.cpp
OrangeSodahub/ROS-WS
5b3c56ea1b46025298360eed9c06f25f7c5f7fe6
[ "MIT" ]
null
null
null
ROS_WS/site_ws/src/site_model/src/data_output/radar_listener.cpp
OrangeSodahub/ROS-WS
5b3c56ea1b46025298360eed9c06f25f7c5f7fe6
[ "MIT" ]
null
null
null
/*########################################################### # This cpp file subscribe the topic of radars and save # # the poses information of vehicles. # # Author: Yangxiuyu # ############################################################*/ #include "ros/ros.h" #include "std_msgs/String.h" #include <pcl/point_cloud.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <per_msgs/SensorMsgsRadar.h> #include <per_msgs/GeometryMsgsRadarObject.h> #include <vector> #include <fstream> #include <iostream> #include <time.h> #include <string> using namespace std; void RadarCB(const per_msgs::SensorMsgsRadar &Radarmsg) { time_t currentTime=time(NULL); char chCurrentTime[256]; std::cerr << "Successfully" << std::endl; ros::NodeHandle nh; ros::Publisher radar_pub = nh.advertise<sensor_msgs::PointCloud2> ("/radar_show_2", 1); pcl::PointCloud<pcl::PointXYZ> cloud; sensor_msgs::PointCloud2 output; // Fill in the cloud data int v_num = Radarmsg.front_left_esr_tracklist.size(); std::cerr << "left_tracklist_size: " << Radarmsg.front_left_esr_tracklist.size() << std::endl; if (v_num!=0) { // Set the file name strftime(chCurrentTime,sizeof(chCurrentTime),"%Y%m%d %H%M%S",localtime(&currentTime)); string stCurrentTime=chCurrentTime; string filename="/home/zonlin/IPP_WorkSpace/ROS_WS/site_ws/src/site_model/dataset/radar_data/data"+stCurrentTime+".txt"; cloud.width = v_num; cloud.height = 1; cloud.points.resize(cloud.width * cloud.height); for(int i=0;i<v_num;i++) { cloud.points[i].x = Radarmsg.front_left_esr_tracklist[i].obj_vcs_posex; cloud.points[i].y = Radarmsg.front_left_esr_tracklist[i].obj_vcs_posey; cloud.points[i].z = 2; } // Convert the cloud to ROS message pcl::toROSMsg(cloud, output); output.header.frame_id = "/base_link"; // Publish the data radar_pub.publish(output); // Save data to txt files ofstream fout; fout.open(filename.c_str()); int i=0; while(i<v_num) { fout<< i << " " << cloud.points[i].x <<" "<< cloud.points[i].y << endl; i++; } fout<<flush; fout.close(); } } int main(int argc, char **argv) { ros::init(argc, argv, "radar_listener"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("/ARS_408_21_2_Topic", 10, RadarCB); ros::spin(); return 0; }
29.036145
122
0.645643
[ "vector" ]
19e118f6dc464a1564c86e5b026593451da2ab02
691
cpp
C++
training-sheet/B/002. Bear and Finding Criminals.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
training-sheet/B/002. Bear and Finding Criminals.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
training-sheet/B/002. Bear and Finding Criminals.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define lli long long int #define endl "\n" #define MAX 2005 using namespace std; int main() { int n, k; cin>>n>>k; k--; //for 0 based indexing vector <int > v1(n); for(int i = 0; i<n; i++) cin>>v1[i]; int total = v1[k]; //it will be either 0 or 1 int left = k-1; int right = k+1; map <int , int> mp; for(; right < n; right++) { mp[abs(right-k)] = v1[right]; } for(; left >=0; left--) { if(mp.find(abs(k-left)) != mp.end()) { if(mp[abs(k-left)] >0 && v1[left] > 0) { mp[abs(k-left)] = 2; } else mp[abs(k-left)] = 0; } else mp[abs(k-left)] = v1[left]; } for(auto c: mp) total += c.second; cout<<total; }
16.452381
48
0.523878
[ "vector" ]
19e1f74eb3f4539969120ea96929d6b0757a7eb8
51,560
cc
C++
wrspice/devlib/bjt/bjtdist.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/devlib/bjt/bjtdist.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/devlib/bjt/bjtdist.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool: Device Library * * * *========================================================================* $Id:$ *========================================================================*/ /*************************************************************************** JSPICE3 adaptation of Spice3f2 - Copyright (c) Stephen R. Whiteley 1992 Copyright 1990 Regents of the University of California. All rights reserved. Authors: 1988 Jaijeet S Roychowdhury 1993 Stephen R. Whiteley ****************************************************************************/ #define DISTO #include "bjtdefs.h" #include "distdefs.h" struct bjt_d { double r1h1x, i1h1x; double r1h1y, i1h1y; double r1h1z, i1h1z; double r1h2x, i1h2x; double r1h2y, i1h2y; double r1h2z, i1h2z; double r1hm2x, i1hm2x; double r1hm2y, i1hm2y; double r1hm2z, i1hm2z; double r2h11x, i2h11x; double r2h11y, i2h11y; double r2h11z, i2h11z; double r2h1m2x, i2h1m2x; double r2h1m2y, i2h1m2y; double r2h1m2z, i2h1m2z; }; extern int BJTdSetup(sBJTmodel*, sCKT*); static void bjt_setdprms(sDISTOAN*, sBJTinstance*, struct bjt_d*, double, int); static void bjt_dload(sCKT*, sDISTOAN*, sBJTmodel*, sBJTinstance*, struct bjt_d*, int); // assuming here that ckt->CKTomega has been initialised to // the correct value // int BJTdev::disto(int mode, sGENmodel *genmod, sCKT *ckt) { sBJTmodel *model = (sBJTmodel *) genmod; sBJTinstance *inst; sGENinstance *geninst; sDISTOAN* job = (sDISTOAN*) ckt->CKTcurJob; struct bjt_d d = bjt_d(); double td; if (mode == D_SETUP) return (dSetup(model, ckt)); if ((mode == D_TWOF1) || (mode == D_THRF1) || (mode == D_F1PF2) || (mode == D_F1MF2) || (mode == D_2F1MF2)) { for ( ; genmod != 0; genmod = genmod->GENnextModel) { model = (sBJTmodel*)genmod; td = model->BJTexcessPhaseFactor; for (geninst = genmod->GENinstances; geninst != 0; geninst = geninst->GENnextInstance) { inst = (sBJTinstance*)geninst; bjt_setdprms(job, inst, &d, td, mode); bjt_dload(ckt, job, model, inst, &d, mode); } } return (OK); } return (E_BADPARM); } static void bjt_setdprms(sDISTOAN *job, sBJTinstance *inst, bjt_d *d, double td, int mode) { double temp; // getting Volterra kernels // until further notice x = vbe, y = vbc, z = vbed d->r1h1x = *(job->r1H1ptr + (inst->BJTbasePrimeNode)) - *(job->r1H1ptr + (inst->BJTemitPrimeNode)); d->i1h1x = *(job->i1H1ptr + (inst->BJTbasePrimeNode)) - *(job->i1H1ptr + (inst->BJTemitPrimeNode)); d->r1h1y = *(job->r1H1ptr + (inst->BJTbasePrimeNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1y = *(job->i1H1ptr + (inst->BJTbasePrimeNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); if (td != 0) { temp = job->Domega1 * td; // multiplying r1h1x by exp(-j omega td) d->r1h1z = d->r1h1x*cos(temp) + d->i1h1x*sin(temp); d->i1h1z = d->i1h1x*cos(temp) - d->r1h1x*sin(temp); } else { d->r1h1z = d->r1h1x; d->i1h1z = d->i1h1x; } if ((mode == D_F1MF2) || (mode == D_2F1MF2)) { d->r1hm2x = *(job->r1H2ptr + (inst->BJTbasePrimeNode)) - *(job->r1H2ptr + (inst->BJTemitPrimeNode)); d->i1hm2x = -(*(job->i1H2ptr + (inst->BJTbasePrimeNode)) - *(job->i1H2ptr + (inst->BJTemitPrimeNode))); d->r1hm2y = *(job->r1H2ptr + (inst->BJTbasePrimeNode)) - *(job->r1H2ptr + (inst->BJTcolPrimeNode)); d->i1hm2y = -(*(job->i1H2ptr + (inst->BJTbasePrimeNode)) - *(job->i1H2ptr + (inst->BJTcolPrimeNode))); if (td != 0) { temp = -job->Domega2 * td; d->r1hm2z = d->r1hm2x*cos(temp) + d->i1hm2x*sin(temp); d->i1hm2z = d->i1hm2x*cos(temp) - d->r1hm2x*sin(temp); } else { d->r1hm2z = d->r1hm2x; d->i1hm2z = d->i1hm2x; } } if ((mode == D_THRF1) || (mode == D_2F1MF2)) { d->r2h11x = *(job->r2H11ptr + (inst->BJTbasePrimeNode)) - *(job->r2H11ptr + (inst->BJTemitPrimeNode)); d->i2h11x = *(job->i2H11ptr + (inst->BJTbasePrimeNode)) - *(job->i2H11ptr + (inst->BJTemitPrimeNode)); d->r2h11y = *(job->r2H11ptr + (inst->BJTbasePrimeNode)) - *(job->r2H11ptr + (inst->BJTcolPrimeNode)); d->i2h11y = *(job->i2H11ptr + (inst->BJTbasePrimeNode)) - *(job->i2H11ptr + (inst->BJTcolPrimeNode)); if (td != 0) { temp = 2*job->Domega1* td ; d->r2h11z = d->r2h11x*cos(temp) + d->i2h11x*sin(temp); d->i2h11z = d->i2h11x*cos(temp) - d->r2h11x*sin(temp); } else { d->r2h11z = d->r2h11x; d->i2h11z = d->i2h11x; } } if (mode == D_2F1MF2) { d->r2h1m2x = *(job->r2H1m2ptr + (inst->BJTbasePrimeNode)) - *(job->r2H1m2ptr + (inst->BJTemitPrimeNode)); d->i2h1m2x = *(job->i2H1m2ptr + (inst->BJTbasePrimeNode)) - *(job->i2H1m2ptr + (inst->BJTemitPrimeNode)); d->r2h1m2y = *(job->r2H1m2ptr + (inst->BJTbasePrimeNode)) - *(job->r2H1m2ptr + (inst->BJTcolPrimeNode)); d->i2h1m2y = *(job->i2H1m2ptr + (inst->BJTbasePrimeNode)) - *(job->i2H1m2ptr + (inst->BJTcolPrimeNode)); if (td != 0) { temp = (job->Domega1 - job->Domega2) * td; d->r2h1m2z = d->r2h1m2x*cos(temp) + d->i2h1m2x*sin(temp); d->i2h1m2z = d->i2h1m2x*cos(temp) - d->r2h1m2x*sin(temp); } else { d->r2h1m2z = d->r2h1m2x; d->i2h1m2z = d->i2h1m2x; } } if (mode == D_F1PF2) { d->r1h2x = *(job->r1H2ptr + (inst->BJTbasePrimeNode)) - *(job->r1H2ptr + (inst->BJTemitPrimeNode)); d->i1h2x = *(job->i1H2ptr + (inst->BJTbasePrimeNode)) - *(job->i1H2ptr + (inst->BJTemitPrimeNode)); d->r1h2y = *(job->r1H2ptr + (inst->BJTbasePrimeNode)) - *(job->r1H2ptr + (inst->BJTcolPrimeNode)); d->i1h2y = *(job->i1H2ptr + (inst->BJTbasePrimeNode)) - *(job->i1H2ptr + (inst->BJTcolPrimeNode)); if (td != 0) { temp = job->Domega2 * td; d->r1h2z = d->r1h2x*cos(temp) + d->i1h2x*sin(temp); d->i1h2z = d->i1h2x*cos(temp) - d->r1h2x*sin(temp); } else { d->r1h2z = d->r1h2x; d->i1h2z = d->i1h2x; } } } static void bjt_dload(sCKT *ckt, sDISTOAN *job, sBJTmodel *model, sBJTinstance *inst, bjt_d *d, int mode) { double temp, itemp; DpassStr pass; #ifdef DISTODEBUG double time; #endif if (mode == D_TWOF1) { // ic term #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = DFn2F1( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z); itemp = DFi2F1( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for DFn2F1: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTcolPrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // finish ic term // loading ib term // x and y still the same temp = DFn2F1( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0); itemp = DFi2F1( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // ib term over // loading ibb term // now x = vbe, y = vbc, z = vbb if ( !((model->BJTminBaseResist == 0.0) && (model->BJTbaseResist == model->BJTminBaseResist))) { d->r1h1z = *(job->r1H1ptr + (inst->BJTbaseNode)) - *(job->r1H1ptr + (inst->BJTbasePrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTbaseNode)) - *(job->i1H1ptr + (inst->BJTbasePrimeNode)); temp = DFn2F1( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z); itemp = DFi2F1( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z); *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTbasePrimeNode) += temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) += itemp; } // ibb term over // loading qbe term // x = vbe, y = vbc, z not used // (have to multiply by j omega for charge storage // elements to get the current) temp = - ckt->CKTomega*DFi2F1( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0); itemp = ckt->CKTomega*DFn2F1( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // qbe term over // loading qbx term // z = vbx= vb - vcPrime d->r1h1z = d->r1h1z + d->r1h1y; d->i1h1z = d->i1h1z + d->i1h1y; #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = - ckt->CKTomega*D1i2F1(inst->capbx2, d->r1h1z, d->i1h1z); itemp = ckt->CKTomega*D1n2F1(inst->capbx2, d->r1h1z, d->i1h1z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for D1n2F1: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbx term over // loading qbc term temp = - ckt->CKTomega*D1i2F1(inst->capbc2, d->r1h1y, d->i1h1y); itemp = ckt->CKTomega*D1n2F1(inst->capbc2, d->r1h1y, d->i1h1y); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbc term over // loading qsc term // z = vsc d->r1h1z = *(job->r1H1ptr + (inst->BJTsubstNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTsubstNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); temp = - ckt->CKTomega*D1i2F1(inst->capsc2, d->r1h1z, d->i1h1z); itemp = ckt->CKTomega*D1n2F1(inst->capsc2, d->r1h1z, d->i1h1z); *(ckt->CKTrhs + inst->BJTsubstNode) -= temp; *(ckt->CKTirhs + inst->BJTsubstNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qsc term over } else if (mode == D_THRF1) { // ic term #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = DFn3F1( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, inst->ic_x3, inst->ic_y3, inst->ic_w3, inst->ic_x2y, inst->ic_x2w, inst->ic_xy2, inst->ic_y2w, inst->ic_xw2, inst->ic_yw2, inst->ic_xyw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, d->r2h11z, d->i2h11z); itemp = DFi3F1( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, inst->ic_x3, inst->ic_y3, inst->ic_w3, inst->ic_x2y, inst->ic_x2w, inst->ic_xy2, inst->ic_y2w, inst->ic_xw2, inst->ic_yw2, inst->ic_xyw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, d->r2h11z, d->i2h11z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for DFn3F1: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTcolPrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // finish ic term // loading ib term // x and y still the same temp = DFn3F1( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, inst->ib_x3, inst->ib_y3, 0.0, inst->ib_x2y, 0.0, inst->ib_xy2, 0.0, 0.0, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, 0.0, 0.0); itemp = DFi3F1( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, inst->ib_x3, inst->ib_y3, 0.0, inst->ib_x2y, 0.0, inst->ib_xy2, 0.0, 0.0, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // ib term over // loading ibb term if ( !((model->BJTminBaseResist == 0.0) && (model->BJTbaseResist == model->BJTminBaseResist))) { // now x = vbe, y = vbc, z = vbb d->r1h1z = *(job->r1H1ptr + (inst->BJTbaseNode)) - *(job->r1H1ptr + (inst->BJTbasePrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTbaseNode)) - *(job->i1H1ptr + (inst->BJTbasePrimeNode)); d->r2h11z = *(job->r2H11ptr + (inst->BJTbaseNode)) - *(job->r2H11ptr + (inst->BJTbasePrimeNode)); d->i2h11z = *(job->i2H11ptr + (inst->BJTbaseNode)) - *(job->i2H11ptr + (inst->BJTbasePrimeNode)); temp = DFn3F1( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, inst->ibb_x3, inst->ibb_y3, inst->ibb_z3, inst->ibb_x2y, inst->ibb_x2z, inst->ibb_xy2, inst->ibb_y2z, inst->ibb_xz2, inst->ibb_yz2, inst->ibb_xyz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, d->r2h11z, d->i2h11z); itemp = DFi3F1( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, inst->ibb_x3, inst->ibb_y3, inst->ibb_z3, inst->ibb_x2y, inst->ibb_x2z, inst->ibb_xy2, inst->ibb_y2z, inst->ibb_xz2, inst->ibb_yz2, inst->ibb_xyz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, d->r2h11z, d->i2h11z); *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTbasePrimeNode) += temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) += itemp; } // ibb term over // loading qbe term // x = vbe, y = vbc, z not used // (have to multiply by j omega for charge storage // elements to get the current) temp = - ckt->CKTomega*DFi3F1( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, inst->qbe_x3, inst->qbe_y3, 0.0, inst->qbe_x2y, 0.0, inst->qbe_xy2, 0.0, 0.0, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, 0.0, 0.0); itemp = ckt->CKTomega*DFn3F1( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, inst->qbe_x3, inst->qbe_y3, 0.0, inst->qbe_x2y, 0.0, inst->qbe_xy2, 0.0, 0.0, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r2h11x, d->i2h11x, d->r2h11y, d->i2h11y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // qbe term over // loading qbx term // z = vbx = vb - vcPrime d->r1h1z = d->r1h1z + d->r1h1y; d->i1h1z = d->i1h1z + d->i1h1y; d->r2h11z = d->r2h11z + d->r2h11y; d->i2h11z = d->i2h11z + d->i2h11y; #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = - ckt->CKTomega*D1i3F1(inst->capbx2, inst->capbx3, d->r1h1z, d->i1h1z, d->r2h11z, d->i2h11z); itemp = ckt->CKTomega*D1n3F1(inst->capbx2, inst->capbx3, d->r1h1z, d->i1h1z, d->r2h11z, d->i2h11z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for D1n3F1: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbx term over // loading qbc term temp = - ckt->CKTomega*D1i3F1(inst->capbc2, inst->capbc3, d->r1h1y, d->i1h1y, d->r2h11y, d->i2h11y); itemp = ckt->CKTomega*D1n3F1(inst->capbc2, inst->capbc3, d->r1h1y, d->i1h1y, d->r2h11y, d->i2h11y); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbc term over // loading qsc term // z = vsc d->r1h1z = *(job->r1H1ptr + (inst->BJTsubstNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTsubstNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); d->r2h11z = *(job->r2H11ptr + (inst->BJTsubstNode)) - *(job->r2H11ptr + (inst->BJTcolPrimeNode)); d->i2h11z = *(job->i2H11ptr + (inst->BJTsubstNode)) - *(job->i2H11ptr + (inst->BJTcolPrimeNode)); temp = - ckt->CKTomega*D1i3F1(inst->capsc2, inst->capsc3, d->r1h1z, d->i1h1z, d->r2h11z, d->i2h11z); itemp = ckt->CKTomega*D1n3F1(inst->capsc2, inst->capsc3, d->r1h1z, d->i1h1z, d->r2h11z, d->i2h11z); *(ckt->CKTrhs + inst->BJTsubstNode) -= temp; *(ckt->CKTirhs + inst->BJTsubstNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qsc term over } else if (mode == D_F1PF2) { // ic term temp = DFnF12( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, d->r1h2z, d->i1h2z); itemp = DFiF12( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, d->r1h2z, d->i1h2z); *(ckt->CKTrhs + inst->BJTcolPrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // finish ic term // loading ib term // x and y still the same #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = DFnF12( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, 0.0, 0.0); itemp = DFiF12( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, 0.0, 0.0); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for DFnF12: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // ib term over // loading ibb term if ( !((model->BJTminBaseResist == 0.0) && (model->BJTbaseResist == model->BJTminBaseResist))) { /* now x = vbe, y = vbc, z = vbb */ d->r1h1z = *(job->r1H1ptr + (inst->BJTbaseNode)) - *(job->r1H1ptr + (inst->BJTbasePrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTbaseNode)) - *(job->i1H1ptr + (inst->BJTbasePrimeNode)); d->r1h2z = *(job->r1H2ptr + (inst->BJTbaseNode)) - *(job->r1H2ptr + (inst->BJTbasePrimeNode)); d->i1h2z = *(job->i1H2ptr + (inst->BJTbaseNode)) - *(job->i1H2ptr + (inst->BJTbasePrimeNode)); temp = DFnF12( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, d->r1h2z, d->i1h2z); itemp = DFiF12( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, d->r1h2z, d->i1h2z); *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTbasePrimeNode) += temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) += itemp; } // ibb term over // loading qbe term // x = vbe, y = vbc, z not used // (have to multiply by j omega for charge storage // elements - to get the current) temp = - ckt->CKTomega*DFiF12( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, 0.0, 0.0); itemp = ckt->CKTomega*DFnF12( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1h2x, d->i1h2x, d->r1h2y, d->i1h2y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // qbe term over // loading qbx term // z = vbx= vb - vcPrime d->r1h1z = d->r1h1z + d->r1h1y; d->i1h1z = d->i1h1z + d->i1h1y; d->r1h2z = d->r1h2z + d->r1h2y; d->i1h2z = d->i1h2z + d->i1h2y; #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = - ckt->CKTomega*D1iF12(inst->capbx2, d->r1h1z, d->i1h1z, d->r1h2z, d->i1h2z); itemp = ckt->CKTomega*D1nF12(inst->capbx2, d->r1h1z, d->i1h1z, d->r1h2z, d->i1h2z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for D1nF12: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbx term over // loading qbc term temp = - ckt->CKTomega*D1iF12(inst->capbc2, d->r1h1y, d->i1h1y, d->r1h2y, d->i1h2y); itemp = ckt->CKTomega*D1nF12(inst->capbc2, d->r1h1y, d->i1h1y, d->r1h2y, d->i1h2y); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbc term over // loading qsc term // z = vsc d->r1h1z = *(job->r1H1ptr + (inst->BJTsubstNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTsubstNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); d->r1h2z = *(job->r1H2ptr + (inst->BJTsubstNode)) - *(job->r1H2ptr + (inst->BJTcolPrimeNode)); d->i1h2z = *(job->i1H2ptr + (inst->BJTsubstNode)) - *(job->i1H2ptr + (inst->BJTcolPrimeNode)); temp = - ckt->CKTomega*D1iF12(inst->capsc2, d->r1h1z, d->i1h1z, d->r1h2z, d->i1h2z); itemp = ckt->CKTomega*D1nF12(inst->capsc2, d->r1h1z, d->i1h1z, d->r1h2z, d->i1h2z); *(ckt->CKTrhs + inst->BJTsubstNode) -= temp; *(ckt->CKTirhs + inst->BJTsubstNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qsc term over } else if (mode == D_F1MF2) { // ic term temp = DFnF12( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, d->r1hm2z, d->i1hm2z); itemp = DFiF12( inst->ic_x2, inst->ic_y2, inst->ic_w2, inst->ic_xy, inst->ic_yw, inst->ic_xw, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, d->r1hm2z, d->i1hm2z); *(ckt->CKTrhs + inst->BJTcolPrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // finish ic term // loading ib term // x and y still the same temp = DFnF12( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, 0.0, 0.0); itemp = DFiF12( inst->ib_x2, inst->ib_y2, 0.0, inst->ib_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // ib term over // loading ibb term if ( !((model->BJTminBaseResist == 0.0) && (model->BJTbaseResist == model->BJTminBaseResist))) { // now x = vbe, y = vbc, z = vbb d->r1h1z = *(job->r1H1ptr + (inst->BJTbaseNode)) - *(job->r1H1ptr + (inst->BJTbasePrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTbaseNode)) - *(job->i1H1ptr + (inst->BJTbasePrimeNode)); d->r1hm2z = *(job->r1H2ptr + (inst->BJTbaseNode)) - *(job->r1H2ptr + (inst->BJTbasePrimeNode)); d->i1hm2z = *(job->i1H2ptr + (inst->BJTbaseNode)) - *(job->i1H2ptr + (inst->BJTbasePrimeNode)); temp = DFnF12( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, d->r1hm2z, d->i1hm2z); itemp = DFiF12( inst->ibb_x2, inst->ibb_y2, inst->ibb_z2, inst->ibb_xy, inst->ibb_yz, inst->ibb_xz, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, d->r1h1z, d->i1h1z, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, d->r1hm2z, d->i1hm2z); *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTbasePrimeNode) += temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) += itemp; } // ibb term over // loading qbe term // x = vbe, y = vbc, z not used // (have to multiply by j omega for charge storage // elements - to get the current) temp = - ckt->CKTomega*DFiF12( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, 0.0, 0.0); itemp = ckt->CKTomega*DFnF12( inst->qbe_x2, inst->qbe_y2, 0.0, inst->qbe_xy, 0.0, 0.0, d->r1h1x, d->i1h1x, d->r1h1y, d->i1h1y, 0.0, 0.0, d->r1hm2x, d->i1hm2x, d->r1hm2y, d->i1hm2y, 0.0, 0.0); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // qbe term over // loading qbx term // z = vbx= vb - vcPrime d->r1h1z = d->r1h1z + d->r1h1y; d->i1h1z = d->i1h1z + d->i1h1y; d->r1hm2z = d->r1hm2z + d->r1hm2y; d->i1hm2z = d->i1hm2z + d->i1hm2y; temp = - ckt->CKTomega*D1iF12(inst->capbx2, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z); itemp = ckt->CKTomega*D1nF12(inst->capbx2, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z); *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbx term over // loading qbc term temp = - ckt->CKTomega*D1iF12(inst->capbc2, d->r1h1y, d->i1h1y, d->r1hm2y, d->i1hm2y); itemp = ckt->CKTomega*D1nF12(inst->capbc2, d->r1h1y, d->i1h1y, d->r1hm2y, d->i1hm2y); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbc term over // loading qsc term // z = vsc d->r1h1z = *(job->r1H1ptr + (inst->BJTsubstNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTsubstNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); d->r1hm2z = *(job->r1H2ptr + (inst->BJTsubstNode)) - *(job->r1H2ptr + (inst->BJTcolPrimeNode)); d->i1hm2z = *(job->i1H2ptr + (inst->BJTsubstNode)) - *(job->i1H2ptr + (inst->BJTcolPrimeNode)); temp = - ckt->CKTomega*D1iF12(inst->capsc2, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z); itemp = ckt->CKTomega*D1nF12(inst->capsc2, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z); *(ckt->CKTrhs + inst->BJTsubstNode) -= temp; *(ckt->CKTirhs + inst->BJTsubstNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qsc term over } else if (mode == D_2F1MF2) { // ic term { pass.cxx = inst->ic_x2; pass.cyy = inst->ic_y2; pass.czz = inst->ic_w2; pass.cxy = inst->ic_xy; pass.cyz = inst->ic_yw; pass.cxz = inst->ic_xw; pass.cxxx = inst->ic_x3; pass.cyyy = inst->ic_y3; pass.czzz = inst->ic_w3; pass.cxxy = inst->ic_x2y; pass.cxxz = inst->ic_x2w; pass.cxyy = inst->ic_xy2; pass.cyyz = inst->ic_y2w; pass.cxzz = inst->ic_xw2; pass.cyzz = inst->ic_yw2; pass.cxyz = inst->ic_xyw; pass.r1h1x = d->r1h1x; pass.i1h1x = d->i1h1x; pass.r1h1y = d->r1h1y; pass.i1h1y = d->i1h1y; pass.r1h1z = d->r1h1z; pass.i1h1z = d->i1h1z; pass.r1h2x = d->r1hm2x; pass.i1h2x = d->i1hm2x; pass.r1h2y = d->r1hm2y; pass.i1h2y = d->i1hm2y; pass.r1h2z = d->r1hm2z; pass.i1h2z = d->i1hm2z; pass.r2h11x = d->r2h11x; pass.i2h11x = d->i2h11x; pass.r2h11y = d->r2h11y; pass.i2h11y = d->i2h11y; pass.r2h11z = d->r2h11z; pass.i2h11z = d->i2h11z; pass.h2f1f2x = d->r2h1m2x; pass.ih2f1f2x = d->i2h1m2x; pass.h2f1f2y = d->r2h1m2y; pass.ih2f1f2y = d->i2h1m2y; pass.h2f1f2z = d->r2h1m2z; pass.ih2f1f2z = d->i2h1m2z; #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = DFn2F12(&pass); itemp = DFi2F12(&pass); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for DFn2F12: %g seconds \n", time); #endif } *(ckt->CKTrhs + inst->BJTcolPrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // finish ic term // loading ib term // x and y still the same { pass.cxx = inst->ib_x2; pass.cyy = inst->ib_y2; pass.czz = 0.0; pass.cxy = inst->ib_xy; pass.cyz = 0.0; pass.cxz = 0.0; pass.cxxx = inst->ib_x3; pass.cyyy = inst->ib_y3; pass.czzz = 0.0; pass.cxxy = inst->ib_x2y; pass.cxxz = 0.0; pass.cxyy = inst->ib_xy2; pass.cyyz = 0.0; pass.cxzz = 0.0; pass.cyzz = 0.0; pass.cxyz = 0.0; pass.r1h1x = d->r1h1x; pass.i1h1x = d->i1h1x; pass.r1h1y = d->r1h1y; pass.i1h1y = d->i1h1y; pass.r1h1z = 0.0; pass.i1h1z = 0.0; pass.r1h2x = d->r1hm2x; pass.i1h2x = d->i1hm2x; pass.r1h2y = d->r1hm2y; pass.i1h2y = d->i1hm2y; pass.r1h2z = 0.0; pass.i1h2z = 0.0; pass.r2h11x = d->r2h11x; pass.i2h11x = d->i2h11x; pass.r2h11y = d->r2h11y; pass.i2h11y = d->i2h11y; pass.r2h11z = 0.0; pass.i2h11z = 0.0; pass.h2f1f2x = d->r2h1m2x; pass.ih2f1f2x = d->i2h1m2x; pass.h2f1f2y = d->r2h1m2y; pass.ih2f1f2y = d->i2h1m2y; pass.h2f1f2z = 0.0; pass.ih2f1f2z = 0.0; temp = DFn2F12(&pass); itemp = DFi2F12(&pass); } *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // ib term over // loading ibb term if ( !((model->BJTminBaseResist == 0.0) && (model->BJTbaseResist == model->BJTminBaseResist))) { // now x = vbe, y = vbc, z = vbb d->r1h1z = *(job->r1H1ptr + (inst->BJTbaseNode)) - *(job->r1H1ptr + (inst->BJTbasePrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTbaseNode)) - *(job->i1H1ptr + (inst->BJTbasePrimeNode)); d->r1hm2z = *(job->r1H2ptr + (inst->BJTbaseNode)) - *(job->r1H2ptr + (inst->BJTbasePrimeNode)); d->i1hm2z = -(*(job->i1H2ptr + (inst->BJTbaseNode)) - *(job->i1H2ptr + (inst->BJTbasePrimeNode))); d->r2h11z = *(job->r2H11ptr + (inst->BJTbaseNode)) - *(job->r2H11ptr + (inst->BJTbasePrimeNode)); d->i2h11z = *(job->i2H11ptr + (inst->BJTbaseNode)) - *(job->i2H11ptr + (inst->BJTbasePrimeNode)); d->r2h1m2z = *(job->r2H1m2ptr + (inst->BJTbaseNode)) - *(job->r2H1m2ptr + (inst->BJTbasePrimeNode)); d->i2h1m2z = *(job->i2H1m2ptr + (inst->BJTbaseNode)) - *(job->i2H1m2ptr + (inst->BJTbasePrimeNode)); { pass.cxx = inst->ibb_x2; pass.cyy = inst->ibb_y2; pass.czz = inst->ibb_z2; pass.cxy = inst->ibb_xy; pass.cyz = inst->ibb_yz; pass.cxz = inst->ibb_xz; pass.cxxx = inst->ibb_x3; pass.cyyy = inst->ibb_y3; pass.czzz = inst->ibb_z3; pass.cxxy = inst->ibb_x2y; pass.cxxz = inst->ibb_x2z; pass.cxyy = inst->ibb_xy2; pass.cyyz = inst->ibb_y2z; pass.cxzz = inst->ibb_xz2; pass.cyzz = inst->ibb_yz2; pass.cxyz = inst->ibb_xyz; pass.r1h1x = d->r1h1x; pass.i1h1x = d->i1h1x; pass.r1h1y = d->r1h1y; pass.i1h1y = d->i1h1y; pass.r1h1z = d->r1h1z; pass.i1h1z = d->i1h1z; pass.r1h2x = d->r1hm2x; pass.i1h2x = d->i1hm2x; pass.r1h2y = d->r1hm2y; pass.i1h2y = d->i1hm2y; pass.r1h2z = d->r1hm2z; pass.i1h2z = d->i1hm2z; pass.r2h11x = d->r2h11x; pass.i2h11x = d->i2h11x; pass.r2h11y = d->r2h11y; pass.i2h11y = d->i2h11y; pass.r2h11z = d->r2h11z; pass.i2h11z = d->i2h11z; pass.h2f1f2x = d->r2h1m2x; pass.ih2f1f2x = d->i2h1m2x; pass.h2f1f2y = d->r2h1m2y; pass.ih2f1f2y = d->i2h1m2y; pass.h2f1f2z = d->r2h1m2z; pass.ih2f1f2z = d->i2h1m2z; temp = DFn2F12(&pass); itemp = DFi2F12(&pass); } *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTbasePrimeNode) += temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) += itemp; } // ibb term over // loading qbe term // x = vbe, y = vbc, z not used // (have to multiply by j omega for charge storage // elements to get the current) { pass.cxx = inst->qbe_x2; pass.cyy = inst->qbe_y2; pass.czz = 0.0; pass.cxy = inst->qbe_xy; pass.cyz = 0.0; pass.cxz = 0.0; pass.cxxx = inst->qbe_x3; pass.cyyy = inst->qbe_y3; pass.czzz = 0.0; pass.cxxy = inst->qbe_x2y; pass.cxxz = 0.0; pass.cxyy = inst->qbe_xy2; pass.cyyz = 0.0; pass.cxzz = 0.0; pass.cyzz = 0.0; pass.cxyz = 0.0; pass.r1h1x = d->r1h1x; pass.i1h1x = d->i1h1x; pass.r1h1y = d->r1h1y; pass.i1h1y = d->i1h1y; pass.r1h1z = 0.0; pass.i1h1z = 0.0; pass.r1h2x = d->r1hm2x; pass.i1h2x = d->i1hm2x; pass.r1h2y = d->r1hm2y; pass.i1h2y = d->i1hm2y; pass.r1h2z = 0.0; pass.i1h2z = 0.0; pass.r2h11x = d->r2h11x; pass.i2h11x = d->i2h11x; pass.r2h11y = d->r2h11y; pass.i2h11y = d->i2h11y; pass.r2h11z = 0.0; pass.i2h11z = 0.0; pass.h2f1f2x = d->r2h1m2x; pass.ih2f1f2x = d->i2h1m2x; pass.h2f1f2y = d->r2h1m2y; pass.ih2f1f2y = d->i2h1m2y; pass.h2f1f2z = 0.0; pass.ih2f1f2z = 0.0; temp = - ckt->CKTomega*DFi2F12(&pass); itemp = ckt->CKTomega*DFn2F12(&pass); } *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTemitPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTemitPrimeNode) += itemp; // qbe term over // loading qbx term // z = vbx= vb - vcPrime d->r1h1z = d->r1h1z + d->r1h1y; d->i1h1z = d->i1h1z + d->i1h1y; d->r1hm2z = d->r1hm2z + d->r1hm2y; d->i1hm2z = d->i1hm2z + d->i1hm2y; d->r2h11z = d->r2h11z + d->r2h11y; d->i2h11z = d->i2h11z + d->i2h11y; d->r2h1m2z = d->r2h1m2z + d->r2h1m2y; d->i2h1m2z = d->i2h1m2z + d->i2h1m2y; #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds(); #endif temp = - ckt->CKTomega*D1i2F12(inst->capbx2, inst->capbx3, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z, d->r2h11z, d->i2h11z, d->r2h1m2z, d->i2h1m2z); itemp = ckt->CKTomega*D1n2F12(inst->capbx2, inst->capbx3, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z, d->r2h11z, d->i2h11z, d->r2h1m2z, d->i2h1m2z); #ifdef D_DBG_SMALLTIMES time = SPoutput.seconds() - time; printf("Time for D1n2F12: %g seconds \n", time); #endif *(ckt->CKTrhs + inst->BJTbaseNode) -= temp; *(ckt->CKTirhs + inst->BJTbaseNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbx term over // loading qbc term temp = - ckt->CKTomega*D1i2F12(inst->capbc2, inst->capbc3, d->r1h1y, d->i1h1y, d->r1hm2y, d->i1hm2y, d->r2h11y, d->i2h11y, d->r2h1m2y, d->i2h1m2y); itemp = ckt->CKTomega*D1n2F12(inst->capbc2, inst->capbc3, d->r1h1y, d->i1h1y, d->r1hm2y, d->i1hm2y, d->r2h11y, d->i2h11y, d->r2h1m2y, d->i2h1m2y); *(ckt->CKTrhs + inst->BJTbasePrimeNode) -= temp; *(ckt->CKTirhs + inst->BJTbasePrimeNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qbc term over // loading qsc term // z = vsc d->r1h1z = *(job->r1H1ptr + (inst->BJTsubstNode)) - *(job->r1H1ptr + (inst->BJTcolPrimeNode)); d->i1h1z = *(job->i1H1ptr + (inst->BJTsubstNode)) - *(job->i1H1ptr + (inst->BJTcolPrimeNode)); d->r1hm2z = *(job->r1H2ptr + (inst->BJTsubstNode)) - *(job->r1H2ptr + (inst->BJTcolPrimeNode)); d->i1hm2z = -(*(job->i1H2ptr + (inst->BJTsubstNode)) - *(job->i1H2ptr + (inst->BJTcolPrimeNode))); d->r2h11z = *(job->r2H11ptr + (inst->BJTsubstNode)) - *(job->r2H11ptr + (inst->BJTcolPrimeNode)); d->i2h11z = *(job->i2H11ptr + (inst->BJTsubstNode)) - *(job->i2H11ptr + (inst->BJTcolPrimeNode)); d->r2h1m2z = *(job->r2H1m2ptr + (inst->BJTsubstNode)) - *(job->r2H1m2ptr + (inst->BJTcolPrimeNode)); d->i2h1m2z = *(job->i2H1m2ptr + (inst->BJTsubstNode)) - *(job->i2H1m2ptr + (inst->BJTcolPrimeNode)); temp = - ckt->CKTomega*D1i2F12(inst->capsc2, inst->capsc3, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z, d->r2h11z, d->i2h11z, d->r2h1m2z, d->i2h1m2z); itemp = ckt->CKTomega*D1n2F12(inst->capsc2, inst->capsc3, d->r1h1z, d->i1h1z, d->r1hm2z, d->i1hm2z, d->r2h11z, d->i2h11z, d->r2h1m2z, d->i2h1m2z); *(ckt->CKTrhs + inst->BJTsubstNode) -= temp; *(ckt->CKTirhs + inst->BJTsubstNode) -= itemp; *(ckt->CKTrhs + inst->BJTcolPrimeNode) += temp; *(ckt->CKTirhs + inst->BJTcolPrimeNode) += itemp; // qsc term over } }
28.772321
78
0.471102
[ "model" ]
19e6a9c117367e63808495190a9281ff5b106065
17,274
cpp
C++
src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
src/reco/shaperec/featureextractor/l7/L7ShapeFeatureExtractor.cpp
bhardwajhp/lipitk-git-repo
def89fffc64394ff310b07bb7775df2564ecea34
[ "Apache-2.0" ]
null
null
null
/***************************************************************************************** * Copyright (c) 2006 Hewlett-Packard Development Company, L.P. * 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. *****************************************************************************************/ /************************************************************************ * SVN MACROS * * $LastChangedDate: 2008-02-20 10:03:51 +0530 (Wed, 20 Feb 2008) $ * $Revision: 423 $ * $Author: sharmnid $ * ************************************************************************/ /************************************************************************ * FILE DESCR: Implementation of RunShaperec tool * * CONTENTS: * extractFeatures * getShapeFeatureInstance * clearFeatureVector * computeDerivativeDenominator * computeDerivative * * AUTHOR: Naveen Sundar G. * * DATE: August 30, 2005 * CHANGE HISTORY: * Author Date Description of change ************************************************************************/ #include "L7ShapeFeatureExtractor.h" #include "L7ShapeFeature.h" #include "LTKTraceGroup.h" #include "LTKTrace.h" #include "LTKChannel.h" #include "LTKTraceFormat.h" #include "LTKConfigFileReader.h" #include "LTKMacros.h" #include "LTKException.h" #include "LTKErrors.h" #include "LTKLoggerUtil.h" /****************************************************************************** * AUTHOR : Dinesh M * DATE : 1-Oct-2007 * NAME : L7ShapeFeatureExtractor * DESCRIPTION : parameterized constructor * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date *******************************************************************************/ L7ShapeFeatureExtractor::L7ShapeFeatureExtractor(const LTKControlInfo& controlInfo): m_radius(FEATEXTR_L7_DEF_RADIUS) { string cfgFilePath = ""; // Config file if ( ! ((controlInfo.lipiRoot).empty()) && ! ((controlInfo.projectName).empty()) && ! ((controlInfo.profileName).empty()) && ! ((controlInfo.cfgFileName).empty())) { // construct the cfg path using project and profile name cfgFilePath = (controlInfo.lipiRoot) + PROJECTS_PATH_STRING + (controlInfo.projectName) + PROFILE_PATH_STRING + (controlInfo.profileName) + SEPARATOR + (controlInfo.cfgFileName) + CONFIGFILEEXT; } else if ( ! ((controlInfo.cfgFilePath).empty() )) { cfgFilePath = controlInfo.cfgFilePath; } else { throw LTKException(EINVALID_PROJECT_NAME); } int returnVal = readConfig(cfgFilePath); if (returnVal != SUCCESS) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error: L7ShapeFeatureExtractor::L7ShapeFeatureExtractor()" <<endl; throw LTKException(returnVal); } LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " << "L7ShapeFeatureExtractor::L7ShapeFeatureExtractor()" << endl; } /********************************************************************************** * AUTHOR : Dinesh M * DATE : 1-Oct-2007 * NAME : readConfig * DESCRIPTION : read the config values from cfg file and set member variables * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date *************************************************************************************/ int L7ShapeFeatureExtractor::readConfig(const string& cfgFilePath) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " << "L7ShapeFeatureExtractor::readConfig()" << endl; LTKConfigFileReader* configurableProperties = NULL; string tempStringVar = ""; try { configurableProperties = new LTKConfigFileReader(cfgFilePath); int errorCode = configurableProperties->getConfigValue(L7RADIUS, tempStringVar); if( errorCode == SUCCESS) { if (setRadius(atoi((tempStringVar).c_str())) != SUCCESS) { LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << ECONFIG_FILE_RANGE << " : " << getErrorMessage(ECONFIG_FILE_RANGE) << " L7ShapeFeatureExtractor::readConfig" <<endl; throw LTKException(ECONFIG_FILE_RANGE); } } } catch(LTKException e) { delete configurableProperties; int eCode = e.getErrorCode(); LOG( LTKLogger::LTK_LOGLEVEL_ERR) << "Error: " << eCode << " : " << getErrorMessage(eCode) << " L7ShapeFeatureExtractor::readConfig" <<endl; LTKReturnError(eCode); } delete configurableProperties; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " << "L7ShapeFeatureExtractor::readConfig()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Dinesh M * DATE : 1-Oct-2007 * NAME : setRadius * DESCRIPTION : set the radius(the size of window) to compute L7 features * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date *************************************************************************************/ int L7ShapeFeatureExtractor::setRadius(int radius) { int returnVal = FAILURE; if ( radius > 0 ) { m_radius = radius; returnVal = SUCCESS; } return returnVal; } /********************************************************************************** * AUTHOR : Nidhi Sharma * DATE : 15-Feb-2008 * NAME : getRadius * DESCRIPTION : * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date *************************************************************************************/ int L7ShapeFeatureExtractor::getRadius() { return m_radius; } /********************************************************************************** * AUTHOR : Naveen Sundar G. * DATE : 10-AUGUST-2007 * NAME : extractFeatures * DESCRIPTION : Extracts L7 features from a trace group * ARGUMENTS : The trace group from which features have to be extracted * RETURNS : vector of L7ShapeFeature objects * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int L7ShapeFeatureExtractor::extractFeatures(const LTKTraceGroup& inTraceGroup, vector<LTKShapeFeaturePtr>& outFeatureVec) { LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " << "L7ShapeFeatureExtractor::extractFeatures()" << endl; L7ShapeFeature* featurePtr = NULL; float delta; int currentStrokeSize; int numPoints; int numberOfTraces = inTraceGroup.getNumTraces(); if (numberOfTraces == 0 ) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error :" << EEMPTY_TRACE_GROUP << " : " << getErrorMessage(EEMPTY_TRACE_GROUP) << "L7ShapeFeatureExtractor::extractFeatures()" << endl; LTKReturnError(EEMPTY_TRACE_GROUP); } LTKTraceVector allTraces = inTraceGroup.getAllTraces(); LTKTraceVector::iterator traceIter = allTraces.begin(); LTKTraceVector::iterator traceEnd = allTraces.end(); //the feature vector vector<float> xVec; vector<float> yVec; vector<bool> penUp; //concatentating the strokes for (; traceIter != traceEnd ; ++traceIter) { floatVector tempxVec, tempyVec; (*traceIter).getChannelValues("X", tempxVec); (*traceIter).getChannelValues("Y", tempyVec); currentStrokeSize = tempxVec.size(); if (currentStrokeSize == 0) { LOG(LTKLogger::LTK_LOGLEVEL_ERR) << "Error :" << EEMPTY_TRACE<< " : " << getErrorMessage(EEMPTY_TRACE) << "L7ShapeFeatureExtractor::extractFeatures()" << endl; LTKReturnError(EEMPTY_TRACE); } for(int point=0;point<currentStrokeSize;point++) { xVec.push_back(tempxVec[point]); yVec.push_back(tempyVec[point]); if(point == currentStrokeSize - 1 ) { penUp.push_back(true); } else { penUp.push_back(false); } } } //concatentating the strokes numPoints=xVec.size(); vector<float> normfirstderv_x(numPoints); // Array to store the first normalized derivative w.r.t x vector<float> normfirstderv_y(numPoints); // Array to store the first normalized derivative w.r.t y vector<float> normsecondderv_x(numPoints); // Array to store the second normalized derivative w.r.t x vector<float> normsecondderv_y(numPoints); // Array to store the second normalized derivative w.r.t y vector<float> curvature(numPoints); // Array to store the curvature computeDerivative(xVec,yVec,normfirstderv_x,normfirstderv_y,m_radius); computeDerivative(normfirstderv_x,normfirstderv_y,normsecondderv_x,normsecondderv_y,m_radius); for(int i=0; i<numPoints; ++i) { //computing the curvature delta= sqrt(pow(pow(normfirstderv_x[i],2)+pow(normfirstderv_y[i],2),3)); curvature[i]= ((normfirstderv_x[i]*normsecondderv_y[i]) - (normsecondderv_x[i]*normfirstderv_y[i]))/(delta+EPS); featurePtr = new L7ShapeFeature(xVec[i], yVec[i], normfirstderv_x[i], normfirstderv_y[i], normsecondderv_x[i], normsecondderv_y[i], curvature[i], penUp[i]); //populating the feature vector outFeatureVec.push_back(LTKShapeFeaturePtr(featurePtr)); featurePtr = NULL; } LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " << "L7ShapeFeatureExtractor::extractFeatures()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Naveen Sundar G. * DATE : 10-AUGUST-2007 * NAME : getShapeFeatureInstance * DESCRIPTION : Returns an L7ShapeFeature instance * ARGUMENTS : * RETURNS : An L7ShapeFeature instance * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ LTKShapeFeaturePtr L7ShapeFeatureExtractor::getShapeFeatureInstance() { LTKShapeFeaturePtr tempPtr(new L7ShapeFeature); return tempPtr; } /****************************************************************************** * AUTHOR : Naveen Sundar G. * DATE : Sept-10-2007 * NAME : convertFeatVecToTraceGroup * DESCRIPTION : * ARGUMENTS : * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description ******************************************************************************/ int L7ShapeFeatureExtractor::convertFeatVecToTraceGroup( const vector<LTKShapeFeaturePtr>& shapeFeature, LTKTraceGroup& outTraceGroup) { LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " << "L7ShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl; vector<LTKChannel> channels; // channels of a trace LTKChannel xChannel("X", DT_INT, true); // x-coordinate channel of the trace LTKChannel yChannel("Y", DT_INT, true); // y-coordinate channel of the trace //initializing the channels of the trace channels.push_back(xChannel); channels.push_back(yChannel); // composing the trace format object LTKTraceFormat traceFormat(channels); vector<float> point; // a point of a trace LTKTrace trace(traceFormat); for(int count=0;count<(int)shapeFeature.size();count++) { float Xpoint, Ypoint; bool penUp; L7ShapeFeature* ptr = (L7ShapeFeature*)(shapeFeature[count].operator ->()); Xpoint = ptr->getX(); Ypoint = ptr->getY(); penUp = ptr->isPenUp(); point.push_back(Xpoint); point.push_back(Ypoint); trace.addPoint(point); point.clear(); if(penUp == true) // end of a trace, clearing the trace now { outTraceGroup.addTrace(trace); trace.emptyTrace(); LTKTrace tempTrace(traceFormat); trace = tempTrace; } } LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " << "L7ShapeFeatureExtractor::convertFeatVecToTraceGroup()" << endl; return SUCCESS; } /********************************************************************************** * AUTHOR : Naveen Sundar G. * DATE : 10-AUGUST-2007 * NAME : computeDerivativeDenominator * DESCRIPTION : Computes the denominator to be used in the derivative computation * ARGUMENTS : The index used in derivative computation * RETURNS : The denominator * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ int L7ShapeFeatureExtractor::computeDerivativeDenominator(int index) { int denominator=0; for (int i=1;i<=index;i++) { denominator=denominator+i*i; } return 2*denominator; } /********************************************************************************** * AUTHOR : Naveen Sundar G. * DATE : 10-AUGUST-2007 * NAME : computeDerivative * DESCRIPTION : Computes the derivative * ARGUMENTS : The input and output vectors. The output vectors are the derivatives of the input vectors * RETURNS : * NOTES : * CHANGE HISTROY * Author Date Description of change *************************************************************************************/ void L7ShapeFeatureExtractor::computeDerivative(const vector<float>& xVec, const vector<float>& yVec, vector<float>& dx, vector<float>& dy, int index) { int size = xVec.size(); int denominator = computeDerivativeDenominator(index); float x,y,diffx,diffy,delta; float firstderv_x,firstderv_y; int i,j; if(index<size-index) { for(i=index; i<size-index; ++i) { x= xVec[i]; y= yVec[i]; diffx=0; diffy=0; for( j=1;j<=index;j++) { diffx = diffx + j*(xVec[i+j]-xVec[i-j]) ; diffy = diffy + j*(yVec[i+j]-yVec[i-j]) ; } firstderv_x = diffx/denominator; firstderv_y = diffy/denominator; delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2)); if(delta!=0) { dx[i] = firstderv_x/(delta); dy[i] = firstderv_y/(delta); } else { dx[i] = 0; dy[i] = 0; } } for(i=0;i<index;i++) { x= xVec[i]; y= yVec[i]; diffx=0; diffy=0; for( j=1;j<=index;j++) { diffx = diffx + j*(xVec[i+j]-x) ; diffy = diffy + j*(yVec[i+j]-y) ; } firstderv_x = diffx/denominator; firstderv_y = diffy/denominator; delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2)); if(delta!=0) { dx[i] = firstderv_x/(delta); dy[i] = firstderv_y/(delta); } else { dx[i] = 0; dy[i] = 0; } } for(i=size-index;i<=size-1;i++) { x= xVec[i]; y= yVec[i]; diffx=0; diffy=0; for( j=1;j<=index;j++) { diffx = diffx + j*(x-xVec[i-j]) ; diffy = diffy + j*(y-yVec[i-j]) ; } firstderv_x = diffx/denominator; firstderv_y = diffy/denominator; delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2)); if(delta!=0) { dx[i] = firstderv_x/(delta); dy[i] = firstderv_y/(delta); } else { dx[i] = 0; dy[i] = 0; } } } if(index>size-index) { for(i=0; i<size; ++i) { x= xVec[i]; y= yVec[i]; diffx=0; diffy=0; if((0<i+j)&(i+j<size)) { for( j=1;j<=index;j++) { diffx = diffx + j*(xVec[i+j]-x) ; diffy = diffy + j*(yVec[i+j]-y) ; } } else { for(j=1;j<=index;j++) { diffx = diffx + j*(x-xVec[i-j]) ; diffy = diffy + j*(y-yVec[i-j]) ; } } firstderv_x = diffx/denominator; firstderv_y = diffy/denominator; delta = sqrt(pow(firstderv_x,2)+pow(firstderv_y,2)); if(delta!=0) { dx[i] = firstderv_x/(delta); dy[i] = firstderv_y/(delta); } else { dx[i] = 0; dy[i] = 0; } } } }
29.377551
128
0.551291
[ "object", "vector" ]
19e714271dfa659d26be7f44b861ee0e94762e12
26,005
cpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_tacacs_tacacs_server.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_tacacs_tacacs_server.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_tacacs_tacacs_server.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_sysadmin_tacacs_tacacs_server.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_sysadmin_tacacs_tacacs_server { TacacsServer::TacacsServer() : timeout{YType::uint32, "timeout"}, key{YType::str, "key"} , host(this, {"ip", "port"}) , requests(std::make_shared<TacacsServer::Requests>()) , test_authentication(nullptr) // presence node , test_authorization(nullptr) // presence node , test_accounting(nullptr) // presence node { requests->parent = this; yang_name = "tacacs-server"; yang_parent_name = "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server"; is_top_level_class = true; has_list_ancestor = false; } TacacsServer::~TacacsServer() { } bool TacacsServer::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<host.len(); index++) { if(host[index]->has_data()) return true; } return timeout.is_set || key.is_set || (requests != nullptr && requests->has_data()) || (test_authentication != nullptr && test_authentication->has_data()) || (test_authorization != nullptr && test_authorization->has_data()) || (test_accounting != nullptr && test_accounting->has_data()); } bool TacacsServer::has_operation() const { for (std::size_t index=0; index<host.len(); index++) { if(host[index]->has_operation()) return true; } return is_set(yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(key.yfilter) || (requests != nullptr && requests->has_operation()) || (test_authentication != nullptr && test_authentication->has_operation()) || (test_authorization != nullptr && test_authorization->has_operation()) || (test_accounting != nullptr && test_accounting->has_operation()); } std::string TacacsServer::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (key.is_set || is_set(key.yfilter)) leaf_name_data.push_back(key.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "host") { auto ent_ = std::make_shared<TacacsServer::Host>(); ent_->parent = this; host.append(ent_); return ent_; } if(child_yang_name == "Cisco-IOS-XR-sysadmin-tacacs-show-tacacs:requests") { if(requests == nullptr) { requests = std::make_shared<TacacsServer::Requests>(); } return requests; } if(child_yang_name == "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authentication") { if(test_authentication == nullptr) { test_authentication = std::make_shared<TacacsServer::TestAuthentication>(); } return test_authentication; } if(child_yang_name == "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authorization") { if(test_authorization == nullptr) { test_authorization = std::make_shared<TacacsServer::TestAuthorization>(); } return test_authorization; } if(child_yang_name == "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-accounting") { if(test_accounting == nullptr) { test_accounting = std::make_shared<TacacsServer::TestAccounting>(); } return test_accounting; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : host.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } if(requests != nullptr) { _children["Cisco-IOS-XR-sysadmin-tacacs-show-tacacs:requests"] = requests; } if(test_authentication != nullptr) { _children["Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authentication"] = test_authentication; } if(test_authorization != nullptr) { _children["Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authorization"] = test_authorization; } if(test_accounting != nullptr) { _children["Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-accounting"] = test_accounting; } return _children; } void TacacsServer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "key") { key = value; key.value_namespace = name_space; key.value_namespace_prefix = name_space_prefix; } } void TacacsServer::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "key") { key.yfilter = yfilter; } } std::shared_ptr<ydk::Entity> TacacsServer::clone_ptr() const { return std::make_shared<TacacsServer>(); } std::string TacacsServer::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string TacacsServer::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function TacacsServer::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> TacacsServer::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool TacacsServer::has_leaf_or_child_of_name(const std::string & name) const { if(name == "host" || name == "requests" || name == "test-authentication" || name == "test-authorization" || name == "test-accounting" || name == "timeout" || name == "key") return true; return false; } TacacsServer::Host::Host() : ip{YType::str, "ip"}, port{YType::uint16, "port"}, timeout{YType::uint32, "timeout"}, key{YType::str, "key"} { yang_name = "host"; yang_parent_name = "tacacs-server"; is_top_level_class = false; has_list_ancestor = false; } TacacsServer::Host::~Host() { } bool TacacsServer::Host::has_data() const { if (is_presence_container) return true; return ip.is_set || port.is_set || timeout.is_set || key.is_set; } bool TacacsServer::Host::has_operation() const { return is_set(yfilter) || ydk::is_set(ip.yfilter) || ydk::is_set(port.yfilter) || ydk::is_set(timeout.yfilter) || ydk::is_set(key.yfilter); } std::string TacacsServer::Host::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::Host::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "host"; ADD_KEY_TOKEN(ip, "ip"); ADD_KEY_TOKEN(port, "port"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::Host::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ip.is_set || is_set(ip.yfilter)) leaf_name_data.push_back(ip.get_name_leafdata()); if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); if (key.is_set || is_set(key.yfilter)) leaf_name_data.push_back(key.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::Host::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::Host::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void TacacsServer::Host::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ip") { ip = value; ip.value_namespace = name_space; ip.value_namespace_prefix = name_space_prefix; } if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } if(value_path == "timeout") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } if(value_path == "key") { key = value; key.value_namespace = name_space; key.value_namespace_prefix = name_space_prefix; } } void TacacsServer::Host::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ip") { ip.yfilter = yfilter; } if(value_path == "port") { port.yfilter = yfilter; } if(value_path == "timeout") { timeout.yfilter = yfilter; } if(value_path == "key") { key.yfilter = yfilter; } } bool TacacsServer::Host::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ip" || name == "port" || name == "timeout" || name == "key") return true; return false; } TacacsServer::Requests::Requests() : ipv4(this, {"addr", "port"}) { yang_name = "requests"; yang_parent_name = "tacacs-server"; is_top_level_class = false; has_list_ancestor = false; } TacacsServer::Requests::~Requests() { } bool TacacsServer::Requests::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv4.len(); index++) { if(ipv4[index]->has_data()) return true; } return false; } bool TacacsServer::Requests::has_operation() const { for (std::size_t index=0; index<ipv4.len(); index++) { if(ipv4[index]->has_operation()) return true; } return is_set(yfilter); } std::string TacacsServer::Requests::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::Requests::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-show-tacacs:requests"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::Requests::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::Requests::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv4") { auto ent_ = std::make_shared<TacacsServer::Requests::Ipv4>(); ent_->parent = this; ipv4.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::Requests::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv4.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void TacacsServer::Requests::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void TacacsServer::Requests::set_filter(const std::string & value_path, YFilter yfilter) { } bool TacacsServer::Requests::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4") return true; return false; } TacacsServer::Requests::Ipv4::Ipv4() : addr{YType::str, "addr"}, port{YType::uint16, "port"}, opens{YType::uint32, "opens"}, closes{YType::uint32, "closes"}, aborts{YType::uint32, "aborts"}, errors{YType::uint32, "errors"}, packets_in{YType::uint32, "packets_in"}, packets_out{YType::uint32, "packets_out"} { yang_name = "ipv4"; yang_parent_name = "requests"; is_top_level_class = false; has_list_ancestor = false; } TacacsServer::Requests::Ipv4::~Ipv4() { } bool TacacsServer::Requests::Ipv4::has_data() const { if (is_presence_container) return true; return addr.is_set || port.is_set || opens.is_set || closes.is_set || aborts.is_set || errors.is_set || packets_in.is_set || packets_out.is_set; } bool TacacsServer::Requests::Ipv4::has_operation() const { return is_set(yfilter) || ydk::is_set(addr.yfilter) || ydk::is_set(port.yfilter) || ydk::is_set(opens.yfilter) || ydk::is_set(closes.yfilter) || ydk::is_set(aborts.yfilter) || ydk::is_set(errors.yfilter) || ydk::is_set(packets_in.yfilter) || ydk::is_set(packets_out.yfilter); } std::string TacacsServer::Requests::Ipv4::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/Cisco-IOS-XR-sysadmin-tacacs-show-tacacs:requests/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::Requests::Ipv4::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4"; ADD_KEY_TOKEN(addr, "addr"); ADD_KEY_TOKEN(port, "port"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::Requests::Ipv4::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (addr.is_set || is_set(addr.yfilter)) leaf_name_data.push_back(addr.get_name_leafdata()); if (port.is_set || is_set(port.yfilter)) leaf_name_data.push_back(port.get_name_leafdata()); if (opens.is_set || is_set(opens.yfilter)) leaf_name_data.push_back(opens.get_name_leafdata()); if (closes.is_set || is_set(closes.yfilter)) leaf_name_data.push_back(closes.get_name_leafdata()); if (aborts.is_set || is_set(aborts.yfilter)) leaf_name_data.push_back(aborts.get_name_leafdata()); if (errors.is_set || is_set(errors.yfilter)) leaf_name_data.push_back(errors.get_name_leafdata()); if (packets_in.is_set || is_set(packets_in.yfilter)) leaf_name_data.push_back(packets_in.get_name_leafdata()); if (packets_out.is_set || is_set(packets_out.yfilter)) leaf_name_data.push_back(packets_out.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::Requests::Ipv4::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::Requests::Ipv4::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void TacacsServer::Requests::Ipv4::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "addr") { addr = value; addr.value_namespace = name_space; addr.value_namespace_prefix = name_space_prefix; } if(value_path == "port") { port = value; port.value_namespace = name_space; port.value_namespace_prefix = name_space_prefix; } if(value_path == "opens") { opens = value; opens.value_namespace = name_space; opens.value_namespace_prefix = name_space_prefix; } if(value_path == "closes") { closes = value; closes.value_namespace = name_space; closes.value_namespace_prefix = name_space_prefix; } if(value_path == "aborts") { aborts = value; aborts.value_namespace = name_space; aborts.value_namespace_prefix = name_space_prefix; } if(value_path == "errors") { errors = value; errors.value_namespace = name_space; errors.value_namespace_prefix = name_space_prefix; } if(value_path == "packets_in") { packets_in = value; packets_in.value_namespace = name_space; packets_in.value_namespace_prefix = name_space_prefix; } if(value_path == "packets_out") { packets_out = value; packets_out.value_namespace = name_space; packets_out.value_namespace_prefix = name_space_prefix; } } void TacacsServer::Requests::Ipv4::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "addr") { addr.yfilter = yfilter; } if(value_path == "port") { port.yfilter = yfilter; } if(value_path == "opens") { opens.yfilter = yfilter; } if(value_path == "closes") { closes.yfilter = yfilter; } if(value_path == "aborts") { aborts.yfilter = yfilter; } if(value_path == "errors") { errors.yfilter = yfilter; } if(value_path == "packets_in") { packets_in.yfilter = yfilter; } if(value_path == "packets_out") { packets_out.yfilter = yfilter; } } bool TacacsServer::Requests::Ipv4::has_leaf_or_child_of_name(const std::string & name) const { if(name == "addr" || name == "port" || name == "opens" || name == "closes" || name == "aborts" || name == "errors" || name == "packets_in" || name == "packets_out") return true; return false; } TacacsServer::TestAuthentication::TestAuthentication() : authentication{YType::str, "authentication"} { yang_name = "test-authentication"; yang_parent_name = "tacacs-server"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } TacacsServer::TestAuthentication::~TestAuthentication() { } bool TacacsServer::TestAuthentication::has_data() const { if (is_presence_container) return true; return authentication.is_set; } bool TacacsServer::TestAuthentication::has_operation() const { return is_set(yfilter) || ydk::is_set(authentication.yfilter); } std::string TacacsServer::TestAuthentication::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::TestAuthentication::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authentication"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::TestAuthentication::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (authentication.is_set || is_set(authentication.yfilter)) leaf_name_data.push_back(authentication.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::TestAuthentication::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::TestAuthentication::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void TacacsServer::TestAuthentication::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "authentication") { authentication = value; authentication.value_namespace = name_space; authentication.value_namespace_prefix = name_space_prefix; } } void TacacsServer::TestAuthentication::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "authentication") { authentication.yfilter = yfilter; } } bool TacacsServer::TestAuthentication::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authentication") return true; return false; } TacacsServer::TestAuthorization::TestAuthorization() : authorization{YType::str, "authorization"} { yang_name = "test-authorization"; yang_parent_name = "tacacs-server"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } TacacsServer::TestAuthorization::~TestAuthorization() { } bool TacacsServer::TestAuthorization::has_data() const { if (is_presence_container) return true; return authorization.is_set; } bool TacacsServer::TestAuthorization::has_operation() const { return is_set(yfilter) || ydk::is_set(authorization.yfilter); } std::string TacacsServer::TestAuthorization::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::TestAuthorization::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-authorization"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::TestAuthorization::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (authorization.is_set || is_set(authorization.yfilter)) leaf_name_data.push_back(authorization.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::TestAuthorization::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::TestAuthorization::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void TacacsServer::TestAuthorization::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "authorization") { authorization = value; authorization.value_namespace = name_space; authorization.value_namespace_prefix = name_space_prefix; } } void TacacsServer::TestAuthorization::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "authorization") { authorization.yfilter = yfilter; } } bool TacacsServer::TestAuthorization::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authorization") return true; return false; } TacacsServer::TestAccounting::TestAccounting() : accounting{YType::str, "accounting"} { yang_name = "test-accounting"; yang_parent_name = "tacacs-server"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } TacacsServer::TestAccounting::~TestAccounting() { } bool TacacsServer::TestAccounting::has_data() const { if (is_presence_container) return true; return accounting.is_set; } bool TacacsServer::TestAccounting::has_operation() const { return is_set(yfilter) || ydk::is_set(accounting.yfilter); } std::string TacacsServer::TestAccounting::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-tacacs-server:tacacs-server/" << get_segment_path(); return path_buffer.str(); } std::string TacacsServer::TestAccounting::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-tacacs-test-tacacs:test-accounting"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > TacacsServer::TestAccounting::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (accounting.is_set || is_set(accounting.yfilter)) leaf_name_data.push_back(accounting.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> TacacsServer::TestAccounting::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> TacacsServer::TestAccounting::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void TacacsServer::TestAccounting::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "accounting") { accounting = value; accounting.value_namespace = name_space; accounting.value_namespace_prefix = name_space_prefix; } } void TacacsServer::TestAccounting::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "accounting") { accounting.yfilter = yfilter; } } bool TacacsServer::TestAccounting::has_leaf_or_child_of_name(const std::string & name) const { if(name == "accounting") return true; return false; } } }
28.830377
178
0.684791
[ "vector" ]
19eba7c587baa35b43794606ef6c4b420eb75ad9
25,326
cpp
C++
C++/Shared/Audio.cpp
3282269202/Windows-appsample-marble-maze
cc9ec5b4002c0a51b49275e52e4c77a26ce6d3e3
[ "MIT" ]
73
2015-09-09T18:35:36.000Z
2019-05-01T03:14:57.000Z
C++/Shared/Audio.cpp
3282269202/Windows-appsample-marble-maze
cc9ec5b4002c0a51b49275e52e4c77a26ce6d3e3
[ "MIT" ]
4
2015-10-04T07:23:19.000Z
2018-11-20T21:51:45.000Z
C++/Shared/Audio.cpp
3282269202/Windows-appsample-marble-maze
cc9ec5b4002c0a51b49275e52e4c77a26ce6d3e3
[ "MIT" ]
40
2015-10-11T15:23:35.000Z
2019-04-19T13:01:25.000Z
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "DirectXHelper.h" #include "Audio.h" void AudioEngineCallbacks::Initialize(Audio* audio) { m_audio = audio; } // Called when a critical system error causes XAudio2 // to be closed and restarted. The error code is given in Error. void _stdcall AudioEngineCallbacks::OnCriticalError(HRESULT Error) { m_audio->SetEngineExperiencedCriticalError(); } Audio::Audio() { m_currentBuffer = 0; m_engineExperiencedCriticalError = false; m_isAudioStarted = false; m_musicEngine = nullptr; m_soundEffectEngine = nullptr; m_musicMasteringVoice = nullptr; m_soundEffectMasteringVoice = nullptr; m_musicSourceVoice = nullptr; m_soundEffectReverbVoiceSmallRoom = nullptr; m_soundEffectReverbVoiceLargeRoom = nullptr; m_musicReverbVoiceSmallRoom = nullptr; m_musicReverbVoiceLargeRoom = nullptr; } Audio::~Audio() { SuspendAudio(); } void Audio::Initialize() { m_isAudioStarted = false; m_musicEngine = nullptr; m_soundEffectEngine = nullptr; m_musicMasteringVoice = nullptr; m_soundEffectMasteringVoice = nullptr; m_musicSourceVoice = nullptr; m_reverbParametersSmall.ReflectionsDelay = XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_DELAY; m_reverbParametersSmall.ReverbDelay = XAUDIO2FX_REVERB_DEFAULT_REVERB_DELAY; m_reverbParametersSmall.RearDelay = XAUDIO2FX_REVERB_DEFAULT_REAR_DELAY; m_reverbParametersSmall.PositionLeft = XAUDIO2FX_REVERB_DEFAULT_POSITION; m_reverbParametersSmall.PositionRight = XAUDIO2FX_REVERB_DEFAULT_POSITION; m_reverbParametersSmall.PositionMatrixLeft = XAUDIO2FX_REVERB_DEFAULT_POSITION_MATRIX; m_reverbParametersSmall.PositionMatrixRight = XAUDIO2FX_REVERB_DEFAULT_POSITION_MATRIX; m_reverbParametersSmall.EarlyDiffusion = 4; m_reverbParametersSmall.LateDiffusion = 15; m_reverbParametersSmall.LowEQGain = XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_GAIN; m_reverbParametersSmall.LowEQCutoff = XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_CUTOFF; m_reverbParametersSmall.HighEQGain = XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_GAIN; m_reverbParametersSmall.HighEQCutoff = XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_CUTOFF; m_reverbParametersSmall.RoomFilterFreq = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_FREQ; m_reverbParametersSmall.RoomFilterMain = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_MAIN; m_reverbParametersSmall.RoomFilterHF = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_HF; m_reverbParametersSmall.ReflectionsGain = XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_GAIN; m_reverbParametersSmall.ReverbGain = XAUDIO2FX_REVERB_DEFAULT_REVERB_GAIN; m_reverbParametersSmall.DecayTime = XAUDIO2FX_REVERB_DEFAULT_DECAY_TIME; m_reverbParametersSmall.Density = XAUDIO2FX_REVERB_DEFAULT_DENSITY; m_reverbParametersSmall.RoomSize = XAUDIO2FX_REVERB_DEFAULT_ROOM_SIZE; m_reverbParametersSmall.WetDryMix = XAUDIO2FX_REVERB_DEFAULT_WET_DRY_MIX; m_reverbParametersSmall.DisableLateField = TRUE; m_reverbParametersLarge.ReflectionsDelay = XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_DELAY; m_reverbParametersLarge.ReverbDelay = XAUDIO2FX_REVERB_DEFAULT_REVERB_DELAY; m_reverbParametersLarge.RearDelay = XAUDIO2FX_REVERB_DEFAULT_REAR_DELAY; m_reverbParametersLarge.PositionLeft = XAUDIO2FX_REVERB_DEFAULT_POSITION; m_reverbParametersLarge.PositionRight = XAUDIO2FX_REVERB_DEFAULT_POSITION; m_reverbParametersLarge.PositionMatrixLeft = XAUDIO2FX_REVERB_DEFAULT_POSITION_MATRIX; m_reverbParametersLarge.PositionMatrixRight = XAUDIO2FX_REVERB_DEFAULT_POSITION_MATRIX; m_reverbParametersLarge.EarlyDiffusion = 4; m_reverbParametersLarge.LateDiffusion = 4; m_reverbParametersLarge.LowEQGain = XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_GAIN; m_reverbParametersLarge.LowEQCutoff = XAUDIO2FX_REVERB_DEFAULT_LOW_EQ_CUTOFF; m_reverbParametersLarge.HighEQGain = XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_GAIN; m_reverbParametersLarge.HighEQCutoff = XAUDIO2FX_REVERB_DEFAULT_HIGH_EQ_CUTOFF; m_reverbParametersLarge.RoomFilterFreq = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_FREQ; m_reverbParametersLarge.RoomFilterMain = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_MAIN; m_reverbParametersLarge.RoomFilterHF = XAUDIO2FX_REVERB_DEFAULT_ROOM_FILTER_HF; m_reverbParametersLarge.ReflectionsGain = XAUDIO2FX_REVERB_DEFAULT_REFLECTIONS_GAIN; m_reverbParametersLarge.ReverbGain = XAUDIO2FX_REVERB_DEFAULT_REVERB_GAIN; m_reverbParametersLarge.DecayTime = 1.0f; m_reverbParametersLarge.Density = 10; m_reverbParametersLarge.RoomSize = 100; m_reverbParametersLarge.WetDryMix = XAUDIO2FX_REVERB_DEFAULT_WET_DRY_MIX; m_reverbParametersLarge.DisableLateField = FALSE; for (int i = 0; i < ARRAYSIZE(m_soundEffects); i++) { m_soundEffects[i].m_soundEffectBufferData = nullptr; m_soundEffects[i].m_soundEffectSourceVoice = nullptr; m_soundEffects[i].m_soundEffectStarted = false; ZeroMemory(&m_soundEffects[i].m_audioBuffer, sizeof(m_soundEffects[i].m_audioBuffer)); } ZeroMemory(m_audioBuffers, sizeof(m_audioBuffers)); } void Audio::SetRoomSize(float roomSize, float* wallDistances) { // Maximum "outdoors" is a room size of 1000.0f float normalizedRoomSize = roomSize / 1000.0f; float outputMatrix[4] = {0, 0, 0, 0}; float leftRatio = wallDistances[2] / (wallDistances[2] + wallDistances[3]); if ((wallDistances[2] + wallDistances[3]) == 0) { leftRatio = 0.5f; } float width = abs((wallDistances[3] + wallDistances[5] + wallDistances[7]) / 3.0f - (wallDistances[2] + wallDistances[4] + wallDistances[6]) / 3.0f); float height = abs(wallDistances[1] - wallDistances[0]); float widthNormalized = width / max(width, height); if (width == 0) { widthNormalized = 1.0f; } // As widthNormalized approaches 0, the room is taller than wide. // This means that the late-field reverb should be non-localized across both speakers. leftRatio -= .5f; leftRatio *= widthNormalized; leftRatio += .5f; // Near-field reverb with the speaker closest to the wall getting more reverb outputMatrix[0] = (1.0f - leftRatio)* normalizedRoomSize; outputMatrix[1] = 0; outputMatrix[2] = 0; outputMatrix[3] = leftRatio * normalizedRoomSize; DX::ThrowIfFailed( m_soundEffectReverbVoiceSmallRoom->SetOutputMatrix(m_soundEffectMasteringVoice, 2, 2, outputMatrix) ); outputMatrix[0] = (1.0f - leftRatio) * normalizedRoomSize; outputMatrix[1] = 0; outputMatrix[2] = 0; outputMatrix[3]= leftRatio * normalizedRoomSize; DX::ThrowIfFailed( m_musicReverbVoiceSmallRoom->SetOutputMatrix(m_musicMasteringVoice, 2, 2, outputMatrix) ); // Late-field reverb: The wall furthest away gets more of the late-field reverb outputMatrix[0] = leftRatio * (1.0f - normalizedRoomSize); outputMatrix[1] = 0; outputMatrix[2] = 0; outputMatrix[3]= (1.0f - leftRatio) * (1.0f - normalizedRoomSize); DX::ThrowIfFailed( m_soundEffectReverbVoiceLargeRoom->SetOutputMatrix(m_soundEffectMasteringVoice, 2, 2, outputMatrix) ); outputMatrix[0] = leftRatio * (1.0f - normalizedRoomSize); outputMatrix[1] = 0; outputMatrix[2] = 0; outputMatrix[3] = (1.0f - leftRatio) * (1.0f - normalizedRoomSize); DX::ThrowIfFailed( m_musicReverbVoiceLargeRoom->SetOutputMatrix(m_musicMasteringVoice, 2, 2, outputMatrix) ); } void Audio::CreateResources() { try { // Media Foundation is a convenient way to get both file I/O and format decode for // audio assets. You can replace the streamer in this sample with your own file I/O // and decode routines. m_musicStreamer.Initialize(L"Media\\Audio\\background.wma"); DX::ThrowIfFailed( XAudio2Create(&m_musicEngine) ); #if defined(_DEBUG) XAUDIO2_DEBUG_CONFIGURATION debugConfig = {0}; debugConfig.BreakMask = XAUDIO2_LOG_ERRORS; debugConfig.TraceMask = XAUDIO2_LOG_ERRORS; m_musicEngine->SetDebugConfiguration(&debugConfig); #endif m_musicEngineCallback.Initialize(this); m_musicEngine->RegisterForCallbacks(&m_musicEngineCallback); // This sample plays the equivalent of background music, which we tag on the // mastering voice as AudioCategory_GameMedia. In ordinary usage, if we were // playing the music track with no effects, we could route it entirely through // Media Foundation. Here we are using XAudio2 to apply a reverb effect to the // music, so we use Media Foundation to decode the data then we feed it through // the XAudio2 pipeline as a separate Mastering Voice, so that we can tag it // as Game Media. We default the mastering voice to 2 channels to simplify // the reverb logic. DX::ThrowIfFailed( m_musicEngine->CreateMasteringVoice( &m_musicMasteringVoice, 2, 48000, 0, nullptr, nullptr, AudioCategory_GameMedia ) ); CreateReverb( m_musicEngine, m_musicMasteringVoice, &m_reverbParametersSmall, &m_musicReverbVoiceSmallRoom, true ); CreateReverb( m_musicEngine, m_musicMasteringVoice, &m_reverbParametersLarge, &m_musicReverbVoiceLargeRoom, true ); XAUDIO2_SEND_DESCRIPTOR descriptors[3]; descriptors[0].pOutputVoice = m_musicMasteringVoice; descriptors[0].Flags = 0; descriptors[1].pOutputVoice = m_musicReverbVoiceSmallRoom; descriptors[1].Flags = 0; descriptors[2].pOutputVoice = m_musicReverbVoiceLargeRoom; descriptors[2].Flags = 0; XAUDIO2_VOICE_SENDS sends = {0}; sends.SendCount = 3; sends.pSends = descriptors; WAVEFORMATEX& waveFormat = m_musicStreamer.GetOutputWaveFormatEx(); DX::ThrowIfFailed( m_musicEngine->CreateSourceVoice(&m_musicSourceVoice, &waveFormat, 0, 1.0f, &m_voiceContext, &sends, nullptr) ); DX::ThrowIfFailed( m_musicMasteringVoice->SetVolume(0.4f) ); // Create a separate engine and mastering voice for sound effects in the sample // Games will use many voices in a complex graph for audio, mixing all effects down to a // single mastering voice. // We are creating an entirely new engine instance and mastering voice in order to tag // our sound effects with the audio category AudioCategory_GameEffects. DX::ThrowIfFailed( XAudio2Create(&m_soundEffectEngine) ); m_soundEffectEngineCallback.Initialize(this); m_soundEffectEngine->RegisterForCallbacks(&m_soundEffectEngineCallback); // We default the mastering voice to 2 channels to simplify the reverb logic. DX::ThrowIfFailed( m_soundEffectEngine->CreateMasteringVoice(&m_soundEffectMasteringVoice, 2, 48000, 0, nullptr, nullptr, AudioCategory_GameEffects) ); CreateReverb(m_soundEffectEngine, m_soundEffectMasteringVoice, &m_reverbParametersSmall, &m_soundEffectReverbVoiceSmallRoom, true); CreateReverb(m_soundEffectEngine, m_soundEffectMasteringVoice, &m_reverbParametersLarge, &m_soundEffectReverbVoiceLargeRoom, true); CreateSourceVoice(RollingEvent); CreateSourceVoice(FallingEvent); CreateSourceVoice(CollisionEvent); CreateSourceVoice(MenuChangeEvent); CreateSourceVoice(MenuSelectedEvent); CreateSourceVoice(CheckpointEvent); } catch (...) { m_engineExperiencedCriticalError = true; } } void Audio::CreateReverb(IXAudio2* engine, IXAudio2MasteringVoice* masteringVoice, XAUDIO2FX_REVERB_PARAMETERS* parameters, IXAudio2SubmixVoice** newSubmix, bool enableEffect) { XAUDIO2_EFFECT_DESCRIPTOR soundEffectdescriptor; XAUDIO2_EFFECT_CHAIN soundEffectChain; Microsoft::WRL::ComPtr<IUnknown> soundEffectXAPO; DX::ThrowIfFailed( XAudio2CreateReverb(&soundEffectXAPO) ); soundEffectdescriptor.InitialState = false; soundEffectdescriptor.OutputChannels = 2; soundEffectdescriptor.pEffect = soundEffectXAPO.Get(); soundEffectChain.EffectCount = 1; soundEffectChain.pEffectDescriptors = &soundEffectdescriptor; DX::ThrowIfFailed( engine->CreateSubmixVoice(newSubmix, 2, 48000, 0, 0, nullptr, &soundEffectChain) ); DX::ThrowIfFailed( (*newSubmix)->SetEffectParameters(0, parameters, sizeof(m_reverbParametersSmall)) ); if (enableEffect) { DX::ThrowIfFailed( (*newSubmix)->EnableEffect(0) ); } DX::ThrowIfFailed( (*newSubmix)->SetVolume (1.0f) ); float outputMatrix[4] = {0, 0, 0, 0}; DX::ThrowIfFailed( (*newSubmix)->SetOutputMatrix(masteringVoice, 2, 2, outputMatrix) ); } void Audio::CreateSourceVoice(SoundEvent sound) { // Load all data for each sound effect into a single in-memory buffer MediaStreamer soundEffectStream; switch (sound) { case RollingEvent: soundEffectStream.Initialize(L"Media\\Audio\\MarbleRoll.wav"); break; case FallingEvent: soundEffectStream.Initialize(L"Media\\Audio\\MarbleFall.wav"); break; case CollisionEvent: soundEffectStream.Initialize(L"Media\\Audio\\MarbleHit.wav"); break; case MenuChangeEvent: soundEffectStream.Initialize(L"Media\\Audio\\MenuChange.wav"); break; case MenuSelectedEvent: soundEffectStream.Initialize(L"Media\\Audio\\MenuSelect.wav"); break; case CheckpointEvent: soundEffectStream.Initialize(L"Media\\Audio\\Checkpoint.wav"); break; } m_soundEffects[sound].m_soundEventType = sound; uint32 bufferLength = soundEffectStream.GetMaxStreamLengthInBytes(); m_soundEffects[sound].m_soundEffectBufferData = new byte[bufferLength]; soundEffectStream.ReadAll(m_soundEffects[sound].m_soundEffectBufferData, bufferLength, &m_soundEffects[sound].m_soundEffectBufferLength); XAUDIO2_SEND_DESCRIPTOR descriptors[3]; descriptors[0].pOutputVoice = m_soundEffectMasteringVoice; descriptors[0].Flags = 0; descriptors[1].pOutputVoice = m_soundEffectReverbVoiceSmallRoom; descriptors[1].Flags = 0; descriptors[2].pOutputVoice = m_soundEffectReverbVoiceLargeRoom; descriptors[2].Flags = 0; XAUDIO2_VOICE_SENDS sends = {0}; sends.SendCount = 3; sends.pSends = descriptors; // The rolling sound can have pitch shifting and a low-pass filter. if (sound == RollingEvent) { DX::ThrowIfFailed( m_soundEffectEngine->CreateSourceVoice( &m_soundEffects[sound].m_soundEffectSourceVoice, &(soundEffectStream.GetOutputWaveFormatEx()), XAUDIO2_VOICE_USEFILTER, 2.0f, &m_voiceContext, &sends) ); } else { DX::ThrowIfFailed( m_soundEffectEngine->CreateSourceVoice( &m_soundEffects[sound].m_soundEffectSourceVoice, &(soundEffectStream.GetOutputWaveFormatEx()), 0, 1.0f, &m_voiceContext, &sends) ); } m_soundEffects[sound].m_soundEffectSampleRate = soundEffectStream.GetOutputWaveFormatEx().nSamplesPerSec; // Queue in-memory buffer for playback ZeroMemory(&m_soundEffects[sound].m_audioBuffer, sizeof(m_soundEffects[sound].m_audioBuffer)); m_soundEffects[sound].m_audioBuffer.AudioBytes = m_soundEffects[sound].m_soundEffectBufferLength; m_soundEffects[sound].m_audioBuffer.pAudioData = m_soundEffects[sound].m_soundEffectBufferData; m_soundEffects[sound].m_audioBuffer.pContext = &m_soundEffects[sound]; m_soundEffects[sound].m_audioBuffer.Flags = XAUDIO2_END_OF_STREAM; if (sound == RollingEvent) { m_soundEffects[sound].m_audioBuffer.LoopCount = XAUDIO2_LOOP_INFINITE; } else { m_soundEffects[sound].m_audioBuffer.LoopCount = 0; } if (sound == FallingEvent || sound == CheckpointEvent) { m_soundEffects[sound].m_soundEffectSourceVoice->SetVolume(0.4f); } DX::ThrowIfFailed( m_soundEffects[sound].m_soundEffectSourceVoice->SubmitSourceBuffer(&m_soundEffects[sound].m_audioBuffer) ); } void Audio::ReleaseResources() { if (m_musicSourceVoice != nullptr) { m_musicSourceVoice->DestroyVoice(); } if (m_soundEffectReverbVoiceSmallRoom != nullptr) { m_soundEffectReverbVoiceSmallRoom->DestroyVoice(); } if (m_soundEffectReverbVoiceLargeRoom != nullptr) { m_soundEffectReverbVoiceLargeRoom->DestroyVoice(); } if (m_musicReverbVoiceSmallRoom != nullptr) { m_musicReverbVoiceSmallRoom->DestroyVoice(); } if (m_musicReverbVoiceLargeRoom != nullptr) { m_musicReverbVoiceLargeRoom->DestroyVoice(); } for (int i = 0; i < ARRAYSIZE(m_soundEffects); i++) { if (m_soundEffects[i].m_soundEffectSourceVoice != nullptr) { m_soundEffects[i].m_soundEffectSourceVoice->DestroyVoice(); } m_soundEffects[i].m_soundEffectSourceVoice = nullptr; } if (m_musicMasteringVoice != nullptr) { m_musicMasteringVoice->DestroyVoice(); } if (m_soundEffectMasteringVoice != nullptr) { m_soundEffectMasteringVoice->DestroyVoice(); } m_musicSourceVoice = nullptr; m_musicMasteringVoice = nullptr; m_soundEffectMasteringVoice = nullptr; m_soundEffectReverbVoiceSmallRoom = nullptr; m_soundEffectReverbVoiceLargeRoom = nullptr; m_musicReverbVoiceSmallRoom = nullptr; m_musicReverbVoiceLargeRoom = nullptr; m_musicEngine = nullptr; m_soundEffectEngine = nullptr; } void Audio::Start() { if (m_engineExperiencedCriticalError) { return; } HRESULT hr = m_musicSourceVoice->Start(0); if SUCCEEDED(hr) { m_isAudioStarted = true; } else { m_engineExperiencedCriticalError = true; } } // This sample processes audio buffers during the render cycle of the application. // As long as the sample maintains a high-enough frame rate, this approach should // not glitch audio. In game code, it is best for audio buffers to be processed // on a separate thread that is not synced to the main render loop of the game. void Audio::Render() { if (m_engineExperiencedCriticalError) { m_engineExperiencedCriticalError = false; ReleaseResources(); Initialize(); CreateResources(); Start(); if (m_engineExperiencedCriticalError) { return; } } try { bool streamComplete; XAUDIO2_VOICE_STATE state; uint32 bufferLength; XAUDIO2_BUFFER buf = {0}; // Use MediaStreamer to stream the buffers. m_musicSourceVoice->GetState(&state); while (state.BuffersQueued <= MAX_BUFFER_COUNT - 1) { streamComplete = m_musicStreamer.GetNextBuffer( m_audioBuffers[m_currentBuffer], STREAMING_BUFFER_SIZE, &bufferLength ); if (bufferLength > 0) { buf.AudioBytes = bufferLength; buf.pAudioData = m_audioBuffers[m_currentBuffer]; buf.Flags = (streamComplete) ? XAUDIO2_END_OF_STREAM : 0; buf.pContext = 0; DX::ThrowIfFailed( m_musicSourceVoice->SubmitSourceBuffer(&buf) ); m_currentBuffer++; m_currentBuffer %= MAX_BUFFER_COUNT; } if (streamComplete) { // Loop the stream. m_musicStreamer.Restart(); break; } m_musicSourceVoice->GetState(&state); } } catch (...) { m_engineExperiencedCriticalError = true; } } void Audio::PlaySoundEffect(SoundEvent sound) { XAUDIO2_BUFFER buf = {0}; XAUDIO2_VOICE_STATE state = {0}; if (m_engineExperiencedCriticalError) { // If there's an error, then we'll recreate the engine on the next // render pass. return; } SoundEffectData* soundEffect = &m_soundEffects[sound]; HRESULT hr = soundEffect->m_soundEffectSourceVoice->Start(); if FAILED(hr) { m_engineExperiencedCriticalError = true; return; } // For one-off voices, submit a new buffer if there's none queued up, // and allow up to two collisions to be queued up. if (sound != RollingEvent) { XAUDIO2_VOICE_STATE state = {0}; soundEffect->m_soundEffectSourceVoice->GetState(&state, XAUDIO2_VOICE_NOSAMPLESPLAYED); if (state.BuffersQueued == 0) { soundEffect->m_soundEffectSourceVoice->SubmitSourceBuffer(&soundEffect->m_audioBuffer); } else if (state.BuffersQueued < 2 && sound == CollisionEvent) { soundEffect->m_soundEffectSourceVoice->SubmitSourceBuffer(&soundEffect->m_audioBuffer); } // For the menu clicks, we want to stop the voice and replay the click right away. // Note that stopping and then flushing could cause a glitch due to the // waveform not being at a zero-crossing, but due to the nature of the sound // (fast and 'clicky'), we don't mind. if (state.BuffersQueued > 0 && sound == MenuChangeEvent) { soundEffect->m_soundEffectSourceVoice->Stop(); soundEffect->m_soundEffectSourceVoice->FlushSourceBuffers(); soundEffect->m_soundEffectSourceVoice->SubmitSourceBuffer(&soundEffect->m_audioBuffer); soundEffect->m_soundEffectSourceVoice->Start(); } } m_soundEffects[sound].m_soundEffectStarted = true; } void Audio::StopSoundEffect(SoundEvent sound) { if (m_engineExperiencedCriticalError) { return; } HRESULT hr = m_soundEffects[sound].m_soundEffectSourceVoice->Stop(); if FAILED(hr) { // If there's an error, then we'll recreate the engine on the next render pass m_engineExperiencedCriticalError = true; return; } m_soundEffects[sound].m_soundEffectStarted = false; } bool Audio::IsSoundEffectStarted(SoundEvent sound) { return m_soundEffects[sound].m_soundEffectStarted; } void Audio::SetSoundEffectVolume(SoundEvent sound, float volume) { if (m_soundEffects[sound].m_soundEffectSourceVoice != nullptr) { m_soundEffects[sound].m_soundEffectSourceVoice->SetVolume(volume); } } void Audio::SetSoundEffectPitch(SoundEvent sound, float pitch) { if (m_soundEffects[sound].m_soundEffectSourceVoice != nullptr) { m_soundEffects[sound].m_soundEffectSourceVoice->SetFrequencyRatio(pitch); } } void Audio::SetSoundEffectFilter(SoundEvent sound, float frequency, float oneOverQ) { if (m_soundEffects[sound].m_soundEffectSourceVoice != nullptr) { if (oneOverQ <= 0.1f) { oneOverQ = 0.1f; } if (oneOverQ > XAUDIO2_MAX_FILTER_ONEOVERQ) { oneOverQ = XAUDIO2_MAX_FILTER_ONEOVERQ; } XAUDIO2_FILTER_PARAMETERS params = {LowPassFilter, XAudio2CutoffFrequencyToRadians(frequency, m_soundEffects[sound].m_soundEffectSampleRate), oneOverQ}; m_soundEffects[sound].m_soundEffectSourceVoice->SetFilterParameters(&params); } } // Uses the IXAudio2::StopEngine method to stop all audio immediately. // It leaves the audio graph untouched, which preserves all effect parameters // and effect histories (like reverb effects) voice states, pending buffers, // cursor positions and so on. // When the engines are restarted, the resulting audio will sound as if it had // never been stopped except for the period of silence. void Audio::SuspendAudio() { if (m_engineExperiencedCriticalError) { return; } if (m_isAudioStarted) { m_musicEngine->StopEngine(); m_soundEffectEngine->StopEngine(); } m_isAudioStarted = false; } // Restarts the audio streams. A call to this method must match a previous call // to SuspendAudio. This method causes audio to continue where it left off. // If there is a problem with the restart, the m_engineExperiencedCriticalError // flag is set. The next call to Render will recreate all the resources and // reset the audio pipeline. void Audio::ResumeAudio() { if (m_engineExperiencedCriticalError) { return; } HRESULT hr = m_musicEngine->StartEngine(); HRESULT hr2 = m_soundEffectEngine->StartEngine(); if (FAILED(hr) || FAILED(hr2)) { m_engineExperiencedCriticalError = true; } }
36.918367
175
0.697228
[ "render" ]
19f395651739d5b215314033bdd30aebc1a78344
3,022
cpp
C++
src/sampling.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/sampling.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
src/sampling.cpp
kdbohne/pt
78250c676b9cd03f1acdd27dcbec1e0b6209572b
[ "BSD-2-Clause" ]
null
null
null
#include "sampling.h" #include "math.h" float uniform_float() { // TODO: improve? return (float)drand48(); } Vector3f uniform_sample_sphere(const Point2f &u) { float z = 1 - 2 * u[0]; float r = std::sqrt(std::max((float)0, (float)1 - z * z)); float phi = 2 * PI * u[1]; return Vector3f(r * std::cos(phi), r * std::sin(phi), z); } Point2f uniform_sample_triangle(const Point2f &u) { float su0 = std::sqrt(u[0]); return Point2f(1 - su0, u[1] * su0); } Point2f concentric_sample_disk(const Point2f &u) { Point2f u_offset = (float)2 * u - Vector2f(1, 1); if ((u_offset.x == 0) && (u_offset.y == 0)) return Point2f(0, 0); float r, theta; if (std::abs(u_offset.x) > std::abs(u_offset.y)) { r = u_offset.x; theta = PI_OVER_4 * (u_offset.y / u_offset.x); } else { r = u_offset.y; theta = PI_OVER_2 - PI_OVER_4 * (u_offset.x / u_offset.y); } return r * Point2f(std::cos(theta), std::sin(theta)); } Vector3f cosine_sample_hemisphere(const Point2f &u) { Point2f d = concentric_sample_disk(u); float z = std::sqrt(std::max((float)0, 1 - d.x * d.x - d.y * d.y)); return Vector3f(d.x, d.y, z); } float uniform_cone_pdf(float cos_theta_max) { return 1 / (2 * PI * (1 - cos_theta_max)); } Distribution1d::Distribution1d(const float *f, int n) : func(f, f + n), cdf(n + 1) { cdf[0] = 0; for (int i = 1; i < n + 1; ++i) cdf[i] = cdf[i - 1] + func[i - 1] / n; func_int = cdf[n]; if (func_int == 0) { for (int i = 1; i < n + 1; ++i) cdf[i] = (float)i / (float)n; } else { for (int i = 1; i < n + 1; ++i) cdf[i] /= func_int; } } float Distribution1d::sample_continuous(float u, float *pdf, int *offset) const { int off = find_interval((int)cdf.size(), [&](int index) { return cdf[index] <= u; }); if (offset) *offset = off; float du = u - cdf[off]; if ((cdf[off + 1] - cdf[off]) > 0) { assert(cdf[off + 1] > cdf[off]); du /= (cdf[off + 1] - cdf[off]); } assert(!std::isnan(du)); if (pdf) *pdf = (func_int > 0) ? func[off] / func_int : 0; int count = (int)func.size(); return (off + du) / count; } Distribution2d::Distribution2d(float *func, int nu, int nv) { p_conditional_v.reserve(nv); for (int v = 0; v < nv; ++v) p_conditional_v.emplace_back(new Distribution1d(&func[v * nu], nu)); std::vector<float> marginal_func; marginal_func.reserve(nv); for (int v = 0; v < nv; ++v) marginal_func.push_back(p_conditional_v[v]->func_int); p_marginal = new Distribution1d(&marginal_func[0], nv); } Point2f Distribution2d::sample_continuous(const Point2f &u, float *pdf) const { float pdfs[2]; int v; float d1 = p_marginal->sample_continuous(u[1], &pdfs[1], &v); float d0 = p_conditional_v[v]->sample_continuous(u[0], &pdfs[0]); *pdf = pdfs[0] * pdfs[1]; return Point2f(d0, d1); }
24.569106
89
0.562541
[ "vector" ]
19f777e1718a5bb11dc1b3873774deaa786533dc
8,876
cpp
C++
IProc/IProc/IProc.cpp
heshanera/IProc
5e444038f46eec6f5d43e8d2fc169531aa8b68e5
[ "MIT" ]
3
2018-11-20T20:17:00.000Z
2020-02-25T07:33:53.000Z
IProc/IProc/IProc.cpp
heshanera/IProc
5e444038f46eec6f5d43e8d2fc169531aa8b68e5
[ "MIT" ]
2
2018-05-22T08:48:15.000Z
2021-11-08T10:47:34.000Z
IProc/IProc/IProc.cpp
heshanera/IProc
5e444038f46eec6f5d43e8d2fc169531aa8b68e5
[ "MIT" ]
null
null
null
/* * File: IProc.cpp * Author: heshan * * Created on October 5, 2017, 1:32 PM */ #include <iostream> #include <algorithm> #include "IProc.h" IProc::IProc() { } IProc::IProc(const IProc& orig) { } IProc::~IProc() { } /** * * @param path of the image ( source or the target) * @return an integer according to the image format * 1 : PNG * 2 : JPEG/JPG * 3 : TIFF/TIF * 4 : BMP */ int IProc::getImageFormat(std::string path){ // getting the image type from path (file extension) std::string extension; extension = path.substr(path.find_last_of(".") + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); if (extension == "png") return 1; else if (extension == "jpeg") return 2; else if (extension == "jpg") return 2; else if (extension == "tiff") return 3; else if (extension == "tif") return 3; else if (extension == "bmp") return 4; else return 0; } /** * prints the version of the image library used [ libpng, libjpeg ] * @return */ int IProc::readImageFormatInfo(std::string path){ if ( path == "png" ){ pngProc.readPNGVersionInfo(); } else { fprintf(stderr, " Invalid Image Format or Image format is not supported by IProc\n"); } return 0; } /** * * @param imgPath path of the image source * @return 1 */ int IProc::readImage(std::string imgPath){ char *path = new char[imgPath.length() + 1]; strcpy(path, imgPath.c_str()); switch(getImageFormat(imgPath)){ case 1: pngProc.readImage(path); imgDataStruct = pngProc.getImageDataStruct(); pngProc.freeImageData(); break; case 2: jpegProc.readImage(path); imgDataStruct = jpegProc.getImageDataStruct(); jpegProc.freeImageData(); break; case 3: tifProc.readImage(path); imgDataStruct = tifProc.getImageDataStruct(); tifProc.freeImageData(); break; case 4: bmpProc.readImage(path); imgDataStruct = bmpProc.getImageDataStruct(); bmpProc.freeImageData(); break; default: fprintf(stderr, " Invalid Image Format or Image format is not supported by IProc\n"); } delete [] path; return 1; } /** * * @param imgPath path of the target image * @return 1 */ int IProc::writeImage(std::string imgPath){ char *path = new char[imgPath.length() + 1]; strcpy(path, imgPath.c_str()); switch(getImageFormat(imgPath)){ case 1: pngProc.writeImage(path,imgDataStruct); break; case 2: jpegProc.writeImage(path,imgDataStruct); break; case 3: tifProc.writeImage(path,imgDataStruct); break; case 4: bmpProc.writeImage(path,imgDataStruct,32); break; default: fprintf(stderr, " Invalid Image Format or Image format is not supported by IProc\n"); } return 0; } int IProc::writeImage(std::string imgPath, int bBit){ char *path = new char[imgPath.length() + 1]; strcpy(path, imgPath.c_str()); switch(getImageFormat(imgPath)){ case 4: bmpProc.writeImage(path,imgDataStruct,bBit); break; default: fprintf(stderr, " Invalid Image Format or Image format is not supported by IProc\n"); } return 0; } /** * * @param x position of pixel * @param y position of pixel * @return RGBApixel data structure */ RGBApixel IProc::getPixel(int x,int y){ RGBApixel pixel; pixel = imgDataStruct.imgPixArray[x+(y*imgDataStruct.imgWidth)]; return pixel; } /** * * @return ImageDataStruct */ ImageDataStruct IProc::getImageDataStruct(){ return this->imgDataStruct; } /** * * @param x position of pixel * @param y position of pixel * @param pixel new pixel to replace with the old pixel in that position * @return 1 */ int IProc::setPixel(int x,int y,RGBApixel pixel){ imgDataStruct.imgPixArray[x+(y*imgDataStruct.imgWidth)] = pixel; return 1; } /** * * @param imgDataStruct image data structure * @return 1 */ int IProc::setImageDataStruct(ImageDataStruct imgDataStruct){ this->imgDataStruct = imgDataStruct; return 1; } /** * * @param targetWidth new width of the image * @param targetHeight new height of the image * @return 1 */ int IProc::resize(int targetWidth, int targetHeight) { if (targetWidth == -1 && targetHeight == -1) { return 0; } else if (targetWidth == -1) { targetWidth = (int)(imgDataStruct.imgWidth)*targetHeight/imgDataStruct.imgHeight; } else if (targetHeight == -1) { targetHeight = (int)(imgDataStruct.imgHeight*targetWidth)/imgDataStruct.imgWidth; } targetWidth += targetWidth/5; targetHeight += targetHeight/5; ImageDataStruct newImgDataStruct; newImgDataStruct.imgWidth = targetWidth; newImgDataStruct.imgHeight = targetHeight; newImgDataStruct.imgPixArray = new RGBApixel[targetWidth*targetHeight]; int sourceWidth = imgDataStruct.imgWidth; int sourceHeight = imgDataStruct.imgHeight; RGBApixel a, b, c, d; int x, y, index; int x_ratio = ((int)(sourceWidth - 1)) / targetWidth; int y_ratio = ((int)(sourceHeight - 1)) / targetHeight; int x_diff, y_diff, blue, red, green ; int offset = 0 ; for (int i = 0; i < targetHeight; i++) { for (int j = 0; j < targetWidth; j++) { x = (int)(x_ratio * j) ; y = (int)(y_ratio * i) ; x_diff = (x_ratio * j) - x ; y_diff = (y_ratio * i) - y ; index = (y * sourceWidth + x) ; a = imgDataStruct.imgPixArray[index] ; b = imgDataStruct.imgPixArray[index + 1] ; c = imgDataStruct.imgPixArray[index + sourceWidth] ; d = imgDataStruct.imgPixArray[index + sourceWidth + 1] ; // blue element blue = (a.b)*(1-x_diff)*(1-y_diff) + (b.b)*(x_diff)*(1-y_diff) + (c.b)*(y_diff)*(1-x_diff) + (d.b)*(x_diff*y_diff); // green element green = (a.g)*(1-x_diff)*(1-y_diff) + (b.g)*(x_diff)*(1-y_diff) + (c.g)*(y_diff)*(1-x_diff) + (d.g)*(x_diff*y_diff); // red element red = (a.r)*(1-x_diff)*(1-y_diff) + (b.r)*(x_diff)*(1-y_diff) + (c.r)*(y_diff)*(1-x_diff) + (d.r)*(x_diff*y_diff); newImgDataStruct.imgPixArray[offset].r = (int)red; newImgDataStruct.imgPixArray[offset].g = (int)green; newImgDataStruct.imgPixArray[offset].b = (int)blue; newImgDataStruct.imgPixArray[offset].a = 255; offset++; } } this->imgDataStruct = newImgDataStruct; return 1; } /** * * @param row1 * @param col1 * @param row2 * @param col2 * @param originWidth * @param OriginalArray * @return */ int IProc::crop(int row1, int col1, int row2, int col2){ int newHeight = row2 - row1; int newWidth = col2 - col1; int newPixelSize = newWidth * newHeight; int row, pos; ImageDataStruct newImageDataStruct; newImageDataStruct.imgHeight = newHeight; newImageDataStruct.imgWidth = newWidth; newImageDataStruct.imgPixArray = new RGBApixel[newPixelSize]; for ( int i = 0; i < newPixelSize; i++ ) { row = row1 + (int)(i/newWidth); pos = (imgDataStruct.imgWidth * row) + col1 + (i % newWidth); newImageDataStruct.imgPixArray[i] = imgDataStruct.imgPixArray[pos]; } imgDataStruct = newImageDataStruct; return 1; } /** * Convert the RGB pixel values to grayscale * @return 1 */ int IProc::grayscale(){ int pixSize = imgDataStruct.imgWidth*imgDataStruct.imgHeight; RGBApixel pix; int grayPixVal; for(int i = 0; i < pixSize; i++){ pix = imgDataStruct.imgPixArray[i]; // grayPixVal = (pix.r>>2) + (pix.g>>1) + (pix.b>>2); grayPixVal = (int)((pix.r + pix.g + pix.b)/3); pix.r = grayPixVal; pix.g = grayPixVal; pix.b = grayPixVal; imgDataStruct.imgPixArray[i] = pix; } return 1; } /** * * @param limit * @return */ int IProc::binary(int limit){ int pixSize = imgDataStruct.imgWidth * imgDataStruct.imgHeight; int grayVal,binVal; RGBApixel pix; for (int i = 0; i < pixSize; i++) { pix = imgDataStruct.imgPixArray[i]; grayVal = (int)((pix.r + pix.g + pix.b)/3); if (grayVal > limit) binVal = 255; else binVal = 0; pix.r = binVal; pix.g = binVal; pix.b = binVal; imgDataStruct.imgPixArray[i] = pix; } return 1; }
27.310769
97
0.585962
[ "transform" ]
19fa1dbb9f1ae6c5df9042521a9bd9deaa01e02b
2,834
cpp
C++
test/thin_rq_test.cpp
saibalde/tensorfact
7d5d9eea19d30d5ac6e1eb58ef70b23a8a68dbfb
[ "MIT" ]
1
2021-12-31T08:29:42.000Z
2021-12-31T08:29:42.000Z
test/thin_rq_test.cpp
saibalde/tensorfact
7d5d9eea19d30d5ac6e1eb58ef70b23a8a68dbfb
[ "MIT" ]
null
null
null
test/thin_rq_test.cpp
saibalde/tensorfact
7d5d9eea19d30d5ac6e1eb58ef70b23a8a68dbfb
[ "MIT" ]
null
null
null
#include "thin_rq.hpp" #include <gtest/gtest.h> #include <blas.hh> #include <cmath> #include <limits> #include <random> #include <stdexcept> #include <vector> template <typename Real> void CreateRandomMatrix(long m, long n, std::vector<Real> &A) { if (m < 1 || n < 1) { throw std::invalid_argument( "Number of rows and columns must be positive"); } A.resize(m * n); std::random_device device; std::mt19937 generator(device()); std::uniform_real_distribution<Real> distribution(-1, 1); for (long i = 0; i < m * n; ++i) { A[i] = distribution(generator); } } template <typename Real> void ThinRqTest(long m, long n) { std::vector<Real> A; CreateRandomMatrix<Real>(m, n, A); std::vector<Real> C = A; std::vector<Real> R; std::vector<Real> Q; ThinRq<Real>(m, n, A, R, Q); const long k = std::min(m, n); ASSERT_EQ(R.size(), m * k); ASSERT_EQ(Q.size(), k * n); for (long j = 0; j < k; ++j) { for (long i = j + m - k + 1; i < m; ++i) { ASSERT_NEAR(R[i + j * m], static_cast<Real>(0), 10 * std::numeric_limits<Real>::epsilon()); } } for (long i1 = 0; i1 < k; ++i1) { for (long i2 = 0; i2 < i1; ++i2) { Real dot_product = 0.0; for (long j = 0; j < n; ++j) { dot_product += Q[i1 + j * k] * Q[i2 + j * k]; } ASSERT_NEAR(dot_product, static_cast<Real>(0), 10 * std::numeric_limits<Real>::epsilon()); } Real norm_squared = static_cast<Real>(0); for (long j = 0; j < n; ++j) { norm_squared += std::pow(Q[i1 + j * k], 2); } ASSERT_NEAR(norm_squared, static_cast<Real>(1), 10 * std::numeric_limits<Real>::epsilon()); } std::vector<Real> B(m * n); blas::gemm(blas::Layout::ColMajor, blas::Op::NoTrans, blas::Op::NoTrans, m, n, k, static_cast<Real>(1), R.data(), m, Q.data(), k, static_cast<Real>(0), B.data(), m); Real frobenius_error = static_cast<Real>(0); for (long j = 0; j < n; ++j) { for (long i = 0; i < m; ++i) { frobenius_error += std::pow(B[i + j * m] - C[i + j * m], 2); } } frobenius_error = std::sqrt(frobenius_error); ASSERT_NEAR(frobenius_error, static_cast<Real>(0), 100 * std::numeric_limits<Real>::epsilon()); } TEST(ThinRq, Short) { ThinRqTest<float>(4, 64); ThinRqTest<double>(4, 64); } TEST(ThinRq, Square) { ThinRqTest<float>(16, 16); ThinRqTest<double>(16, 16); } TEST(ThinRq, Tall) { ThinRqTest<float>(64, 4); ThinRqTest<double>(64, 4); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26
79
0.528582
[ "vector" ]
c20379497d245e83d2d62fef73d66adc6db6fbcb
4,988
hpp
C++
include/GlobalNamespace/KeySoundController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/KeySoundController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/KeySoundController.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: GameObject class GameObject; // Forward declaring type: Transform class Transform; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: KeySoundController class KeySoundController; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::KeySoundController); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::KeySoundController*, "", "KeySoundController"); // Type namespace: namespace GlobalNamespace { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: KeySoundController // [TokenAttribute] Offset: FFFFFFFF class KeySoundController : public ::UnityEngine::MonoBehaviour { public: // Nested type: ::GlobalNamespace::KeySoundController::$PlayKeySound$d__2 class $PlayKeySound$d__2; public: // public UnityEngine.GameObject KeySoundPlayer // Size: 0x8 // Offset: 0x18 ::UnityEngine::GameObject* KeySoundPlayer; // Field size check static_assert(sizeof(::UnityEngine::GameObject*) == 0x8); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: public UnityEngine.GameObject KeySoundPlayer [[deprecated("Use field access instead!")]] ::UnityEngine::GameObject*& dyn_KeySoundPlayer(); // public System.Void .ctor() // Offset: 0x194C560 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static KeySoundController* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::KeySoundController::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<KeySoundController*, creationType>())); } // public System.Void StartKeySound(UnityEngine.Transform keyTransform) // Offset: 0x194C454 void StartKeySound(::UnityEngine::Transform* keyTransform); // private System.Collections.IEnumerator PlayKeySound(UnityEngine.Transform keyTransform) // Offset: 0x194C4E8 ::System::Collections::IEnumerator* PlayKeySound(::UnityEngine::Transform* keyTransform); }; // KeySoundController #pragma pack(pop) static check_size<sizeof(KeySoundController), 24 + sizeof(::UnityEngine::GameObject*)> __GlobalNamespace_KeySoundControllerSizeCheck; static_assert(sizeof(KeySoundController) == 0x20); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::KeySoundController::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::KeySoundController::StartKeySound // Il2CppName: StartKeySound template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::KeySoundController::*)(::UnityEngine::Transform*)>(&GlobalNamespace::KeySoundController::StartKeySound)> { static const MethodInfo* get() { static auto* keyTransform = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::KeySoundController*), "StartKeySound", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{keyTransform}); } }; // Writing MetadataGetter for method: GlobalNamespace::KeySoundController::PlayKeySound // Il2CppName: PlayKeySound template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (GlobalNamespace::KeySoundController::*)(::UnityEngine::Transform*)>(&GlobalNamespace::KeySoundController::PlayKeySound)> { static const MethodInfo* get() { static auto* keyTransform = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::KeySoundController*), "PlayKeySound", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{keyTransform}); } };
48.427184
228
0.754411
[ "vector", "transform" ]
c20390643825ea8dab06fea61514cb650e88b960
2,564
cpp
C++
Code/src/selectedsourcefieldsselect.cpp
scigeliu/ViaLacteaVisualAnalytics
2ac79301ceaaab0415ec7105b8267552262c7650
[ "Apache-2.0" ]
1
2021-12-15T15:15:50.000Z
2021-12-15T15:15:50.000Z
Code/src/selectedsourcefieldsselect.cpp
scigeliu/ViaLacteaVisualAnalytics
2ac79301ceaaab0415ec7105b8267552262c7650
[ "Apache-2.0" ]
null
null
null
Code/src/selectedsourcefieldsselect.cpp
scigeliu/ViaLacteaVisualAnalytics
2ac79301ceaaab0415ec7105b8267552262c7650
[ "Apache-2.0" ]
null
null
null
#include "selectedsourcefieldsselect.h" #include "ui_selectedsourcefieldsselect.h" #include "qsignalmapper.h" #include <QDebug> #include <QCheckBox> #include "viewselectedsourcedataset.h" selectedSourceFieldsSelect::selectedSourceFieldsSelect(vtkwindow_new *v, QList<QListWidgetItem *> sel, QWidget *parent) : QWidget(parent), ui(new Ui::selectedSourceFieldsSelect) { ui->setupUi(this); vtkwin=v; selectedSources=sel; //Solo per la prima? table=vtkwin->getEllipseList().value(selectedSources.at(0)->text())->getTable(); QHeaderView* header = ui->fieldListTableWidget->horizontalHeader(); header->setVisible(true); header->sectionResizeMode(QHeaderView::Stretch); int row; QSignalMapper* mapper = new QSignalMapper(this); for (int i=0;i<table->getNumberOfColumns();i++) { row= ui->fieldListTableWidget->model()->rowCount(); ui->fieldListTableWidget->insertRow(row); QCheckBox *cb1= new QCheckBox(); cb1->setChecked(true); ui->fieldListTableWidget->setCellWidget(row,0,cb1); connect(cb1, SIGNAL(stateChanged(int)),mapper, SLOT(map())); mapper->setMapping(cb1, row); checkboxList.append(cb1); selectedFields.insert(i,QString::fromStdString(table->getColName(i))); QTableWidgetItem *item_1 = new QTableWidgetItem(); item_1->setText(QString::fromStdString(table->getColName(i))); ui->fieldListTableWidget->setItem(row,1,item_1); connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int))); } } void selectedSourceFieldsSelect::checkboxClicked(int cb) { if(checkboxList.at(cb)->isChecked()) selectedFields.insert(cb,QString::fromStdString(table->getColName(cb))); else selectedFields.remove(cb); } selectedSourceFieldsSelect::~selectedSourceFieldsSelect() { delete ui; } void selectedSourceFieldsSelect::on_selectAllButton_clicked() { for (int i=0;i<checkboxList.size();i++) { checkboxList.at(i)->setChecked(true); selectedFields.insert(i,QString::fromStdString(table->getColName(i))); } } void selectedSourceFieldsSelect::on_deselectAllButton_clicked() { for (int i=0;i<checkboxList.size();i++) { checkboxList.at(i)->setChecked(false); selectedFields.remove(i); } } void selectedSourceFieldsSelect::on_okButton_clicked() { ViewSelectedSourceDataset *selDataset =new ViewSelectedSourceDataset(vtkwin,selectedFields,selectedSources); this->close(); selDataset->show(); }
25.89899
121
0.696178
[ "model" ]
c206707df80c598f2f28813469e0b16720244d58
3,857
cpp
C++
main.cpp
sosastry/BashCrossProduct
3c44193ac6b067b51010c91c06f022550b77cd07
[ "MIT" ]
null
null
null
main.cpp
sosastry/BashCrossProduct
3c44193ac6b067b51010c91c06f022550b77cd07
[ "MIT" ]
null
null
null
main.cpp
sosastry/BashCrossProduct
3c44193ac6b067b51010c91c06f022550b77cd07
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <stack> #include <vector> #include <regex> using namespace std; /* Creates a stack comprised of each element in the input string. * Returns an empty stack if there are invalid characters in the string */ stack<string> createInputStack(string input) { stack<string> inputStack; string temp; string curr; for (int i=0; i<input.length(); i++) { curr = input.substr(i,1); if (!regex_match(curr, regex("[a-zA-Z{},]"))) { // Invalid characters return stack<string>(); } else if (regex_match(curr, regex("[a-zA-Z]"))) { // alphanumeric character temp += curr; // pass consecutive letters to stack (e.g. {AB} -> AB gets pushed to stack) } else { if (temp.length() > 0) { inputStack.push(temp); temp.clear(); } inputStack.push(curr); } } return inputStack; } /* Applies the element input to every item in the result list */ void createCrossProduct(vector<string>& resultList, string element) { for (int i=0; i<resultList.size(); i++) { resultList[i] = element + resultList[i]; } } /* Iterates through stack to determine when to apply cross product. * Returns final list with result of cross product expansion. */ vector<string> getCrossProductExpansion(string input) { stack<string> inputStack = createInputStack(input); vector<string> resultList; vector<string> tempList; // list to hold intermediate results before cross product if (inputStack.empty()) { cout << "Invalid Input. Input characters must match: [a-zA-Z{},]\n"; return resultList; } string curr; string next; int rightBracketCounter = 0; while (!inputStack.empty()) { curr = inputStack.top(); // access top element inputStack.pop(); if (curr == "{") { if (!inputStack.empty()) { next = inputStack.top(); inputStack.pop(); if (next == "}") { next = inputStack.top(); inputStack.pop(); } createCrossProduct(resultList, next); } } else if (regex_match(curr, regex("[a-zA-Z]+"))) { //alphanumeric character(s) resultList.push_back(curr); } else if (curr == "}") { rightBracketCounter++; } } return resultList; } /* Prints cross product result in readable format*/ void printResult(vector<string> input) { if (input.size() != 0) { cout << "Cross Product Result: "; for (int i=input.size()-1; i>=0; i--) { cout << input[i] << " "; } } else { cout << "No Results or Invalid Input"; } cout << "\n"; } /* TODO: move to test suit & use Google Test (or similar test framework) to assert that these match expected output */ void runTestInputs() { vector<string> inputTests; inputTests.push_back("{ABC}"); inputTests.push_back("{A}"); inputTests.push_back("{A,B}"); inputTests.push_back("A{B,C}"); inputTests.push_back("AB{A,C}{D}"); //Note: does not work inputTests.push_back("{A,B}{C,D}"); //Note: does not work inputTests.push_back("123"); inputTests.push_back("{1,2,3}"); vector<string> result; for (int i=0; i<inputTests.size(); i++) { cout << "Input " << i << ": " << inputTests[i] << "\n"; result = getCrossProductExpansion(inputTests[i]); printResult(result); result.clear(); cout << "\n"; } } /* Reads from Standard in */ int main() { cout << "Enter the input:" << endl; string input_str; getline(cin, input_str); vector<string> resultList = getCrossProductExpansion(input_str); printResult(resultList); return 0; }
29.899225
118
0.578429
[ "vector" ]
c20d40888bff3f53baa5e0035dccfece7ffdbc16
1,178
cpp
C++
CodeForces/34A_Reconnaissance2.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-10T15:48:02.000Z
2020-09-12T00:05:35.000Z
CodeForces/34A_Reconnaissance2.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
null
null
null
CodeForces/34A_Reconnaissance2.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-09T17:01:05.000Z
2020-09-09T17:02:27.000Z
/* Author: Davi Augusto Neves Leite Date: 24/06/2021 Compilar com os argumentos: -O2 -Wall -Wextra Executar com os argumentos: < input.txt > output.txt */ #include <bits/stdc++.h> #define MODULO 1000000007 typedef long long ll; using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); int numSoldier; cin >> numSoldier; vector<int> heightSoldier; for(int i = 0; i < numSoldier; i++){ int height; cin >> height; heightSoldier.push_back(height); } int minimumDiff = INT_MAX, diff = 0; pair<int, int> soldiers; for(int i = 1; i < numSoldier; i++){ diff = abs(heightSoldier[i] - heightSoldier[i - 1]); if(diff < minimumDiff){ minimumDiff = diff; soldiers.first = i - 1; soldiers.second = i; } } //Checking the first and last (circle) diff = abs(heightSoldier[numSoldier - 1] - heightSoldier[0]); if (diff < minimumDiff){ minimumDiff = diff; soldiers.first = numSoldier - 1; soldiers.second = 0; } cout << soldiers.first + 1 << " " << soldiers.second + 1 << endl; return 0; }
21.035714
69
0.580645
[ "vector" ]
c20f2e3103ecac73faf76f6e1db001ce28d58950
7,714
cpp
C++
fly/coders/huffman/huffman_decoder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
12
2020-12-26T04:40:48.000Z
2022-02-12T17:58:33.000Z
fly/coders/huffman/huffman_decoder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
308
2017-09-20T22:19:57.000Z
2022-02-26T00:16:11.000Z
fly/coders/huffman/huffman_decoder.cpp
ExternalRepositories/libfly
5acfc424a68031c0004b3c1cb5bef9d76dd129fb
[ "MIT" ]
2
2020-12-26T04:41:02.000Z
2021-06-17T18:24:03.000Z
#include "fly/coders/huffman/huffman_decoder.hpp" #include "fly/logger/logger.hpp" #include "fly/types/bit_stream/bit_stream_reader.hpp" #include "fly/types/numeric/literals.hpp" #include <vector> using namespace fly::literals::numeric_literals; namespace fly::coders { //================================================================================================== HuffmanDecoder::HuffmanDecoder() noexcept : m_huffman_codes_size(0), m_max_code_length(0) { } //================================================================================================== code_type HuffmanDecoder::compute_kraft_mcmillan_constant() const { code_type kraft = 0_u16; for (std::uint16_t i = 0; i < m_huffman_codes_size; ++i) { kraft += 1_u16 << (m_max_code_length - m_huffman_codes[i].m_length); } return kraft; } //================================================================================================== bool HuffmanDecoder::decode_binary(fly::BitStreamReader &encoded, std::ostream &decoded) { std::uint32_t chunk_size; if (!decode_header(encoded, chunk_size)) { LOGW("Error decoding header from stream"); return false; } m_chunk_buffer = std::make_unique<symbol_type[]>(chunk_size); m_prefix_table = std::make_unique<HuffmanCode[]>(1_zu << m_max_code_length); while (!encoded.fully_consumed()) { length_type max_code_length = 0; if (!decode_codes(encoded, max_code_length)) { LOGW("Error decoding codes from stream (maximum code length = {})", m_max_code_length); return false; } else if (!decode_symbols(encoded, max_code_length, chunk_size, decoded)) { LOGW( "Error decoding {} symbols from stream (fully consumed = {})", chunk_size, encoded.fully_consumed()); return false; } } return decoded.good(); } //================================================================================================== bool HuffmanDecoder::decode_header(fly::BitStreamReader &encoded, std::uint32_t &chunk_size) { // Decode the Huffman coder version. byte_type huffman_version; if (!encoded.read_byte(huffman_version)) { LOGW("Could not decode Huffman coder version"); return false; } switch (huffman_version) { case 1: return decode_header_version1(encoded, chunk_size); default: LOGW("Decoded invalid Huffman version {}", huffman_version); break; } return false; } //================================================================================================== bool HuffmanDecoder::decode_header_version1( fly::BitStreamReader &encoded, std::uint32_t &chunk_size) { // Decode the chunk size. word_type encoded_chunk_size_kb; if (!encoded.read_word(encoded_chunk_size_kb)) { LOGW("Could not decode chunk size"); return false; } else if (encoded_chunk_size_kb == 0) { LOGW("Decoded invalid chunk size {}", encoded_chunk_size_kb); return false; } // Decode the maximum Huffman code length. byte_type encoded_max_code_length; if (!encoded.read_byte(encoded_max_code_length)) { LOGW("Could not decode maximum code length"); return false; } else if ( (encoded_max_code_length == 0) || (encoded_max_code_length >= std::numeric_limits<code_type>::digits)) { LOGW("Decoded invalid maximum code length {}", encoded_max_code_length); return false; } chunk_size = static_cast<std::uint32_t>(encoded_chunk_size_kb) << 10; m_max_code_length = static_cast<length_type>(encoded_max_code_length); return true; } //================================================================================================== bool HuffmanDecoder::decode_codes(fly::BitStreamReader &encoded, length_type &max_code_length) { m_huffman_codes_size = 0; // Decode the number of code length counts. byte_type counts_size; if (!encoded.read_byte(counts_size)) { LOGW("Could not decode number of code length counts"); return false; } else if ((counts_size == 0) || (counts_size > (m_max_code_length + 1))) { LOGW("Decoded invalid number of code length counts {}", counts_size); return false; } // The first code length is 0, so the actual maximum code length is 1 less than the number of // length counts. max_code_length = counts_size - 1; // Decode the code length counts. std::vector<std::uint16_t> counts(counts_size); for (std::uint16_t &count : counts) { if (!encoded.read_word(count)) { LOGW("Could not decode code length counts"); return false; } } // Decode the symbols. for (length_type length = 0; length < counts_size; ++length) { for (std::uint16_t i = 0; i < counts[length]; ++i) { byte_type symbol; if (!encoded.read_byte(symbol)) { LOGW("Could not decode symbol of length {} bits", length); return false; } // First code is always set to zero. code_type code = 0; // Subsequent codes are one greater than the previous code, but also bit-shifted left // enough to maintain the right code length. if (m_huffman_codes_size != 0) { const HuffmanCode &last = m_huffman_codes[m_huffman_codes_size - 1_u16]; const length_type shift = length - last.m_length; code = (last.m_code + 1) << shift; } if (m_huffman_codes_size == m_huffman_codes.size()) { LOGW("Exceeded maximum number of codes: {}", m_huffman_codes_size); return false; } m_huffman_codes[m_huffman_codes_size++] = HuffmanCode(static_cast<symbol_type>(symbol), code, length); } } convert_to_prefix_table(max_code_length); return true; } //================================================================================================== void HuffmanDecoder::convert_to_prefix_table(length_type max_code_length) { for (std::uint16_t i = 0; i < m_huffman_codes_size; ++i) { const HuffmanCode code = std::move(m_huffman_codes[i]); const length_type shift = max_code_length - code.m_length; for (code_type j = 0; j < (1_u16 << shift); ++j) { const code_type index = (code.m_code << shift) + j; m_prefix_table[index].m_symbol = code.m_symbol; m_prefix_table[index].m_length = code.m_length; } } } //================================================================================================== bool HuffmanDecoder::decode_symbols( fly::BitStreamReader &encoded, length_type max_code_length, std::uint32_t chunk_size, std::ostream &decoded) const { std::uint32_t bytes = 0; code_type prefix; while ((bytes < chunk_size) && (encoded.peek_bits(prefix, max_code_length) != 0)) { const HuffmanCode &code = m_prefix_table[prefix]; m_chunk_buffer[bytes++] = code.m_symbol; encoded.discard_bits(code.m_length); } if (bytes > 0) { decoded.write( reinterpret_cast<const std::ios::char_type *>(m_chunk_buffer.get()), static_cast<std::streamsize>(bytes)); } return (bytes == chunk_size) || encoded.fully_consumed(); } } // namespace fly::coders
30.25098
100
0.556261
[ "vector" ]
c216a60140eed39787cc78b8190940754dda7d3c
1,707
cpp
C++
fboss/agent/hw/sai/tracer/VirtualRouterApiTracer.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
834
2015-03-10T18:12:28.000Z
2022-03-31T20:16:17.000Z
fboss/agent/hw/sai/tracer/VirtualRouterApiTracer.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
82
2015-04-07T08:48:29.000Z
2022-03-11T21:56:58.000Z
fboss/agent/hw/sai/tracer/VirtualRouterApiTracer.cpp
nathanawmk/fboss
9f36dbaaae47202f9131598560c65715334a9a83
[ "BSD-3-Clause" ]
296
2015-03-11T03:45:37.000Z
2022-03-14T22:54:22.000Z
/* * Copyright (c) 2004-present, Facebook, 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 "fboss/agent/hw/sai/tracer/VirtualRouterApiTracer.h" #include "fboss/agent/hw/sai/tracer/Utils.h" namespace facebook::fboss { WRAP_CREATE_FUNC(virtual_router, SAI_OBJECT_TYPE_VIRTUAL_ROUTER, virtualRouter); WRAP_REMOVE_FUNC(virtual_router, SAI_OBJECT_TYPE_VIRTUAL_ROUTER, virtualRouter); WRAP_SET_ATTR_FUNC( virtual_router, SAI_OBJECT_TYPE_VIRTUAL_ROUTER, virtualRouter); WRAP_GET_ATTR_FUNC( virtual_router, SAI_OBJECT_TYPE_VIRTUAL_ROUTER, virtualRouter); sai_virtual_router_api_t* wrappedVirtualRouterApi() { static sai_virtual_router_api_t virtualRouterWrappers; virtualRouterWrappers.create_virtual_router = &wrap_create_virtual_router; virtualRouterWrappers.remove_virtual_router = &wrap_remove_virtual_router; virtualRouterWrappers.set_virtual_router_attribute = &wrap_set_virtual_router_attribute; virtualRouterWrappers.get_virtual_router_attribute = &wrap_get_virtual_router_attribute; return &virtualRouterWrappers; } void setVirtualRouterAttributes( const sai_attribute_t* attr_list, uint32_t attr_count, std::vector<std::string>& attrLines) { for (int i = 0; i < attr_count; ++i) { switch (attr_list[i].id) { case SAI_VIRTUAL_ROUTER_ATTR_SRC_MAC_ADDRESS: macAddressAttr(attr_list, i, attrLines); break; default: break; } } } } // namespace facebook::fboss
30.482143
80
0.768014
[ "vector" ]
c217e5baf283b83a1274756a672020c7b8f5b25c
453
cpp
C++
source/utility/text_parser.cpp
thomastli/k-means-cpp
2e8e27a57e448b40f093e2e678e99a0b1bb909c1
[ "MIT" ]
null
null
null
source/utility/text_parser.cpp
thomastli/k-means-cpp
2e8e27a57e448b40f093e2e678e99a0b1bb909c1
[ "MIT" ]
1
2021-08-21T23:28:02.000Z
2021-08-21T23:28:02.000Z
source/utility/text_parser.cpp
thomastli/k-means-cpp
2e8e27a57e448b40f093e2e678e99a0b1bb909c1
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "algorithm/jaro_winkler.h" #include "utility/text_parser.h" using namespace utility; std::vector<std::string> TextParser::RetrieveList(const std::string &filename) { std::vector<std::string> name_list; std::string line; std::ifstream input_file(filename); while(std::getline(input_file, line)) { name_list.push_back(line); } input_file.close(); return name_list; }
22.65
80
0.699779
[ "vector" ]
c219d9da9b425abf6a41184ad89c73aad9939fc6
4,016
hpp
C++
src/tl/utility.hpp
Sebanisu/ToolsLibrary
008773ee21bb160abc24c2f28c4f743813cdc777
[ "BSL-1.0" ]
1
2021-03-04T17:11:34.000Z
2021-03-04T17:11:34.000Z
src/tl/utility.hpp
Sebanisu/ToolsLibrary
008773ee21bb160abc24c2f28c4f743813cdc777
[ "BSL-1.0" ]
4
2021-03-04T17:12:49.000Z
2021-03-25T02:08:29.000Z
src/tl/utility.hpp
Sebanisu/ToolsLibrary
008773ee21bb160abc24c2f28c4f743813cdc777
[ "BSL-1.0" ]
null
null
null
#ifndef TOOLSLIBRARY_UTILITY_HPP #define TOOLSLIBRARY_UTILITY_HPP #include "tl/concepts.hpp" #include <array> #include <cassert> #include <cstring> #include <filesystem> #include <fstream> #include <istream> #include <optional> #include <span> #include <vector> namespace tl::utility { /** * Utility functions used by the rest of the library */ /** * Convert Type to bytes array * @tparam T Trivially copyable value type * @param in Trivially copyable value * @return array of bytes */ template<concepts::is_trivially_copyable T> [[nodiscard]] inline std::array<char, sizeof(T)> to_bytes(const T &in) { // todo std::bit_cast will be able to make this function constexpr // todo this is only in gcc trunk and msvc right now. auto tmp = std::array<char, sizeof(T)>{}; std::memcpy(std::data(tmp), &in, std::size(tmp)); return tmp; } /** * Convert Type to bytes vector * @tparam T Trivially copyable value type * @param in Trivially copyable value source pointer * @param count number of elements from source pointer. * @return vector of bytes */ template<concepts::is_trivially_copyable T> [[nodiscard]] inline std::vector<char> to_bytes(const T *const in, std::size_t count = 1) { assert(count != 0); auto tmp = std::vector<char>(count * sizeof(T)); std::memcpy(std::data(tmp), in, std::size(tmp)); return tmp; } /** * Get remaining amount of bytes in a std::span. * @param in span */ [[nodiscard]] inline auto get_remaining(const std::span<const char> in) { return std::size(in); } /** * Get remaining amount of bytes in a std::istream. * @param in stream */ [[nodiscard]] inline auto get_remaining(std::istream &in) { const auto current = in.tellg(); in.seekg(0, std::ios::end); const auto end = in.tellg(); in.seekg(current, std::ios::beg); return static_cast<std::size_t>(end - current); } /** * Get amount of bytes in a std::span. * @param in span */ [[nodiscard]] inline auto get_position(const std::span<const char> in) { return std::size(in); } /** * Get position in a std::ostream. * @param in stream */ [[nodiscard]] inline auto get_position(std::ostream &in) { return in.tellp(); } /** * Create a temp file filled with data you want. * @param file_name desired filename * @param data data you want wrote to the file. * @return optional path to file */ [[nodiscard]] inline std::optional<std::filesystem::path> create_temp_file(const std::filesystem::path &file_name, const std::string_view &data) { using namespace std::string_view_literals; std::filesystem::path out_path = std::filesystem::temp_directory_path() / file_name; auto fp = std::fstream(out_path, std::ios::binary | std::ios::out); if (fp.is_open()) { const auto write = [&fp](const std::string_view &buffer) { fp.write(std::data(buffer), static_cast<long>(std::size(buffer))); }; write(data); } return out_path; } /** * Holds number sequence and has operator to pass a lambda that takes 1 of the * sequence as a template parameter. * @tparam number_sequence */ template<std::size_t... number_sequence> struct sequence_impl { template<typename lambdaT> constexpr void operator()(const lambdaT &op) const { (op.template operator()<number_sequence>(), ...); } }; /** * * @tparam Min min value of I. * @tparam I is the current number in sequence * @tparam Ns sequence is number of values. * @return * @see https://stackoverflow.com/a/49673314/2588183 */ template<std::size_t Min, std::size_t I, std::size_t... Ns> inline auto make_sequence_impl() { static_assert(I >= Min); if constexpr (I == Min) return sequence_impl<Ns...>(); else return make_sequence_impl<Min, I - 1U, I - 1U, Ns...>(); } /** * Get sequence_impl from Min to Max numbers * @tparam Min number * @tparam Max number */ template<size_t Min, size_t Count> using sequence = std::decay_t<decltype(make_sequence_impl<Min, Count + Min>())>; }// namespace tl::utility #endif// TOOLSLIBRARY_UTILITY_HPP
26.077922
80
0.683267
[ "vector" ]
c22038fe8f911a24ee0616c21a50ae4aa53e2b45
1,597
cpp
C++
Client/main.cpp
PeriodicSeizures/CPPNetworking
eb26674f7a1bf4e93622825b974dec4463959f93
[ "MIT" ]
null
null
null
Client/main.cpp
PeriodicSeizures/CPPNetworking
eb26674f7a1bf4e93622825b974dec4463959f93
[ "MIT" ]
null
null
null
Client/main.cpp
PeriodicSeizures/CPPNetworking
eb26674f7a1bf4e93622825b974dec4463959f93
[ "MIT" ]
null
null
null
#define SDL_MAIN_HANDLED #include <SDL.h> #include <stdio.h> #include <iostream> #include <string> #include "task/Task.h" #include "engine/Engine.h" int main(void) { Engine::init(); Task::init(); MAIN_MENU_TASK.focus(); //WORLD_TASK.focus(); //std::chrono:: //bool alive = true; bool render = true; unsigned int last_update = SDL_GetTicks(); while (Task::GAME_ALIVE) { unsigned int current = SDL_GetTicks(); float delta = (current - last_update) / 1000.f; // event polling thousands of times per second is // unnecessary and drastically increases cpu usage std::this_thread::sleep_for(std::chrono::milliseconds(10)); SDL_Event e; while (SDL_PollEvent(&e)) { Task::current_task->on_event(e); switch (e.type) { case SDL_QUIT: Task::GAME_ALIVE = false; break; case SDL_WINDOWEVENT: switch (e.window.event) { case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_EXPOSED: case SDL_WINDOWEVENT_MAXIMIZED: //case SDL_WINDOWEVENT_ENTER: case SDL_WINDOWEVENT_FOCUS_GAINED: //case SDL_WINDOWEVENT_TAKE_FOCUS: render = true; break; case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_MINIMIZED: //case SDL_WINDOWEVENT_LEAVE: case SDL_WINDOWEVENT_FOCUS_LOST: render = false; break; } } } Task::current_task->on_update(delta); // only render on mouse focus if (render) { Engine::fill({0, 0, 0, 255}); //player.onRender(); Task::current_task->on_render(); Engine::doRender(); } last_update = current; } Task::uninit(); Engine::uninit(); return 0; }
19.716049
61
0.673137
[ "render" ]
c227ba66c8fdb188b2458225eb9b59d92735a71b
1,780
hpp
C++
cpp/include/raft/linalg/axpy.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/linalg/axpy.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/linalg/axpy.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * 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 is deprecated and will be removed in release 22.06. * Please use the cuh version instead. */ #ifndef __AXPY_H #define __AXPY_H #pragma once #include "detail/axpy.cuh" namespace raft::linalg { /** * @brief the wrapper of cublas axpy function * It computes the following equation: y = alpha * x + y * * @tparam T the element type * @tparam DevicePointerMode whether pointers alpha, beta point to device memory * @param [in] handle raft handle * @param [in] n number of elements in x and y * @param [in] alpha host or device scalar * @param [in] x vector of length n * @param [in] incx stride between consecutive elements of x * @param [inout] y vector of length n * @param [in] incy stride between consecutive elements of y * @param [in] stream */ template <typename T, bool DevicePointerMode = false> void axpy(const raft::handle_t& handle, const int n, const T* alpha, const T* x, const int incx, T* y, const int incy, cudaStream_t stream) { detail::axpy<T, DevicePointerMode>(handle, n, alpha, x, incx, y, incy, stream); } } // namespace raft::linalg #endif
29.666667
81
0.688202
[ "vector" ]
c22ded9c3c91047701ac5cdfd2acba48a01e878d
5,339
cpp
C++
src/server.cpp
f0lg0/tcp-server-boilerplate
54250c8da8dac2f7f57820af4322f7acfc29bff5
[ "MIT" ]
21
2022-01-09T19:04:49.000Z
2022-01-23T00:47:36.000Z
src/server.cpp
f0lg0/tcp-server-boilerplate
54250c8da8dac2f7f57820af4322f7acfc29bff5
[ "MIT" ]
null
null
null
src/server.cpp
f0lg0/tcp-server-boilerplate
54250c8da8dac2f7f57820af4322f7acfc29bff5
[ "MIT" ]
3
2022-01-10T15:22:14.000Z
2022-01-18T15:14:59.000Z
#include "server.hpp" #include <iostream> #include <cstdint> #include <unistd.h> #include <algorithm> #include <sys/epoll.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> Epoll::EpollHandler::EpollHandler() { this->epfd = epoll_create(this->nthreads); if (this->epfd < 0) { std::cerr << "[!] Failed to create epoll, exiting..." << std::endl; exit(1); } this->events.resize(this->max_events); } bool Epoll::EpollHandler::epoll_add(int32_t fd, uint32_t events) { struct epoll_event event = {0}; event.events = events; event.data.fd = fd; if (epoll_ctl(this->epfd, EPOLL_CTL_ADD, fd, &event) < 0) return false; return true; } bool Epoll::EpollHandler::epoll_del(int32_t fd) { return epoll_ctl(this->epfd, EPOLL_CTL_DEL, fd, NULL) < 0 ? false : true; } int32_t Epoll::EpollHandler::wait_events() { return epoll_wait(this->epfd, &(this->events[0]), this->max_events, this->timeout); } const std::vector<struct epoll_event>& Epoll::EpollHandler::get_events_vector() const { return this->events; } Server::TCPServer::TCPServer() { this->sfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP); if (this->sfd == -1) { std::cerr << "[!] Erro while creating socket, exiting..." << std::endl; exit(1); } struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("0.0.0.0"); address.sin_port = htons(strtol("1234", NULL, 10)); if (bind(this->sfd, (struct sockaddr*) &address, sizeof(address)) < 0) { std::cerr << "[!] Erro while binding socket to specified address (0.0.0.0:1234), exiting..." << std::endl; exit(1); } } Server::TCPServer::~TCPServer() { close(this->sfd); } // get sockaddr ip_v4 static void* get_in_addr(struct sockaddr *sa) { return &(((struct sockaddr_in*)sa)->sin_addr); } // get sockaddr port static unsigned short get_in_port(struct sockaddr *sa) { return ((struct sockaddr_in*)sa)->sin_port; } bool Server::TCPServer::accept_new_client() { sockaddr_storage clients; socklen_t clients_size = sizeof(clients); int32_t conn = accept(this->sfd, (sockaddr*) &clients, &clients_size); char conn_addr[INET_ADDRSTRLEN]; inet_ntop(clients.ss_family, get_in_addr((struct sockaddr*)&clients), conn_addr, sizeof(conn_addr)); std::cout << "[+] Got connection from: " << conn_addr << ":" << get_in_port((struct sockaddr*)&clients) << " --> fd: " << conn << std::endl; // tell epoll to monitor client fd return this->epoll_handler.epoll_add(conn, EPOLLIN | EPOLLPRI); } void Server::TCPServer::close_connection(int32_t conn) { std::cout << "[!] Client with fd: " << conn << " has closed its connection" << std::endl; this->epoll_handler.epoll_del(conn); close(conn); } void Server::TCPServer::recv_message(int32_t conn) { char len_str[4]; int32_t recvd = recv(conn, len_str, sizeof(uint32_t), 0); if (recvd == 0) { // client disconnected this->close_connection(conn); return; } // parse header (uint32_t representing the size of the full message) if (recvd == sizeof(uint32_t)) { uint32_t len = atoi(len_str); std::vector<char> buffer(len + 1, 0x00); uint32_t bytes_read = 0; bool streaming_err = false; while (bytes_read < len) { int32_t recvd_bytes = recv(conn, &buffer[bytes_read], len - bytes_read, 0); if(recvd_bytes != -1) { bytes_read += recvd_bytes; } else { streaming_err = true; break; } } if (streaming_err) { std::cerr << "[!] Errors while receiving message from fd: " << conn << std::endl; this->close_connection(conn); return; } // buffer now contains the complete message std::cout << "[+] Received: "; for (auto c : buffer) { std::cout << c; } std::cout << " (from fd: " << conn << ")" << std::endl; } } void Server::TCPServer::handle_client_event(int32_t conn, uint32_t events) { const uint32_t err_mask = EPOLLERR | EPOLLHUP; if (events & err_mask) { this->close_connection(conn); return; } // stream incoming message this->recv_message(conn); } void Server::TCPServer::listen_conns() { if (listen(this->sfd, this->backlog) < 0) { std::cerr << "[!] Error while listening on specified address (0.0.0.0:1234), exiting..." << std::endl; exit(1); } // add sock_fd to epoll monitoring if (!(this->epoll_handler.epoll_add(this->sfd, EPOLLIN | EPOLLPRI))) { std::cerr << "[!] Failed to add fd to epoll, exiting..." << std::endl; exit(1); } std::cout << "[+] Listening on 0.0.0.0:1234" << std::endl; bool err = false; int32_t events_ret = 0x00; while (1) { events_ret = this->epoll_handler.wait_events(); if (events_ret == 0) { continue; } if (events_ret == -1) { if (errno == EINTR) continue; std::cerr << "[!] epoll error!" << std::endl; err = true; break; } std::vector<struct epoll_event> events = this->epoll_handler.get_events_vector(); for (uint32_t i = 0; i < events_ret; i++) { if (events[i].data.fd == this->sfd) { // new client is connecting to us if (!(this->accept_new_client())) { std::cerr << "[!] Error while accepting client connection!" << std::endl; err = true; break; } continue; } // we have event(s) from client this->handle_client_event(events[i].data.fd, events[i].events); } if (err) break; } } int main() { Server::TCPServer server; server.listen_conns(); return 0; }
25.303318
141
0.657239
[ "vector" ]
ea588e6e11a2f285abf3e5bb2a7b29e449134308
2,262
cpp
C++
examples/mult_example.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
5
2019-11-06T15:02:41.000Z
2022-01-14T20:25:50.000Z
examples/mult_example.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
3
2018-01-25T21:25:22.000Z
2022-03-14T17:35:27.000Z
examples/mult_example.cpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
1
2020-07-15T11:05:43.000Z
2020-07-15T11:05:43.000Z
#include <algorithm> #include <iostream> #include <vector> #include "autotune/autotune.hpp" #include "autotune/parameter.hpp" #include "autotune/tuners/bruteforce.hpp" #include "autotune/tuners/countable_set.hpp" AUTOTUNE_KERNEL(void(size_t, std::vector<double> &, size_t, std::vector<double> &, std::vector<double> &, std::vector<double> &, std::vector<double> &), mult_kernel, "examples/mult_kernel") int main(void) { std::cout << "testing countable set interface" << std::endl; autotune::mult_kernel.set_verbose(true); auto &builder = autotune::mult_kernel.get_builder<cppjit::builder::gcc>(); // builder.set_verbose(true); builder.set_include_paths( "-I/home/pfandedd/git/AutoTuneTMP/AutoTuneTMP_install_debug/include " "-I/home/pfandedd/git/AutoTuneTMP/Vc_install/include " "-I/home/pfandedd/git/AutoTuneTMP/boost_install/include"); builder.set_cpp_flags( "-Wall -Wextra -std=c++17 -march=native -mtune=native " "-O3 -g -ffast-math -fPIC -fno-gnu-unique"); // -fopenmp builder.set_link_flags("-shared -fno-gnu-unique "); // -fopenmp autotune::countable_set parameters; autotune::fixed_set_parameter<size_t> p1("DATA_BLOCKING", {6}); parameters.add_parameter(p1); // std::vector<size_t> thread_values{3, 100}; autotune::fixed_set_parameter<size_t> p2("KERNEL_OMP_THREADS", {3, 100}); parameters.add_parameter(p2); autotune::mult_kernel.set_parameter_values(parameters); size_t dims = 2; size_t dataset_size = 16; size_t grid_size = 16; std::vector<double> dataset_SoA(dataset_size); std::vector<double> level_list(grid_size); std::vector<double> index_list(grid_size); std::vector<double> alpha(grid_size); std::vector<double> result_padded(dataset_size); dataset_size = 0; autotune::mult_kernel(dims, dataset_SoA, dataset_size, level_list, index_list, alpha, result_padded); parameters[1]->next(); // compile beforehand so that compilation is not part of the measured duration autotune::mult_kernel.set_parameter_values(parameters); autotune::mult_kernel(dims, dataset_SoA, dataset_size, level_list, index_list, alpha, result_padded); return 0; }
35.904762
80
0.702918
[ "vector" ]
ea5da3e06c79192974a9190f4c22d1a55d4c5adc
5,956
cpp
C++
Elements/src/higgs_couplings_table.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-09-17T22:53:26.000Z
2021-09-17T22:53:26.000Z
Elements/src/higgs_couplings_table.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
3
2021-07-22T11:23:48.000Z
2021-08-22T17:24:41.000Z
Elements/src/higgs_couplings_table.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-08-14T10:31:41.000Z
2021-08-14T10:31:41.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Lightweight higgs partial widths container /// /// ********************************************* /// /// Authors (add name and date if you modify): /// /// \author Pat Scott /// (p.scott@imperial.ac.uk) /// \date 2016 Sep /// /// ********************************************* #include "gambit/Elements/higgs_couplings_table.hpp" namespace Gambit { /// Set the number of neutral Higgses void HiggsCouplingsTable::set_n_neutral_higgs(int n) { n_neutral_higgses = n; neutral_decays_SM_array.resize(n); neutral_decays_array.resize(n); CP.resize(n); C_WW2.resize(n); C_ZZ2.resize(n); C_tt2.resize(n); C_bb2.resize(n); C_cc2.resize(n); C_tautau2.resize(n); C_gaga2.resize(n); C_gg2.resize(n); C_mumu2.resize(n); C_Zga2.resize(n); C_ss2.resize(n); C_hiZ2.resize(n); for (int i = 0; i < n; i++) C_hiZ2[i].resize(n); } /// Set the number of charged Higgses void HiggsCouplingsTable::set_n_charged_higgs(int n) { n_charged_higgses = n; charged_decays_array.resize(n); } /// Retrieve number of neutral higgses int HiggsCouplingsTable::get_n_neutral_higgs() const { return n_neutral_higgses; } /// Retrieve number of charged higgses int HiggsCouplingsTable::get_n_charged_higgs() const { return n_charged_higgses; } /// Set all effective couplings to 1 void HiggsCouplingsTable::set_effective_couplings_to_unity() { for (int i = 0; i < n_neutral_higgses; i++) { C_WW2[i] = 1.0; C_ZZ2[i] = 1.0; C_tt2[i] = 1.0; C_bb2[i] = 1.0; C_cc2[i] = 1.0; C_tautau2[i] = 1.0; C_gaga2[i] = 1.0; C_gg2[i] = 1.0; C_mumu2[i] = 1.0; C_Zga2[i] = 1.0; C_ss2[i] = 1.0; for(int j = 0; j < n_neutral_higgses; j++) C_hiZ2[i][j] = 1.0; } } /// Assign SM decay entries to neutral higgses void HiggsCouplingsTable::set_neutral_decays_SM(int index, const str& name, const DecayTable::Entry& entry) { if (index > n_neutral_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_neutral_higgses."); neutral_decays_SM_array[index] = &entry; neutral_decays_SM_map.insert(std::pair<str, const DecayTable::Entry&>(name,entry)); } /// Assign decay entries to neutral higgses void HiggsCouplingsTable::set_neutral_decays(int index, const str& name, const DecayTable::Entry& entry) { if (index > n_neutral_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_neutral_higgses."); neutral_decays_array[index] = &entry; neutral_decays_map.insert(std::pair<str, const DecayTable::Entry&>(name,entry)); } /// Assign decay entries to charged higgses void HiggsCouplingsTable::set_charged_decays(int index, const str& name, const DecayTable::Entry& entry) { if (index > n_charged_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_charged_higgses."); charged_decays_array[index] = &entry; charged_decays_map.insert(std::pair<str, const DecayTable::Entry&>(name,entry)); } /// Assign decay entries to top void HiggsCouplingsTable::set_t_decays(const DecayTable::Entry& entry) { t_decays = &entry; } /// Retrieve SM decays of all neutral higgses const std::vector<const DecayTable::Entry*>& HiggsCouplingsTable::get_neutral_decays_SM_array() const { return neutral_decays_SM_array; } /// Retrieve SM decays of a specific neutral Higgs, by index const DecayTable::Entry& HiggsCouplingsTable::get_neutral_decays_SM(int index) const { if (index > n_neutral_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_neutral_higgses."); return *neutral_decays_SM_array[index]; } /// Retrieve SM decays of a specific neutral Higgs, by name const DecayTable::Entry& HiggsCouplingsTable::get_neutral_decays_SM(const str& name) const { if (neutral_decays_SM_map.find(name) == neutral_decays_SM_map.end()) utils_error().raise(LOCAL_INFO, "Requested higgs not found."); return neutral_decays_SM_map.at(name); } /// Retrieve decays of all neutral higgses const std::vector<const DecayTable::Entry*>& HiggsCouplingsTable::get_neutral_decays_array() const { return neutral_decays_array; } /// Retrieve decays of a specific neutral Higgs, by index const DecayTable::Entry& HiggsCouplingsTable::get_neutral_decays(int index) const { if (index > n_neutral_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_neutral_higgses."); return *neutral_decays_array[index]; } /// Retrieve decays of a specific neutral Higgs, by name const DecayTable::Entry& HiggsCouplingsTable::get_neutral_decays(const str& name) const { if (neutral_decays_map.find(name) == neutral_decays_map.end()) utils_error().raise(LOCAL_INFO, "Requested higgs not found."); return neutral_decays_map.at(name); } /// Retrieve decays of all charged higgses const std::vector<const DecayTable::Entry*>& HiggsCouplingsTable::get_charged_decays_array() const { return charged_decays_array; } /// Retrieve decays of a specific charged Higgs, by index const DecayTable::Entry& HiggsCouplingsTable::get_charged_decays(int index) const { if (index > n_charged_higgses - 1) utils_error().raise(LOCAL_INFO, "Requested index beyond n_charged_higgses."); return *charged_decays_array[index]; } /// Retrieve decays of a specific charged Higgs, by name const DecayTable::Entry& HiggsCouplingsTable::get_charged_decays(const str& name) const { if (charged_decays_map.find(name) == charged_decays_map.end()) utils_error().raise(LOCAL_INFO, "Requested higgs not found."); return charged_decays_map.at(name); } /// Retrieve decays of the top quark const DecayTable::Entry& HiggsCouplingsTable::get_t_decays() const { return *t_decays; } }
34.427746
135
0.688885
[ "vector" ]
ea6379935919f0b341d58479f05b855122ac2984
625
cpp
C++
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_DrawInstancedPass.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_DrawInstancedPass.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_DrawInstancedPass.cpp
shh1473/Sunrin_Engine_2019
1782d10a397055f8a64f3b772b342438ede02b36
[ "MIT" ]
null
null
null
#include "SR_PCH.h" #include "SR_DrawInstancedPass.h" #include "SR_App.h" namespace SunrinEngine { SR_DrawInstancedPass::SR_DrawInstancedPass(SR_Component * owner) noexcept : SR_CommonPass(owner), m_vertexCountPerInstance { 0 }, m_instanceCount { 0 }, m_startVertexLocation { 0 }, m_startInstanceLocation { 0 } { } bool SR_DrawInstancedPass::Render(unsigned threadID) { SR_RF_BOOL(Apply(threadID)); SR_App::GetInstance()->GetGraphic().GetD3DDeferredContext(threadID)->DrawInstanced(m_vertexCountPerInstance, m_instanceCount, m_startVertexLocation, m_startInstanceLocation); return true; } }
22.321429
176
0.7648
[ "render" ]
ea6644e611d271e78b484a16a354363f0aa4b3da
19,896
cpp
C++
gl_impl.cpp
Meisaka/ICIClient
cc0a11031338fed79019aa8c997c6a5f09c514d6
[ "MIT" ]
2
2016-05-19T16:18:38.000Z
2021-05-19T15:12:12.000Z
gl_impl.cpp
Meisaka/ICIClient
cc0a11031338fed79019aa8c997c6a5f09c514d6
[ "MIT" ]
1
2016-10-30T21:49:18.000Z
2016-11-01T01:29:53.000Z
gl_impl.cpp
Meisaka/ICIClient
cc0a11031338fed79019aa8c997c6a5f09c514d6
[ "MIT" ]
1
2016-05-19T16:18:41.000Z
2016-05-19T16:18:41.000Z
// ImGui SDL2 binding with OpenGL3 (slightly modified) // In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. #include "ici.h" // SDL WM #include <SDL_syswm.h> // Data static double g_Time = 0.0f; static bool g_MousePressed[5] = { false, false, false, false, false }; static float g_MouseWheel = 0.0f; static icitexture g_FontTexture; static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; static struct AttribLocs { int Tex; int Offset; int Mode; int Position; int UV; int Color; } g_Attribs = {0,}; static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0, g_SamplerHandle = 0; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void ICIC_RenderDrawLists(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) ImGuiIO& io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Setup orthographic projection matrix glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float screen_offset[2] = { 2.0f / io.DisplaySize.x, 2.0f / -io.DisplaySize.y }; glUseProgram(g_ShaderHandle); glUniform1i(g_Attribs.Tex, 0); glUniform1i(g_Attribs.Mode, 0); glUniform2fv(g_Attribs.Offset, 1, screen_offset); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { icitexture *ici = (icitexture*)pcmd->TextureId; if(ici) { glBindTexture(GL_TEXTURE_2D, ici->handle); glUniform1i(g_Attribs.Mode, ici->type); } else { glBindTexture(GL_TEXTURE_2D, 0); glUniform1i(g_Attribs.Mode, 0); } glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glActiveTexture(last_active_texture); glBindTexture(GL_TEXTURE_2D, last_texture); glBindVertexArray(last_vertex_array); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); } static const char* ICIC_GetClipboardText() { return SDL_GetClipboardText(); } static void ICIC_SetClipboardText(const char* text) { SDL_SetClipboardText(text); } bool ICIC_ProcessEvent(SDL_Event* event) { ImGuiIO& io = ImGui::GetIO(); int key; switch (event->type) { case SDL_MOUSEWHEEL: if (event->wheel.y > 0) g_MouseWheel = 1; if (event->wheel.y < 0) g_MouseWheel = -1; return true; case SDL_MOUSEBUTTONDOWN: if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; if (event->button.button == SDL_BUTTON_X1) g_MousePressed[3] = true; if (event->button.button == SDL_BUTTON_X2) g_MousePressed[4] = true; return true; case SDL_TEXTINPUT: io.AddInputCharactersUTF8(event->text.text); return true; case SDL_KEYDOWN: case SDL_KEYUP: key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK; if(key == SDL_SCANCODE_KP_ENTER) key = SDLK_RETURN; io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); return true; } return false; } void ICIC_UpdateHWTexture(icitexture *tex, int width, int height, uint32_t *pixels) { // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glBindTexture(GL_TEXTURE_2D, tex->handle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); } void ICIC_CreateHWTexture(icitexture *tex, int width, int height) { // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &tex->handle); glBindTexture(GL_TEXTURE_2D, tex->handle); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); tex->type = 1; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); } void ICIC_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; LogMessage("Generating Atlas...\n"); io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height); // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &g_FontTexture.handle); glBindTexture(GL_TEXTURE_2D, g_FontTexture.handle); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)&g_FontTexture; // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); } bool ICIC_CreateDeviceObjects() { LogMessage("Building GL Objects\n"); // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar *vertex_shader = "#version 330\n" "uniform vec2 Offset;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = vec4((Offset * Position.xy) + vec2(-1.0, 1.0),0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "uniform int Mode;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " if(Mode == 1) {\n" " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" " } else {\n" " Out_Color = Frag_Color * vec4(1,1,1,texture(Texture, Frag_UV.st).r);\n" " }\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_Attribs.Tex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_Attribs.Offset = glGetUniformLocation(g_ShaderHandle, "Offset"); g_Attribs.Mode = glGetUniformLocation(g_ShaderHandle, "Mode"); g_Attribs.Position = glGetAttribLocation(g_ShaderHandle, "Position"); g_Attribs.UV = glGetAttribLocation(g_ShaderHandle, "UV"); g_Attribs.Color = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_Attribs.Position); glEnableVertexAttribArray(g_Attribs.UV); glEnableVertexAttribArray(g_Attribs.Color); glGenSamplers(1, &g_SamplerHandle); glSamplerParameteri(g_SamplerHandle, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameteri(g_SamplerHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindSampler(0, g_SamplerHandle); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_Attribs.Position, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_Attribs.UV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_Attribs.Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF ICIC_CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); LogMessage("Complete\n"); return true; } void ICIC_InvalidateDeviceObjects() { if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; glDetachShader(g_ShaderHandle, g_VertHandle); glDeleteShader(g_VertHandle); g_VertHandle = 0; glDetachShader(g_ShaderHandle, g_FragHandle); glDeleteShader(g_FragHandle); g_FragHandle = 0; glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; if(g_FontTexture.handle) { glDeleteTextures(1, &g_FontTexture.handle); ImGui::GetIO().Fonts->TexID = 0; g_FontTexture.handle = 0; } } bool ICIC_Init(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; io.RenderDrawListsFn = ICIC_RenderDrawLists; io.SetClipboardTextFn = ICIC_SetClipboardText; io.GetClipboardTextFn = ICIC_GetClipboardText; ImGuiStyle& style = ImGui::GetStyle(); style.AntiAliasedLines = false; style.AntiAliasedShapes = false; style.WindowPadding = ImVec2(6.f, 6.f); style.WindowRounding = 0; style.ChildWindowRounding = 0; style.FramePadding = ImVec2(3.f, 3.f); style.FrameRounding = 0; style.ItemSpacing = ImVec2(6.f, 2.f); style.ItemInnerSpacing = ImVec2(2.f, 2.f); style.IndentSpacing = 20; style.ScrollbarSize = 14; style.ScrollbarRounding = 0; style.GrabMinSize = 10; style.GrabRounding = 0; style.Colors[ImGuiCol_Text] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); style.Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.02f, 0.13f, 0.90f); style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style.Colors[ImGuiCol_PopupBg] = ImVec4(0.00f, 0.07f, 0.25f, 0.85f); style.Colors[ImGuiCol_Border] = ImVec4(0.00f, 0.71f, 0.56f, 0.57f); style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style.Colors[ImGuiCol_FrameBg] = ImVec4(0.42f, 0.42f, 0.54f, 0.44f); style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.83f, 0.65f, 0.72f, 0.45f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.51f, 0.69f, 0.67f); style.Colors[ImGuiCol_TitleBg] = ImVec4(0.12f, 0.33f, 0.38f, 0.73f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.83f, 0.97f, 0.14f); style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.24f, 0.51f, 0.55f, 0.94f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.24f, 0.31f, 0.42f, 0.53f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.38f, 0.41f, 0.67f); style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.71f, 0.85f, 0.43f); style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.83f, 0.95f, 0.43f); style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 1.00f, 1.00f, 0.84f); style.Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); style.Colors[ImGuiCol_CheckMark] = ImVec4(0.28f, 1.00f, 0.59f, 0.72f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.92f, 0.59f, 0.37f, 1.00f); style.Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.25f, 0.92f, 0.60f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.50f, 1.00f, 1.00f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.84f, 0.66f, 1.00f, 1.00f); style.Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); style.Colors[ImGuiCol_Column] = ImVec4(0.41f, 0.25f, 0.40f, 1.00f); style.Colors[ImGuiCol_ColumnHovered] = ImVec4(1.00f, 0.60f, 0.69f, 1.00f); style.Colors[ImGuiCol_ColumnActive] = ImVec4(1.00f, 0.87f, 0.72f, 1.00f); style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.50f); style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.71f); style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); style.Colors[ImGuiCol_CloseButton] = ImVec4(0.70f, 0.50f, 1.00f, 0.55f); style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.96f, 0.43f, 0.78f, 1.00f); style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); style.Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 1.00f, 1.00f, 0.37f); style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.05f, 0.00f, 0.00f, 0.69f); #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #else (void)window; #endif return true; } void ICIC_Shutdown() { ICIC_InvalidateDeviceObjects(); ImGui::Shutdown(); } void ICIC_NewFrame(SDL_Window* window) { if (!g_FontTexture.handle) ICIC_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent()) int mx, my; Uint32 mouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) else io.MousePos = ImVec2(-1, -1); io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; io.MouseDown[3] = g_MousePressed[3] || (mouseMask & SDL_BUTTON(SDL_BUTTON_X1)) != 0; io.MouseDown[4] = g_MousePressed[4] || (mouseMask & SDL_BUTTON(SDL_BUTTON_X2)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); // Start the frame ImGui::NewFrame(); }
41.107438
232
0.734318
[ "render" ]
ea6698ccdd76e3dc4e0800fe457eb4ba83d6e3c0
7,048
cxx
C++
utilities/goal_distance/src/main.cxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
utilities/goal_distance/src/main.cxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
utilities/goal_distance/src/main.cxx
miquelramirez/aamas18-planning-for-transparency
dff3e635102bf351906807c5181113fbf4b67083
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <map> #include <ctype.h> #include <climits> #include <strips_prob.hxx> #include <ff_to_aptk.hxx> #include <fluent.hxx> #include <action.hxx> #include <cond_eff.hxx> #include <strips_state.hxx> #include <fwd_search_prob.hxx> #include <rp_heuristic.hxx> #include <aptk/open_list.hxx> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <string> #include <aptk/string_conversions.hxx> #include <aptk/at_bfs.hxx> #include <aptk/closed_list.hxx> #include "utility.hxx" #include "goal_set_parse.hxx" #include "dalandmarks.hxx" #include "gd.hxx" namespace po = boost::program_options; using aptk::STRIPS_Problem; using aptk::Action; using aptk::agnostic::Fwd_Search_Problem; using namespace gd; void process_command_line_options( int ac, char** av, po::variables_map& vm) { po::options_description desc( "Additional Options" ); desc.add_options() ( "domain,d", po::value<std::string>(), "Input PDDL domain description" ) ( "problem,p", po::value<std::string>(), "Input PDDL problem description" ) ( "goalset,g", po::value<std::string>(), "Input PDDL goal-set description\n" ) ( "max-nodes,m", po::value<unsigned int>()->default_value(100), "The maximum amount of nodes in earch MCTS tree." ) ( "max-simulate-nodes,s", po::value<unsigned int>(), "The maximum amount of nodes to be simulated in the rollout policy.\n" ) ( "beta,b", po::value<float>()->default_value(1), "Value determining how rational an observer believes the agent to be." ) ( "theta,t", po::value<double>()->default_value(1.0f), "Threshold for goal filtering" ) ( "discount-factor,D", po::value<double>()->default_value(1.0f), "The amount by which transparent plans are penalised by their distance." ) ( "precision,P", po::value<int>()->default_value(2), "The precision to which the belief state is stored as within the state.\n" ) ( "landmark,L", po::bool_switch()->default_value(false), "Use landmark plan recognition." ) ( "filter,f", po::bool_switch()->default_value(false), "Use goal filtering with plan recognition." ) ( "optimal,o", po::bool_switch()->default_value(false), "Use optimal plan recognition." ) ( "nan,n", po::bool_switch()->default_value(false), "Approximate C(G, ~O) as c(G) in approximate plan recognition." ) ( "static-beta,S", po::bool_switch()->default_value(false), "Keep beta value static in search." ) ( "diff-plan-rec,r", po::bool_switch()->default_value(false), "Use difference based plan recognition." ) ( "closed-list-tree,l", po::bool_switch()->default_value(false), "Use a closed list in the tree policy of the MCTS.\n" ) ( "verbose,v", po::bool_switch()->default_value(false), "Verbose results." ) ( "pr-verbose,V", po::bool_switch()->default_value(false), "Verbose plan recognition results." ) ( "continue,c", po::bool_switch()->default_value(false), "Continue actions without pause." ) ( "one-action,O", po::bool_switch()->default_value(false), "Finish program after one action." ) ( "help,h", "Show help message" ) ; po::positional_options_description positionalOptions; positionalOptions.add("domain", 1); positionalOptions.add("problem", 1); positionalOptions.add("goalset", 1); try { po::store(po::command_line_parser(ac, av).options(desc).positional(positionalOptions).run(), vm); //po::store( po::parse_command_line( ac, av, desc ), vm); po::notify( vm ); } catch ( std::exception& e ) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } catch ( ... ) { std::cerr << "Exception of unknown type!" << std::endl; std::exit(1); } if ( vm.count("help") ) { std::cout << "Author: Aleck MacNally\n"; std::cout << "Purpose: This program is an AI planner for classical planning domains.\n\ It differs from other AI planners in that it's objective is to find the plan which\n\ which is most obviously attempting to achieve it's goal to an observer.\n\n"; std::cout << "Usage: PFT DOMAIN PROBLEM GOALSET [OPTIONS]" << std::endl << std::endl; std::cout << desc << std::endl; std::exit(0); } } int main( int argc, char** argv){ po::variables_map vm; process_command_line_options( argc, argv, vm ); if ( !vm.count( "domain" ) ) { std::cerr << "No PDDL domain was specified!" << std::endl; std::exit(1); } if ( !vm.count( "problem" ) ) { std::cerr << "No PDDL problem was specified!" << std::endl; std::exit(1); } if ( !vm.count( "goalset" ) ) { std::cerr << "No Goal Set file was specified!" << std::endl; std::exit(1); } std::string goal_set_name = vm["goalset"].as<std::string>(); float beta = vm["beta"].as<float>(); bool optimal = vm["optimal"].as<bool>(); double discount_factor = vm["discount-factor"].as<double>(); unsigned int max_nodes = vm["max-nodes"].as<unsigned int>(); bool diff_plan_rec = vm["diff-plan-rec"].as<bool>(); bool closed_list_tree = vm["closed-list-tree"].as<bool>(); bool verbose = vm["verbose"].as<bool>(); bool continue_pause = vm["continue"].as<bool>(); bool one_action = vm["one-action"].as<bool>(); bool negated_as_neutral = vm["nan"].as<bool>(); bool variable_beta = !vm["static-beta"].as<bool>(); bool pr_verbose = vm["pr-verbose"].as<bool>(); double theta = vm["theta"].as<double>(); bool landmark = vm["landmark"].as<bool>(); bool filter = vm["filter"].as<bool>(); unsigned int max_simulate_nodes; if(!vm.count("max-simulate-nodes")){ max_simulate_nodes = INT_MAX; }else{ max_simulate_nodes = vm["max-simulate-nodes"].as<unsigned int>(); } unsigned int precision; if(!vm.count("precision")){ precision = -1; }else{ precision = vm["precision"].as<int>(); } aptk::STRIPS_Problem prob; aptk::FF_Parser::get_problem_description( vm["domain"].as<std::string>(), vm["problem"].as<std::string>(), prob ); std::vector<aptk::Fluent_Vec> goal_set = goal_set_parsing(goal_set_name, prob); std::vector<double> priors; for (unsigned int i = 0; i < goal_set.size(); i++){ priors.push_back(0.5); } priors = normalize_vector(priors); unsigned int goal_index = 0; std::vector<unsigned> true_goal_v = prob.goal(); std::set<unsigned> true_goal(true_goal_v.begin(), true_goal_v.end()); for (unsigned int i = 0; i < goal_set.size(); i++){ std::vector<unsigned> cand_goal_v = goal_set[i]; std::set<unsigned> cand_goal (cand_goal_v.begin(), cand_goal_v.end()); if (cand_goal == true_goal) goal_index = i; } prob.set_goal_set(goal_set); prob.set_priors(priors); prob.set_beta(beta); prob.set_df(discount_factor); prob.set_precision(precision); prob.set_pr_verbose(pr_verbose); prob.set_nan(negated_as_neutral); prob.set_v_beta(variable_beta); prob.set_optimal(optimal); prob.set_true_init(prob.init()); prob.set_theta(theta); prob.set_filter(filter); prob.set_landmark(landmark); std::cout << std::endl; goal_distance_calculator gd(prob, goal_set); double distance = gd.complete_goal_distance(); std::cout << "Goal Distance: " << distance << std::endl; }
35.77665
141
0.6792
[ "vector" ]
ea69646686934cf7b546679da08cb56d42a054d3
1,878
cpp
C++
inst/isource/cluster4.cpp
trosendal/sourceSim
190c86db6edd07d217321393679e0b9152b7c032
[ "BSD-3-Clause" ]
null
null
null
inst/isource/cluster4.cpp
trosendal/sourceSim
190c86db6edd07d217321393679e0b9152b7c032
[ "BSD-3-Clause" ]
1
2021-11-01T14:39:13.000Z
2021-11-01T14:39:13.000Z
inst/isource/cluster4.cpp
trosendal/sourceSim
190c86db6edd07d217321393679e0b9152b7c032
[ "BSD-3-Clause" ]
null
null
null
#include "cluster.h" void Cluster::recalc_b(Matrix<double> &a, Matrix< Vector<double> > &b) { int i,j,k,l; for(i=0;i<ng;i++) { for(j=0;j<nloc;j++) { for(k=0;k<acount[i][j].size();k++) { b[i][j][k] = 0.0; for(l=0;l<ng;l++) { b[i][j][k] += acount[l][j][k] * a[i][l]; // bk[i][j][k] += (acount[l][j][k]*(double)size[l]-1.0)/(double)(size[l]-1) * a[i][l]; } } } } } mydouble Cluster::known_source_lik4_composite(Matrix<double> &a, Matrix< Vector<double> > &b) { int i,j,l; mydouble lik = 1.0; /* Cycle through each unique ST in each group, taking account of abundance of the STs */ for(i=0;i<ng;i++) { for(j=0;j<nST[i];j++) { double ncopies = ceil(freq[i][j].todouble()*(double)size[i]-0.5); for(l=0;l<nloc;l++) { int allele = MLST[i][j][l]; double num = acount[ng][l][allele] * (double)size[ng]; if(num<1.1) { // new allele (allow some rounding error) lik *= mydouble(a[i][ng])^ncopies; } else { // previously observed // double bk = b[i][l][allele] + a[i][i]/(double)(size[i]-1)*(acount[i][l][allele] - 1.0); double ac = acount[i][l][allele]; double bk = b[i][l][allele] - a[i][i]*ac + a[i][i]*(ac*(double)size[i]-1.0)/(double)(size[i]-1); if(fabs(bk)<1.0e-7) { bk = 0.0; warning("Factor of zero in likelihood"); } lik *= mydouble(bk)^ncopies; } } } } return lik; } mydouble Cluster::likHi4(const int id, const int i, Matrix<double> &a, Matrix< Vector<double> > &b) { // return mydouble(1.0); int k; mydouble l_i(1.0); /* Assume free recombination between loci */ for(k=0;k<nloc;k++) { int human_allele = human[id][k]; if(human_allele>=acount[ng][k].size() || acount[ng][k][human_allele]==0) { // unique l_i *= mydouble(a[i][ng]); } else { // not unique l_i *= mydouble(b[i][k][human_allele]); } } return l_i; // return l_i^0.1; }
28.892308
101
0.561235
[ "vector" ]
ea72b836fbacbb3bc732a8c7d9f61eea0493215c
7,230
cpp
C++
tools/clang/tools/dxlib-sample/lib_cache_manager.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/clang/tools/dxlib-sample/lib_cache_manager.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/clang/tools/dxlib-sample/lib_cache_manager.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // lib_cache_manager.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Implements lib blob cache manager. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/WinIncludes.h" #include "dxc/Support/Global.h" #include "dxc/dxcapi.h" #include "llvm37/ADT/DenseMap.h" #include "llvm37/ADT/Hashing.h" #include <mutex> #include <shared_mutex> #include <unordered_map> #include "lib_share_helper.h" #include "llvm37/ADT/STLExtras.h" #include "dxc/Support/FileIOHelper.h" using namespace llvm37; using namespace libshare; #include "dxc/Support/dxcapi.use.h" #include "dxc/dxctools.h" namespace { class NoFuncBodyRewriter { public: NoFuncBodyRewriter() { if (!m_dllSupport.IsEnabled()) m_dllSupport.Initialize(); m_dllSupport.CreateInstance(CLSID_DxcRewriter, &m_pRewriter); } HRESULT RewriteToNoFuncBody(LPCWSTR pFilename, IDxcBlobEncoding *pSource, std::vector<DxcDefine> &m_defines, IDxcBlob **ppNoFuncBodySource); private: CComPtr<IDxcRewriter> m_pRewriter; dxc::DxcDllSupport m_dllSupport; }; HRESULT NoFuncBodyRewriter::RewriteToNoFuncBody( LPCWSTR pFilename, IDxcBlobEncoding *pSource, std::vector<DxcDefine> &m_defines, IDxcBlob **ppNoFuncBodySource) { // Create header with no function body. CComPtr<IDxcOperationResult> pRewriteResult; IFT(m_pRewriter->RewriteUnchangedWithInclude( pSource, pFilename, m_defines.data(), m_defines.size(), // Don't need include handler here, include already read in // RewriteIncludesToSnippet nullptr, RewriterOptionMask::SkipFunctionBody | RewriterOptionMask::KeepUserMacro, &pRewriteResult)); HRESULT status; if (!SUCCEEDED(pRewriteResult->GetStatus(&status)) || !SUCCEEDED(status)) { CComPtr<IDxcBlobEncoding> pErr; IFT(pRewriteResult->GetErrorBuffer(&pErr)); std::string errString = std::string((char *)pErr->GetBufferPointer(), pErr->GetBufferSize()); IFTMSG(E_FAIL, errString); return E_FAIL; }; // Get result. IFT(pRewriteResult->GetResult(ppNoFuncBodySource)); return S_OK; } } // namespace namespace { struct KeyHash { std::size_t operator()(const hash_code &k) const { return k; } }; struct KeyEqual { bool operator()(const hash_code &l, const hash_code &r) const { return l == r; } }; class LibCacheManagerImpl : public libshare::LibCacheManager { public: ~LibCacheManagerImpl() {} HRESULT AddLibBlob(std::string &processedHeader, const std::string &snippet, CompileInput &compiler, size_t &hash, IDxcBlob **pResultLib, std::function<void(IDxcBlob *pSource)> compileFn) override; bool GetLibBlob(std::string &processedHeader, const std::string &snippet, CompileInput &compiler, size_t &hash, IDxcBlob **pResultLib) override; void Release() { m_libCache.clear(); } private: hash_code GetHash(const std::string &header, const std::string &snippet, CompileInput &compiler); using libCacheType = std::unordered_map<hash_code, CComPtr<IDxcBlob>, KeyHash, KeyEqual>; libCacheType m_libCache; using headerCacheType = std::unordered_map<hash_code, std::string, KeyHash, KeyEqual>; headerCacheType m_headerCache; std::shared_mutex m_mutex; NoFuncBodyRewriter m_rewriter; }; static hash_code CombineWStr(hash_code hash, LPCWSTR Arg) { CW2A pUtf8Arg(Arg, CP_UTF8); unsigned length = strlen(pUtf8Arg.m_psz); return hash_combine(hash, StringRef(pUtf8Arg.m_psz, length)); } hash_code LibCacheManagerImpl::GetHash(const std::string &header, const std::string &snippet, CompileInput &compiler) { hash_code libHash = hash_value(header); libHash = hash_combine(libHash, snippet); // Combine compile input. for (auto &Arg : compiler.arguments) { libHash = CombineWStr(libHash, Arg); } // snippet has been processed so don't add define to hash. return libHash; } using namespace hlsl; HRESULT LibCacheManagerImpl::AddLibBlob(std::string &processedHeader, const std::string &snippet, CompileInput &compiler, size_t &hash, IDxcBlob **pResultLib, std::function<void(IDxcBlob *pSource)> compileFn) { if (!pResultLib) { return E_FAIL; } std::unique_lock<std::shared_mutex> lk(m_mutex); auto it = m_libCache.find(hash); if (it != m_libCache.end()) { *pResultLib = it->second; DXASSERT(m_headerCache.count(hash), "else mismatch header and lib"); processedHeader = m_headerCache[hash]; return S_OK; } std::string shader = processedHeader + snippet; CComPtr<IDxcBlobEncoding> pSource; IFT(DxcCreateBlobWithEncodingOnMallocCopy(GetGlobalHeapMalloc(), shader.data(), shader.size(), CP_UTF8, &pSource)); compileFn(pSource); m_libCache[hash] = *pResultLib; // Rewrite curHeader to remove function body. CComPtr<IDxcBlob> result; IFT(m_rewriter.RewriteToNoFuncBody(L"input.hlsl", pSource, compiler.defines, &result)); processedHeader = std::string((char *)(result)->GetBufferPointer(), (result)->GetBufferSize()); m_headerCache[hash] = processedHeader; return S_OK; } bool LibCacheManagerImpl::GetLibBlob(std::string &processedHeader, const std::string &snippet, CompileInput &compiler, size_t &hash, IDxcBlob **pResultLib) { if (!pResultLib) { return false; } // Create hash from source. hash_code libHash = GetHash(processedHeader, snippet, compiler); hash = libHash; // lock std::shared_lock<std::shared_mutex> lk(m_mutex); auto it = m_libCache.find(libHash); if (it != m_libCache.end()) { *pResultLib = it->second; DXASSERT(m_headerCache.count(libHash), "else mismatch header and lib"); processedHeader = m_headerCache[libHash]; return true; } else { return false; } } LibCacheManager *GetLibCacheManagerPtr(bool bFree) { static std::unique_ptr<LibCacheManagerImpl> g_LibCache = llvm37::make_unique<LibCacheManagerImpl>(); if (bFree) g_LibCache.reset(); return g_LibCache.get(); } } // namespace LibCacheManager &LibCacheManager::GetLibCacheManager() { return *GetLibCacheManagerPtr(/*bFree*/false); } void LibCacheManager::ReleaseLibCacheManager() { GetLibCacheManagerPtr(/*bFree*/true); }
35.097087
117
0.625311
[ "vector" ]
ea75fa57c8610a61af723957f18542b82d7ec372
798
hpp
C++
apal_cxx/include/chc_noise.hpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
apal_cxx/include/chc_noise.hpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
15
2019-05-23T07:18:19.000Z
2019-12-17T08:01:10.000Z
apal_cxx/include/chc_noise.hpp
davidkleiven/APAL
f3d549498d312b98f55aad5db7c4ad061785ecbf
[ "MIT" ]
null
null
null
#ifndef CHC_NOISE_H #define CHC_NOISE_H #include <vector> #include <string> #include "thermal_noise_generator.hpp" template<int dim> class CHCNoise: public ThermalNoiseGenerator{ public: CHCNoise(double dt, double mobility, double amplitude, unsigned int L); ~CHCNoise(); /** Create noise */ void create(std::vector<double> &noise) const; void set_timestep(double new_dt){dt = new_dt;}; /** Store noise at MMSP grid */ void noise2grid(const std::string &fname, const std::vector<double> &noise) const; private: double mobility{0.0}; double dt{1.0}; double amplitude{0.0}; unsigned int L{1}; MMSP::grid<dim, int> *indexGrid{nullptr}; void chc_noise(const std::vector<double> &gaussian_white, std::vector<double> &chc_noise) const; }; #endif
25.741935
100
0.697995
[ "vector" ]
ea7618086f4342b8dabe62820d06573d78639f51
27,820
cpp
C++
tests/unit/plugins/matrixops/dot_operation.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
tests/unit/plugins/matrixops/dot_operation.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
tests/unit/plugins/matrixops/dot_operation.cpp
NK-Nikunj/phylanx
6898992513a122c49d26947d877f329365486665
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017 Hartmut Kaiser // Copyright (c) 2017 Parsa Amini // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/phylanx.hpp> #include <hpx/hpx_main.hpp> #include <hpx/include/lcos.hpp> #include <hpx/util/lightweight_test.hpp> #include <iostream> #include <utility> #include <vector> #include <blaze/Math.h> void test_dot_operation_0d() { phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(7.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ( 42.0, phylanx::execution_tree::extract_numeric_value(f.get())[0]); } void test_dot_operation_0d_lit() { phylanx::ir::node_data<double> lhs(6.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(7.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ( 42.0, phylanx::execution_tree::extract_numeric_value(f.get())[0]); } void test_dot_operation_0d1d() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = 6.0 * v; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_0d1d_lit() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL); phylanx::ir::node_data<double> lhs(6.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = 6.0 * v; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_0d1d_numpy() { blaze::DynamicVector<double> v{1.0, 3.0, 4.0}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected{6.0, 18.0, 24.0}; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_0d2d() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected = 6.0 * m; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_0d2d_lit() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL); phylanx::ir::node_data<double> lhs(6.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected = 6.0 * m; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_0d2d_numpy() { blaze::DynamicMatrix<double> m{{1.0, 3.0, 4.0}, {2.0, 5.0, 6.0}}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected{ {6.0, 18.0, 24.0}, {12.0, 30.0, 36.0}}; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d0d() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = v * 6.0; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d0d_lit() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL); phylanx::ir::node_data<double> lhs(v); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = v * 6.0; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d0d_numpy() { blaze::DynamicVector<double> v{1.0, 3.0, 4.0}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected{6.0, 18.0, 24.0}; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v1 = gen.generate(1007UL); blaze::DynamicVector<double> v2 = gen.generate(1007UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); double expected = blaze::dot(v1, v2); HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d_lit() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v1 = gen.generate(1007UL); blaze::DynamicVector<double> v2 = gen.generate(1007UL); phylanx::ir::node_data<double> lhs(v1); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); double expected = blaze::dot(v1, v2); HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d_numpy() { blaze::DynamicVector<double> v1{1.0, 4.0, 9.0, 7.0}; blaze::DynamicVector<double> v2{3.0, 2.0, 1.0, 0.0}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); double expected=20.0; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d2d() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(101UL); blaze::Rand<blaze::DynamicMatrix<double>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = blaze::trans(blaze::trans(v) * m); HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d2d_lit() { blaze::Rand<blaze::DynamicVector<double>> gen{}; blaze::DynamicVector<double> v = gen.generate(101UL); blaze::Rand<blaze::DynamicMatrix<double>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL); phylanx::ir::node_data<double> lhs(v); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected = blaze::trans(blaze::trans(v) * m); HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_1d2d_numpy() { blaze::DynamicVector<double> v{4.0, 2.0, 3.0}; blaze::DynamicMatrix<double> m{ {2.0, 3.0, 4.0}, {1.0, 3.0, 4.0}, {2.0, 5.0, 6.0}}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected{16.0, 33.0, 42.0}; HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d0d() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected = m * 6.0; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d0d_lit() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL); phylanx::ir::node_data<double> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected = m * 6.0; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d0d_numpy() { blaze::DynamicMatrix<double> m{{1.0, 3.0, 4.0}, {2.0, 5.0, 6.0}}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(6.0)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected{ {6.0, 18.0, 24.0}, {12.0, 30.0, 36.0}}; HPX_TEST_EQ(phylanx::ir::node_data<double>{expected}, phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d1d() { blaze::Rand<blaze::DynamicMatrix<double>> gen1{}; blaze::DynamicMatrix<double> m = gen1.generate(1007UL, 42UL); blaze::Rand<blaze::DynamicVector<double>> gen2{}; blaze::DynamicVector<double> v = gen2.generate(42UL); blaze::DynamicVector<double> expected = m * v; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs) }); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d1d_lit() { blaze::Rand<blaze::DynamicMatrix<double>> gen1{}; blaze::DynamicMatrix<double> m = gen1.generate(1007UL, 42UL); blaze::Rand<blaze::DynamicVector<double>> gen2{}; blaze::DynamicVector<double> v = gen2.generate(42UL); blaze::DynamicVector<double> expected = m * v; phylanx::ir::node_data<double> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d1d_numpy() { blaze::DynamicVector<double> v{4.0, 2.0, 3.0}; blaze::DynamicMatrix<double> m{ {2.0, 3.0, 4.0}, {1.0, 3.0, 4.0}}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicVector<double> expected{26.0, 22.0}; HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d2d() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m1 = gen.generate(42UL, 42UL); blaze::DynamicMatrix<double> m2 = gen.generate(42UL, 42UL); blaze::DynamicMatrix<double> expected = m1 * m2; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs) }); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d2d_lit() { blaze::Rand<blaze::DynamicMatrix<double>> gen{}; blaze::DynamicMatrix<double> m1 = gen.generate(42UL, 42UL); blaze::DynamicMatrix<double> m2 = gen.generate(42UL, 42UL); blaze::DynamicMatrix<double> expected = m1 * m2; phylanx::ir::node_data<double> lhs(m1); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } void test_dot_operation_2d2d_numpy() { blaze::DynamicMatrix<double> m1{{4.0, 2.0}, {3.0, 5.0}}; blaze::DynamicMatrix<double> m2{{2.0, 3.0, 4.0}, {1.0, 3.0, 4.0}}; phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m2)); phylanx::execution_tree::primitive dot = phylanx::execution_tree::primitives::create_dot_operation( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); hpx::future<phylanx::execution_tree::primitive_argument_type> f = dot.eval(); blaze::DynamicMatrix<double> expected{ {10.0, 18.0, 24.0}, {11.0, 24.0, 32.0}}; HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)), phylanx::execution_tree::extract_numeric_value(f.get())); } int main(int argc, char* argv[]) { test_dot_operation_0d(); test_dot_operation_0d_lit(); test_dot_operation_0d1d(); test_dot_operation_0d1d_lit(); test_dot_operation_0d1d_numpy(); test_dot_operation_0d2d(); test_dot_operation_0d2d_lit(); test_dot_operation_0d2d_numpy(); test_dot_operation_1d0d(); test_dot_operation_1d0d_lit(); test_dot_operation_1d0d_numpy(); test_dot_operation_1d(); test_dot_operation_1d_lit(); test_dot_operation_1d_numpy(); test_dot_operation_1d2d(); test_dot_operation_1d2d_lit(); test_dot_operation_1d2d_numpy(); test_dot_operation_2d0d(); test_dot_operation_2d0d_lit(); test_dot_operation_2d0d_numpy(); test_dot_operation_2d1d(); test_dot_operation_2d1d_lit(); test_dot_operation_2d1d_numpy(); test_dot_operation_2d2d(); test_dot_operation_2d2d_lit(); test_dot_operation_2d2d_numpy(); return hpx::util::report_errors(); }
36.557162
82
0.664881
[ "vector" ]
ea8163a77f40dd68454774e43094b79d87cfa81a
9,178
cpp
C++
src/glui_treepanel.cpp
mick-p1982/glui
1fa44ceadd135bdb022a0117e8437979d5cd7c9c
[ "Zlib" ]
null
null
null
src/glui_treepanel.cpp
mick-p1982/glui
1fa44ceadd135bdb022a0117e8437979d5cd7c9c
[ "Zlib" ]
1
2020-07-22T03:14:59.000Z
2020-07-22T03:14:59.000Z
src/glui_treepanel.cpp
mick-p1982/glui
1fa44ceadd135bdb022a0117e8437979d5cd7c9c
[ "Zlib" ]
1
2021-03-31T18:13:11.000Z
2021-03-31T18:13:11.000Z
/* This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../include/glui_internal.h" //PCH #if defined(GLUI_BUILD_TREE_CONTROLS) || defined(GLUI_BUILD_EXAMPLES) namespace GLUI_Library {//-. //<-' /****************************** GLUI_TreePanel::ab() *********/ /* Adds branch to curr_root */ UI::Experiments::Tree* UI::Experiments::TreePanel::add_tree(Tree *o) { //if(root) go_to_root(); //Tree *o = new Tree(curr_root,name); if(!o->parent()) o->set_parent(curr_root); //init_node(o); /**** GLUI_TreePanel::initNode() ****/ { int level = o->get_level(); int child_number = 1; //Tree *ptree = dynamic_cast<Tree*>(o->parent()); Tree *ptree = dynamic_cast<Tree*>(curr_root); if(ptree) { level = 1+ptree->get_level(); Tree *prevTree = dynamic_cast<Tree*>(o->prev()); if(prevTree) { child_number = 1+prevTree->get_child_number(); } else assert(!o->prev()); } else //if(dynamic_cast<Tree*>(o)) { //if(dynamic_cast<TreePanel*>(o->parent())) if(dynamic_cast<TreePanel*>(curr_root)) { child_number = ++root_children; } } //UNUSED (why not userid?) //o->set_id(_unique_id());// -1 if unset o->set_level(level); o->set_child_number(child_number); } update_tree(o); curr_root = o; curr_branch = NULL; /* Currently at leaf */ o->set_current(true); //refresh(); //o->activate(); return o; } /****************************** GLUI_TreePanel::format_node() *********/ void UI::Experiments::TreePanel::update_tree(Tree *tree) { if(!tree) return; tree->set_level_color(lred,lgreen,lblue); tree->set_format(format); tree->level_name.clear(); if(format&DISPLAY_HIERARCHY) { if(format&HIERARCHY_LEVEL_ONLY) glui_format_str(tree->level_name,"%d",tree->get_level()); if(format&HIERARCHY_NUMERICDOT) if(dynamic_cast<Tree*>(tree->parent())) glui_format_str(tree->level_name,"%s.%d", ((Tree*)tree->parent())->level_name.c_str(),tree->get_child_number()); else glui_format_str(tree->level_name,"%d",tree->get_child_number()); } /*UNUSED (Tree doesn't render set_color) if(format&ALTERNATE_COLOR) switch(8%tree->get_level()) { case 7: tree->set_color(0.5f,0.5f,0.5f); break; case 6: tree->set_color(0.3f,0.5f,0.5f); break; case 5: tree->set_color(0.5f,0.3f,0.5f); break; case 4: tree->set_color(0.3f,0.3f,0.5f); break; case 3: tree->set_color(0.5f,0.5f,0.3f); break; case 2: tree->set_color(0.3f,0.5f,0.3f); break; case 1: tree->set_color(0.5f,0.3f,0.3f); break; default:tree->set_color(0.3f,0.3f,0.3f); break; } else tree->set_color(red,green,blue); */ if(~format&DISABLE_BAR) { if(format&DISABLE_DEEPEST_BAR) { tree->disable_bar(); if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->enable_bar(); } } else if(format&CONNECT_CHILDREN_ONLY) { tree->disable_bar(); if(tree->prev()&&dynamic_cast<Tree*>(tree->prev())) { ((Tree*)tree->prev())->enable_bar(); } } } else tree->disable_bar(); redraw(); //2019 } /****************************** GLUI_TreePanel::update_all() *********/ void UI::Experiments::TreePanel::update_all() { /*2019: Looks fine to me, except for root_children = 0; printf("UI::Experiments::TreePanel::update_all() doesn't work yet. - JVK\n"); return; root_children = 0; */ Panel *saved_root = curr_root; Tree *saved_branch = curr_branch; go_to_root(); if(curr_branch&&dynamic_cast<Tree*>(curr_branch)) { update_tree(curr_branch); } go_to_next(); while(curr_root&&curr_branch!=first_child()) { if(curr_branch&&dynamic_cast<Tree*>(curr_branch)) { update_tree(curr_branch); } go_to_next(); } curr_root = saved_root; curr_branch = saved_branch; } /****************************** GLUI_TreePanel::expand_all() *********/ void UI::Experiments::TreePanel::expand_all() { Panel *saved_root = curr_root; Tree *saved_branch = curr_branch; go_to_root(); if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->open(); } go_to_next(); while(curr_root&&curr_branch!=first_child()) { if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->open(); } go_to_next(); } curr_root = saved_root; curr_branch = saved_branch; } /****************************** GLUI_TreePanel::collapse_all() *********/ void UI::Experiments::TreePanel::collapse_all() { Panel *saved_root = curr_root; Tree *saved_branch = curr_branch; go_to_root(); go_to_next(); while(curr_root!=NULL&&curr_branch!=first_child()) { if(!curr_branch&&dynamic_cast<Tree*>(curr_root)) { /* we want to close everything leaf-first */ ((Tree*)curr_root)->close(); /* Rather than simply go_to_next(), we need to manually move the curr_root because this node has been moved to the collapsed_node list */ curr_branch = (Tree*)curr_root->next(); curr_root = (Panel*)curr_root->parent(); } else go_to_next(); } curr_root = saved_root; curr_branch = saved_branch; } /****************************** GLUI_TreePanel::db() *********/ /* Deletes the curr_root */ void UI::Experiments::TreePanel::delete_tree(Panel *root) { if(root==this) return; if(root) { curr_root = root; curr_branch = NULL; } if(!curr_root||curr_root==this) { go_to_root(); return; } Tree *temp_branch = (Tree*)curr_root->next(); /* Next branch, if any */ Panel *temp_root = (Panel*)curr_root->parent(); /* new root */ //2019: This was a memory-leak because unlink was zeroing its child pointers //curr_root->_unlink(); delete curr_root; curr_root->_delete(); curr_branch = (Tree*)temp_branch; curr_root = (Panel*)temp_root; if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->open(); if(format&DISABLE_DEEPEST_BAR&&!curr_root->next()) { ((Tree*)curr_root)->disable_bar(); } } //refresh(); } /****************************** GLUI_TreePanel::fb() *********/ /* Goes up one level, resets curr_root and curr_branch to parents*/ void UI::Experiments::TreePanel::go_up_tree(Panel *branch) { if(branch==this) return; if(_curr_branch==this||curr_root==this) { go_to_root(); return; } if(!branch) { branch = curr_root;/* up one parent */ if(!branch) return; } if(dynamic_cast<Tree*>(branch)) { ((Tree*)branch)->set_current(false); } curr_branch = (Tree*)branch->next(); curr_root = (Panel*)branch->parent(); if(!curr_branch&&curr_root->collapsible->first_child()) { curr_branch = (Tree*)curr_root->collapsible->first_child(); } if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->set_current(true); } } /****************************** GLUI_TreePanel::descendBranch() *********/ /* Finds the very last branch of curr_root, resets vars */ void UI::Experiments::TreePanel::go_to_leaf(Panel *root) { go_to_root(root?root:curr_root); if(curr_branch&&_curr_branch!=this) { if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->set_current(false); } go_to_leaf(curr_branch); } } /****************************** GLUI_TreePanel::next() *********/ void UI::Experiments::TreePanel::go_to_next() { if(!curr_root) go_to_root(); if(!curr_branch&&curr_root->collapsible->first_child()) { curr_branch = (Tree*)curr_root->collapsible->first_child(); } if(curr_branch&&_curr_branch!=this) { /* Descend into branch */ if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->set_current(false); } go_to_root(curr_branch); } else if(!curr_branch) { go_up_tree();/* Backup and move on */ } } /****************************** GLUI_TreePanel::resetToRoot() *********/ /* Resets curr_root and curr branch to TreePanel and last_child */ void UI::Experiments::TreePanel::go_to_root(Panel *new_root) { Panel *root = new_root?new_root:this; curr_root = root; if(dynamic_cast<Tree*>(curr_root)) { ((Tree*)curr_root)->set_current(true); } /* since Trees are collapsable, we need to check the collapsed nodes in case the curr_root is collapsed */ Node *c = !root->first_child()?root->collapsible:root; //2019: Why not just use last_child? curr_branch = dynamic_cast<Tree*>(c->last_child()); if(!curr_branch&&c->last_child()) { //OLD CODE: Falling back to old linked-list traversal assert(0); curr_branch = (Tree*)c->first_child(); while(curr_branch&&dynamic_cast<Tree*>(curr_branch)) { curr_branch = (Tree*)curr_branch->next(); } } assert(!curr_branch||dynamic_cast<Tree*>(curr_branch)); } //---. }//<-' #endif //GLUI_BUILD_TREE_CONTROLS
22.887781
78
0.653519
[ "render" ]
ea85acbeaf3f93fabd21bff1883e333cbe758c46
6,273
cc
C++
tests/client_tests/packet_loss_test.cc
gjerecze/eRPC
3516d5d8973a7b12f7141a4d4be3ba3a671c41a4
[ "Apache-2.0" ]
null
null
null
tests/client_tests/packet_loss_test.cc
gjerecze/eRPC
3516d5d8973a7b12f7141a4d4be3ba3a671c41a4
[ "Apache-2.0" ]
null
null
null
tests/client_tests/packet_loss_test.cc
gjerecze/eRPC
3516d5d8973a7b12f7141a4d4be3ba3a671c41a4
[ "Apache-2.0" ]
null
null
null
/** * @file test_packet_loss.cc * @brief Test packet losses. Most of the code here is derived from * `test_large_msg.cc`. */ #include "client_tests.h" void req_handler(ReqHandle *, void *); // Forward declaration /// Request handler for foreground testing auto reg_info_vec_fg = { ReqFuncRegInfo(kTestReqType, req_handler, ReqFuncType::kForeground)}; /// Request handler for background testing auto reg_info_vec_bg = { ReqFuncRegInfo(kTestReqType, req_handler, ReqFuncType::kBackground)}; /// Per-thread application context class AppContext : public BasicAppContext { public: FastRand fastrand; ///< Used for picking large message sizes }; static constexpr double kPktDropProb = 0.3; /// Configuration for controlling the test size_t config_num_iters; ///< The number of iterations size_t config_num_rpcs; ///< Number of Rpcs per iteration size_t config_num_bg_threads; ///< Number of background threads /// The common request handler for all subtests. Copies the request message to /// the response. void req_handler(ReqHandle *req_handle, void *_context) { auto *context = static_cast<AppContext *>(_context); if (config_num_bg_threads > 0) assert(context->rpc->in_background()); const MsgBuffer *req_msgbuf = req_handle->get_req_msgbuf(); size_t resp_size = req_msgbuf->get_data_size(); // MsgBuffer allocation is thread safe req_handle->dyn_resp_msgbuf = context->rpc->alloc_msg_buffer_or_die(resp_size); size_t user_alloc_tot = context->rpc->get_stat_user_alloc_tot(); memcpy(reinterpret_cast<char *>(req_handle->dyn_resp_msgbuf.buf), reinterpret_cast<char *>(req_msgbuf->buf), resp_size); req_handle->prealloc_used = false; test_printf( "Server: Received request of length %zu. " "Rpc memory used = %zu bytes (%.3f MB)\n", resp_size, user_alloc_tot, 1.0 * user_alloc_tot / MB(1)); context->rpc->enqueue_response(req_handle); } /// The common continuation function for all subtests. This checks that the /// request buffer is identical to the response buffer, and increments the /// number of responses in the context. void cont_func(RespHandle *resp_handle, void *_context, size_t tag) { const MsgBuffer *resp_msgbuf = resp_handle->get_resp_msgbuf(); test_printf("Client: Received response of length %zu.\n", resp_msgbuf->get_data_size()); for (size_t i = 0; i < resp_msgbuf->get_data_size(); i++) { ASSERT_EQ(resp_msgbuf->buf[i], static_cast<uint8_t>(tag)); } auto *context = static_cast<AppContext *>(_context); assert(context->is_client); context->num_rpc_resps++; context->rpc->release_response(resp_handle); } /// The generic test function that issues \p config_num_rpcs Rpcs /// on the session, for multiple iterations. /// /// The second \p size_t argument exists only because the client thread function /// template in client_tests.h requires it. void generic_test_func(Nexus *nexus, size_t) { // Create the Rpc and connect the session AppContext context; client_connect_sessions(nexus, context, 1, basic_sm_handler); // 1 session Rpc<CTransport> *rpc = context.rpc; rpc->fault_inject_set_pkt_drop_prob_st(kPktDropProb); // Pre-create MsgBuffers so we can test reuse and resizing std::vector<MsgBuffer> req_msgbufs(config_num_rpcs); std::vector<MsgBuffer> resp_msgbufs(config_num_rpcs); for (size_t req_i = 0; req_i < config_num_rpcs; req_i++) { req_msgbufs[req_i] = rpc->alloc_msg_buffer_or_die(rpc->get_max_msg_size()); resp_msgbufs[req_i] = rpc->alloc_msg_buffer_or_die(rpc->get_max_msg_size()); } // The main request-issuing loop for (size_t iter = 0; iter < config_num_iters; iter++) { context.num_rpc_resps = 0; test_printf("Client: Iteration %zu.\n", iter); size_t iter_req_i = 0; // Request MsgBuffer index in this iteration for (size_t w_i = 0; w_i < config_num_rpcs; w_i++) { assert(iter_req_i < config_num_rpcs); MsgBuffer &cur_req_msgbuf = req_msgbufs[iter_req_i]; // Don't use very large requests because we drop a lot of packets size_t req_pkts = (kSessionCredits * 2) + (context.fastrand.next_u32() % kSessionCredits); size_t req_size = req_pkts * rpc->get_max_data_per_pkt(); rpc->resize_msg_buffer(&cur_req_msgbuf, req_size); memset(cur_req_msgbuf.buf, iter_req_i, req_size); rpc->enqueue_request(context.session_num_arr[0], kTestReqType, &cur_req_msgbuf, &resp_msgbufs[iter_req_i], cont_func, iter_req_i); iter_req_i++; } // The default timeout for tests is 20 seconds. This test takes more time // because of packet drops. for (size_t i = 0; i < 5; i++) { wait_for_rpc_resps_or_timeout(context, config_num_rpcs, nexus->freq_ghz); if (context.num_rpc_resps == config_num_rpcs) break; } assert(context.num_rpc_resps == config_num_rpcs); } // Free the MsgBuffers for (auto &req_msgbuf : req_msgbufs) rpc->free_msg_buffer(req_msgbuf); for (auto &resp_msgbuf : resp_msgbufs) rpc->free_msg_buffer(resp_msgbuf); rpc->destroy_session(context.session_num_arr[0]); rpc->run_event_loop(kTestEventLoopMs); // Free resources delete rpc; client_done = true; } void launch_helper() { auto &reg_info_vec = config_num_bg_threads == 0 ? reg_info_vec_fg : reg_info_vec_bg; launch_server_client_threads(1 /* num_sessions */, config_num_bg_threads, generic_test_func, reg_info_vec, ConnectServers::kFalse, kPktDropProb); } TEST(OneLargeRpc, Foreground) { config_num_iters = 1; config_num_rpcs = 1; config_num_bg_threads = 0; launch_helper(); } TEST(OneLargeRpc, Background) { config_num_iters = 1; config_num_rpcs = 1; config_num_bg_threads = 1; launch_helper(); } TEST(MultiLargeRpcOneSession, Foreground) { config_num_iters = 2; config_num_rpcs = kSessionReqWindow; config_num_bg_threads = 0; launch_helper(); } TEST(MultiLargeRpcOneSession, Background) { config_num_iters = 2; config_num_rpcs = kSessionReqWindow; config_num_bg_threads = 1; launch_helper(); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.092391
80
0.713375
[ "vector" ]
ea8d9ee9e35fb63f385febc4ec177b6c8ad267c1
832
cpp
C++
leet/ac/0053.maximum-subarray.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
leet/ac/0053.maximum-subarray.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
leet/ac/0053.maximum-subarray.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
class Solution { // Time O(n) public: int maxSubArray(vector<int> &nums) { int maxSum = nums[0]; vector<int> dp; dp.push_back(nums[0]); for (int i = 1; i < nums.size(); i++) { dp.push_back(max(nums[i], dp[i - 1] + nums[i])); if (dp[i] > maxSum) maxSum = dp[i]; } return maxSum; } }; class SolutionB { // Time O(n^2) public: int maxSubArray(vector<int> &nums) { int maxSum = nums[0], windowSum = 0; for (int l = 0; l < nums.size(); l++) { windowSum = 0; for (int r = l; r < nums.size(); r++) { windowSum += nums[r]; if (windowSum > maxSum) { maxSum = windowSum; } } } return maxSum; } };
26
60
0.424279
[ "vector" ]
ea8f378b52a11f13bf022c41b2dedc4d39280c49
4,455
cc
C++
console-plugins/map-sparsification-plugin/src/map-sparsification-plugin.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
1,936
2017-11-27T23:11:37.000Z
2022-03-30T14:24:14.000Z
console-plugins/map-sparsification-plugin/src/map-sparsification-plugin.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
353
2017-11-29T18:40:39.000Z
2022-03-30T15:53:46.000Z
console-plugins/map-sparsification-plugin/src/map-sparsification-plugin.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
661
2017-11-28T07:20:08.000Z
2022-03-28T08:06:29.000Z
#include "map-sparsification-plugin/map-sparsification-plugin.h" #include <string> #include <vector> #include <console-common/console.h> #include <map-manager/map-manager.h> #include <map-sparsification-plugin/landmark-sparsification.h> #include <vi-map/unique-id.h> #include <vi-map/vi-map.h> #include <visualization/viwls-graph-plotter.h> #include "map-sparsification-plugin/keyframe-pruning.h" DECLARE_string(map_mission); DECLARE_string(map_mission_list); DEFINE_int32( num_landmarks_to_keep, -1, "Number of landmarks to keep after sparsification."); namespace map_sparsification_plugin { MapSparsificationPlugin::MapSparsificationPlugin( common::Console* console, visualization::ViwlsGraphRvizPlotter* plotter) : common::ConsolePluginBaseWithPlotter(console, plotter) { addCommand( {"keyframe_heuristic", "kfh"}, [this]() -> int { // Select map. std::string selected_map_key; if (!getSelectedMapKeyIfSet(&selected_map_key)) { return common::kStupidUserError; } vi_map::VIMapManager map_manager; vi_map::VIMapManager::MapWriteAccess map = map_manager.getMapWriteAccess(selected_map_key); // Select mission. vi_map::MissionIdList missions_to_keyframe; if (!FLAGS_map_mission.empty()) { if (!FLAGS_map_mission_list.empty()) { LOG(ERROR) << "Please provide only one of --map_mission and " << "--map_mission_list."; return common::kStupidUserError; } vi_map::MissionId mission_id; if (!map->hexStringToMissionIdIfValid( FLAGS_map_mission, &mission_id)) { LOG(ERROR) << "The given mission id \"" << FLAGS_map_mission << "\" is not valid."; return common::kStupidUserError; } missions_to_keyframe.emplace_back(mission_id); } else if (!FLAGS_map_mission_list.empty()) { if (!vi_map::csvIdStringToIdList( FLAGS_map_mission_list, &missions_to_keyframe)) { LOG(ERROR) << "The provided CSV mission id list is not valid!"; return common::kStupidUserError; } } else { map->getAllMissionIds(&missions_to_keyframe); } if (missions_to_keyframe.empty()) { LOG(ERROR) << "No missions found to keyframe."; return common::kStupidUserError; } using map_sparsification::KeyframingHeuristicsOptions; KeyframingHeuristicsOptions options = KeyframingHeuristicsOptions::initializeFromGFlags(); for (const vi_map::MissionId& mission_id : missions_to_keyframe) { VLOG(1) << "Keyframing mission " << mission_id << '.'; if (keyframeMapBasedOnHeuristics( options, mission_id, plotter_, map.get()) != common::kSuccess) { LOG(ERROR) << "Keyframing of mission " << mission_id << " failed."; return common::kUnknownError; } } return common::kSuccess; }, "Keyframe map based on heuristics. Use the flag --map_mission or " "--map_mission_list to specify which missions to keyframe. If neither " "flag is given, all missions of the selected map will be keyframed.", common::Processing::Sync); addCommand( {"landmark_sparsify", "lsparsify"}, [this]() -> int { // Select map. std::string selected_map_key; if (!getSelectedMapKeyIfSet(&selected_map_key)) { return common::kStupidUserError; } vi_map::VIMapManager map_manager; vi_map::VIMapManager::MapWriteAccess map = map_manager.getMapWriteAccess(selected_map_key); if (FLAGS_num_landmarks_to_keep < 0) { LOG(WARNING) << "Specify the number of landmarks to be kept using " << "the --num_landmarks_to_keep flag."; return common::kStupidUserError; } sparsifyMapLandmarks(FLAGS_num_landmarks_to_keep, map.get()); return common::kSuccess; }, "Sparsify landmarks using summarization techniques. Use the flag " "--num_of_landmarks_to_keep to set the number of desired landmarks.", common::Processing::Sync); } } // namespace map_sparsification_plugin MAPLAB_CREATE_CONSOLE_PLUGIN_WITH_PLOTTER( map_sparsification_plugin::MapSparsificationPlugin);
37.436975
79
0.6422
[ "vector" ]
ea908590a4d5c1f3080daa4bbc66a251140275f2
18,079
cpp
C++
apps/esmtool/esmtool.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/esmtool/esmtool.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/esmtool/esmtool.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <deque> #include <list> #include <map> #include <set> #include <boost/program_options.hpp> #include <components/esm/esmreader.hpp> #include <components/esm/esmwriter.hpp> #include <components/esm/records.hpp> #include "record.hpp" #define ESMTOOL_VERSION 1.2 // Create a local alias for brevity namespace bpo = boost::program_options; struct ESMData { std::string author; std::string description; int version; std::vector<ESM::Header::MasterData> masters; std::deque<EsmTool::RecordBase *> mRecords; std::map<ESM::Cell *, std::deque<ESM::CellRef> > mCellRefs; std::map<int, int> mRecordStats; static const std::set<int> sLabeledRec; }; static const int sLabeledRecIds[] = { ESM::REC_GLOB, ESM::REC_CLAS, ESM::REC_FACT, ESM::REC_RACE, ESM::REC_SOUN, ESM::REC_REGN, ESM::REC_BSGN, ESM::REC_LTEX, ESM::REC_STAT, ESM::REC_DOOR, ESM::REC_MISC, ESM::REC_WEAP, ESM::REC_CONT, ESM::REC_SPEL, ESM::REC_CREA, ESM::REC_BODY, ESM::REC_LIGH, ESM::REC_ENCH, ESM::REC_NPC_, ESM::REC_ARMO, ESM::REC_CLOT, ESM::REC_REPA, ESM::REC_ACTI, ESM::REC_APPA, ESM::REC_LOCK, ESM::REC_PROB, ESM::REC_INGR, ESM::REC_BOOK, ESM::REC_ALCH, ESM::REC_LEVI, ESM::REC_LEVC, ESM::REC_SNDG, ESM::REC_CELL, ESM::REC_DIAL }; const std::set<int> ESMData::sLabeledRec = std::set<int>(sLabeledRecIds, sLabeledRecIds + 34); // Based on the legacy struct struct Arguments { unsigned int raw_given; unsigned int quiet_given; unsigned int loadcells_given; bool plain_given; std::string mode; std::string encoding; std::string filename; std::string outname; std::vector<std::string> types; ESMData data; ESM::ESMReader reader; ESM::ESMWriter writer; }; bool parseOptions (int argc, char** argv, Arguments &info) { bpo::options_description desc("Inspect and extract from Morrowind ES files (ESM, ESP, ESS)\nSyntax: esmtool [options] mode infile [outfile]\nAllowed modes:\n dump\t Dumps all readable data from the input file.\n clone\t Clones the input file to the output file.\n comp\t Compares the given files.\n\nAllowed options"); desc.add_options() ("help,h", "print help message.") ("version,v", "print version information and quit.") ("raw,r", "Show an unformatted list of all records and subrecords.") // The intention is that this option would interact better // with other modes including clone, dump, and raw. ("type,t", bpo::value< std::vector<std::string> >(), "Show only records of this type (four character record code). May " "be specified multiple times. Only affects dump mode.") ("plain,p", "Print contents of dialogs, books and scripts. " "(skipped by default)" "Only affects dump mode.") ("quiet,q", "Supress all record information. Useful for speed tests.") ("loadcells,C", "Browse through contents of all cells.") ( "encoding,e", bpo::value<std::string>(&(info.encoding))-> default_value("win1252"), "Character encoding used in ESMTool:\n" "\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, Croatian, Serbian (Latin script), Romanian and Albanian languages\n" "\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n" "\n\twin1252 - Western European (Latin) alphabet, used by default") ; std::string finalText = "\nIf no option is given, the default action is to parse all records in the archive\nand display diagnostic information."; // input-file is hidden and used as a positional argument bpo::options_description hidden("Hidden Options"); hidden.add_options() ( "mode,m", bpo::value<std::string>(), "esmtool mode") ( "input-file,i", bpo::value< std::vector<std::string> >(), "input file") ; bpo::positional_options_description p; p.add("mode", 1).add("input-file", 2); // there might be a better way to do this bpo::options_description all; all.add(desc).add(hidden); bpo::variables_map variables; try { bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv) .options(all).positional(p).run(); bpo::store(valid_opts, variables); } catch(boost::program_options::unknown_option & x) { std::cerr << "ERROR: " << x.what() << std::endl; return false; } catch(boost::program_options::invalid_command_line_syntax & x) { std::cerr << "ERROR: " << x.what() << std::endl; return false; } bpo::notify(variables); if (variables.count ("help")) { std::cout << desc << finalText << std::endl; return false; } if (variables.count ("version")) { std::cout << "ESMTool version " << ESMTOOL_VERSION << std::endl; return false; } if (!variables.count("mode")) { std::cout << "No mode specified!" << std::endl << std::endl << desc << finalText << std::endl; return false; } if (variables.count("type") > 0) info.types = variables["type"].as< std::vector<std::string> >(); info.mode = variables["mode"].as<std::string>(); if (!(info.mode == "dump" || info.mode == "clone" || info.mode == "comp")) { std::cout << std::endl << "ERROR: invalid mode \"" << info.mode << "\"" << std::endl << std::endl << desc << finalText << std::endl; return false; } if ( !variables.count("input-file") ) { std::cout << "\nERROR: missing ES file\n\n"; std::cout << desc << finalText << std::endl; return false; } // handling gracefully the user adding multiple files /* if (variables["input-file"].as< std::vector<std::string> >().size() > 1) { std::cout << "\nERROR: more than one ES file specified\n\n"; std::cout << desc << finalText << std::endl; return false; }*/ info.filename = variables["input-file"].as< std::vector<std::string> >()[0]; if (variables["input-file"].as< std::vector<std::string> >().size() > 1) info.outname = variables["input-file"].as< std::vector<std::string> >()[1]; info.raw_given = variables.count ("raw"); info.quiet_given = variables.count ("quiet"); info.loadcells_given = variables.count ("loadcells"); info.plain_given = (variables.count("plain") > 0); // Font encoding settings info.encoding = variables["encoding"].as<std::string>(); if(info.encoding != "win1250" && info.encoding != "win1251" && info.encoding != "win1252") { std::cout << info.encoding << " is not a valid encoding option." << std::endl; info.encoding = "win1252"; } std::cout << ToUTF8::encodingUsingMessage(info.encoding) << std::endl; return true; } void printRaw(ESM::ESMReader &esm); void loadCell(ESM::Cell &cell, ESM::ESMReader &esm, Arguments& info); int load(Arguments& info); int clone(Arguments& info); int comp(Arguments& info); int main(int argc, char**argv) { Arguments info; if(!parseOptions (argc, argv, info)) return 1; if (info.mode == "dump") return load(info); else if (info.mode == "clone") return clone(info); else if (info.mode == "comp") return comp(info); else { std::cout << "Invalid or no mode specified, dying horribly. Have a nice day." << std::endl; return 1; } return 0; } void loadCell(ESM::Cell &cell, ESM::ESMReader &esm, Arguments& info) { bool quiet = (info.quiet_given || info.mode == "clone"); bool save = (info.mode == "clone"); // Skip back to the beginning of the reference list // FIXME: Changes to the references backend required to support multiple plugins have // almost certainly broken this following line. I'll leave it as is for now, so that // the compiler does not complain. cell.restore(esm, 0); // Loop through all the references ESM::CellRef ref; if(!quiet) std::cout << " References:\n"; bool deleted = false; while(cell.getNextRef(esm, ref, deleted)) { if (save) { info.data.mCellRefs[&cell].push_back(ref); } if(quiet) continue; std::cout << " Refnum: " << ref.mRefNum.mIndex << std::endl; std::cout << " ID: '" << ref.mRefID << "'\n"; std::cout << " Owner: '" << ref.mOwner << "'\n"; std::cout << " Global: '" << ref.mGlobalVariable << "'" << std::endl; std::cout << " Faction: '" << ref.mFaction << "'" << std::endl; std::cout << " Faction rank: '" << ref.mFactionRank << "'" << std::endl; std::cout << " Enchantment charge: '" << ref.mEnchantmentCharge << "'\n"; std::cout << " Uses/health: '" << ref.mCharge << "'\n"; std::cout << " Gold value: '" << ref.mGoldValue << "'\n"; std::cout << " Blocked: '" << static_cast<int>(ref.mReferenceBlocked) << "'" << std::endl; std::cout << " Deleted: " << deleted << std::endl; } } void printRaw(ESM::ESMReader &esm) { while(esm.hasMoreRecs()) { ESM::NAME n = esm.getRecName(); std::cout << "Record: " << n.toString() << std::endl; esm.getRecHeader(); while(esm.hasMoreSubs()) { uint64_t offs = esm.getOffset(); esm.getSubName(); esm.skipHSub(); n = esm.retSubName(); std::cout << " " << n.toString() << " - " << esm.getSubSize() << " bytes @ 0x" << std::hex << offs << "\n"; } } } int load(Arguments& info) { ESM::ESMReader& esm = info.reader; ToUTF8::Utf8Encoder encoder (ToUTF8::calculateEncoding(info.encoding)); esm.setEncoder(&encoder); std::string filename = info.filename; std::cout << "Loading file: " << filename << std::endl; std::list<int> skipped; try { if(info.raw_given && info.mode == "dump") { std::cout << "RAW file listing:\n"; esm.openRaw(filename); printRaw(esm); return 0; } bool quiet = (info.quiet_given || info.mode == "clone"); bool loadCells = (info.loadcells_given || info.mode == "clone"); bool save = (info.mode == "clone"); esm.open(filename); info.data.author = esm.getAuthor(); info.data.description = esm.getDesc(); info.data.masters = esm.getGameFiles(); if (!quiet) { std::cout << "Author: " << esm.getAuthor() << std::endl << "Description: " << esm.getDesc() << std::endl << "File format version: " << esm.getFVer() << std::endl; std::vector<ESM::Header::MasterData> m = esm.getGameFiles(); if (!m.empty()) { std::cout << "Masters:" << std::endl; for(unsigned int i=0;i<m.size();i++) std::cout << " " << m[i].name << ", " << m[i].size << " bytes" << std::endl; } } // Loop through all records while(esm.hasMoreRecs()) { ESM::NAME n = esm.getRecName(); uint32_t flags; esm.getRecHeader(flags); // Is the user interested in this record type? bool interested = true; if (!info.types.empty()) { std::vector<std::string>::iterator match; match = std::find(info.types.begin(), info.types.end(), n.toString()); if (match == info.types.end()) interested = false; } std::string id = esm.getHNOString("NAME"); if (id.empty()) id = esm.getHNOString("INAM"); if(!quiet && interested) std::cout << "\nRecord: " << n.toString() << " '" << id << "'\n"; EsmTool::RecordBase *record = EsmTool::RecordBase::create(n); if (record == 0) { if (std::find(skipped.begin(), skipped.end(), n.val) == skipped.end()) { std::cout << "Skipping " << n.toString() << " records." << std::endl; skipped.push_back(n.val); } esm.skipRecord(); if (quiet) break; std::cout << " Skipping\n"; } else { if (record->getType().val == ESM::REC_GMST) { // preset id for GameSetting record record->cast<ESM::GameSetting>()->get().mId = id; } record->setId(id); record->setFlags((int) flags); record->setPrintPlain(info.plain_given); record->load(esm); if (!quiet && interested) record->print(); if (record->getType().val == ESM::REC_CELL && loadCells) { loadCell(record->cast<ESM::Cell>()->get(), esm, info); } if (save) { info.data.mRecords.push_back(record); } else { delete record; } ++info.data.mRecordStats[n.val]; } } } catch(std::exception &e) { std::cout << "\nERROR:\n\n " << e.what() << std::endl; typedef std::deque<EsmTool::RecordBase *> RecStore; RecStore &store = info.data.mRecords; for (RecStore::iterator it = store.begin(); it != store.end(); ++it) { delete *it; } store.clear(); return 1; } return 0; } #include <iomanip> int clone(Arguments& info) { if (info.outname.empty()) { std::cout << "You need to specify an output name" << std::endl; return 1; } if (load(info) != 0) { std::cout << "Failed to load, aborting." << std::endl; return 1; } int recordCount = info.data.mRecords.size(); int digitCount = 1; // For a nicer output if (recordCount > 9) ++digitCount; if (recordCount > 99) ++digitCount; if (recordCount > 999) ++digitCount; if (recordCount > 9999) ++digitCount; if (recordCount > 99999) ++digitCount; if (recordCount > 999999) ++digitCount; std::cout << "Loaded " << recordCount << " records:" << std::endl << std::endl; ESM::NAME name; int i = 0; typedef std::map<int, int> Stats; Stats &stats = info.data.mRecordStats; for (Stats::iterator it = stats.begin(); it != stats.end(); ++it) { name.val = it->first; float amount = it->second; std::cout << std::setw(digitCount) << amount << " " << name.toString() << " "; if (++i % 3 == 0) std::cout << std::endl; } if (i % 3 != 0) std::cout << std::endl; std::cout << std::endl << "Saving records to: " << info.outname << "..." << std::endl; ESM::ESMWriter& esm = info.writer; ToUTF8::Utf8Encoder encoder (ToUTF8::calculateEncoding(info.encoding)); esm.setEncoder(&encoder); esm.setAuthor(info.data.author); esm.setDescription(info.data.description); esm.setVersion(info.data.version); esm.setRecordCount (recordCount); for (std::vector<ESM::Header::MasterData>::iterator it = info.data.masters.begin(); it != info.data.masters.end(); ++it) esm.addMaster(it->name, it->size); std::fstream save(info.outname.c_str(), std::fstream::out | std::fstream::binary); esm.save(save); int saved = 0; typedef std::deque<EsmTool::RecordBase *> Records; Records &records = info.data.mRecords; for (Records::iterator it = records.begin(); it != records.end() && i > 0; ++it) { EsmTool::RecordBase *record = *it; name.val = record->getType().val; esm.startRecord(name.toString(), record->getFlags()); // TODO wrap this with std::set if (ESMData::sLabeledRec.count(name.val) > 0) { esm.writeHNCString("NAME", record->getId()); } else { esm.writeHNOString("NAME", record->getId()); } record->save(esm); if (name.val == ESM::REC_CELL) { ESM::Cell *ptr = &record->cast<ESM::Cell>()->get(); if (!info.data.mCellRefs[ptr].empty()) { typedef std::deque<ESM::CellRef> RefList; RefList &refs = info.data.mCellRefs[ptr]; for (RefList::iterator it = refs.begin(); it != refs.end(); ++it) { it->save(esm); } } } esm.endRecord(name.toString()); saved++; int perc = (saved / (float)recordCount)*100; if (perc % 10 == 0) { std::cerr << "\r" << perc << "%"; } } std::cout << "\rDone!" << std::endl; esm.close(); save.close(); return 0; } int comp(Arguments& info) { if (info.filename.empty() || info.outname.empty()) { std::cout << "You need to specify two input files" << std::endl; return 1; } Arguments fileOne; Arguments fileTwo; fileOne.raw_given = 0; fileTwo.raw_given = 0; fileOne.mode = "clone"; fileTwo.mode = "clone"; fileOne.encoding = info.encoding; fileTwo.encoding = info.encoding; fileOne.filename = info.filename; fileTwo.filename = info.outname; if (load(fileOne) != 0) { std::cout << "Failed to load " << info.filename << ", aborting comparison." << std::endl; return 1; } if (load(fileTwo) != 0) { std::cout << "Failed to load " << info.outname << ", aborting comparison." << std::endl; return 1; } if (fileOne.data.mRecords.size() != fileTwo.data.mRecords.size()) { std::cout << "Not equal, different amount of records." << std::endl; return 1; } return 0; }
31.99823
325
0.554345
[ "vector" ]
ea95798ff8b29d2a635f70e0f1c8f2928eff37a8
1,372
hpp
C++
include/tsk/thread_pool.hpp
edouarda/task-manager
abec3f0dfdbd97204f7f68d03e3ca136346c6304
[ "BSD-3-Clause" ]
null
null
null
include/tsk/thread_pool.hpp
edouarda/task-manager
abec3f0dfdbd97204f7f68d03e3ca136346c6304
[ "BSD-3-Clause" ]
null
null
null
include/tsk/thread_pool.hpp
edouarda/task-manager
abec3f0dfdbd97204f7f68d03e3ca136346c6304
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <thread> #include <tsk/task.hpp> namespace tsk { template <typename Queue> class thread_pool { public: explicit thread_pool(Queue & q, size_t s) : _queue{q} , _size{s} {} thread_pool(const thread_pool &) = delete; public: void start() { if (_run.exchange(true)) return; for (size_t i = 0; i < _size; ++i) { _threads.emplace_back(std::bind(&thread_pool<Queue>::runner, this)); } } void stop() { if (!_run.exchange(false)) return; for (auto & t : _threads) { t.join(); } _threads.clear(); } private: void runner() { while (_run) { tsk::task_ptr to_run = nullptr; try { while (_run && !_queue.pop(to_run)) { std::this_thread::sleep_for(std::chrono::microseconds{100}); } if (to_run) { to_run->run(); delete to_run; } } catch (...) { delete to_run; } } } private: Queue & _queue; size_t _size; std::atomic<bool> _run{false}; std::vector<std::thread> _threads; }; } // namespace tsk
17.15
80
0.443878
[ "vector" ]
eaa27c2ef6319a05297038a6b8ff46c33e855ca9
2,388
cpp
C++
src/caffe/layers/cross_entropy_loss_layer.cpp
chenbinghui1/Hybrid-Attention-based-Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
44
2019-04-03T16:51:30.000Z
2022-02-02T15:19:48.000Z
src/caffe/layers/cross_entropy_loss_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
1
2021-06-01T10:00:00.000Z
2021-06-23T01:46:43.000Z
src/caffe/layers/cross_entropy_loss_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
8
2019-05-16T05:44:41.000Z
2020-08-19T17:16:28.000Z
#include <algorithm> #include <cfloat> #include <vector> #include "caffe/layers/cross_entropy_loss_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void CrossEntropyLossLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::LayerSetUp(bottom, top); } template <typename Dtype> void CrossEntropyLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { vector<int> loss_shape(0); // Loss layers output a scalar; 0 axes. top[0]->Reshape(loss_shape); } template <typename Dtype> void CrossEntropyLossLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // The forward pass computes the softmax prob values. const Dtype* bottom_data = bottom[0]->cpu_data(); const Dtype* label = bottom[1]->cpu_data(); Dtype loss = 0.0; for(int i = 0; i < bottom[0]->num(); i++){ const int label_value = static_cast<int>(label[i]); DCHECK_GE(label_value, 0); loss -= log(std::max(bottom_data[i * bottom[0]->channels() + label_value], Dtype(FLT_MIN))); } top[0]->mutable_cpu_data()[0] = loss / bottom[0]->num(); } template <typename Dtype> void CrossEntropyLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } if (propagate_down[0]) { caffe_set(bottom[0]->count(), Dtype(0), bottom[0]->mutable_cpu_diff()); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); for(int i = 0; i < bottom[0]->num(); i++){ const int label_value = static_cast<int>(label[i]); DCHECK_GE(label_value, 0); bottom_diff[i * bottom[0]->channels() + label_value]-= Dtype(1)/std::max(bottom[0]->cpu_data()[i * bottom[0]->channels() + label_value],Dtype(FLT_MIN)); } caffe_scal(bottom[0]->count(), Dtype(1.0)/Dtype(bottom[0]->num()) * top[0]->cpu_diff()[0], bottom_diff); } } #ifdef CPU_ONLY STUB_GPU(CrossEntropyLossLayer); #endif INSTANTIATE_CLASS(CrossEntropyLossLayer); REGISTER_LAYER_CLASS(CrossEntropyLoss); } // namespace caffe
34.114286
160
0.667923
[ "vector" ]
eaa97709e55b9c5346d8cade7fbaf537f3a4742e
14,382
cpp
C++
src/merge-name.cpp
shirok1/font-merger
9dc6a2b98f58e751940e33700e0ad39189a7ccb8
[ "MIT" ]
227
2019-07-30T15:36:57.000Z
2022-03-27T00:47:40.000Z
src/merge-name.cpp
shirok1/font-merger
9dc6a2b98f58e751940e33700e0ad39189a7ccb8
[ "MIT" ]
3
2020-03-23T13:53:21.000Z
2021-12-25T19:39:19.000Z
src/merge-name.cpp
shirok1/font-merger
9dc6a2b98f58e751940e33700e0ad39189a7ccb8
[ "MIT" ]
21
2019-09-10T11:59:01.000Z
2022-03-22T06:37:26.000Z
#include <algorithm> #include <iterator> #include <map> #include <optional> #include <sstream> #include <string> #include <tuple> #include <utility> #include "merge-name.h" using namespace std; namespace LicenseString { const char *Apache = "This Font Software is licensed under the Apache License, Version 2.0. " "This Font Software is distributed on an \"AS IS\" BASIS, WITHOUT " "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the " "Apache License for the specific language, permissions and limitations " "governing your use of this Font Software."; const char *GPL = "This Font Software is licensed under the GNU General Public License, " "either version 3 of the License, or (at your option) any later version. " "This font 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."; const char *LGPL = "This Font Software is licensed under the GNU Lesser General Public " "License, either version 3 of the License, or (at your option) any later " "version. This font 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."; const char *OFL = "This Font Software is licensed under the SIL Open Font License, Version " "1.1. This Font Software is distributed on an \"AS IS\" BASIS, WITHOUT " "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the " "SIL Open Font License for the specific language, permissions and " "limitations governing your use of this Font Software."; } // namespace LicenseString namespace LicenseUrlString { const char *Apache = "https://www.apache.org/licenses/LICENSE-2.0"; const char *GPL = "https://www.gnu.org/copyleft/gpl.html"; const char *LGPL = "https://www.gnu.org/copyleft/lesser.html"; const char *OFL = "https://scripts.sil.org/OFL"; } // namespace LicenseUrlString using json = nlohmann::json; struct License { // share alike bool GPL; bool LGPL; bool OFL; // bool UFL; // non-share-alike bool Apache; // bool BSD; // bool MIT; operator bool() { return GPL || LGPL || OFL || Apache; } }; enum class Platform { Unicode = 0, Macintosh = 1, Windows = 3, }; enum class Encoding { UnicodeBMP = 1, Unicode = 10, MacRoman = 1, }; enum class Language { en_US = 0x0409, // English (United States) en_GB = 0x0809, // English (United Kingdom) zh_CN = 0x0804, // Chinese (People’s Republic of China) zh_HK = 0x0C04, // Chinese (Hong Kong S.A.R.) zh_MO = 0x1404, // Chinese (Macao S.A.R.) zh_SG = 0x1004, // Chinese (Singapore) zh_TW = 0x0404, // Chinese (Taiwan) MacEnglish = 0, }; map<Language, Language> LanguageFallback{ {Language::en_GB, Language::en_US}, {Language::zh_CN, Language::en_US}, {Language::zh_SG, Language::zh_CN}, {Language::zh_TW, Language::en_US}, {Language::zh_HK, Language::zh_TW}, {Language::zh_MO, Language::zh_TW}, }; enum class NameId { Copyright = 0, Family = 1, Subfamily = 2, UniqueIdentifier = 3, FullName = 4, Version = 5, PostScript = 6, Trademark = 7, Manufacturer = 8, Designer = 9, Description = 10, VendorUrl = 11, DesignerUrl = 12, LicenseDescription = 13, LicenseUrl = 14, PreferredFamily = 16, PreferredSubfamily = 17, }; constexpr char NormalizeToPostScriptName(char ch) { switch (ch) { case ' ': return '-'; case '%': case '(': case ')': case '/': case '<': case '>': case '[': case ']': case '{': case '}': return '_'; case '!': case '"': case '#': case '$': case '&': case '\'': case '*': case '+': case ',': case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '=': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '|': case '~': return ch; default: return '_'; } } string GeneratePostScriptName(string name, string style) { transform(name.begin(), name.end(), name.begin(), NormalizeToPostScriptName); transform(style.begin(), style.end(), style.begin(), NormalizeToPostScriptName); if (style.length() > 31) style = style.substr(0, 31); if (name.length() > 63 - 1 - style.length()) name = name.substr(0, 63 - 1 - style.length()); return name + "-" + style; } string GetNameEntry(const json &name, NameId nameid, Platform platform = Platform::Windows, Encoding encoding = Encoding::UnicodeBMP, Language language = Language::en_US, bool enableLanguageFallback = false) { for (const auto &entry : name) if (nameid == entry["nameID"] && platform == entry["platformID"] && encoding == entry["encodingID"] && language == entry["languageID"]) return entry["nameString"]; if (enableLanguageFallback) { auto pFallback = LanguageFallback.find(language); if (pFallback != LanguageFallback.end()) return GetNameEntry(name, nameid, platform, encoding, pFallback->second, true); } return {}; } License GuessLicense(const string &license, const string &url, const string &copyright) { #define FindURL(str) (url.find(str) != string::npos) #define FindLiteral(str) \ (license.find(str) != string::npos || copyright.find(str) != string::npos) License result{}; if (FindURL("www.apache.org/licenses") || FindLiteral("Apache License")) result.Apache = true; /* LGPL will be treated as GPL, but that's okay. * * We cannot add a condition "not find a specific string" to avoid it, * because a font can be dual licensed. * * `FindLiteral("GPL")` is a trick for 文泉驿正黑 (WenQuanYi Zen Hei). */ if (FindURL("www.gnu.org/copyleft/gpl") || FindLiteral("General Public License") || FindLiteral("GPL")) result.GPL = true; if (FindURL("www.gnu.org/copyleft/lesser") || FindLiteral("Lesser General Public License")) result.LGPL = true; if (FindURL("scripts.sil.org/OFL") || FindLiteral("Open Font License")) result.OFL = true; return result; #undef FindLiteral #undef FindURL } pair<string, string> MergeLicense(const vector<json> &nametables) { vector<License> licenses; vector<string> licenseStrings; for (const json &name : nametables) { const string &license = GetNameEntry(name, NameId::LicenseDescription); const string &url = GetNameEntry(name, NameId::LicenseUrl); const string &copyright = GetNameEntry(name, NameId::Copyright); licenses.push_back(GuessLicense(license, url, copyright)); string fullname = GetNameEntry(name, NameId::FullName); if (!fullname.length()) fullname = GetNameEntry(name, NameId::Family) + " " + GetNameEntry(name, NameId::Subfamily); licenseStrings.push_back(fullname + ": " + license); } bool Apache = false; bool GPL = false; bool LGPL = false; bool OFL = false; for (License l : licenses) { // one of them are not licensed under Apache, GPL, LGPL or OFL. if (!l) goto cannot_decide; Apache = Apache || l.Apache; GPL = GPL || l.GPL; LGPL = LGPL || l.LGPL; OFL = OFL || l.OFL; // printf("Apache: %d, GPL: %d, LGPL: %d, OFL: %d\n", l.Apache, l.GPL, // l.LGPL, l.OFL); } // try promoting to Apache { bool noShareAlike = true; for (License l : licenses) { if ((l.OFL || l.GPL) && !l.Apache) { noShareAlike = false; break; } } if (noShareAlike) return {LicenseString::Apache, LicenseUrlString::Apache}; } // try promoting to OFL if (OFL) { bool noGPL = true; for (License l : licenses) { if (l.GPL && !l.OFL) { noGPL = false; break; } } if (noGPL) return {LicenseString::OFL, LicenseUrlString::OFL}; } // try promoting to (L)GPL if (GPL) { bool noOFL = true; bool canBeLGPL = true; for (License l : licenses) { if (l.OFL && !l.GPL) noOFL = false; if (l.GPL && !l.LGPL) canBeLGPL = false; } if (noOFL) { if (canBeLGPL) return {LicenseString::LGPL, LicenseUrlString::LGPL}; else return {LicenseString::GPL, LicenseUrlString::GPL}; } } cannot_decide: string license = "WFM cannot decide the license for merged font. " "Please check again before distribute."; for (const auto &l : licenseStrings) license += "\n" + l; return {license, {}}; } pair<string, string> GetLagacyFamilyAndStyle(string family, string style) { // 4 standard styles if (style == "Regular" || style == "Italic" || style == "Bold" || style == "Bold Italic") return {family, style}; size_t pos; if ((pos = style.find(" Bold Italic")) != style.npos || (pos = style.find(" Italic")) != style.npos || (pos = style.find(" Bold")) != style.npos) { return {family + " " + style.substr(0, pos), style.substr(pos + 1)}; } return {family + " " + style, "Regular"}; } tuple<string, string, string> MergeName(const vector<json> &nametables) { const json &first = nametables[0]; string style = GetNameEntry(first, NameId::PreferredSubfamily); if (!style.length()) style = GetNameEntry(first, NameId::Subfamily); if (!style.length()) style = "Regular"; string family = GetNameEntry(first, NameId::PreferredFamily); if (!family.length()) family = GetNameEntry(first, NameId::Family); string psname = family; for (size_t i = 1; i < nametables.size(); i++) { const json &second = nametables[i]; string family2 = GetNameEntry(second, NameId::PreferredFamily); if (!family2.length()) family2 = GetNameEntry(second, NameId::Family); family += " + " + family2; psname += "+" + family2; } psname = GeneratePostScriptName(psname, style); return {family, style, psname}; } string MergeCopyright(const vector<json> &nametables) { string result = GetNameEntry(nametables[0], NameId::Copyright); for (size_t i = 1; i < nametables.size(); i++) result += "\n" + GetNameEntry(nametables[i], NameId::Copyright); return result; } void RemoveRedundantTable(vector<json> &nametables) { vector<string> names; size_t nowarlcg = -1; for (size_t i = 0; i < nametables.size();) { const json &table = nametables[i]; string family = GetNameEntry(table, NameId::PreferredFamily); if (!family.length()) family = GetNameEntry(table, NameId::Family); if (find(names.begin(), names.end(), family) != names.end()) { nametables.erase(nametables.begin() + i); } else { names.push_back(family); if (family == "Nowar Sans LCG") nowarlcg = i; i++; } } // Nowar Sans LCG + Nowar Sans CJK if (nowarlcg != size_t(-1)) { bool hascjk = false; for (size_t i = 0; i < nametables.size(); i++) { json &table = nametables[i]; string family = GetNameEntry(table, NameId::PreferredFamily); if (family.length() >= 14 && family.substr(0, 14) == "Nowar Sans CJK") { hascjk = true; for (auto &entry : table) switch (NameId(entry["nameID"])) { case NameId::Family: case NameId::PreferredFamily: entry["nameString"] = string(entry["nameString"]).replace(10, 4, ""); break; default: break; } } } if (hascjk) nametables.erase(nametables.begin() + nowarlcg); } } json MergeNameTable(vector<json> &nametables) { RemoveRedundantTable(nametables); auto [family, style, psname] = MergeName(nametables); auto [legacyFamily, legacyStyle] = GetLagacyFamilyAndStyle(family, style); auto [license, licenseUrl] = MergeLicense(nametables); auto copyright = MergeCopyright(nametables); auto version = GetNameEntry(nametables[0], NameId::Version); json result = nametables[0]; for (auto &entry : result) { switch (NameId(entry["nameID"])) { case NameId::Copyright: entry["nameString"] = copyright; break; case NameId::Family: entry["nameString"] = legacyFamily; break; case NameId::Subfamily: entry["nameString"] = legacyStyle; break; case NameId::UniqueIdentifier: entry["nameString"] = family + " " + style + " " + version; break; case NameId::FullName: entry["nameString"] = family + " " + style; break; case NameId::PostScript: entry["nameString"] = psname; break; case NameId::LicenseDescription: entry["nameString"] = license; break; case NameId::LicenseUrl: entry["nameString"] = licenseUrl; break; case NameId::PreferredFamily: entry["nameString"] = family; break; case NameId::PreferredSubfamily: entry["nameString"] = style; break; default: break; } } if (GetNameEntry(result, NameId::LicenseDescription) == "") result.push_back({ {"platformID", Platform::Windows}, {"encodingID", Encoding::Unicode}, {"languageID", Language::en_US}, {"nameID", NameId::LicenseDescription}, {"nameString", license}, }); if (GetNameEntry(result, NameId::Copyright) == "") result.push_back({ {"platformID", Platform::Windows}, {"encodingID", Encoding::Unicode}, {"languageID", Language::en_US}, {"nameID", NameId::Copyright}, {"nameString", copyright}, }); return result; }
26.983114
81
0.615909
[ "vector", "transform" ]
eaae68c5001724aa400f21c3868ef85205f31b82
20,879
cxx
C++
vendor/fltk-sys/cfltk/fltk/src/drivers/Android/Fl_Android_Graphics_Clipping.cxx
dareludum/icfpc2020
a4fae7389da30a8f1d151df00752290ec2472b84
[ "MIT" ]
null
null
null
vendor/fltk-sys/cfltk/fltk/src/drivers/Android/Fl_Android_Graphics_Clipping.cxx
dareludum/icfpc2020
a4fae7389da30a8f1d151df00752290ec2472b84
[ "MIT" ]
null
null
null
vendor/fltk-sys/cfltk/fltk/src/drivers/Android/Fl_Android_Graphics_Clipping.cxx
dareludum/icfpc2020
a4fae7389da30a8f1d151df00752290ec2472b84
[ "MIT" ]
null
null
null
// // Clipping region routines for the Fast Light Tool Kit (FLTK). // // Copyright 2018 by Bill Spitzak and others. // // This library is free software. Distribution and use rights are outlined in // the file "COPYING" which should have been included with this file. If this // file is missing or damaged, see the license at: // // https://www.fltk.org/COPYING.php // // Please see the following page on how to report bugs and issues: // // https://www.fltk.org/bugs.php // #include "../../config_lib.h" #include "Fl_Android_Graphics_Driver.H" #include "Fl_Android_Application.H" #include <FL/platform.H> /** Create an empty clipping region. */ Fl_Rect_Region::Fl_Rect_Region() : pLeft(0), pTop(0), pRight(0), pBottom(0) { } /** Create a clipping region based on position and size. \param x, y position \param w, h size */ Fl_Rect_Region::Fl_Rect_Region(int x, int y, int w, int h) : pLeft(x), pTop(y), pRight(x+w), pBottom(y+h) { } /** Clone a clipping rectangle. */ Fl_Rect_Region::Fl_Rect_Region(const Fl_Rect_Region &r) : pLeft(r.pLeft), pTop(r.pTop), pRight(r.pRight), pBottom(r.pBottom) { } /** Clone a clipping rectangle. The pointer can be NULL if an empty rectangle is needed. */ Fl_Rect_Region::Fl_Rect_Region(enum Type what) { if (what==INFINITE) { pLeft = pTop = INT_MIN; pRight = pBottom = INT_MAX; } else { pLeft = pTop = pRight = pBottom = 0; } } /** If the rectangle has no width or height, it's considered empty. \return true, if everything will be clipped and there is nothing to draw */ bool Fl_Rect_Region::is_empty() const { return (pRight<=pLeft || pBottom<=pTop); } /** Return true, if the rectangle is of unlimited size and nothing should be clipped. \return treu, if there is no clipping */ bool Fl_Rect_Region::is_infinite() const { return (pLeft==INT_MIN); } /** Set an empty clipping rect. */ void Fl_Rect_Region::set_empty() { pLeft = pTop = pRight = pBottom = 0; } /** Set a clipping rect using position and size \param x, y position \param w, h size */ void Fl_Rect_Region::set(int x, int y, int w, int h) { pLeft = x; pTop = y; pRight = x+w; pBottom = y+h; } /** Set a rectangle using the coordinates of two points, top left and bottom right. \param l, t left and top coordinate \param r, b right and bottom coordinate */ void Fl_Rect_Region::set_ltrb(int l, int t, int r, int b) { pLeft = l; pTop = t; pRight = r; pBottom = b; } /** Copy the corrdinates from another rect. \param r source rectangle */ void Fl_Rect_Region::set(const Fl_Rect_Region &r) { pLeft = r.pLeft; pTop = r.pTop; pRight = r.pRight; pBottom = r.pBottom; } /** Set this rect to be the intersecting area between the original rect and another rect. \param r another rectangular region \return EMPTY, if rectangles are not intersecting, SAME if this and rect are equal, LESS if the new rect is smaller than the original rect */ int Fl_Rect_Region::intersect_with(const Fl_Rect_Region &r) { if (is_empty()) { return EMPTY; } if (r.is_empty()) { set_empty(); return EMPTY; } bool same = true; if ( pLeft != r.pLeft ) { same = false; if ( r.pLeft > pLeft ) pLeft = r.pLeft; } if ( pTop != r.pTop ) { same = false; if ( r.pTop > pTop ) pTop = r.pTop; } if ( pRight != r.pRight ) { same = false; if ( r.pRight < pRight ) pRight = r.pRight; } if ( pBottom != r.pBottom ) { same = false; if ( r.pBottom < pBottom ) pBottom = r.pBottom; } if (same) return SAME; if (is_empty()) return EMPTY; return LESS; } /** Use rectangle as a bounding box and add the outline of another rect. */ void Fl_Rect_Region::add_to_bbox(const Fl_Rect_Region &r) { if (is_empty()) return; if (r.pLeft<pLeft) pLeft = r.pLeft; if (r.pTop<pTop) pTop = r.pTop; if (r.pRight>pRight) pRight = r.pRight; if (r.pBottom>pBottom) pBottom = r.pBottom; } /** Print the coordinates of the rect to the log. \param label some text that is logged with this message. */ void Fl_Rect_Region::print(const char *label) const { Fl_Android_Application::log_i("---> Fl_Rect_Region: %s", label); Fl_Android_Application::log_i("Rect l:%d t:%d r:%d b:%d", left(), top(), right(), bottom()); } // ============================================================================= /** Create an empty complex region. */ Fl_Complex_Region::Fl_Complex_Region() : Fl_Rect_Region() { } /** Create a complex region with the same bounds as the give rect. \param r region size */ Fl_Complex_Region::Fl_Complex_Region(const Fl_Rect_Region &r) : Fl_Rect_Region(r) { } /** Delete this region, all subregions recursively, and all following regions. */ Fl_Complex_Region::~Fl_Complex_Region() { delete_all_subregions(); } /** Delete all subregions of this region. The pSubregion pointer should always be seen as a list of subregions, rather than a single region and some pNext pointer. So everything we do, we should probably do for every object in that list. Also note, that the top level region never has pNext pointing to anything. */ void Fl_Complex_Region::delete_all_subregions() { // Do NOT delete the chain in pNext! The caller has to that job. // A top-level coplex region has pNext always set to NULL, and it does // delete all subregions chained via the subregion pNext. while (pSubregion) { Fl_Complex_Region *rgn = pSubregion; pSubregion = rgn->pNext; delete rgn; rgn = 0; } } /** Print the entire content of this region recursively. */ void Fl_Complex_Region::print(const char *label) const { Fl_Android_Application::log_i("---> Fl_Complex_Region: %s", label); print_data(0); } /* Print the rectangular data only. */ void Fl_Complex_Region::print_data(int indent) const { static const char *space = " "; if (pSubregion) { Fl_Android_Application::log_i("%sBBox l:%d t:%d r:%d b:%d", space+16-indent, left(), top(), right(), bottom()); pSubregion->print_data(indent+1); } else { Fl_Android_Application::log_i("%sRect l:%d t:%d r:%d b:%d", space+16-indent, left(), top(), right(), bottom()); } if (pNext) { pNext->print_data(indent); } } /** Replace this region with a rectangle. \param r the source rectangle */ void Fl_Complex_Region::set(const Fl_Rect_Region &r) { Fl_Rect_Region::set(r); delete_all_subregions(); } /** Replace this region with a copy of another region. This operation can be expensive for very complex regions. \param r the source region */ void Fl_Complex_Region::set(const Fl_Complex_Region &r) { Fl_Rect_Region::set((const Fl_Rect_Region&)r); delete_all_subregions(); Fl_Complex_Region *srcRgn = r.pSubregion; if (srcRgn) { // copy first subregion Fl_Complex_Region *dstRgn = pSubregion = new Fl_Complex_Region(); pSubregion->set(*srcRgn); // copy rest of list while (srcRgn) { dstRgn->pNext = new Fl_Complex_Region(); dstRgn = dstRgn->next(); dstRgn->set(*srcRgn); srcRgn = srcRgn->next(); } } } /** Set this region to the intersection of the original region and some rect. \param r intersect with this rectangle \return EMPTY, SAME, LESS */ int Fl_Complex_Region::intersect_with(const Fl_Rect_Region &r) { if (pSubregion) { Fl_Complex_Region *rgn = pSubregion; while (rgn) { rgn->intersect_with(r); rgn = rgn->next(); } compress(); } else { Fl_Rect_Region::intersect_with(r); } return 0; } /** Subtract a rectangular region from this region. \param r the rect that we want removed \return currently 0, but could return something meaningful */ int Fl_Complex_Region::subtract(const Fl_Rect_Region &r) { if (pSubregion) { Fl_Complex_Region *rgn = pSubregion; while (rgn) { rgn->subtract(r); rgn = rgn->next(); } compress(); } else { // Check if we overlap at all Fl_Rect_Region s(r); int intersects = s.intersect_with(*this); switch (intersects) { case EMPTY: // nothing to do break; case SAME: set_empty(); // Will be deleted by compress() break; case LESS: // split this rect into 1, 2, 3, or 4 new ones subtract_smaller_region(s); break; default: Fl_Android_Application::log_e("Invalid case in %s:%d", __FUNCTION__, __LINE__); break; } if (pSubregion) compress(); // because intersecting this may have created subregions } return 0; } /** Compress the subregion of this region if possible and update the bounding box of this region. Does not recurse down the tree! */ void Fl_Complex_Region::compress() { // Can't compress anything that does not have a subregion if (!pSubregion) return; // remove all empty regions, because the really don't add anything (literally) // print("Compress"); Fl_Complex_Region *rgn = pSubregion; while (rgn && rgn->is_empty()) { pSubregion = rgn->next(); delete rgn; rgn = pSubregion; } if (!pSubregion) return; rgn = pSubregion; while (rgn) { while (rgn->pNext && rgn->pNext->is_empty()) { Fl_Complex_Region *nextNext = rgn->pNext->pNext; delete rgn->pNext; rgn->pNext = nextNext; } rgn = rgn->next(); } // find rectangles that can be merged into a single new rectangle // (Too much work for much too little benefit) // if there is only a single subregion left, merge it into this region if (pSubregion->pNext==nullptr) { set((Fl_Rect_Region&)*pSubregion); // deletes subregion for us } if (!pSubregion) return; // finally, update the boudning box Fl_Rect_Region::set((Fl_Rect_Region&)*pSubregion); for (rgn=pSubregion->pNext; rgn; rgn=rgn->pNext) { add_to_bbox(*rgn); } } /** Subtract a smaller rect from a larger rect, potentially creating four new rectangles. This assumes that the calling region is NOT complex. \param r subtract the area of this rectangle; r must fit within ``this``. \return currently 0, but this may change */ int Fl_Complex_Region::subtract_smaller_region(const Fl_Rect_Region &r) { // subtract a smaller rect from a larger rect and create subrects as needed // if there is only one single coordinate different, we can reuse this container if (left()==r.left() && top()==r.top() && right()==r.right() && bottom()==r.bottom()) { // this should not happen set_empty(); } else if (left()!=r.left() && top()==r.top() && right()==r.right() && bottom()==r.bottom()) { pRight = r.left(); } else if (left()==r.left() && top()!=r.top() && right()==r.right() && bottom()==r.bottom()) { pBottom = r.top(); } else if (left()==r.left() && top()==r.top() && right()!=r.right() && bottom()==r.bottom()) { pLeft = r.right(); } else if (left()==r.left() && top()==r.top() && right()==r.right() && bottom()!=r.bottom()) { pTop = r.bottom(); } else { // create multiple regions if (pTop!=r.top()) { Fl_Complex_Region *s = add_subregion(); s->set_ltrb(pLeft, pTop, pRight, r.top()); } if (pBottom!=r.bottom()) { Fl_Complex_Region *s = add_subregion(); s->set_ltrb(pLeft, r.bottom(), pRight, pBottom); } if (pLeft!=r.left()) { Fl_Complex_Region *s = add_subregion(); s->set_ltrb(pLeft, r.top(), r.left(), r.bottom()); } if (pRight!=r.right()) { Fl_Complex_Region *s = add_subregion(); s->set_ltrb(r.right(), r.top(), pRight, r.bottom()); } } return 0; } /** Add an empty subregion to the current region. \return a pointer to the newly created region. */ Fl_Complex_Region *Fl_Complex_Region::add_subregion() { Fl_Complex_Region *r = new Fl_Complex_Region(); r->pParent = this; r->pNext = pSubregion; pSubregion = r; return r; } // ----------------------------------------------------------------------------- /** Returns an iterator object for loops that traverse the entire region tree. C++11 interface to range-based loops. \return Iterator pointing to the first element. */ Fl_Complex_Region::Iterator Fl_Complex_Region::begin() { return Iterator(this); } /** Returns an interator object to mark the end of travesing the tree. C++11 interface to range-based loops. \return */ Fl_Complex_Region::Iterator Fl_Complex_Region::end() { return Iterator(nullptr); } /** Create an iterator to walk the entire tree. \param r Iterate through this region, r must not have a parent(). */ Fl_Complex_Region::Iterator::Iterator(Fl_Complex_Region *r) : pRegion(r) { } /** Compare two iterators. C++11 needs this to find the end of a for loop. \param other \return */ bool Fl_Complex_Region::Iterator::operator!=(const Iterator &other) const { return pRegion != other.pRegion; } /** Set the iterator to the next object in the tree, down first. C++11 needs this to iterate in a for loop. \return */ const Fl_Complex_Region::Iterator &Fl_Complex_Region::Iterator::operator++() { if (pRegion->subregion()) { pRegion = pRegion->subregion(); } else if (pRegion->next()) { pRegion = pRegion->next(); } else { pRegion = pRegion->parent(); } return *this; } /** Return the current object while iterating through the tree. \return */ Fl_Complex_Region *Fl_Complex_Region::Iterator::operator*() const { return pRegion; } // ----------------------------------------------------------------------------- /** Use this to iterate through a region, hitting only nodes that intersect with this rect. \param r find all parts of the region that intersect with this rect. \return an object that can be used in range-based for loops in C++11. */ Fl_Complex_Region::Overlapping Fl_Complex_Region::overlapping(const Fl_Rect_Region &r) { return Overlapping(this, r); } /** A helper object for iterating through a region, finding only overlapping rects. \param rgn \param rect */ Fl_Complex_Region::Overlapping::Overlapping(Fl_Complex_Region *rgn, const Fl_Rect_Region &rect) : pRegion(rgn), pOriginalRect(rect), pClippedRect(rect) { } /** Return an itertor for the first clipping rectangle inside the region. \return */ Fl_Complex_Region::Overlapping::OverlappingIterator Fl_Complex_Region::Overlapping::begin() { find_intersecting(); return OverlappingIterator(this); } /** Return an iterator for the end of forward iteration. \return */ Fl_Complex_Region::Overlapping::OverlappingIterator Fl_Complex_Region::Overlapping::end() { return OverlappingIterator(nullptr); } /** Return the result of intersecting the original rect with this iterator. \return */ Fl_Rect_Region &Fl_Complex_Region::Overlapping::clipped_rect() { return pClippedRect; } /** Store the intersection in pClippedRect and return true if there was an intersection. \return */ bool Fl_Complex_Region::Overlapping::intersects() { return (pClippedRect.intersect_with(*pRegion) != EMPTY); } /** Find the next element in the tree that actually intersects with the initial rect. Starting the search at the current object, NOT the next object. \return */ bool Fl_Complex_Region::Overlapping::find_intersecting() { for (;;) { if (!pRegion) return false; pClippedRect.set(pOriginalRect); if (intersects()) { if (!pRegion->subregion()) { return true; } else { pRegion = pRegion->subregion(); } } else { find_next(); } } } /** Find the next object in the tree, complex, simple, intersecting or not. \return */ bool Fl_Complex_Region::Overlapping::find_next() { if (pRegion->subregion()) { pRegion = pRegion->subregion(); } else if (pRegion->next()) { pRegion = pRegion->next(); } else { pRegion = pRegion->parent(); // can be NULL } return (pRegion != nullptr); } // ----------------------------------------------------------------------------- /** Create the actual iterator for finding true clipping rects. \see Fl_Complex_Region::Overlapping \param ov */ Fl_Complex_Region::Overlapping::OverlappingIterator::OverlappingIterator( Overlapping *ov) : pOv(ov) { } /** Compare two iterator. This is used by C++11 range-based for loops to find the end of the range. \param other \return */ bool Fl_Complex_Region::Overlapping::OverlappingIterator::operator!=( const OverlappingIterator &other) const { auto thisRegion = pOv ? pOv->pRegion : nullptr; auto otherRegion = other.pOv ? other.pOv->pRegion : nullptr; return thisRegion != otherRegion; } /** Wrapper to find and set the next intersecting rectangle. \see Fl_Complex_Region::Overlapping::find_intersecting \see Fl_Complex_Region::Overlapping::find_next \return */ const Fl_Complex_Region::Overlapping::OverlappingIterator & Fl_Complex_Region::Overlapping::OverlappingIterator::operator++() { pOv->find_next(); if (pOv->pRegion) pOv->find_intersecting(); return *this; } /** Return the Fl_Complex_Region::Overlapping state for this iterator. This gives the user access to the current rectangular fragment of the clipping region. \return */ Fl_Complex_Region::Overlapping * Fl_Complex_Region::Overlapping::OverlappingIterator::operator*() const { return pOv; } // ============================================================================= void Fl_Android_Graphics_Driver::restore_clip() { fl_clip_state_number++; // find the current user clipping rectangle Fl_Region b = rstack[rstackptr]; // Fl_Region is a pointer to Fl_Rect_Region if (b) { if (b->is_empty()) { // if this is an empty region, the intersection is always empty as well pClippingRegion.set_empty(); } else { // if there is a region, copy the full window region pClippingRegion.set(pDesktopWindowRegion); if (!b->is_infinite()) { // if the rect has dimensions, calculate the intersection pClippingRegion.intersect_with(*b); } } } else { // no rect? Just copy the window region pClippingRegion.set(pDesktopWindowRegion); } } void Fl_Android_Graphics_Driver::clip_region(Fl_Region r) { Fl_Region oldr = rstack[rstackptr]; if (oldr) ::free(oldr); rstack[rstackptr] = r; restore_clip(); } Fl_Region Fl_Android_Graphics_Driver::clip_region() { return rstack[rstackptr]; } void Fl_Android_Graphics_Driver::push_clip(int x, int y, int w, int h) { Fl_Region r; if (w > 0 && h > 0) { r = new Fl_Rect_Region(x, y, w, h); Fl_Region current = rstack[rstackptr]; if (current) { r->intersect_with(*current); } } else { // make empty clip region: r = new Fl_Rect_Region(); } if (rstackptr < region_stack_max) rstack[++rstackptr] = r; else Fl::warning("Fl_Android_Graphics_Driver::push_clip: clip stack overflow!\n"); restore_clip(); } void Fl_Android_Graphics_Driver::push_no_clip() { if (rstackptr < region_stack_max) rstack[++rstackptr] = 0; else Fl::warning("Fl_Android_Graphics_Driver::push_no_clip: clip stack overflow!\n"); restore_clip(); } void Fl_Android_Graphics_Driver::pop_clip() { if (rstackptr > 0) { Fl_Region oldr = rstack[rstackptr--]; if (oldr) ::free(oldr); } else Fl::warning("Fl_Android_Graphics_Driver::pop_clip: clip stack underflow!\n"); restore_clip(); } /* Intersects the rectangle with the current clip region and returns the bounding box of the result. Returns non-zero if the resulting rectangle is different to the original. This can be used to limit the necessary drawing to a rectangle. \p W and \p H are set to zero if the rectangle is completely outside the region. \param[in] x,y,w,h position and size of rectangle \param[out] X,Y,W,H position and size of resulting bounding box. \returns Non-zero if the resulting rectangle is different to the original. */ int Fl_Android_Graphics_Driver::clip_box(int x, int y, int w, int h, int& X, int& Y, int& W, int& H) { Fl_Region r = rstack[rstackptr]; if (r) { Fl_Rect_Region a(x, y, w, h); int ret = a.intersect_with(*r); X = a.x(); Y = a.y(); W = a.w(); H = a.h(); return (ret!=Fl_Rect_Region::SAME); } else { X = x; Y = y; W = w; H = h; return 0; } } /* Does the rectangle intersect the current clip region? \param[in] x,y,w,h position and size of rectangle \returns non-zero if any of the rectangle intersects the current clip region. If this returns 0 you don't have to draw the object. \note Under X this returns 2 if the rectangle is partially clipped, and 1 if it is entirely inside the clip region. */ int Fl_Android_Graphics_Driver::not_clipped(int x, int y, int w, int h) { if (w <= 0 || h <= 0) return 0; Fl_Region r = rstack[rstackptr]; if (r) { Fl_Rect_Region a(x, y, w, h); // return 0 for empty, 1 for same, 2 if intersecting return a.intersect_with(*r); } else { return 1; } }
25.808405
115
0.659898
[ "object" ]
eab33d842eed78f97404458b04f30e6b7022fed1
10,909
cpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/resources/BrushTypeUtils.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/resources/BrushTypeUtils.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/resources/BrushTypeUtils.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_brush // $Keywords: // // $Description: // Implementation of methods used to create intermediate brush // representations from user-defined state. // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" MtDefine(CBrushTypeUtils, MILRender, "CBrushTypeUtils"); /*++ Routine Description: Obtains immediate (realized) value of the brush transform. We derive the brush transform from converting the relative transform to absolute space using the bounding box and combining it with the absolute transform. Per spec, the relative transform is applied before the absolute transform. This allows users to do things like rotating about the center of a shape using the relative transform and then offseting it by a constant amount amoungst all shapes being filled using the absolute transform. Return Value: HRESULT --*/ VOID CBrushTypeUtils::GetBrushTransform( __in_ecount_opt(1) const CMILMatrix *pmatRelative, // Current value of user-specified Brush.RelativeTransform property __in_ecount_opt(1) const CMILMatrix *pmatTransform, // Current value of user-specified Brush.Transform property __in_ecount(1) const MilPointAndSizeD *pBoundingBox, // Bounding box the relative transform is relative to __out_ecount(1) CMILMatrix *pResultTransform // Output combined transform ) { // Assert required parameters Assert(pBoundingBox && pResultTransform); // fResultSet specifies whether or not the result matrix has been set. // We use this knowledge to avoid unncessary matrix operations when // the relative and/or absolute transforms aren't set. BOOL fResultSet = FALSE; // // Apply the relative transform // if (pmatRelative) { // Handle relative transforms applied to degenerate shapes. This equality // check has been added to maintain parity with the previous InferAffineMatrix // implementation. But we need to handle dimensions close to zero, in addition // to zero. if ( (pBoundingBox->Width != 0.0) && (pBoundingBox->Height != 0.0)) { // Bounding box relative coordinates are relative to MilPointAndSizeF absoluteBounds; MilPointAndSizeFFromMilPointAndSizeD(&absoluteBounds, pBoundingBox); // Calculate matrix that transforms absolute coordinates by the relative transform ConvertRelativeTransformToAbsolute( &absoluteBounds, pmatRelative, pResultTransform ); fResultSet = TRUE; } } // // Apply the absolute transform, if one was specified // if (pmatTransform) { if (fResultSet) { // Append the absolute transform to the relative transform if // a relative transform was set pResultTransform->Multiply(*pmatTransform); } else { // Copy the absolute transform directly to the out-param if no // relative transform was specified *pResultTransform = *pmatTransform; } fResultSet = TRUE; } // Set the matrix to identity if the matrix hasn't been initialized because // no transforms were specified if (!fResultSet) { pResultTransform->SetToIdentity(); } } //+----------------------------------------------------------------------------- // // Member: // CBrushTypeUtils::ConvertRelativeTransformToAbsolute // // Synopsis: // Given the relative transform & bounding box it's relative to, this // function calculates an absolute derivation of the relative tranform. // // The relative transform is modified to take absolute coordinates as // input, transform those coordinates by the user-specified relative // transform, and then output absolute coordinates. // // Notes: // This function is an optimized equivalent of the following operations: // // MilRectF relativeBounds = {0.0, 0.0, 1.0, 1.0}; // pResultTransform->InferAffineMatrix(/*from*/ pBoundingBox, /*to*/ relativeBounds); // pResultTransform->Multiply(*pmatRelative); // relativeToAbsolute.InferAffineMatrix(/*from*/ relativeBounds, /*to*/ pBoundingBox); // pResultTransform->Multiply(relativeToAbsolute); // // To avoid inferring 2 rectangle mappings, & performing 2 full matrix // multiplications, the resultant math performed by these 4 operations was // expanded out, and terms which cancel or always evaluate to 0 were // removed. As a final optimization, this function assumes (and asserts) // that the input relative transform only has 6 elements set to // non-identity values. // //------------------------------------------------------------------------------ VOID CBrushTypeUtils::ConvertRelativeTransformToAbsolute( __in_ecount(1) const MilPointAndSizeF *pBoundingBox, // Bounds that the relative transform is relative to. The unit square in the relative // coordinate space is mapped to these bounds in the absolute coordinate space. __in_ecount(1) const CMILMatrix *pRelativeTransform, // User-specified relative transform __out_ecount(1) CMILMatrix* pConvertedTransform // Relative transform that has been modified to take absolute coordinates as input, // transform those coordinates by the relative transform, and then output absolute // coordinates. ) { // Copy commonly used variables to the stack for quicker access (and to make the implementation // more readable) REAL X = pBoundingBox->X; REAL Y = pBoundingBox->Y; REAL W = pBoundingBox->Width; REAL H = pBoundingBox->Height; // Precompute divides that are needed more than once. REAL rHeightDividedByWidth = H / W; REAL rWidthDividedByHeight = W / H; // Guard that entries other than _11, _12, _21, _22, _41, & _42 are still identity // // Only these 6 matrix entries can be set at our API, which is assumed by this // implementation. Doing so allows us to dramatically reduce the number of // calculations performed by this function. // // We allow NaN through these Asserts as NaN can pop up through matrix multiplies. // Unfortunately for matrix multiplies, NaN * 0 == NaN. // Assert (IsNaNOrIsEqualTo(pRelativeTransform->_13, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_14, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_23, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_24, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_31, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_32, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_33, 1.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_34, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_43, 0.0f)); Assert (IsNaNOrIsEqualTo(pRelativeTransform->_44, 1.0f)); // // Calculate the first vector // pConvertedTransform->_11 = pRelativeTransform->_11; pConvertedTransform->_12 = pRelativeTransform->_12 * rHeightDividedByWidth; pConvertedTransform->_13 = 0.0f; pConvertedTransform->_14 = 0.0f; // // Calculate the second vector // pConvertedTransform->_21 = pRelativeTransform->_21 * rWidthDividedByHeight; pConvertedTransform->_22 = pRelativeTransform->_22; pConvertedTransform->_23 = 0.0f; pConvertedTransform->_24 = 0.0f; // // Calculate the third vector // pConvertedTransform->_31 = 0.0f; pConvertedTransform->_32 = 0.0f; pConvertedTransform->_33 = 1.0f; pConvertedTransform->_34 = 0.0f; // // Calculate fourth vector // pConvertedTransform->_41 = pRelativeTransform->_41 * W - pRelativeTransform->_11 * X - pRelativeTransform->_21 * Y * rWidthDividedByHeight + X; pConvertedTransform->_42 = pRelativeTransform->_42 * H - pRelativeTransform->_12 * X * rHeightDividedByWidth - pRelativeTransform->_22 * Y + Y; pConvertedTransform->_43 = 0.0f; pConvertedTransform->_44 = 1.0f; } /*++ Routine Description: Calculates an absolute point from a relative point and bounding box. Arguments: pBoundingBox: Bounding box pt is relative to pt: IN: Relative point OUT: Absolute Point Return Value: void --*/ VOID AdjustRelativePoint( __in const MilPointAndSizeD *pBoundingBox, __inout MilPoint2F *pt ) { Assert(pt); // Must have bounding box Assert(pBoundingBox); // Relative points are defined as a decimal perctange of a bounding box // dimension. Any given coordinate, "A", will reside within the bounding // box over the range 0.0 <= A <= 1.0. E.g., if pt->X is 0.5, then the // absolute X coordinate is half the width of the bounding box, // or: pBoundingBox->X + 0.5 * pBoundingBox->Width. // Likewise, if pt->X is defined as 3.1, then the absolute coordinate is // 3.1 times the width of the bounding box + the bounding box's X coordinate // Calculate absolute point pt->X = static_cast<float>(pBoundingBox->X) + pt->X * static_cast<float>(pBoundingBox->Width); pt->Y = static_cast<float>(pBoundingBox->Y) + pt->Y * static_cast<float>(pBoundingBox->Height); } /*++ Routine Description: Calculates an absolute rectangle from a relative rectangle and bounding box. Arguments: pBoundingBox: Bounding box pt is relative to pRelativeRectangle: IN: Relative Rectangle OUT: Absolute Rectangle Return Value: void --*/ VOID AdjustRelativeRectangle( __in const MilPointAndSizeD *prcBoundingBox, __inout MilPointAndSizeD *prcAdjustRectangle ) { Assert(prcBoundingBox && prcAdjustRectangle); if (IsRectEmptyOrInvalid(prcBoundingBox) || IsRectEmptyOrInvalid(prcAdjustRectangle)) { *prcAdjustRectangle = MilEmptyPointAndSizeD; } else { prcAdjustRectangle->X = prcBoundingBox->X + (prcAdjustRectangle->X * prcBoundingBox->Width); prcAdjustRectangle->Y = prcBoundingBox->Y + (prcAdjustRectangle->Y * prcBoundingBox->Height); prcAdjustRectangle->Width = prcAdjustRectangle->Width * prcBoundingBox->Width; prcAdjustRectangle->Height = prcAdjustRectangle->Height * prcBoundingBox->Height; } }
33.158055
101
0.659822
[ "shape", "vector", "transform" ]
ead2b77d14b11898ba36339f34efa1982c672282
2,319
cpp
C++
solutions/LeetCode/C++/799.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/799.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/799.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { if (query_row == 0) return poured < 1.0 ? poured : 1.0; int queryId = query_row * (query_row + 1) / 2 + query_glass + 1; vector<double> currentRow = {(double)poured}; int count = 1; double retVal; while (count <= queryId) { double newHead = 0; double newTail = 0; if (currentRow.front() > 1.0) newHead = (currentRow.front() - 1.0) / 2; if (currentRow.back() > 1.0) newTail = (currentRow.back() - 1.0) / 2; double a = currentRow[0]; double b; for (int i = 0; i < currentRow.size() - 1; ++i) { b = currentRow[i + 1]; currentRow[i + 1] = 0; if (a > 1.0) currentRow[i + 1] += (a - 1.0) / 2; if (b > 1.0) currentRow[i + 1] += (b - 1.0) / 2; a = b; } currentRow.front() = newHead; currentRow.push_back(newTail); if (count + currentRow.size() >= queryId) { retVal = currentRow[queryId - count - 1] > 1.0 ? 1.0 : currentRow[queryId - count - 1]; break; } count += currentRow.size(); } return retVal; } }; __________________________________________________________________________________________________ sample 10136 kb submission class Solution { public: // O(n ^ 2) space double champagneTower(int poured, int query_row, int query_glass) { double result[101][101] = {0.0}; // query_row and query_glass belong to [0,99] result[0][0] = poured; for (int i = 0; i <= query_row; i++) { for (int j = 0; j <= i; j++) { if (result[i][j] >= 1) { result[i+1][j] += (result[i][j] - 1) / 2; result[i+1][j+1] += (result[i][j] - 1) / 2; result[i][j] = 1; } } } return result[query_row][query_glass]; } }; __________________________________________________________________________________________________
40.684211
103
0.530832
[ "vector" ]
eadeafe8fe4d9d8e083d21c908c7b50148071393
30,023
cc
C++
chrome/browser/extensions/extensions_ui.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/browser/extensions/extensions_ui.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extensions_ui.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extensions_ui.h" #include "app/gfx/codec/png_codec.h" #include "app/gfx/color_utils.h" #include "app/gfx/skbitmap_operations.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/base64.h" #include "base/file_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_disabled_infobar_delegate.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/google_util.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_error_reporter.h" #include "chrome/common/extensions/user_script.h" #include "chrome/common/extensions/url_pattern.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/net_util.h" #include "webkit/glue/image_decoder.h" //////////////////////////////////////////////////////////////////////////////// // // ExtensionsHTMLSource // //////////////////////////////////////////////////////////////////////////////// ExtensionsUIHTMLSource::ExtensionsUIHTMLSource() : DataSource(chrome::kChromeUIExtensionsHost, MessageLoop::current()) { } void ExtensionsUIHTMLSource::StartDataRequest(const std::string& path, bool is_off_the_record, int request_id) { DictionaryValue localized_strings; localized_strings.SetString(L"title", l10n_util::GetString(IDS_EXTENSIONS_TITLE)); localized_strings.SetString(L"devModeLink", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings.SetString(L"devModePrefix", l10n_util::GetString(IDS_EXTENSIONS_DEVELOPER_MODE_PREFIX)); localized_strings.SetString(L"loadUnpackedButton", l10n_util::GetString(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings.SetString(L"packButton", l10n_util::GetString(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings.SetString(L"updateButton", l10n_util::GetString(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings.SetString(L"noExtensions", l10n_util::GetString(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings.SetString(L"suggestGallery", l10n_util::GetStringF(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, std::wstring(L"<a href='") + ASCIIToWide(google_util::AppendGoogleLocaleParam( GURL(extension_urls::kGalleryBrowsePrefix)).spec()) + L"'>", L"</a>")); localized_strings.SetString(L"getMoreExtensions", std::wstring(L"<a href='") + ASCIIToWide(google_util::AppendGoogleLocaleParam( GURL(extension_urls::kGalleryBrowsePrefix)).spec()) + L"'>" + l10n_util::GetString(IDS_GET_MORE_EXTENSIONS) + L"</a>"); localized_strings.SetString(L"extensionDisabled", l10n_util::GetString(IDS_EXTENSIONS_DISABLED_EXTENSION)); localized_strings.SetString(L"inDevelopment", l10n_util::GetString(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings.SetString(L"extensionId", l10n_util::GetString(IDS_EXTENSIONS_ID)); localized_strings.SetString(L"extensionVersion", l10n_util::GetString(IDS_EXTENSIONS_VERSION)); localized_strings.SetString(L"inspectViews", l10n_util::GetString(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings.SetString(L"disable", l10n_util::GetString(IDS_EXTENSIONS_DISABLE)); localized_strings.SetString(L"enable", l10n_util::GetString(IDS_EXTENSIONS_ENABLE)); localized_strings.SetString(L"reload", l10n_util::GetString(IDS_EXTENSIONS_RELOAD)); localized_strings.SetString(L"uninstall", l10n_util::GetString(IDS_EXTENSIONS_UNINSTALL)); localized_strings.SetString(L"options", l10n_util::GetString(IDS_EXTENSIONS_OPTIONS)); localized_strings.SetString(L"packDialogTitle", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_TITLE)); localized_strings.SetString(L"packDialogHeading", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_HEADING)); localized_strings.SetString(L"rootDirectoryLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_ROOT_DIRECTORY_LABEL)); localized_strings.SetString(L"packDialogBrowse", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_BROWSE)); localized_strings.SetString(L"privateKeyLabel", l10n_util::GetString(IDS_EXTENSION_PACK_DIALOG_PRIVATE_KEY_LABEL)); localized_strings.SetString(L"okButton", l10n_util::GetString(IDS_OK)); localized_strings.SetString(L"cancelButton", l10n_util::GetString(IDS_CANCEL)); SetFontAndTextDirection(&localized_strings); static const base::StringPiece extensions_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_EXTENSIONS_UI_HTML)); std::string full_html(extensions_html.data(), extensions_html.size()); jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html); jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html); jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html); jstemplate_builder::AppendJsTemplateSourceHtml(&full_html); scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(full_html.size()); std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); } //////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler::IconLoader // //////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::IconLoader::IconLoader(ExtensionsDOMHandler* handler) : handler_(handler) { } void ExtensionsDOMHandler::IconLoader::LoadIcons( std::vector<ExtensionResource>* icons, DictionaryValue* json) { ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(this, &IconLoader::LoadIconsOnFileThread, icons, json)); } void ExtensionsDOMHandler::IconLoader::Cancel() { handler_ = NULL; } void ExtensionsDOMHandler::IconLoader::LoadIconsOnFileThread( std::vector<ExtensionResource>* icons, DictionaryValue* json) { scoped_ptr<std::vector<ExtensionResource> > icons_deleter(icons); scoped_ptr<DictionaryValue> json_deleter(json); ListValue* extensions = NULL; CHECK(json->GetList(L"extensions", &extensions)); for (size_t i = 0; i < icons->size(); ++i) { DictionaryValue* extension = NULL; CHECK(extensions->GetDictionary(static_cast<int>(i), &extension)); // Read the file. std::string file_contents; if (icons->at(i).relative_path().empty() || !file_util::ReadFileToString(icons->at(i).GetFilePath(), &file_contents)) { // If there's no icon, default to the puzzle icon. This is safe to do from // the file thread. file_contents = ResourceBundle::GetSharedInstance().GetDataResource( IDR_EXTENSION_DEFAULT_ICON); } // If the extension is disabled, we desaturate the icon to add to the // disabledness effect. bool enabled = false; CHECK(extension->GetBoolean(L"enabled", &enabled)); if (!enabled) { const unsigned char* data = reinterpret_cast<const unsigned char*>(file_contents.data()); webkit_glue::ImageDecoder decoder; scoped_ptr<SkBitmap> decoded(new SkBitmap()); *decoded = decoder.Decode(data, file_contents.length()); // Desaturate the icon and lighten it a bit. color_utils::HSL shift = {-1, 0, 0.6}; *decoded = SkBitmapOperations::CreateHSLShiftedBitmap(*decoded, shift); std::vector<unsigned char> output; gfx::PNGCodec::EncodeBGRASkBitmap(*decoded, false, &output); // Lame, but we must make a copy of this now, because base64 doesn't take // the same input type. file_contents.assign(reinterpret_cast<char*>(&output.front()), output.size()); } // Create a data URL (all icons are converted to PNGs during unpacking). std::string base64_encoded; base::Base64Encode(file_contents, &base64_encoded); GURL icon_url("data:image/png;base64," + base64_encoded); extension->SetString(L"icon", icon_url.spec()); } ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &IconLoader::ReportResultOnUIThread, json_deleter.release())); } void ExtensionsDOMHandler::IconLoader::ReportResultOnUIThread( DictionaryValue* json) { if (handler_) handler_->OnIconsLoaded(json); } /////////////////////////////////////////////////////////////////////////////// // // ExtensionsDOMHandler // /////////////////////////////////////////////////////////////////////////////// ExtensionsDOMHandler::ExtensionsDOMHandler(ExtensionsService* extension_service) : extensions_service_(extension_service) { } void ExtensionsDOMHandler::RegisterMessages() { dom_ui_->RegisterMessageCallback("requestExtensionsData", NewCallback(this, &ExtensionsDOMHandler::HandleRequestExtensionsData)); dom_ui_->RegisterMessageCallback("toggleDeveloperMode", NewCallback(this, &ExtensionsDOMHandler::HandleToggleDeveloperMode)); dom_ui_->RegisterMessageCallback("inspect", NewCallback(this, &ExtensionsDOMHandler::HandleInspectMessage)); dom_ui_->RegisterMessageCallback("reload", NewCallback(this, &ExtensionsDOMHandler::HandleReloadMessage)); dom_ui_->RegisterMessageCallback("enable", NewCallback(this, &ExtensionsDOMHandler::HandleEnableMessage)); dom_ui_->RegisterMessageCallback("uninstall", NewCallback(this, &ExtensionsDOMHandler::HandleUninstallMessage)); dom_ui_->RegisterMessageCallback("options", NewCallback(this, &ExtensionsDOMHandler::HandleOptionsMessage)); dom_ui_->RegisterMessageCallback("load", NewCallback(this, &ExtensionsDOMHandler::HandleLoadMessage)); dom_ui_->RegisterMessageCallback("pack", NewCallback(this, &ExtensionsDOMHandler::HandlePackMessage)); dom_ui_->RegisterMessageCallback("autoupdate", NewCallback(this, &ExtensionsDOMHandler::HandleAutoUpdateMessage)); dom_ui_->RegisterMessageCallback("selectFilePath", NewCallback(this, &ExtensionsDOMHandler::HandleSelectFilePathMessage)); } void ExtensionsDOMHandler::HandleRequestExtensionsData(const Value* value) { DictionaryValue* results = new DictionaryValue(); // Add the extensions to the results structure. ListValue *extensions_list = new ListValue(); // Stores the icon resource for each of the extensions in extensions_list. We // build up a list of them here, then load them on the file thread in // ::LoadIcons(). std::vector<ExtensionResource>* extension_icons = new std::vector<ExtensionResource>(); const ExtensionList* extensions = extensions_service_->extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { // Don't show the themes since this page's UI isn't really useful for // themes. if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), true)); extension_icons->push_back(PickExtensionIcon(*extension)); } } extensions = extensions_service_->disabled_extensions(); for (ExtensionList::const_iterator extension = extensions->begin(); extension != extensions->end(); ++extension) { if (!(*extension)->IsTheme()) { extensions_list->Append(CreateExtensionDetailValue( *extension, GetActivePagesForExtension((*extension)->id()), false)); extension_icons->push_back(PickExtensionIcon(*extension)); } } results->Set(L"extensions", extensions_list); bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); results->SetBoolean(L"developerMode", developer_mode); if (icon_loader_.get()) icon_loader_->Cancel(); icon_loader_ = new IconLoader(this); icon_loader_->LoadIcons(extension_icons, results); } void ExtensionsDOMHandler::OnIconsLoaded(DictionaryValue* json) { dom_ui_->CallJavascriptFunction(L"returnExtensionsData", *json); delete json; // Register for notifications that we need to reload the page. registrar_.RemoveAll(); registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_PROCESS_CREATED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UPDATE_DISABLED, NotificationService::AllSources()); } ExtensionResource ExtensionsDOMHandler::PickExtensionIcon( Extension* extension) { // Try to fetch the medium sized icon, then (if missing) go for the large one. const std::map<int, std::string>& icons = extension->icons(); std::map<int, std::string>::const_iterator iter = icons.find(Extension::EXTENSION_ICON_MEDIUM); if (iter == icons.end()) iter = icons.find(Extension::EXTENSION_ICON_LARGE); if (iter != icons.end()) return extension->GetResource(iter->second); else return ExtensionResource(); } void ExtensionsDOMHandler::HandleToggleDeveloperMode(const Value* value) { bool developer_mode = dom_ui_->GetProfile()->GetPrefs() ->GetBoolean(prefs::kExtensionsUIDeveloperMode); dom_ui_->GetProfile()->GetPrefs()->SetBoolean( prefs::kExtensionsUIDeveloperMode, !developer_mode); } void ExtensionsDOMHandler::HandleInspectMessage(const Value* value) { std::string render_process_id_str; std::string render_view_id_str; int render_process_id; int render_view_id; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &render_process_id_str)); CHECK(list->GetString(1, &render_view_id_str)); CHECK(StringToInt(render_process_id_str, &render_process_id)); CHECK(StringToInt(render_view_id_str, &render_view_id)); RenderViewHost* host = RenderViewHost::FromID(render_process_id, render_view_id); if (!host) { // This can happen if the host has gone away since the page was displayed. return; } DevToolsManager::GetInstance()->OpenDevToolsWindow(host); } void ExtensionsDOMHandler::HandleReloadMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); extensions_service_->ReloadExtension(extension_id); } void ExtensionsDOMHandler::HandleEnableMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); std::string extension_id, enable_str; CHECK(list->GetString(0, &extension_id)); CHECK(list->GetString(1, &enable_str)); if (enable_str == "true") { ExtensionPrefs* prefs = extensions_service_->extension_prefs(); if (prefs->DidExtensionEscalatePermissions(extension_id)) { Extension* extension = extensions_service_->GetExtensionById(extension_id, true); ShowExtensionDisabledDialog(extensions_service_, dom_ui_->GetProfile(), extension); } else { extensions_service_->EnableExtension(extension_id); } } else { extensions_service_->DisableExtension(extension_id); } } void ExtensionsDOMHandler::HandleUninstallMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); Extension *extension = extensions_service_->GetExtensionById(extension_id, true); if (!extension) return; scoped_ptr<SkBitmap> uninstall_icon; Extension::DecodeIcon(extension, Extension::EXTENSION_ICON_LARGE, &uninstall_icon); extension_id_uninstalling_ = extension_id; ExtensionInstallUI client(dom_ui_->GetProfile()); client.ConfirmUninstall(this, extension, uninstall_icon.get()); } void ExtensionsDOMHandler::InstallUIProceed() { extensions_service_->UninstallExtension(extension_id_uninstalling_, false); extension_id_uninstalling_ = ""; } void ExtensionsDOMHandler::InstallUIAbort() { extension_id_uninstalling_ = ""; } void ExtensionsDOMHandler::HandleOptionsMessage(const Value* value) { CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1); std::string extension_id; CHECK(list->GetString(0, &extension_id)); Extension *extension = extensions_service_->GetExtensionById(extension_id, false); if (!extension || extension->options_url().is_empty()) { return; } Browser* browser = Browser::GetOrCreateTabbedBrowser(dom_ui_->GetProfile()); CHECK(browser); browser->OpenURL(extension->options_url(), GURL(), SINGLETON_TAB, PageTransition::LINK); } void ExtensionsDOMHandler::HandleLoadMessage(const Value* value) { FilePath::StringType string_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 1) << list->GetSize(); CHECK(list->GetString(0, &string_path)); extensions_service_->LoadExtension(FilePath(string_path)); } void ExtensionsDOMHandler::ShowAlert(const std::string& message) { ListValue arguments; arguments.Append(Value::CreateStringValue(message)); dom_ui_->CallJavascriptFunction(L"alert", arguments); } void ExtensionsDOMHandler::HandlePackMessage(const Value* value) { std::string extension_path; std::string private_key_path; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &extension_path)); CHECK(list->GetString(1, &private_key_path)); FilePath root_directory = FilePath::FromWStringHack(ASCIIToWide( extension_path)); FilePath key_file = FilePath::FromWStringHack(ASCIIToWide(private_key_path)); if (root_directory.empty()) { if (extension_path.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_REQUIRED)); } else { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_INVALID)); } return; } if (!private_key_path.empty() && key_file.empty()) { ShowAlert(l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_KEY_INVALID)); return; } pack_job_ = new PackExtensionJob(this, root_directory, key_file); pack_job_->Start(); } void ExtensionsDOMHandler::OnPackSuccess(const FilePath& crx_file, const FilePath& pem_file) { std::string message; if (!pem_file.empty()) { message = WideToUTF8(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_NEW, crx_file.ToWStringHack(), pem_file.ToWStringHack())); } else { message = WideToUTF8(l10n_util::GetStringF( IDS_EXTENSION_PACK_DIALOG_SUCCESS_BODY_UPDATE, crx_file.ToWStringHack())); } ShowAlert(message); ListValue results; dom_ui_->CallJavascriptFunction(L"hidePackDialog", results); } void ExtensionsDOMHandler::OnPackFailure(const std::wstring& error) { ShowAlert(WideToASCII(error)); } void ExtensionsDOMHandler::HandleAutoUpdateMessage(const Value* value) { ExtensionUpdater* updater = extensions_service_->updater(); if (updater) { updater->CheckNow(); } } void ExtensionsDOMHandler::HandleSelectFilePathMessage(const Value* value) { std::string select_type; std::string operation; CHECK(value->IsType(Value::TYPE_LIST)); const ListValue* list = static_cast<const ListValue*>(value); CHECK(list->GetSize() == 2); CHECK(list->GetString(0, &select_type)); CHECK(list->GetString(1, &operation)); SelectFileDialog::Type type = SelectFileDialog::SELECT_FOLDER; static SelectFileDialog::FileTypeInfo info; int file_type_index = 0; if (select_type == "file") type = SelectFileDialog::SELECT_OPEN_FILE; string16 select_title; if (operation == "load") select_title = l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY); else if (operation == "packRoot") select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_ROOT); else if (operation == "pem") { select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_KEY); info.extensions.push_back(std::vector<FilePath::StringType>()); info.extensions.front().push_back(FILE_PATH_LITERAL("pem")); info.extension_description_overrides.push_back(WideToUTF16( l10n_util::GetString( IDS_EXTENSION_PACK_DIALOG_KEY_FILE_TYPE_DESCRIPTION))); info.include_all_files = true; file_type_index = 1; } else { NOTREACHED(); return; } load_extension_dialog_ = SelectFileDialog::Create(this); load_extension_dialog_->SelectFile(type, select_title, FilePath(), &info, file_type_index, FILE_PATH_LITERAL(""), dom_ui_->tab_contents()->view()->GetTopLevelNativeWindow(), NULL); } void ExtensionsDOMHandler::FileSelected(const FilePath& path, int index, void* params) { // Add the extensions to the results structure. ListValue results; results.Append(Value::CreateStringValue(path.value())); dom_ui_->CallJavascriptFunction(L"window.handleFilePathSelected", results); } void ExtensionsDOMHandler::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { // We listen to both EXTENSION_LOADED and EXTENSION_PROCESS_CREATED because // we don't know about the views for an extension at EXTENSION_LOADED, but // if we only listen to EXTENSION_PROCESS_CREATED, we'll miss extensions // that don't have a process at startup. // // Doing it this way gets everything, but it means that we will actually // render the page twice. This doesn't seem to result in any noticeable // flicker, though. case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_PROCESS_CREATED: case NotificationType::EXTENSION_UNLOADED: case NotificationType::EXTENSION_UNLOADED_DISABLED: case NotificationType::EXTENSION_UPDATE_DISABLED: if (dom_ui_->tab_contents()) HandleRequestExtensionsData(NULL); break; default: NOTREACHED(); } } static void CreateScriptFileDetailValue( const FilePath& extension_path, const UserScript::FileList& scripts, const wchar_t* key, DictionaryValue* script_data) { if (scripts.empty()) return; ListValue *list = new ListValue(); for (size_t i = 0; i < scripts.size(); ++i) { const UserScript::File& file = scripts[i]; // TODO(cira): this information is not used on extension page yet. We // may want to display actual resource that got loaded, not default. list->Append( new StringValue(file.relative_path().value())); } script_data->Set(key, list); } // Static DictionaryValue* ExtensionsDOMHandler::CreateContentScriptDetailValue( const UserScript& script, const FilePath& extension_path) { DictionaryValue* script_data = new DictionaryValue(); CreateScriptFileDetailValue(extension_path, script.js_scripts(), L"js", script_data); CreateScriptFileDetailValue(extension_path, script.css_scripts(), L"css", script_data); // Get list of glob "matches" strings ListValue *url_pattern_list = new ListValue(); const std::vector<URLPattern>& url_patterns = script.url_patterns(); for (std::vector<URLPattern>::const_iterator url_pattern = url_patterns.begin(); url_pattern != url_patterns.end(); ++url_pattern) { url_pattern_list->Append(new StringValue(url_pattern->GetAsString())); } script_data->Set(L"matches", url_pattern_list); return script_data; } // Static DictionaryValue* ExtensionsDOMHandler::CreateExtensionDetailValue( const Extension *extension, const std::vector<ExtensionPage>& pages, bool enabled) { DictionaryValue* extension_data = new DictionaryValue(); extension_data->SetString(L"id", extension->id()); extension_data->SetString(L"name", extension->name()); extension_data->SetString(L"description", extension->description()); extension_data->SetString(L"version", extension->version()->GetString()); extension_data->SetBoolean(L"enabled", enabled); extension_data->SetBoolean(L"allow_reload", extension->location() == Extension::LOAD); // Determine the sort order: Extensions loaded through --load-extensions show // up at the top. Disabled extensions show up at the bottom. if (extension->location() == Extension::LOAD) extension_data->SetInteger(L"order", 1); else extension_data->SetInteger(L"order", 2); if (!extension->options_url().is_empty()) extension_data->SetString(L"options_url", extension->options_url().spec()); // Add list of content_script detail DictionaryValues ListValue *content_script_list = new ListValue(); UserScriptList content_scripts = extension->content_scripts(); for (UserScriptList::const_iterator script = content_scripts.begin(); script != content_scripts.end(); ++script) { content_script_list->Append( CreateContentScriptDetailValue(*script, extension->path())); } extension_data->Set(L"content_scripts", content_script_list); // Add permissions ListValue *permission_list = new ListValue; std::vector<URLPattern> permissions = extension->host_permissions(); for (std::vector<URLPattern>::iterator permission = permissions.begin(); permission != permissions.end(); ++permission) { permission_list->Append(Value::CreateStringValue( permission->GetAsString())); } extension_data->Set(L"permissions", permission_list); // Add views ListValue* views = new ListValue; for (std::vector<ExtensionPage>::const_iterator iter = pages.begin(); iter != pages.end(); ++iter) { DictionaryValue* view_value = new DictionaryValue; view_value->SetString(L"path", iter->url.path().substr(1, std::string::npos)); // no leading slash view_value->SetInteger(L"renderViewId", iter->render_view_id); view_value->SetInteger(L"renderProcessId", iter->render_process_id); views->Append(view_value); } extension_data->Set(L"views", views); return extension_data; } std::vector<ExtensionPage> ExtensionsDOMHandler::GetActivePagesForExtension( const std::string& extension_id) { std::vector<ExtensionPage> result; std::set<ExtensionFunctionDispatcher*>* all_instances = ExtensionFunctionDispatcher::all_instances(); for (std::set<ExtensionFunctionDispatcher*>::iterator iter = all_instances->begin(); iter != all_instances->end(); ++iter) { RenderViewHost* view = (*iter)->render_view_host(); if ((*iter)->extension_id() == extension_id && view) { result.push_back(ExtensionPage((*iter)->url(), view->process()->id(), view->routing_id())); } } return result; } ExtensionsDOMHandler::~ExtensionsDOMHandler() { if (pack_job_.get()) pack_job_->ClearClient(); if (icon_loader_.get()) icon_loader_->Cancel(); } // ExtensionsDOMHandler, public: ----------------------------------------------- ExtensionsUI::ExtensionsUI(TabContents* contents) : DOMUI(contents) { ExtensionsService *exstension_service = GetProfile()->GetOriginalProfile()->GetExtensionsService(); ExtensionsDOMHandler* handler = new ExtensionsDOMHandler(exstension_service); AddMessageHandler(handler); handler->Attach(this); ExtensionsUIHTMLSource* html_source = new ExtensionsUIHTMLSource(); // Set up the chrome://extensions/ source. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( Singleton<ChromeURLDataManager>::get(), &ChromeURLDataManager::AddDataSource, make_scoped_refptr(html_source))); } // static RefCountedMemory* ExtensionsUI::GetFaviconResourceBytes() { return ResourceBundle::GetSharedInstance(). LoadDataResourceBytes(IDR_PLUGIN); } // static void ExtensionsUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kExtensionsUIDeveloperMode, false); }
39.194517
80
0.720115
[ "render", "vector" ]
eaef5c066cdda0db81e4249abde97864f2488dbb
2,811
cpp
C++
Atcoder/ABC 159/E.cpp
JanaSabuj/cpmaster
d943780c7ca4badbefbce2d300848343c4032650
[ "MIT" ]
1
2020-11-29T08:36:38.000Z
2020-11-29T08:36:38.000Z
Atcoder/ABC 159/E.cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
Atcoder/ABC 159/E.cpp
Sahu49/CompetitiveProgramming
adf11a546f81878ad2975926219af84deb3414e8
[ "MIT" ]
null
null
null
/*--------------------------"SABUJ-JANA"------"JADAVPUR UNIVERSITY"--------*/ /*-------------------------------@greenindia-----------------------------------*/ // // _____ _ _ _ // / ____| | | (_) | | // | (___ __ _| |__ _ _ _ | | __ _ _ __ __ _ // \___ \ / _` | '_ \| | | | | _ | |/ _` | '_ \ / _` | // ____) | (_| | |_) | |_| | | | |__| | (_| | | | | (_| | // |_____/ \__,_|_.__/ \__,_| | \____/ \__,_|_| |_|\__,_| // _/ | // |__/ /*---------------------- Magic. Do not touch.-----------------------------*/ /*------------------------------God is Great/\---------------------------------*/ #include <bits/stdc++.h> using namespace std; #define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) //cout<<fixed<<showpoint<<setprecision(12)<<ans<<endl; #define int long long int #define double long double #define PI acos(-1) void print1d(const vector<int>& vec) {for (auto val : vec) {cerr << val << " ";} cerr << endl;} void print2d(const vector<vector<int>>& vec) {for (auto row : vec) {for (auto val : row) {cerr << val << " ";} cerr << endl;}} signed main() { // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("error.txt", "w", stderr); // #endif crap; int h, w, k; cin >> h >> w >> k; int white = 0; vector<vector<int>> arr(h, vector<int>(w)); for (int i = 0; i < h; i++) { string str; cin >> str; for (int j = 0; j < w; j++) { arr[i][j] = str[j] - '0'; white += arr[i][j]; } } if (white <= k) { cout << 0 << endl; return 0; } vector<vector<int>> cum(h, vector<int>(w)); for (int j = 0; j < w; j++) { for (int i = 0; i < h; i++) { if (i == 0) cum[i][j] = arr[i][j]; else cum[i][j] = cum[i - 1][j] + arr[i][j]; } } print2d(cum); int req = INT_MAX; for (int mask = 1; mask <= (1 << (h - 1)); mask++) { int ans = 0; vector<int> cuts; for (int i = 0; i < h; i++) { if (mask & (1 << i)) cuts.push_back(i); } int sz = cuts.size(); ans += sz; vector<vector<int>> rows(sz + 1, vector<int>(w)); for (int j = 0; j < w; j++) { for (int i = 0; i <= sz; i++ ) { if (i == 0) rows[i][j] = cum[cuts[i]][j]; else if (i == sz) rows[i][j] = cum[h - 1][j] - cum[cuts[sz - 1]][j]; else rows[i][j] = cum[cuts[i]][j] - cum[cuts[i - 1]][j]; } } int curr[sz + 1]; for (int i = 0; i <= sz; i++) curr[i] = rows[i][0]; memset(curr,0,sizeof(curr)); for (int j = 1; j < w; j++) { for (int i = 0; i <= sz; i++) { curr[i] += rows[i][j]; if (curr[i] > k) { ans++; for (int i = 0; i <= sz; i++) curr[i] = rows[i][j]; break; } } } req = min(ans, req); } cout << req << endl; return 0; }
22.488
126
0.412665
[ "vector" ]
eaf0f74863f03b17d31c439e724ff3751fcf9614
718
cpp
C++
BashuOJ-Code/4585.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/4585.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/4585.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<vector> #define ri register int #define ll long long using namespace std; const int INF=0x7fffffff/2; int n,dist[205][205],f[205]; inline int getint() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } int main() { n=getint(); for(ri i=1;i<n;i++) for(ri j=i+1;j<=n;j++)dist[i][j]=dist[j][i]=getint(); for(ri i=2;i<=n;i++)f[i]=INF; f[1]=0; for(ri i=2;i<=n;i++) for(ri j=1;j<i;j++)f[i]=min(f[i],f[j]+dist[i][j]); printf("%d",f[n]); return 0; }
19.944444
57
0.60585
[ "vector" ]
46ac98be0a4a747e53adde57ccda100b683b62d4
303
hpp
C++
src/cartridge/Cartridge.hpp
zombre98/gameboy-emulator
7741d8c5f77a94c91a24c9fdeeb7c6dbfa525cba
[ "MIT" ]
null
null
null
src/cartridge/Cartridge.hpp
zombre98/gameboy-emulator
7741d8c5f77a94c91a24c9fdeeb7c6dbfa525cba
[ "MIT" ]
null
null
null
src/cartridge/Cartridge.hpp
zombre98/gameboy-emulator
7741d8c5f77a94c91a24c9fdeeb7c6dbfa525cba
[ "MIT" ]
null
null
null
// // Created by Thomas Burgaud on 2019-01-11. // #pragma once #include <string> #include <vector> namespace gb { class Cartridge { public: Cartridge(std::string const &romPath); ~Cartridge() = default; bool init(); private: std::string const &_romPath; std::vector<char> _cart; }; }
13.173913
43
0.660066
[ "vector" ]
46b045d8e796195868e19ef11e4cfb586bab1030
4,281
cpp
C++
Gameplay/EnemyController.cpp
Akita-Interactive/Hachiko-Engine
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
[ "MIT" ]
5
2022-02-10T23:31:11.000Z
2022-02-11T19:32:38.000Z
Gameplay/EnemyController.cpp
Akita-Interactive/Hachiko-Engine
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
[ "MIT" ]
null
null
null
Gameplay/EnemyController.cpp
Akita-Interactive/Hachiko-Engine
0e3e0377ac5c8f5b15c525c8fcff384e9c92c14b
[ "MIT" ]
null
null
null
#include "scriptingUtil/gameplaypch.h" #include "EnemyController.h" #include "PlayerController.h" #include "Stats.h" #include <components/ComponentTransform.h> #include <components/ComponentAgent.h> Hachiko::Scripting::EnemyController::EnemyController(GameObject* game_object) : Script(game_object, "EnemyController") , _aggro_range(4) , _attack_range(1.5f) , _spawn_pos(0.0f, 0.0f, 0.0f) , _spawn_is_initial(false) , _stats(2, 2, 5, 10) , _player(nullptr) { } void Hachiko::Scripting::EnemyController::OnAwake() { game_object->GetComponent<ComponentAgent>()->AddToCrowd(); _attack_range = 1.5f; _stun_time = 0.0f; _is_stunned = false; } void Hachiko::Scripting::EnemyController::OnStart() { // TODO: Find by name in scene. _player_controller = _player->GetComponent<PlayerController>(); _acceleration = game_object->GetComponent<ComponentAgent>()->GetMaxAcceleration(); _speed = game_object->GetComponent<ComponentAgent>()->GetMaxSpeed(); transform = game_object->GetTransform(); if (_spawn_is_initial) { _spawn_pos = transform->GetGlobalPosition(); } } void Hachiko::Scripting::EnemyController::OnUpdate() { if (!_stats.IsAlive()) { return; } if (_is_stunned) { if (_stun_time > 0.0f) { _stun_time -= Time::DeltaTime(); RecieveKnockback(); return; } _is_stunned = false; ComponentAgent* agc = game_object->GetComponent<ComponentAgent>(); // We set the variables back to normal agc->SetMaxAcceleration(_acceleration); agc->SetMaxSpeed(_speed); } _player_pos = _player->GetTransform()->GetGlobalPosition(); _current_pos = transform->GetGlobalPosition(); float dist_to_player = _current_pos.Distance(_player_pos); if (dist_to_player <= _aggro_range) { if (dist_to_player <= _attack_range) { Attack(); } else { ChasePlayer(); } } else { GoBack(); } if (_stats._current_hp <= 0) { DestroyEntity(); _stats._is_alive = false; } } Hachiko::Scripting::Stats& Hachiko::Scripting::EnemyController::GetStats() { return _stats; } void Hachiko::Scripting::EnemyController::ReceiveDamage(int damage, float3 direction) { _stats.ReceiveDamage(damage); _is_stunned = true; _stun_time = 1.0f; // Once we have weapons stun duration might be moved to each weapon stat float knockback_intensity = 0.2f; // same with knock-back intensity _knockback_pos = transform->GetGlobalPosition() + (direction * knockback_intensity); } void Hachiko::Scripting::EnemyController::Attack() { _attack_cooldown -= Time::DeltaTime(); _attack_cooldown = _attack_cooldown < 0.0f ? 0.0f : _attack_cooldown; if (_attack_cooldown > 0.0f) { return; } _player_controller->_stats.ReceiveDamage(_stats._attack_power); _attack_cooldown = _stats._attack_cd; } void Hachiko::Scripting::EnemyController::ChasePlayer() { _target_pos = Navigation::GetCorrectedPosition(_player_pos, math::float3(10.0f, 10.0f, 10.0f)); transform->LookAtTarget(_target_pos); MoveInNavmesh(); } void Hachiko::Scripting::EnemyController::GoBack() { _target_pos = Navigation::GetCorrectedPosition(_spawn_pos, math::float3(10.0f, 10.0f, 10.0f)); transform->LookAtTarget(_target_pos); MoveInNavmesh(); } void Hachiko::Scripting::EnemyController::Stop() { float3 temp_pos = transform->GetGlobalPosition(); _target_pos = Navigation::GetCorrectedPosition(temp_pos, math::float3(1.0f, 1.0f, 1.0f)); MoveInNavmesh(); } void Hachiko::Scripting::EnemyController::RecieveKnockback() { ComponentAgent* agc = game_object->GetComponent<ComponentAgent>(); _target_pos = Navigation::GetCorrectedPosition(_knockback_pos, math::float3(5.0f, 1.0f, 5.0f)); // We exagerate the movement agc->SetMaxAcceleration(50.0f); agc->SetMaxSpeed(30.0f); agc->SetTargetPosition(_target_pos); } void Hachiko::Scripting::EnemyController::Move() { math::float3 dir = (_target_pos - game_object->GetComponent<ComponentTransform>()->GetGlobalPosition()).Normalized(); math::float3 step = dir * _stats._move_speed; _current_pos += step; transform->SetGlobalPosition(_current_pos); } void Hachiko::Scripting::EnemyController::MoveInNavmesh() { ComponentAgent* agc = game_object->GetComponent<ComponentAgent>(); agc->SetTargetPosition(_target_pos); } void Hachiko::Scripting::EnemyController::DestroyEntity() { game_object->SetActive(false); }
25.331361
118
0.742116
[ "transform" ]
46c7c4ebc78c2ff914a83da92b4ddec6a38597a7
8,672
cpp
C++
src/dlib/test/statistics.cpp
cpearce/HARM
1e629099bbaa0203b19fe9007a71d9ab9c938be0
[ "Apache-2.0" ]
1
2016-10-11T18:37:52.000Z
2016-10-11T18:37:52.000Z
src/dlib/test/statistics.cpp
wsgan001/HARM
1e629099bbaa0203b19fe9007a71d9ab9c938be0
[ "Apache-2.0" ]
2
2017-03-27T22:58:45.000Z
2017-03-28T04:46:52.000Z
src/dlib/test/statistics.cpp
wsgan001/HARM
1e629099bbaa0203b19fe9007a71d9ab9c938be0
[ "Apache-2.0" ]
4
2016-04-19T06:15:01.000Z
2020-01-02T11:11:57.000Z
// Copyright (C) 2010 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <dlib/statistics.h> #include <dlib/rand.h> #include <algorithm> #include "tester.h" namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.statistics"); class statistics_tester : public tester { public: statistics_tester ( ) : tester ("test_statistics", "Runs tests on the statistics component.") {} void test_random_subset_selector () { random_subset_selector<double> rand_set; for (int j = 0; j < 30; ++j) { print_spinner(); running_stats<double> rs, rs2; rand_set.set_max_size(1000); for (double i = 0; i < 100000; ++i) { rs.add(i); rand_set.add(i); } for (unsigned long i = 0; i < rand_set.size(); ++i) rs2.add(rand_set[i]); dlog << LDEBUG << "true mean: " << rs.mean(); dlog << LDEBUG << "true sampled: " << rs2.mean(); double ratio = rs.mean()/rs2.mean(); DLIB_TEST_MSG(0.96 < ratio && ratio < 1.04, " ratio: " << ratio); } { random_subset_selector<int> r1, r2; r1.set_max_size(300); for (int i = 0; i < 4000; ++i) r1.add(i); ostringstream sout; serialize(r1, sout); istringstream sin(sout.str()); deserialize(r2, sin); DLIB_TEST(r1.size() == r2.size()); DLIB_TEST(r1.max_size() == r2.max_size()); DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts()); DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin())); for (int i = 0; i < 4000; ++i) { r1.add(i); r2.add(i); } DLIB_TEST(r1.size() == r2.size()); DLIB_TEST(r1.max_size() == r2.max_size()); DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts()); DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin())); } } void test_random_subset_selector2 () { random_subset_selector<double> rand_set; DLIB_TEST(rand_set.next_add_accepts() == false); DLIB_TEST(rand_set.size() == 0); DLIB_TEST(rand_set.max_size() == 0); for (int j = 0; j < 30; ++j) { print_spinner(); running_stats<double> rs, rs2; rand_set.set_max_size(1000); DLIB_TEST(rand_set.next_add_accepts() == true); for (double i = 0; i < 100000; ++i) { rs.add(i); if (rand_set.next_add_accepts()) rand_set.add(i); else rand_set.add(); } DLIB_TEST(rand_set.size() == 1000); DLIB_TEST(rand_set.max_size() == 1000); for (unsigned long i = 0; i < rand_set.size(); ++i) rs2.add(rand_set[i]); dlog << LDEBUG << "true mean: " << rs.mean(); dlog << LDEBUG << "true sampled: " << rs2.mean(); double ratio = rs.mean()/rs2.mean(); DLIB_TEST_MSG(0.96 < ratio && ratio < 1.04, " ratio: " << ratio); } } void test_running_covariance ( ) { dlib::rand rnd; std::vector<matrix<double,0,1> > vects; running_covariance<matrix<double,0,1> > cov, cov2; DLIB_TEST(cov.in_vector_size() == 0); for (unsigned long dims = 1; dims < 5; ++dims) { for (unsigned long samps = 2; samps < 10; ++samps) { vects.clear(); cov.clear(); DLIB_TEST(cov.in_vector_size() == 0); for (unsigned long i = 0; i < samps; ++i) { vects.push_back(randm(dims,1,rnd)); cov.add(vects.back()); } DLIB_TEST(cov.in_vector_size() == (long)dims); DLIB_TEST(equal(mean(vector_to_matrix(vects)), cov.mean())); DLIB_TEST_MSG(equal(covariance(vector_to_matrix(vects)), cov.covariance()), max(abs(covariance(vector_to_matrix(vects)) - cov.covariance())) << " dims = " << dims << " samps = " << samps ); } } for (unsigned long dims = 1; dims < 5; ++dims) { for (unsigned long samps = 2; samps < 10; ++samps) { vects.clear(); cov.clear(); cov2.clear(); DLIB_TEST(cov.in_vector_size() == 0); for (unsigned long i = 0; i < samps; ++i) { vects.push_back(randm(dims,1,rnd)); if ((i%2) == 0) cov.add(vects.back()); else cov2.add(vects.back()); } DLIB_TEST((cov+cov2).in_vector_size() == (long)dims); DLIB_TEST(equal(mean(vector_to_matrix(vects)), (cov+cov2).mean())); DLIB_TEST_MSG(equal(covariance(vector_to_matrix(vects)), (cov+cov2).covariance()), max(abs(covariance(vector_to_matrix(vects)) - (cov+cov2).covariance())) << " dims = " << dims << " samps = " << samps ); } } } void test_running_stats() { print_spinner(); running_stats<double> rs, rs2; running_scalar_covariance<double> rsc1, rsc2; for (double i = 0; i < 100; ++i) { rs.add(i); rsc1.add(i,i); rsc2.add(i,i); rsc2.add(i,-i); } // make sure the running_stats and running_scalar_covariance agree DLIB_TEST_MSG(std::abs(rs.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs.mean() - rsc1.mean_x())); DLIB_TEST(std::abs(rs.mean() - rsc1.mean_y()) < 1e-10); DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_x()) < 1e-10); DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_y()) < 1e-10); DLIB_TEST(std::abs(rs.variance() - rsc1.variance_x()) < 1e-10); DLIB_TEST(std::abs(rs.variance() - rsc1.variance_y()) < 1e-10); DLIB_TEST(rs.current_n() == rsc1.current_n()); DLIB_TEST(std::abs(rsc1.correlation() - 1) < 1e-10); DLIB_TEST(std::abs(rsc2.correlation() - 0) < 1e-10); // test serialization of running_stats ostringstream sout; serialize(rs, sout); istringstream sin(sout.str()); deserialize(rs2, sin); // make sure the running_stats and running_scalar_covariance agree DLIB_TEST_MSG(std::abs(rs2.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs2.mean() - rsc1.mean_x())); DLIB_TEST(std::abs(rs2.mean() - rsc1.mean_y()) < 1e-10); DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_x()) < 1e-10); DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_y()) < 1e-10); DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_x()) < 1e-10); DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_y()) < 1e-10); DLIB_TEST(rs2.current_n() == rsc1.current_n()); } void perform_test ( ) { test_random_subset_selector(); test_random_subset_selector2(); test_running_covariance(); test_running_stats(); } } a; }
34.141732
111
0.440613
[ "vector" ]
46cbf5c0432fe698ee456bd9e1c978c5f41ce71b
132,648
cpp
C++
server/sql_utils_container.cpp
bolorerdenee/griddb
993350605124eef8ec9df122aa958d5d6b8fc370
[ "Apache-2.0" ]
646
2016-02-24T13:44:26.000Z
2022-03-30T19:24:55.000Z
server/sql_utils_container.cpp
bolorerdenee/griddb
993350605124eef8ec9df122aa958d5d6b8fc370
[ "Apache-2.0" ]
57
2020-06-20T01:17:56.000Z
2022-03-12T02:22:48.000Z
server/sql_utils_container.cpp
bolorerdenee/griddb
993350605124eef8ec9df122aa958d5d6b8fc370
[ "Apache-2.0" ]
1,697
2020-06-17T08:43:28.000Z
2022-03-31T21:25:58.000Z
/* Copyright (c) 2017 TOSHIBA Digital Solutions Corporation This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef _WIN32 #define NOGDI #endif #include "sql_utils_container_impl.h" #include "sql_operator_utils.h" #include "query.h" #include "sql_execution.h" #include "sql_execution_manager.h" #include "nosql_utils.h" util::AllocUniquePtr<SQLContainerUtils::ScanCursor>::ReturnType SQLContainerUtils::ScanCursor::create( util::StdAllocator<void, void> &alloc, const Source &source) { util::AllocUniquePtr<ScanCursor> ptr( ALLOC_NEW(alloc) SQLContainerImpl::CursorImpl(source), alloc); return ptr; } SQLContainerUtils::ScanCursor::~ScanCursor() { } SQLContainerUtils::ScanCursor::Source::Source( util::StackAllocator &alloc, SQLValues::LatchHolder &latchHolder, const SQLOps::ContainerLocation &location, const ColumnTypeList *columnTypeList, const OpContext::Source &cxtSrc) : alloc_(alloc), latchHolder_(latchHolder), location_(location), columnTypeList_(columnTypeList), indexLimit_(-1), memLimit_(-1), cxtSrc_(cxtSrc) { } SQLContainerUtils::ScanCursor::LatchTarget::LatchTarget(ScanCursor *cursor) : cursor_(cursor) { } void SQLContainerUtils::ScanCursor::LatchTarget::unlatch() throw() { if (cursor_ != NULL) { cursor_->unlatch(); } } void SQLContainerUtils::ScanCursor::LatchTarget::close() throw() { if (cursor_ != NULL) { cursor_->close(); } } size_t SQLContainerUtils::ContainerUtils::findMaxStringLength( const ResourceSet *resourceSet) { do { if (resourceSet == NULL) { break; } DataStore *dataStore = resourceSet->getDataStore(); if (dataStore == NULL) { break; } return dataStore->getValueLimitConfig().getLimitSmallSize(); } while (false); return 0; } bool SQLContainerUtils::ContainerUtils::toTupleColumnType( uint8_t src, bool nullable, TupleColumnType &dest, bool failOnUnknown) { typedef SQLContainerImpl::ContainerValueUtils Utils; dest = Utils::toTupleColumnType(src, nullable); const bool converted = !SQLValues::TypeUtils::isAny(dest) && !SQLValues::TypeUtils::isNull(dest); if (!converted && failOnUnknown) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return converted; } int32_t SQLContainerUtils::ContainerUtils::toSQLColumnType( TupleColumnType type) { typedef SQLContainerImpl::ContainerValueUtils Utils; SQLContainerImpl::ContainerColumnType typeAsContainer; const bool failOnError = true; Utils::toContainerColumnType(type, typeAsContainer, failOnError); return MetaProcessor::SQLMetaUtils::toSQLColumnType(typeAsContainer); } bool SQLContainerUtils::ContainerUtils::predicateToMetaTarget( SQLValues::ValueContext &cxt, const SQLExprs::Expression *pred, uint32_t partitionIdColumn, uint32_t containerNameColumn, uint32_t containerIdColumn, PartitionId partitionCount, PartitionId &partitionId, bool &placeholderAffected) { partitionId = UNDEF_PARTITIONID; placeholderAffected = false; const SQLExprs::ExprFactory &factory = SQLExprs::ExprFactory::getDefaultFactory(); if (containerNameColumn != UNDEF_COLUMNID) { TupleValue containerName; if (!SQLExprs::ExprRewriter::predicateToExtContainerName( cxt, factory, pred, UNDEF_COLUMNID, containerNameColumn, NULL, containerName, placeholderAffected)) { return false; } const TupleString::BufferInfo &nameBuf = TupleString(containerName).getBuffer(); try { FullContainerKey containerKey( cxt.getAllocator(), KeyConstraint::getNoLimitKeyConstraint(), GS_PUBLIC_DB_ID, nameBuf.first, nameBuf.second); const ContainerHashMode hashMode = CONTAINER_HASH_MODE_CRC32; partitionId = DataStore::resolvePartitionId( cxt.getAllocator(), containerKey, partitionCount, hashMode); } catch (UserException&) { return false; } return true; } else if (containerIdColumn != UNDEF_COLUMNID) { ContainerId containerId = UNDEF_CONTAINERID; return SQLExprs::ExprRewriter::predicateToContainerId( cxt, factory, pred, partitionIdColumn, containerIdColumn, partitionId, containerId, placeholderAffected); } else { return false; } } SQLExprs::SyntaxExpr SQLContainerUtils::ContainerUtils::tqlToPredExpr( util::StackAllocator &alloc, const Query &query) { return SQLContainerImpl::TQLTool::genPredExpr(alloc, query); } SQLContainerImpl::CursorImpl::CursorImpl(const Source &source) : location_(source.location_), outIndex_(std::numeric_limits<uint32_t>::max()), cxtSrc_(source.cxtSrc_), mergeMode_(MergeMode::END_MODE), closed_(false), rowIdFiltering_(false), resultSetPreserving_(false), containerExpired_(false), indexLost_(false), resultSetLost_(false), nullsStatsChanged_(false), resultSetId_(UNDEF_RESULTSETID), lastPartitionId_(UNDEF_PARTITIONID), lastDataStore_(NULL), container_(NULL), containerType_(UNDEF_CONTAINER), schemaVersionId_(UNDEF_SCHEMAVERSIONID), nextContainerId_(UNDEF_CONTAINERID), maxRowId_(UNDEF_ROWID), generalRowArray_(NULL), plainRowArray_(NULL), row_(NULL), latchHolder_(source.latchHolder_), scanner_(NULL), initialNullsStats_(source.alloc_), lastNullsStats_(source.alloc_), indexLimit_(source.indexLimit_), memLimit_(source.memLimit_), totalSearchCount_(0), partialExecSizeRange_(source.partialExecSizeRange_), lastPartialExecSize_(partialExecSizeRange_.first), indexSelection_(NULL) { } SQLContainerImpl::CursorImpl::~CursorImpl() { latchHolder_.reset(NULL); destroy(false); } void SQLContainerImpl::CursorImpl::unlatch() throw() { finishScope(); } void SQLContainerImpl::CursorImpl::close() throw() { destroy(true); } void SQLContainerImpl::CursorImpl::destroy(bool withResultSet) throw() { unlatch(); if (closed_) { return; } closed_ = true; destroyUpdateRowIdHandler(); if (resultSetId_ == UNDEF_RESULTSETID) { return; } const ResultSetId rsId = resultSetId_; const PartitionId partitionId = lastPartitionId_; DataStore *dataStore = lastDataStore_; resultSetId_ = UNDEF_RESULTSETID; lastPartitionId_ = UNDEF_PARTITIONID; lastDataStore_ = NULL; if (withResultSet) { dataStore->closeResultSet(partitionId, rsId); } } bool SQLContainerImpl::CursorImpl::scanFull( OpContext &cxt, const Projection &proj) { startScope(cxt); if (getContainer() == NULL) { return true; } BaseContainer &container = resolveContainer(); TransactionContext &txn = resolveTransactionContext(); LocalCursor &localCursor = LocalCursor::resolve(cxt); RowIdFilter *rowIdFilter = checkRowIdFilter(cxt, txn, container, localCursor, true); ContainerRowScanner *scanner = tryCreateScanner(cxt, proj, container, rowIdFilter); BtreeSearchContext sc(cxt.getAllocator(), container.getRowIdColumnId()); preparePartialSearch(cxt, sc, NULL); const OutputOrder outputOrder = ORDER_UNDEFINED; switch (container.getContainerType()) { case COLLECTION_CONTAINER: static_cast<Collection&>(container).scanRowIdIndex(txn, sc, *scanner); break; case TIME_SERIES_CONTAINER: static_cast<TimeSeries&>(container).scanRowIdIndex( txn, sc, outputOrder, *scanner); break; default: assert(false); break; } const bool finished = finishPartialSearch(cxt, sc, false); if (!finished) { return finished; } updateScanner(cxt, finished); return finished; } bool SQLContainerImpl::CursorImpl::scanRange( OpContext &cxt, const Projection &proj) { startScope(cxt); if (getContainer() == NULL || isIndexLost()) { return true; } BaseContainer &container = resolveContainer(); TransactionContext &txn = resolveTransactionContext(); ResultSet &resultSet = resolveResultSet(); LocalCursor &localCursor = LocalCursor::resolve(cxt); OIdTable *oIdTable = localCursor.findOIdTable(); RowIdFilter *rowIdFilter = checkRowIdFilter(cxt, txn, container, localCursor, false); const uint32_t index = 1; TupleListReader &subReader = cxt.getReader(index, 1); if (checkUpdates(cxt, resultSet) || oIdTable != NULL) { const bool found = (oIdTable != NULL); oIdTable = &localCursor.resolveOIdTable(cxt, mergeMode_); if (!found) { const bool forPipe = true; if (SQLOps::OpCodeBuilder::findAggregationProjection( proj, &forPipe) != NULL) { cxt.getExprContext().initializeAggregationValues(); } OIdTable::Reader reader(subReader, cxt.getInputColumnList(index)); oIdTable->load(reader); } rowIdFilter = &localCursor.resolveRowIdFilter( cxt, getMaxRowId(txn, container)); } ContainerRowScanner *scanner = tryCreateScanner(cxt, proj, container, rowIdFilter); clearResultSetPreserving(resultSet, false); util::StackAllocator &alloc = txn.getDefaultAllocator(); SearchResult result(alloc); uint64_t suspendLimit = cxt.getNextCountForSuspend(); bool finished; if (oIdTable != NULL) { if (updateRowIdHandler_->apply(*oIdTable, suspendLimit)) { oIdTable->popAll( result, suspendLimit, container.getNormalRowArrayNum()); finished = oIdTable->isEmpty(); } else { finished = false; } } else { OIdTable::Reader reader( cxt.getReader(index), cxt.getInputColumnList(index)); OIdTable::readAll( result, container.getNormalRowArrayNum(), OIdTable::Source::detectLarge(container.getDataStore()), mergeMode_, container.getNormalRowArrayNum(), reader); finished = !reader.exists(); } acceptSearchResult(cxt, result, NULL, scanner, NULL); if (finished) { finishRowIdFilter(cxt, rowIdFilter); } else { activateResultSetPreserving(resultSet); } updateScanner(cxt, finished); return finished; } bool SQLContainerImpl::CursorImpl::scanIndex( OpContext &cxt, const Projection &proj, const SQLExprs::IndexConditionList &condList) { static_cast<void>(proj); startScope(cxt); if (getContainer() == NULL) { return true; } BaseContainer &container = resolveContainer(); TransactionContext &txn = resolveTransactionContext(); util::StackAllocator &alloc = txn.getDefaultAllocator(); util::Vector<uint32_t> indexColumnList(alloc); const IndexType indexType = acceptIndexCond(cxt, condList, indexColumnList); SQLOps::OpProfilerIndexEntry *profilerEntry = cxt.getIndexProfiler(); bool finished = true; SearchResult result(alloc); if (indexType == SQLType::INDEX_TREE_RANGE || indexType == SQLType::INDEX_TREE_EQ) { BtreeSearchContext sc(alloc, indexColumnList); preparePartialSearch(cxt, sc, &condList); if (profilerEntry != NULL) { profilerEntry->startSearch(); } if (container.getContainerType() == TIME_SERIES_CONTAINER) { TimeSeries &timeSeries = static_cast<TimeSeries&>(container); if (condList.front().column_ == ColumnInfo::ROW_KEY_COLUMN_ID) { const SearchResult::OIdListRef oIdListRef = result.getOIdListRef(true); timeSeries.searchRowIdIndexAsRowArray( txn, sc, *oIdListRef.first, *oIdListRef.second); } else { BtreeSearchContext orgSc(alloc, indexColumnList); setUpSearchContext(cxt, txn, condList, orgSc, container); const SearchResult::OIdListRef oIdListRef = result.getOIdListRef(false); timeSeries.searchColumnIdIndex( txn, sc, orgSc, *oIdListRef.first, *oIdListRef.second); } } else { const SearchResult::OIdListRef oIdListRef = result.getOIdListRef(false); container.searchColumnIdIndex( txn, sc, *oIdListRef.first, *oIdListRef.second); } if (profilerEntry != NULL) { profilerEntry->finishSearch(); } finished = finishPartialSearch(cxt, sc, true); } LocalCursor &localCursor = LocalCursor::resolve(cxt); OIdTable &oIdTable = localCursor.resolveOIdTable(cxt, mergeMode_); acceptSearchResult(cxt, result, &condList, NULL, &oIdTable); return finished; } bool SQLContainerImpl::CursorImpl::scanMeta( OpContext &cxt, const Projection &proj, const Expression *pred) { startScope(cxt); cxt.closeLocalTupleList(outIndex_); cxt.createLocalTupleList(outIndex_); util::StackAllocator &alloc = cxt.getAllocator(); TransactionContext &txn = resolveTransactionContext(); DataStore *dataStore = getDataStore(cxt); assert(dataStore != NULL); util::String dbName(alloc); FullContainerKey *containerKey = predicateToContainerKey( cxt.getValueContext(), txn, *dataStore, pred, location_, dbName); MetaProcessorSource source(location_.dbVersionId_, dbName.c_str()); source.dataStore_ = dataStore; source.eventContext_= getEventContext(cxt); source.transactionManager_ = getTransactionManager(cxt); source.transactionService_ = getTransactionService(cxt); source.partitionTable_ = getPartitionTable(cxt); source.sqlService_ = getSQLService(cxt); source.sqlExecutionManager_ = getExecutionManager(cxt); source.resourceSet_ = source.sqlExecutionManager_->getResourceSet(); const bool forCore = true; MetaScanHandler handler(cxt, *this, proj); MetaProcessor proc(txn, location_.id_, forCore); proc.setNextContainerId(getNextContainerId()); proc.setContainerLimit(cxt.getNextCountForSuspend()); proc.setContainerKey(containerKey); proc.scan(txn, source, handler); setNextContainerId(proc.getNextContainerId()); cxt.closeLocalWriter(outIndex_); return !proc.isSuspended(); } void SQLContainerImpl::CursorImpl::finishIndexScan( OpContext &cxt) { LocalCursor &localCursor = LocalCursor::resolve(cxt); OIdTable *oIdTable = localCursor.findOIdTable(); if (oIdTable != NULL) { const uint32_t index = 0; OIdTable::Writer writer( cxt.getWriter(index), cxt.getOutputColumnList(index)); oIdTable->save(writer); } } void SQLContainerImpl::CursorImpl::getIndexSpec( OpContext &cxt, SQLExprs::IndexSelector &selector) { startScope(cxt); TransactionContext &txn = resolveTransactionContext(); BaseContainer *container = getContainer(); if (container == NULL) { return; } const TupleColumnList &columnList = cxt.getInputColumnList(0); assignIndexInfo(txn, *container, selector, columnList); } bool SQLContainerImpl::CursorImpl::isIndexLost() { return indexLost_; } void SQLContainerImpl::CursorImpl::setIndexSelection( const SQLExprs::IndexSelector &selector) { indexSelection_ = &selector; } const SQLExprs::IndexSelector& SQLContainerImpl::CursorImpl::getIndexSelection() { if (indexSelection_ == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return *indexSelection_; } void SQLContainerImpl::CursorImpl::setRowIdFiltering() { rowIdFiltering_ = true; } bool SQLContainerImpl::CursorImpl::isRowIdFiltering() { return rowIdFiltering_; } uint32_t SQLContainerImpl::CursorImpl::getOutputIndex() { return outIndex_; } void SQLContainerImpl::CursorImpl::setOutputIndex(uint32_t index) { outIndex_ = index; } void SQLContainerImpl::CursorImpl::setMergeMode(MergeMode::Type mode) { assert(mergeMode_ == MergeMode::END_MODE); mergeMode_ = mode; } void SQLContainerImpl::CursorImpl::startScope(OpContext &cxt) { if (scope_.get() != NULL) { return; } scope_ = ALLOC_UNIQUE(cxt.getAllocator(), CursorScope, cxt, *this); } void SQLContainerImpl::CursorImpl::finishScope() throw() { scope_.reset(); } SQLContainerImpl::CursorScope& SQLContainerImpl::CursorImpl::resolveScope() { if (scope_.get() == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return *scope_; } ContainerId SQLContainerImpl::CursorImpl::getNextContainerId() const { if (nextContainerId_ == UNDEF_CONTAINERID) { return 0; } return nextContainerId_; } void SQLContainerImpl::CursorImpl::setNextContainerId(ContainerId containerId) { nextContainerId_ = containerId; } BaseContainer& SQLContainerImpl::CursorImpl::resolveContainer() { if (container_ == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return *container_; } BaseContainer* SQLContainerImpl::CursorImpl::getContainer() { assert(scope_.get() != NULL); return container_; } TransactionContext& SQLContainerImpl::CursorImpl::resolveTransactionContext() { return resolveScope().getTransactionContext(); } ResultSet& SQLContainerImpl::CursorImpl::resolveResultSet() { return resolveScope().getResultSet(); } template<BaseContainer::RowArrayType RAType> void SQLContainerImpl::CursorImpl::setRow( typename BaseContainer::RowArrayImpl< BaseContainer, RAType> &rowArrayImpl) { row_ = rowArrayImpl.getRow(); } bool SQLContainerImpl::CursorImpl::isValueNull(const ContainerColumn &column) { RowArray::Row row(row_, getRowArray()); return row.isNullValue(column.getColumnInfo()); } template<RowArrayType RAType, typename Ret, TupleColumnType T> Ret SQLContainerImpl::CursorImpl::getValueDirect( SQLValues::ValueContext &cxt, const ContainerColumn &column) { return DirectValueAccessor<T>().template access<RAType, Ret>( cxt, *this, column); } template<RowArrayType RAType> void SQLContainerImpl::CursorImpl::writeValue( SQLValues::ValueContext &cxt, TupleListWriter &writer, const TupleList::Column &destColumn, const ContainerColumn &srcColumn, bool forId) { if (!forId) { RowArray::Row row(row_, getRowArray()); if (row.isNullValue(srcColumn.getColumnInfo())) { writeValueAs<TupleTypes::TYPE_ANY>(writer, destColumn, TupleValue()); return; } } switch (srcColumn.getColumnInfo().getColumnType()) { case COLUMN_TYPE_STRING: writeValueAs<TupleTypes::TYPE_STRING>(writer, destColumn, getValueDirect< RAType, TupleString, TupleTypes::TYPE_STRING>( cxt, srcColumn)); break; case COLUMN_TYPE_BOOL: writeValueAs<TupleTypes::TYPE_BOOL>(writer, destColumn, getValueDirect< RAType, bool, TupleTypes::TYPE_BOOL>( cxt, srcColumn)); break; case COLUMN_TYPE_BYTE: writeValueAs<TupleTypes::TYPE_BYTE>(writer, destColumn, getValueDirect< RAType, int8_t, TupleTypes::TYPE_BYTE>( cxt, srcColumn)); break; case COLUMN_TYPE_SHORT: writeValueAs<TupleTypes::TYPE_SHORT>(writer, destColumn, getValueDirect< RAType, int16_t, TupleTypes::TYPE_SHORT>( cxt, srcColumn)); break; case COLUMN_TYPE_INT: writeValueAs<TupleTypes::TYPE_INTEGER>(writer, destColumn, getValueDirect< RAType, int32_t, TupleTypes::TYPE_INTEGER>( cxt, srcColumn)); break; case COLUMN_TYPE_LONG: writeValueAs<TupleTypes::TYPE_LONG>(writer, destColumn, getValueDirect< RAType, int64_t, TupleTypes::TYPE_LONG>( cxt, srcColumn)); break; case COLUMN_TYPE_FLOAT: writeValueAs<TupleTypes::TYPE_FLOAT>(writer, destColumn, getValueDirect< RAType, float, TupleTypes::TYPE_FLOAT>( cxt, srcColumn)); break; case COLUMN_TYPE_DOUBLE: writeValueAs<TupleTypes::TYPE_DOUBLE>(writer, destColumn, getValueDirect< RAType, double, TupleTypes::TYPE_DOUBLE>( cxt, srcColumn)); break; case COLUMN_TYPE_TIMESTAMP: { const int64_t value = getValueDirect< RAType, int64_t, TupleTypes::TYPE_TIMESTAMP>(cxt, srcColumn); if (forId) { writeValueAs<TupleTypes::TYPE_LONG>(writer, destColumn, value); } else { writeValueAs<TupleTypes::TYPE_TIMESTAMP>(writer, destColumn, value); } } break; case COLUMN_TYPE_BLOB: { VarContext::Scope scope(cxt.getVarContext()); writeValueAs<TupleTypes::TYPE_BLOB>(writer, destColumn, getValueDirect< RAType, TupleValue, TupleTypes::TYPE_BLOB>( cxt, srcColumn)); } break; default: writeValueAs<TupleTypes::TYPE_ANY>(writer, destColumn, TupleValue()); break; } } template<TupleColumnType T> void SQLContainerImpl::CursorImpl::writeValueAs( TupleListWriter &writer, const TupleList::Column &column, const typename SQLValues::TypeUtils::Traits<T>::ValueType &value) { WritableTuple tuple = writer.get(); tuple.set(column, ValueUtils::toAnyByValue<T>(value)); } ContainerRowScanner* SQLContainerImpl::CursorImpl::tryCreateScanner( OpContext &cxt, const Projection &proj, const BaseContainer &container, RowIdFilter *rowIdFilter) { if (!updateNullsStats(container) || !resolveResultSet().isPartialExecuteSuspend()) { scanner_ = NULL; if (updatorList_.get() != NULL) { updatorList_->clear(); } } if (scanner_ == NULL) { if (updatorList_.get() == NULL) { updatorList_ = UTIL_MAKE_LOCAL_UNIQUE( updatorList_, UpdatorList, cxt.getValueContext().getVarAllocator()); } scanner_ = &ScannerHandlerFactory::getInstance().create( cxt, *this, *getRowArray(), proj, rowIdFilter); cxt.setUpExprContext(); } updateScanner(cxt, false); return scanner_; } void SQLContainerImpl::CursorImpl::updateScanner( OpContext &cxt, bool finished) { for (UpdatorList::iterator it = updatorList_->begin(); it != updatorList_->end(); ++it) { it->first(cxt, it->second); } if (finished) { scanner_ = NULL; updatorList_->clear(); } } void SQLContainerImpl::CursorImpl::addScannerUpdator( const UpdatorEntry &updator) { updatorList_->push_back(updator); } void SQLContainerImpl::CursorImpl::clearResultSetPreserving( ResultSet &resultSet, bool force) { if (resultSetPreserving_ || (force && !resultSet.isRelease())) { resultSet.setPartialExecStatus(ResultSet::NOT_PARTIAL); resultSet.setResultType(RESULT_NONE); resultSet.resetExecCount(); assert(resultSet.isRelease()); resultSetPreserving_ = false; } } void SQLContainerImpl::CursorImpl::activateResultSetPreserving( ResultSet &resultSet) { if (resultSetPreserving_ || resultSet.isPartialExecuteSuspend()) { return; } resultSet.setPartialExecStatus(ResultSet::PARTIAL_SUSPENDED); resultSet.incrementExecCount(); resultSetPreserving_ = true; } void SQLContainerImpl::CursorImpl::checkInputInfo( OpContext &cxt, const BaseContainer &container) { const uint32_t count = container.getColumnNum(); const SQLOps::TupleColumnList &list = cxt.getInputColumnList(0); if (count != list.size()) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Inconsistent column count"); } for (uint32_t i = 0; i < count; i++) { const TupleColumnType expectedType = list[i].getType(); const TupleColumnType actualType = resolveColumnType( container.getColumnInfo(i), false, false); if (SQLValues::TypeUtils::toNonNullable(expectedType) != SQLValues::TypeUtils::toNonNullable(actualType)) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Inconsistent column type"); } } for (uint32_t i = 0; i < count; i++) { if (container.getColumnInfo(i).getColumnId() != i) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Inconsistent column ID"); } } } TupleColumnType SQLContainerImpl::CursorImpl::resolveColumnType( const ColumnInfo &columnInfo, bool used, bool withStats) { static_cast<void>(used); static_cast<void>(withStats); bool nullable; if (columnInfo.getColumnId() == Constants::SCHEMA_INVALID_COLUMN_ID) { nullable = false; } else { nullable = isColumnSchemaNullable(columnInfo); } return ContainerValueUtils::toTupleColumnType( columnInfo.getColumnType(), nullable); } bool SQLContainerImpl::CursorImpl::isColumnNonNullable(uint32_t pos) { if (nullsStatsChanged_) { return false; } return !getBit(lastNullsStats_, pos); } SQLContainerImpl::ContainerColumn SQLContainerImpl::CursorImpl::resolveColumn( BaseContainer &container, bool forId, uint32_t pos) { if (forId) { if (container.getContainerType() == TIME_SERIES_CONTAINER) { ContainerColumn column = RowArray::getRowIdColumn<TimeSeries>(container); ColumnInfo modInfo = column.getColumnInfo(); modInfo.setType(COLUMN_TYPE_TIMESTAMP, false); column.setColumnInfo(modInfo); return column; } else { return RowArray::getRowIdColumn<Collection>(container); } } else { const ColumnInfo &info = container.getColumnInfo(pos); if (container.getContainerType() == TIME_SERIES_CONTAINER) { return RowArray::getColumn<TimeSeries>(info); } else { return RowArray::getColumn<Collection>(info); } } } void SQLContainerImpl::CursorImpl::preparePartialSearch( OpContext &cxt, BtreeSearchContext &sc, const SQLExprs::IndexConditionList *targetCondList) { BaseContainer &container = resolveContainer(); ResultSet &resultSet = resolveResultSet(); TransactionContext &txn = resolveTransactionContext(); { const uint64_t restSize = cxt.getNextCountForSuspend(); const uint64_t execSize = std::min<uint64_t>(restSize, lastPartialExecSize_); cxt.setNextCountForSuspend(restSize - execSize); resultSet.setPartialExecuteSize(std::max<uint64_t>(execSize, 1)); } const bool lastSuspended = resultSet.isPartialExecuteSuspend(); const ResultSize suspendLimit = resultSet.getPartialExecuteSize(); const OutputOrder outputOrder = ORDER_UNDEFINED; clearResultSetPreserving(resultSet, false); if (targetCondList == NULL) { resultSet.setUpdateIdType(ResultSet::UPDATE_ID_NONE); } else { setUpSearchContext(cxt, txn, *targetCondList, sc, container); if (!lastSuspended) { resultSet.setPartialMode(true); } resultSet.setUpdateIdType(ResultSet::UPDATE_ID_OBJECT); } resultSet.rewritePartialContext( txn, sc, suspendLimit, outputOrder, 0, container, container.getNormalRowArrayNum()); } bool SQLContainerImpl::CursorImpl::finishPartialSearch( OpContext &cxt, BtreeSearchContext &sc, bool forIndex) { ResultSet &resultSet = resolveResultSet(); const bool lastSuspended = resultSet.isPartialExecuteSuspend(); ResultSize suspendLimit = resultSet.getPartialExecuteSize(); resultSet.setPartialContext(sc, suspendLimit, 0, MAP_TYPE_BTREE); if (!lastSuspended) { TransactionContext &txn = resolveTransactionContext(); BaseContainer &container = resolveContainer(); if (!forIndex) { resultSet.setLastRowId(getMaxRowId(txn, container)); } } const bool finished = (!sc.isSuspended() || cxt.isCompleted()); if (finished) { resultSet.setPartialExecStatus(ResultSet::PARTIAL_FINISH); } else { resultSet.setPartialExecStatus(ResultSet::PARTIAL_SUSPENDED); resultSet.incrementExecCount(); } prepareUpdateRowIdHandler(cxt, resultSet); resultSet.incrementReturnCount(); activateResultSetPreserving(resultSet); { CursorScope &scope = resolveScope(); const uint64_t elapsed = scope.getElapsedNanos(); const uint64_t threshold = 1000 * 1000; if (elapsed < threshold / 2) { lastPartialExecSize_ = std::min( lastPartialExecSize_ * 2, partialExecSizeRange_.second); } else { if (elapsed > threshold && resultSet.getPartialExecuteCount() <= scope.getStartPartialExecCount() + 1) { lastPartialExecSize_ = std::max( lastPartialExecSize_ / 2, partialExecSizeRange_.first); } cxt.setNextCountForSuspend(0); } } return finished; } bool SQLContainerImpl::CursorImpl::checkUpdates( OpContext &cxt, ResultSet &resultSet) { TupleUpdateRowIdHandler *handler = prepareUpdateRowIdHandler(cxt, resultSet); return (handler != NULL && handler->isUpdated()); } SQLContainerImpl::TupleUpdateRowIdHandler* SQLContainerImpl::CursorImpl::prepareUpdateRowIdHandler( OpContext &cxt, ResultSet &resultSet) { do { if (resultSet.getUpdateIdType() == ResultSet::UPDATE_ID_NONE) { break; } if (updateRowIdHandler_.get() != NULL && updateRowIdHandler_->isUpdated() && resultSet.getUpdateRowIdHandler() != NULL) { break; } TransactionContext &txn = resolveTransactionContext(); BaseContainer &container = resolveContainer(); if (updateRowIdHandler_.get() == NULL) { updateRowIdHandler_ = ALLOC_UNIQUE( cxt.getValueContext().getVarAllocator(), TupleUpdateRowIdHandler, cxtSrc_, getMaxRowId(txn, container)); } if (resultSet.getUpdateRowIdHandler() == NULL) { util::StackAllocator *rsAlloc = resultSet.getRSAllocator(); const size_t updateListThreshold = 0; resultSet.setUpdateRowIdHandler( updateRowIdHandler_->share(*rsAlloc), updateListThreshold); } if (container.checkRunTime(txn)) { updateRowIdHandler_->setUpdated(); } } while (false); return updateRowIdHandler_.get(); } void SQLContainerImpl::CursorImpl::setUpSearchContext( OpContext &cxt, TransactionContext &txn, const SQLExprs::IndexConditionList &targetCondList, BtreeSearchContext &sc, const BaseContainer &container) { const bool forKey = true; for (SQLExprs::IndexConditionList::const_iterator it = targetCondList.begin(); it != targetCondList.end(); ++it) { const SQLExprs::IndexCondition &cond = *it; const ContainerColumnType columnType = container.getColumnInfo(cond.column_).getColumnType(); if (cond.opType_ != SQLType::OP_EQ && cond.opType_ != SQLType::EXPR_BETWEEN) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } if (!SQLValues::TypeUtils::isNull(cond.valuePair_.first.getType())) { Value *value = ALLOC_NEW(cxt.getAllocator()) Value(); ContainerValueUtils::toContainerValue( cxt.getAllocator(), cond.valuePair_.first, *value); DSExpression::Operation opType; if (cond.opType_ == SQLType::OP_EQ) { opType = DSExpression::EQ; } else if (cond.inclusivePair_.first) { opType = DSExpression::GE; } else { opType = DSExpression::GT; } TermCondition c( columnType, columnType, opType, cond.column_, value->data(), value->size()); sc.addCondition(txn, c, forKey); } if (!SQLValues::TypeUtils::isNull(cond.valuePair_.second.getType())) { Value *value = ALLOC_NEW(cxt.getAllocator()) Value(); ContainerValueUtils::toContainerValue( cxt.getAllocator(), cond.valuePair_.second, *value); DSExpression::Operation opType; if (cond.inclusivePair_.second) { opType = DSExpression::LE; } else { opType = DSExpression::LT; } TermCondition c( columnType, columnType, opType, cond.column_, value->data(), value->size()); sc.addCondition(txn, c, forKey); } } } SQLType::IndexType SQLContainerImpl::CursorImpl::acceptIndexCond( OpContext &cxt, const SQLExprs::IndexConditionList &targetCondList, util::Vector<uint32_t> &indexColumnList) { if (isIndexLost()) { setIndexLost(cxt); return SQLType::END_INDEX; } if (targetCondList.size() <= 1) { assert(!targetCondList.empty()); const SQLExprs::IndexCondition &cond = targetCondList.front(); if (cond.isEmpty() || cond.equals(true)) { setIndexLost(cxt); return SQLType::END_INDEX; } else if (cond.isNull() || cond.equals(false)) { return SQLType::END_INDEX; } } const SQLExprs::IndexCondition &cond = targetCondList.front(); if (cond.specId_ > 0) { const SQLExprs::IndexSpec &spec = cond.spec_; indexColumnList.assign( spec.columnList_, spec.columnList_ + spec.columnCount_); } else { indexColumnList.push_back(cond.column_); } TransactionContext &txn = resolveTransactionContext(); BaseContainer &container = resolveContainer(); typedef util::Vector<IndexInfo> IndexInfoList; util::StackAllocator &alloc = txn.getDefaultAllocator(); IndexInfoList indexInfoList(alloc); getIndexInfoList(txn, container, indexInfoList); for (IndexInfoList::iterator it = indexInfoList.begin();; ++it) { if (it == indexInfoList.end()) { setIndexLost(cxt); return SQLType::END_INDEX; } else if (it->mapType == MAP_TYPE_BTREE && it->columnIds_ == indexColumnList) { acceptIndexInfo(cxt, txn, container, targetCondList, *it); return SQLType::INDEX_TREE_RANGE; } } } void SQLContainerImpl::CursorImpl::acceptSearchResult( OpContext &cxt, const SearchResult &result, const SQLExprs::IndexConditionList *targetCondList, ContainerRowScanner *scanner, OIdTable *oIdTable) { static_cast<void>(targetCondList); if (result.isEmpty()) { return; } if (scanner == NULL) { if (indexLimit_ > 0) { totalSearchCount_ += result.getSize(); if (resolveResultSet().isPartialExecuteSuspend() && totalSearchCount_ > indexLimit_) { setIndexLost(cxt); return; } } assert(oIdTable != NULL); oIdTable->addAll(result); if (memLimit_ > 0 && resolveResultSet().isPartialExecuteSuspend() && oIdTable->getTotalAllocationSize() > static_cast<uint64_t>(memLimit_)) { setIndexLost(cxt); } return; } TransactionContext &txn = resolveTransactionContext(); BaseContainer &container = resolveContainer(); const ContainerType containerType = container.getContainerType(); if (containerType == COLLECTION_CONTAINER) { scanRow(txn, static_cast<Collection&>(container), result, *scanner); } else if (containerType == TIME_SERIES_CONTAINER) { scanRow(txn, static_cast<TimeSeries&>(container), result, *scanner); } else { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } } void SQLContainerImpl::CursorImpl::acceptIndexInfo( OpContext &cxt, TransactionContext &txn, BaseContainer &container, const SQLExprs::IndexConditionList &targetCondList, const IndexInfo &info) { SQLOps::OpProfilerIndexEntry *profilerEntry = cxt.getIndexProfiler(); if (profilerEntry == NULL || !profilerEntry->isEmpty()) { return; } ObjectManager *objectManager = container.getObjectManager(); if (profilerEntry->findIndexName() == NULL) { profilerEntry->setIndexName(info.indexName_.c_str()); } for (util::Vector<uint32_t>::const_iterator it = info.columnIds_.begin(); it != info.columnIds_.end(); ++it) { if (profilerEntry->findColumnName(*it) == NULL) { ColumnInfo &columnInfo = container.getColumnInfo(*it); profilerEntry->setColumnName( *it, columnInfo.getColumnName(txn, *objectManager)); } profilerEntry->addIndexColumn(*it); } for (SQLExprs::IndexConditionList::const_iterator it = targetCondList.begin(); it != targetCondList.end(); ++it) { profilerEntry->addCondition(*it); } } void SQLContainerImpl::CursorImpl::setIndexLost(OpContext &cxt) { scanner_ = NULL; if (updatorList_.get() != NULL) { updatorList_->clear(); } clearResultSetPreserving(resolveResultSet(), true); if (rowIdFiltering_) { cxt.setCompleted(); } else { cxt.invalidate(); } latchHolder_.reset(); indexLost_ = true; } template<typename Container> void SQLContainerImpl::CursorImpl::scanRow( TransactionContext &txn, Container &container, const SearchResult &result, ContainerRowScanner &scanner) { for (size_t i = 0; i < 2; i++) { const bool onMvcc = (i != 0); const SearchResult::Entry &entry = result.getEntry(onMvcc); for (size_t j = 0; j < 2; j++) { const bool forRowArray = (j != 0); const SearchResult::OIdList &oIdList = entry.getOIdList(forRowArray); if (oIdList.empty()) { continue; } const OId *begin = &oIdList.front(); const OId *end = &oIdList.back() + 1; if (forRowArray) { container.scanRowArray(txn, begin, end, onMvcc, scanner); } else { container.scanRow(txn, begin, end, onMvcc, scanner); } } } } void SQLContainerImpl::CursorImpl::initializeScanRange( TransactionContext &txn, BaseContainer &container) { getMaxRowId(txn, container); assert(maxRowId_ != UNDEF_ROWID); } void SQLContainerImpl::CursorImpl::assignIndexInfo( TransactionContext &txn, BaseContainer &container, IndexSelector &indexSelector, const TupleColumnList &columnList) { typedef util::Vector<IndexInfo> IndexInfoList; util::StackAllocator &alloc = txn.getDefaultAllocator(); IndexInfoList indexInfoList(alloc); getIndexInfoList(txn, container, indexInfoList); util::Vector<IndexSelector::IndexFlags> flagsList(alloc); for (IndexInfoList::iterator it = indexInfoList.begin(); it != indexInfoList.end(); ++it) { const util::Vector<uint32_t> &columnIds = it->columnIds_; flagsList.clear(); bool acceptable = true; for (util::Vector<uint32_t>::const_iterator colIt = columnIds.begin(); colIt != columnIds.end(); ++colIt) { const uint32_t columnId = *colIt; ContainerColumnType containerColumnType; if (!ContainerValueUtils::toContainerColumnType( SQLValues::TypeUtils::toNonNullable( columnList[columnId].getType()), containerColumnType, false)) { acceptable = false; break; } const int32_t flags = NoSQLUtils::mapTypeToSQLIndexFlags( it->mapType, containerColumnType); if (flags == 0) { acceptable = false; break; } flagsList.push_back(flags); } if (!acceptable) { continue; } indexSelector.addIndex(columnIds, flagsList); } indexSelector.completeIndex(); } void SQLContainerImpl::CursorImpl::getIndexInfoList( TransactionContext &txn, BaseContainer &container, util::Vector<IndexInfo> &indexInfoList) { container.getIndexInfoList(txn, indexInfoList); if (container.getContainerType() == TIME_SERIES_CONTAINER) { util::StackAllocator &alloc = txn.getDefaultAllocator(); util::Vector<uint32_t> columnIds(alloc); ColumnId firstColumnId = ColumnInfo::ROW_KEY_COLUMN_ID; columnIds.push_back(firstColumnId); IndexInfo indexInfo(alloc, columnIds, MAP_TYPE_BTREE); indexInfoList.push_back(indexInfo); } } TransactionContext& SQLContainerImpl::CursorImpl::prepareTransactionContext( OpContext &cxt) { EventContext *ec = getEventContext(cxt); if (ec->isOnIOWorker()) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Internal error by invalid event context"); } util::StackAllocator &alloc = ec->getAllocator(); const PartitionId partitionId = cxt.getExtContext().getEvent()->getPartitionId(); { GetContainerPropertiesHandler handler; handler.partitionTable_ = getPartitionTable(cxt); const StatementHandler::ClusterRole clusterRole = (StatementHandler::CROLE_MASTER | StatementHandler::CROLE_FOLLOWER); const StatementHandler::PartitionRoleType partitionRole = StatementHandler::PROLE_OWNER; const StatementHandler::PartitionStatus partitionStatus = (StatementHandler::PSTATE_ON | StatementHandler::PSTATE_SYNC); if (cxt.getExtContext().isOnTransactionService()) { handler.checkExecutable( partitionId, clusterRole, partitionRole, partitionStatus, handler.partitionTable_); } else { return getTransactionManager(cxt)->putAuto(alloc); } } { const StatementId stmtId = 0; const TransactionManager::ContextSource src( QUERY_TQL, stmtId, UNDEF_CONTAINERID, TXN_DEFAULT_TRANSACTION_TIMEOUT_INTERVAL, TransactionManager::AUTO, TransactionManager::AUTO_COMMIT, false, cxt.getExtContext().getStoreMemoryAgingSwapRate(), cxt.getExtContext().getTimeZone()); return getTransactionManager(cxt)->put( alloc, partitionId, TXN_EMPTY_CLIENTID, src, ec->getHandlerStartTime(), ec->getHandlerStartMonotonicTime()); } } FullContainerKey* SQLContainerImpl::CursorImpl::predicateToContainerKey( SQLValues::ValueContext &cxt, TransactionContext &txn, DataStore &dataStore, const Expression *pred, const ContainerLocation &location, util::String &dbNameStr) { util::StackAllocator &alloc = cxt.getAllocator(); const MetaContainerInfo &metaInfo = resolveMetaContainerInfo(location.id_); const SQLExprs::ExprFactory &factory = SQLExprs::ExprFactory::getDefaultFactory(); FullContainerKey *containerKey = NULL; bool placeholderAffected; if (metaInfo.commonInfo_.dbNameColumn_ != UNDEF_COLUMNID) { TupleValue dbName; TupleValue containerName; const bool found = SQLExprs::ExprRewriter::predicateToExtContainerName( cxt, factory, pred, metaInfo.commonInfo_.dbNameColumn_, metaInfo.commonInfo_.containerNameColumn_, &dbName, containerName, placeholderAffected); if (dbName.getType() == TupleTypes::TYPE_STRING) { dbNameStr = ValueUtils::valueToString(cxt, dbName); } if (found) { const util::String containerNameStr = ValueUtils::valueToString(cxt, containerName); try { containerKey = ALLOC_NEW(alloc) FullContainerKey( alloc, KeyConstraint::getNoLimitKeyConstraint(), location.dbVersionId_, containerNameStr.c_str(), containerNameStr.size()); } catch (...) { } } VarContext &varCxt = cxt.getVarContext(); varCxt.destroyValue(dbName); varCxt.destroyValue(containerName); } do { if (containerKey != NULL) { break; } if (metaInfo.commonInfo_.containerIdColumn_ == UNDEF_COLUMNID) { break; } PartitionId partitionId = UNDEF_PARTITIONID; ContainerId containerId = UNDEF_CONTAINERID; if (!SQLExprs::ExprRewriter::predicateToContainerId( cxt, factory, pred, metaInfo.commonInfo_.partitionIndexColumn_, metaInfo.commonInfo_.containerIdColumn_, partitionId, containerId, placeholderAffected)) { break; } if (partitionId != txn.getPartitionId()) { break; } try { StackAllocAutoPtr<BaseContainer> containerAutoPtr( alloc, dataStore.getContainer( txn, txn.getPartitionId(), containerId, ANY_CONTAINER)); BaseContainer *container = containerAutoPtr.get(); if (container == NULL) { break; } containerKey = ALLOC_NEW(alloc) FullContainerKey( container->getContainerKey(txn)); } catch (...) { } } while (false); return containerKey; } const MetaContainerInfo& SQLContainerImpl::CursorImpl::resolveMetaContainerInfo( ContainerId id) { const bool forCore = true; const MetaType::InfoTable &infoTable = MetaType::InfoTable::getInstance(); return infoTable.resolveInfo(id, forCore); } DataStore* SQLContainerImpl::CursorImpl::getDataStore(OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getDataStore(); } EventContext* SQLContainerImpl::CursorImpl::getEventContext(OpContext &cxt) { return cxt.getExtContext().getEventContext(); } TransactionManager* SQLContainerImpl::CursorImpl::getTransactionManager( OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getTransactionManager(); } TransactionService* SQLContainerImpl::CursorImpl::getTransactionService( OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getTransactionService(); } PartitionTable* SQLContainerImpl::CursorImpl::getPartitionTable( OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getPartitionTable(); } ClusterService* SQLContainerImpl::CursorImpl::getClusterService( OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getClusterService(); } SQLExecutionManager* SQLContainerImpl::CursorImpl::getExecutionManager( OpContext &cxt) { return cxt.getExtContext().getExecutionManager(); } SQLService* SQLContainerImpl::CursorImpl::getSQLService(OpContext &cxt) { const ResourceSet *resourceSet = getResourceSet(cxt); if (resourceSet == NULL) { return NULL; } return resourceSet->getSQLService(); } const ResourceSet* SQLContainerImpl::CursorImpl::getResourceSet( OpContext &cxt) { return cxt.getExtContext().getResourceSet(); } template<RowArrayType RAType, typename T> const T& SQLContainerImpl::CursorImpl::getFixedValue( const ContainerColumn &column) { return *static_cast<const T*>(getFixedValueAddr<RAType>(column)); } template<RowArrayType RAType> const void* SQLContainerImpl::CursorImpl::getFixedValueAddr( const ContainerColumn &column) { return getRowArrayImpl<RAType>(true)->getRowCursor().getFixedField(column); } template<RowArrayType RAType> inline const void* SQLContainerImpl::CursorImpl::getVariableArray( const ContainerColumn &column) { return getRowArrayImpl<RAType>(true)->getRowCursor().getVariableField( column); } void SQLContainerImpl::CursorImpl::initializeRowArray( TransactionContext &txn, BaseContainer &container) { rowArray_ = UTIL_MAKE_LOCAL_UNIQUE(rowArray_, RowArray, txn, &container); generalRowArray_ = rowArray_->getImpl< BaseContainer, BaseContainer::ROW_ARRAY_GENERAL>(); plainRowArray_ = rowArray_->getImpl< BaseContainer, BaseContainer::ROW_ARRAY_PLAIN>(); } void SQLContainerImpl::CursorImpl::destroyRowArray() { generalRowArray_ = NULL; plainRowArray_ = NULL; rowArray_.reset(); row_ = NULL; } BaseContainer::RowArray* SQLContainerImpl::CursorImpl::getRowArray() { assert(rowArray_.get() != NULL); return rowArray_.get(); } template<> BaseContainer::RowArrayImpl< BaseContainer, BaseContainer::ROW_ARRAY_GENERAL>* SQLContainerImpl::CursorImpl::getRowArrayImpl(bool loaded) { static_cast<void>(loaded); assert(generalRowArray_ != NULL); return generalRowArray_; } template<> BaseContainer::RowArrayImpl< BaseContainer, BaseContainer::ROW_ARRAY_PLAIN>* SQLContainerImpl::CursorImpl::getRowArrayImpl(bool loaded) { static_cast<void>(loaded); assert(plainRowArray_ != NULL); assert(!loaded || getRowArray()->getRowArrayType() == BaseContainer::ROW_ARRAY_PLAIN); return plainRowArray_; } template<RowArrayType RAType> void SQLContainerImpl::CursorImpl::setUpScannerHandler( OpContext &cxt, const Projection &proj, ContainerRowScanner::HandlerSet &handlerSet) { typedef ScannerHandler<RAType> HandlerType; HandlerType *handler = ALLOC_NEW(cxt.getAllocator()) HandlerType(cxt, *this, proj); handlerSet.getEntry<RAType>() = ContainerRowScanner::createHandlerEntry(*handler); } void SQLContainerImpl::CursorImpl::destroyUpdateRowIdHandler() throw() { updateRowIdHandler_.reset(); } RowId SQLContainerImpl::CursorImpl::getMaxRowId( TransactionContext& txn, BaseContainer &container) { if (maxRowId_ == UNDEF_ROWID) { maxRowId_ = resolveMaxRowId(txn, container); if (maxRowId_ == UNDEF_ROWID) { maxRowId_ = 0; } } assert(maxRowId_ != UNDEF_ROWID); return maxRowId_; } RowId SQLContainerImpl::CursorImpl::resolveMaxRowId( TransactionContext& txn, BaseContainer &container) { const ContainerType containerType = container.getContainerType(); if (containerType == COLLECTION_CONTAINER) { return static_cast<Collection&>(container).getMaxRowId(txn); } else if (containerType == TIME_SERIES_CONTAINER) { return static_cast<TimeSeries&>(container).getMaxRowId(txn); } else { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } } bool SQLContainerImpl::CursorImpl::isColumnSchemaNullable( const ColumnInfo &info) { return !info.isNotNull(); } bool SQLContainerImpl::CursorImpl::updateNullsStats( const BaseContainer &container) { if (nullsStatsChanged_) { return true; } getNullsStats(container, lastNullsStats_); if (initialNullsStats_.empty()) { initialNullsStats_.assign( lastNullsStats_.begin(), lastNullsStats_.end()); return true; } const size_t size = initialNullsStats_.size(); return (lastNullsStats_.size() == size && memcmp( initialNullsStats_.data(), lastNullsStats_.data(), size) == 0); } void SQLContainerImpl::CursorImpl::getNullsStats( const BaseContainer &container, util::XArray<uint8_t> &nullsStats) { const uint32_t columnCount = container.getColumnNum(); initializeBits(nullsStats, columnCount); const size_t bitsSize = nullsStats.size(); nullsStats.clear(); container.getNullsStats(nullsStats); if (nullsStats.size() != bitsSize) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } } void SQLContainerImpl::CursorImpl::initializeBits( util::XArray<uint8_t> &bits, size_t bitCount) { const uint8_t unitBits = 0; bits.assign((bitCount + CHAR_BIT - 1) / CHAR_BIT, unitBits); } void SQLContainerImpl::CursorImpl::setBit( util::XArray<uint8_t> &bits, size_t index, bool value) { uint8_t &unitBits = bits[index / CHAR_BIT]; const uint8_t targetBit = static_cast<uint8_t>(1 << (index % CHAR_BIT)); if (value) { unitBits |= targetBit; } else { unitBits &= targetBit; } } bool SQLContainerImpl::CursorImpl::getBit( const util::XArray<uint8_t> &bits, size_t index) { const uint8_t &unitBits = bits[index / CHAR_BIT]; const uint8_t targetBit = static_cast<uint8_t>(1 << (index % CHAR_BIT)); return ((unitBits & targetBit) != 0); } SQLContainerImpl::RowIdFilter* SQLContainerImpl::CursorImpl::checkRowIdFilter( OpContext &cxt, TransactionContext& txn, BaseContainer &container, LocalCursor &cursor, bool readOnly) { RowIdFilter *rowIdFilter = cursor.findRowIdFilter(); if (rowIdFilter != NULL) { return rowIdFilter; } if (!rowIdFiltering_) { return NULL; } rowIdFilter = &cursor.resolveRowIdFilter(cxt, getMaxRowId(txn, container)); if (readOnly) { if (rowIdFilterId_.get() != NULL) { rowIdFilter->load(cxtSrc_, *rowIdFilterId_); } rowIdFilter->setReadOnly(); } return rowIdFilter; } void SQLContainerImpl::CursorImpl::finishRowIdFilter( OpContext &cxt, RowIdFilter *rowIdFilter) { if (rowIdFilter == NULL || !rowIdFiltering_) { return; } assert(rowIdFilterId_.get() == NULL); rowIdFilterId_ = UTIL_MAKE_LOCAL_UNIQUE( rowIdFilterId_, uint32_t, rowIdFilter->save(cxtSrc_)); } template<TupleColumnType T, bool VarSize> template<BaseContainer::RowArrayType RAType, typename Ret> inline Ret SQLContainerImpl::CursorImpl::DirectValueAccessor< T, VarSize>::access( SQLValues::ValueContext &cxt, CursorImpl &cursor, const ContainerColumn &column) const { static_cast<void>(cxt); UTIL_STATIC_ASSERT(!VarSize); return cursor.getFixedValue<RAType, Ret>(column); } template<> template<BaseContainer::RowArrayType RAType, typename Ret> inline Ret SQLContainerImpl::CursorImpl::DirectValueAccessor< TupleTypes::TYPE_BOOL, false>::access( SQLValues::ValueContext &cxt, CursorImpl &cursor, const ContainerColumn &column) const { static_cast<void>(cxt); return !!cursor.getFixedValue<RAType, int8_t>(column); } template<> template<BaseContainer::RowArrayType RAType, typename Ret> inline Ret SQLContainerImpl::CursorImpl::DirectValueAccessor< TupleTypes::TYPE_STRING, true>::access( SQLValues::ValueContext &cxt, CursorImpl &cursor, const ContainerColumn &column) const { static_cast<void>(cxt); return TupleString(cursor.getVariableArray<RAType>(column)); } template<> template<BaseContainer::RowArrayType RAType, typename Ret> inline Ret SQLContainerImpl::CursorImpl::DirectValueAccessor< TupleTypes::TYPE_BLOB, true>::access( SQLValues::ValueContext &cxt, CursorImpl &cursor, const ContainerColumn &column) const { const void *data = cursor.getVariableArray<RAType>(column); const BaseObject &baseObject = *cursor.frontFieldCache_; return TupleValue::LobBuilder::fromDataStore( cxt.getVarContext(), baseObject, data); } SQLContainerImpl::LocalCursor::LocalCursor() { } SQLContainerImpl::LocalCursor& SQLContainerImpl::LocalCursor::resolve( OpContext &cxt) { util::AllocUniquePtr<void> &resource = cxt.getResource(0); if (resource.isEmpty()) { resource = ALLOC_UNIQUE( cxt.getValueContext().getVarAllocator(), LocalCursor); } return resource.resolveAs<LocalCursor>(); } SQLContainerImpl::OIdTable* SQLContainerImpl::LocalCursor::findOIdTable() { return oIdTable_.get(); } SQLContainerImpl::OIdTable& SQLContainerImpl::LocalCursor::resolveOIdTable( OpContext &cxt, MergeMode::Type mode) { if (oIdTable_.get() == NULL) { oIdTable_ = ALLOC_UNIQUE( cxt.getValueContext().getVarAllocator(), OIdTable, OIdTable::Source::ofContext(cxt, mode)); } return *oIdTable_; } SQLContainerImpl::RowIdFilter* SQLContainerImpl::LocalCursor::findRowIdFilter() { return rowIdFilter_.get(); } SQLContainerImpl::RowIdFilter& SQLContainerImpl::LocalCursor::resolveRowIdFilter( OpContext &cxt, RowId maxRowId) { if (rowIdFilter_.get() == NULL) { rowIdFilter_ = ALLOC_UNIQUE( cxt.getValueContext().getVarAllocator(), RowIdFilter, cxt.getAllocatorManager(), cxt.getAllocator().base(), maxRowId); } return *rowIdFilter_; } const uint16_t SQLContainerImpl::Constants::SCHEMA_INVALID_COLUMN_ID = std::numeric_limits<uint16_t>::max(); const uint32_t SQLContainerImpl::Constants::ESTIMATED_ROW_ARRAY_ROW_COUNT = 50; SQLContainerImpl::ColumnCode::ColumnCode() : cursor_(NULL) { } void SQLContainerImpl::ColumnCode::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { static_cast<void>(expr); typedef SQLExprs::ExprCode ExprCode; typedef SQLCoreExprs::VariantUtils VariantUtils; CursorRef &ref = cxt.getInputSourceRef(0).resolveAs<CursorRef>(); CursorImpl &cursor = ref.resolveCursor(); BaseContainer &container = cursor.resolveContainer(); const ExprCode &code = VariantUtils::getBaseExpression(cxt, argIndex).getCode(); const bool forId = (code.getType() == SQLType::EXPR_ID); column_ = CursorImpl::resolveColumn(container, forId, code.getColumnPos()); cursor_ = &cursor; } template<RowArrayType RAType, typename T, typename S, bool Nullable> inline typename SQLContainerImpl::ColumnEvaluator<RAType, T, S, Nullable>::ResultType SQLContainerImpl::ColumnEvaluator<RAType, T, S, Nullable>::eval( ExprContext &cxt) const { if (Nullable && code_.cursor_->isValueNull(code_.column_)) { return ResultType(ValueType(), true); } return ResultType( static_cast<ValueType>(code_.cursor_->getValueDirect< RAType, SourceType, S::COLUMN_TYPE>( cxt.getValueContext(), code_.column_)), false); } SQLContainerImpl::IdExpression::VariantBase::~VariantBase() { } void SQLContainerImpl::IdExpression::VariantBase::initializeCustom( ExprFactoryContext &cxt, const ExprCode &code) { static_cast<void>(code); columnCode_.initialize(cxt, this, NULL); } template<size_t V> TupleValue SQLContainerImpl::IdExpression::VariantAt<V>::eval( ExprContext &cxt) const { const int64_t value = Evaluator::get(Evaluator::evaluator(columnCode_).eval(cxt)); return TupleValue(value); } void SQLContainerImpl::GeneralCondEvaluator::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { static_cast<void>(cxt); static_cast<void>(argIndex); expr_ = expr; } void SQLContainerImpl::VarCondEvaluator::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { static_cast<void>(cxt); static_cast<void>(argIndex); expr_ = expr; } template<typename Func, size_t V> void SQLContainerImpl::ComparisonEvaluator<Func, V>::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { static_cast<void>(expr); typedef SQLExprs::ExprCode ExprCode; typedef SQLCoreExprs::VariantUtils VariantUtils; const ExprCode &code = VariantUtils::getBaseExpression(cxt, argIndex).getCode(); expr_.initializeCustom(cxt, code); } void SQLContainerImpl::EmptyCondEvaluator::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { static_cast<void>(cxt); static_cast<void>(expr); static_cast<void>(argIndex); } template<typename Base, BaseContainer::RowArrayType RAType> SQLContainerImpl::RowIdCondEvaluator<Base, RAType>::RowIdCondEvaluator() : rowIdFilter_(NULL), cursor_(NULL) { } template<typename Base, BaseContainer::RowArrayType RAType> inline bool SQLContainerImpl::RowIdCondEvaluator<Base, RAType>::eval( ExprContext &cxt) const { const typename Base::ResultType &matched = Base::evaluator(baseCode_).eval(cxt); if (!Base::check(matched) || !Base::get(matched)) { return false; } const RowId rowId = cursor_->getValueDirect< RAType, RowId, TupleTypes::TYPE_LONG>( cxt.getValueContext(), column_); if (!rowIdFilter_->accept(rowId)) { return false; } return true; } template<typename Base, BaseContainer::RowArrayType RAType> void SQLContainerImpl::RowIdCondEvaluator<Base, RAType>::initialize( ExprFactoryContext &cxt, const Expression *expr, const size_t *argIndex) { baseCode_.initialize(cxt, expr, argIndex); CursorRef &ref = cxt.getInputSourceRef(0).resolveAs<CursorRef>(); rowIdFilter_ = ref.findRowIdFilter(); assert(rowIdFilter_ != NULL); CursorImpl &cursor = ref.resolveCursor(); BaseContainer &container = cursor.resolveContainer(); const bool forId = true; column_ = CursorImpl::resolveColumn(container, forId, 0); cursor_ = &cursor; } void SQLContainerImpl::GeneralProjector::initialize( ProjectionFactoryContext &cxt, const Projection *proj) { static_cast<void>(cxt); proj_ = proj; } bool SQLContainerImpl::GeneralProjector::update(OpContext &cxt) { proj_->updateProjectionContext(cxt); return true; } bool SQLContainerImpl::CountProjector::update(OpContext &cxt) { SQLValues::VarContext::Scope varScope(cxt.getVarContext()); SQLExprs::ExprContext &exprCxt = cxt.getExprContext(); const int64_t totalCount = exprCxt.getAggregationValueAs<SQLValues::Types::Long>(column_) + counter_; exprCxt.setAggregationValueBy<SQLValues::Types::Long>(column_, totalCount); counter_ = 0; return true; } void SQLContainerImpl::CountProjector::initialize( ProjectionFactoryContext &cxt, const Projection *proj) { const SQLExprs::Expression &countExpr = proj->child(); assert(countExpr.getCode().getType() == SQLType::AGG_COUNT_ALL); const uint32_t aggrIndex = countExpr.getCode().getAggregationIndex(); assert(aggrIndex != std::numeric_limits<uint32_t>::max()); SQLValues::SummaryTupleSet *tupleSet = cxt.getExprFactoryContext().getAggregationTupleSet(); assert(tupleSet != NULL); column_ = tupleSet->getModifiableColumnList()[aggrIndex]; } SQLContainerImpl::CursorRef::CursorRef(util::StackAllocator &alloc) : cursor_(NULL), rowIdFilter_(NULL), cxtRefList_(alloc), exprCxtRefList_(alloc) { } SQLContainerImpl::CursorImpl& SQLContainerImpl::CursorRef::resolveCursor() { if (cursor_ == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return *cursor_; } SQLContainerImpl::RowIdFilter* SQLContainerImpl::CursorRef::findRowIdFilter() { return rowIdFilter_; } void SQLContainerImpl::CursorRef::setCursor( CursorImpl *cursor, RowIdFilter *rowIdFilter) { cursor_ = cursor; rowIdFilter_ = rowIdFilter; } void SQLContainerImpl::CursorRef::addContextRef(OpContext **ref) { cxtRefList_.push_back(ref); } void SQLContainerImpl::CursorRef::addContextRef(ExprContext **ref) { exprCxtRefList_.push_back(ref); } void SQLContainerImpl::CursorRef::updateAll(OpContext &cxt) { for (ContextRefList::const_iterator it = cxtRefList_.begin(); it != cxtRefList_.end(); ++it) { **it = &cxt; } for (ExprContextRefList::const_iterator it = exprCxtRefList_.begin(); it != exprCxtRefList_.end(); ++it) { **it = &cxt.getExprContext(); } } template<BaseContainer::RowArrayType RAType> SQLContainerImpl::ScannerHandler<RAType>::ScannerHandler( OpContext &cxt, CursorImpl &cursor, const Projection &proj) : cxt_(cxt), cursor_(cursor), proj_(proj) { } template<BaseContainer::RowArrayType RAType> template<BaseContainer::RowArrayType InRAType> void SQLContainerImpl::ScannerHandler<RAType>::operator()( TransactionContext &txn, typename BaseContainer::RowArrayImpl< BaseContainer, InRAType> &rowArrayImpl) { static_cast<void>(txn); static_cast<void>(rowArrayImpl); const uint32_t outIndex = cursor_.getOutputIndex(); TupleListWriter &writer= cxt_.getWriter(outIndex); writer.next(); BaseContainer &container = cursor_.resolveContainer(); uint32_t pos = 0; for (Expression::Iterator it(proj_); it.exists(); it.next()) { const bool forId = (it.get().getCode().getType() ==SQLType::EXPR_ID); const ContainerColumn &srcColumn = CursorImpl::resolveColumn( container, forId, it.get().getCode().getColumnPos()); cursor_.writeValue<RAType>( cxt_.getValueContext(), writer, cxt_.getWriterColumn(outIndex, pos), srcColumn, forId); pos++; } } template<BaseContainer::RowArrayType RAType> bool SQLContainerImpl::ScannerHandler<RAType>::update( TransactionContext &txn) { static_cast<void>(txn); return true; } size_t SQLContainerImpl::ScannerHandlerBase::HandlerVariantUtils::toInputSourceNumber( InputSourceType type) { switch (type) { case ExprCode::INPUT_CONTAINER_GENERAL: return 0; case ExprCode::INPUT_CONTAINER_PLAIN: return 1; default: assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } } size_t SQLContainerImpl::ScannerHandlerBase::HandlerVariantUtils::toCompFuncNumber( ExprType type) { switch (type) { case SQLType::OP_LT: return 0; case SQLType::OP_GT: return 1; case SQLType::OP_LE: return 2; case SQLType::OP_GE: return 3; case SQLType::OP_EQ: return 4; case SQLType::OP_NE: return 5; default: assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } } void SQLContainerImpl::ScannerHandlerBase::HandlerVariantUtils::setUpContextRef( ProjectionFactoryContext &cxt, OpContext **ref, ExprContext **exprRef) { typedef SQLExprs::ExprFactoryContext ExprFactoryContext; ExprFactoryContext &exprCxt = cxt.getExprFactoryContext(); CursorRef &cursorRef = exprCxt.getInputSourceRef(0).resolveAs<CursorRef>(); cursorRef.addContextRef(ref); cursorRef.addContextRef(exprRef); } void SQLContainerImpl::ScannerHandlerBase::HandlerVariantUtils::addUpdator( ProjectionFactoryContext &cxt, const UpdatorEntry &updator) { typedef SQLExprs::ExprFactoryContext ExprFactoryContext; ExprFactoryContext &exprCxt = cxt.getExprFactoryContext(); CursorRef &cursorRef = exprCxt.getInputSourceRef(0).resolveAs<CursorRef>(); if (updator.first != NULL) { cursorRef.resolveCursor().addScannerUpdator(updator); } } std::pair<const SQLExprs::Expression*, const SQLOps::Projection*> SQLContainerImpl::ScannerHandlerBase::HandlerVariantUtils:: getFilterProjectionElements(const Projection &src) { const SQLExprs::Expression *filterExpr = NULL; const SQLOps::Projection *chainProj = NULL; do { if (src.getProjectionCode().getType() != SQLOpTypes::PROJ_FILTER) { break; } const SQLExprs::Expression *filterExprBase = src.findChild(); filterExpr = filterExprBase; chainProj = &src.chainAt(0); } while (false); if (chainProj == NULL) { filterExpr = NULL; chainProj = &src; } return std::make_pair(filterExpr, chainProj); } size_t SQLContainerImpl::ScannerHandlerBase::VariantTraits::resolveVariant( FactoryContext &cxt, const Projection &proj) { typedef SQLExprs::ExprCode ExprCode; typedef SQLExprs::ExprFactoryContext ExprFactoryContext; typedef SQLExprs::ExprTypeUtils ExprTypeUtils; ExprFactoryContext &exprCxt = cxt.first->getExprFactoryContext(); CursorRef &ref = exprCxt.getInputSourceRef(0).resolveAs<CursorRef>(); const bool rowIdFiltering = (ref.findRowIdFilter() != NULL); size_t condNumBase = (rowIdFiltering ? COUNT_NO_COMP_FILTER_BASE : 0); const size_t sourceNum = HandlerVariantUtils::toInputSourceNumber( exprCxt.getInputSourceType(0)); const std::pair<const Expression*, const Projection*> &elems = HandlerVariantUtils::getFilterProjectionElements(proj); const Expression *condExpr = elems.first; const Projection *chainProj = elems.second; size_t condNum; do { if (condExpr == NULL) { condNum = EMPTY_FILTER_NUM; break; } const TupleColumnType condColumnType = SQLValues::TypeUtils::findConversionType( condExpr->getCode().getColumnType(), SQLValues::TypeUtils::toNullable(TupleTypes::TYPE_BOOL), true, true); if (SQLValues::TypeUtils::isNull(condColumnType)) { condNum = EMPTY_FILTER_NUM; break; } const ExprCode &condCode = condExpr->getCode(); if (condCode.getType() == SQLType::EXPR_CONSTANT && SQLValues::ValueUtils::isTrue(condCode.getValue())) { condNum = EMPTY_FILTER_NUM; break; } if (SQLExprs::ExprRewriter::findVarGenerativeExpr(*condExpr)) { condNum = VAR_FILTER_NUM; break; } if (rowIdFiltering) { condNum = GENERAL_FILTER_NUM; break; } const bool withNe = true; if (!ExprTypeUtils::isCompOp(condCode.getType(), withNe)) { condNum = GENERAL_FILTER_NUM; break; } ExprFactoryContext::Scope scope(exprCxt); exprCxt.setBaseExpression(condExpr); SQLExprs::ExprProfile exprProfile; exprCxt.setProfile(&exprProfile); const size_t baseNum = CoreCompExpr::VariantTraits::resolveVariant(exprCxt, condCode); SQLOps::OpProfilerOptimizationEntry *profiler = cxt.first->getProfiler(); if (profiler != NULL) { SQLValues::ProfileElement &elem = profiler->get(SQLOpTypes::OPT_OP_COMP_CONST); elem.merge(exprProfile.compConst_); elem.merge(exprProfile.compColumns_); } if (baseNum < OFFSET_COMP_CONTAINER) { condNum = GENERAL_FILTER_NUM; break; } const size_t compFuncNum = HandlerVariantUtils::toCompFuncNumber(condCode.getType()); condNumBase = 0; condNum = COUNT_NO_COMP_FILTER + compFuncNum * COUNT_COMP_BASE + ((baseNum - OFFSET_COMP_CONTAINER) % COUNT_COMP_BASE); } while (false); size_t projNum = 0; do { if (chainProj->getProjectionCode().getType() != SQLOpTypes::PROJ_AGGR_PIPE || chainProj->getProjectionCode().getAggregationPhase() != SQLType::AGG_PHASE_ADVANCE_PIPE || chainProj->findChild() == NULL) { break; } const SQLExprs::Expression &child = chainProj->child(); if (child.findNext() != NULL || child.getCode().getType() != SQLType::AGG_COUNT_ALL) { break; } projNum = 1; } while (false); return sourceNum * (COUNT_PROJECTION * COUNT_FILTER) + projNum * COUNT_FILTER + condNumBase + condNum; } template<size_t V> SQLContainerImpl::ScannerHandlerBase::VariantAt<V>::VariantAt( ProjectionFactoryContext &cxt, const Projection &proj) : cxt_(NULL), exprCxt_(NULL) { typedef SQLExprs::ExprFactoryContext ExprFactoryContext; HandlerVariantUtils::setUpContextRef(cxt, &cxt_, &exprCxt_); const std::pair<const Expression*, const Projection*> &elems = HandlerVariantUtils::getFilterProjectionElements(proj); ExprFactoryContext &exprCxt = cxt.getExprFactoryContext(); exprCxt.setBaseExpression(elems.first); condCode_.initialize(exprCxt, elems.first, NULL); projector_.initialize(cxt, elems.second); HandlerVariantUtils::addUpdator(cxt, projector_.getUpdator()); } template<size_t V> template<BaseContainer::RowArrayType InRAType> inline void SQLContainerImpl::ScannerHandlerBase::VariantAt<V>::operator()( TransactionContext&, typename BaseContainer::RowArrayImpl< BaseContainer, InRAType>&) { const ResultType &matched = Evaluator::evaluator(condCode_).eval(*exprCxt_); if (!Evaluator::check(matched) || !Evaluator::get(matched)) { return; } projector_.project(*cxt_); } template<size_t V> inline bool SQLContainerImpl::ScannerHandlerBase::VariantAt<V>::update( TransactionContext&) { return true; } const SQLContainerImpl::ScannerHandlerFactory &SQLContainerImpl::ScannerHandlerFactory::FACTORY_INSTANCE = getInstanceForRegistrar(); const SQLContainerImpl::ScannerHandlerFactory& SQLContainerImpl::ScannerHandlerFactory::getInstance() { return FACTORY_INSTANCE; } SQLContainerImpl::ScannerHandlerFactory& SQLContainerImpl::ScannerHandlerFactory::getInstanceForRegistrar() { static ScannerHandlerFactory instance; return instance; } ContainerRowScanner& SQLContainerImpl::ScannerHandlerFactory::create( OpContext &cxt, CursorImpl &cursor, RowArray &rowArray, const Projection &proj, RowIdFilter *rowIdFilter) const { typedef SQLExprs::ExprCode ExprCode; typedef SQLExprs::ExprFactoryContext ExprFactoryContext; typedef SQLOps::ProjectionFactoryContext ProjectionFactoryContext; typedef SQLOps::OpCodeBuilder OpCodeBuilder; typedef ExprCode::InputSourceType InputSourceType; OpCodeBuilder builder(OpCodeBuilder::ofContext(cxt)); ProjectionFactoryContext &projCxt = builder.getProjectionFactoryContext(); cxt.setUpProjectionFactoryContext(projCxt, NULL); ContainerRowScanner::HandlerSet handlerSet; FactoryContext factoryCxt(&projCxt, &handlerSet); ExprFactoryContext &exprCxt = projCxt.getExprFactoryContext(); exprCxt.setPlanning(false); exprCxt.getInputSourceRef(0) = ALLOC_UNIQUE(cxt.getAllocator(), CursorRef, cxt.getAllocator()); exprCxt.getInputSourceRef(0).resolveAs<CursorRef>().setCursor( &cursor, rowIdFilter); const uint32_t columnCount = exprCxt.getInputColumnCount(0); for (uint32_t i = 0; i < columnCount; i++) { if (cursor.isColumnNonNullable(i)) { exprCxt.setInputType(0, i, SQLValues::TypeUtils::toNonNullable( exprCxt.getInputType(0, i))); } } const InputSourceType typeList[] = { ExprCode::INPUT_CONTAINER_GENERAL, ExprCode::INPUT_CONTAINER_PLAIN, ExprCode::END_INPUT }; for (const InputSourceType *it = typeList; *it != ExprCode::END_INPUT; ++it) { ExprFactoryContext::Scope scope(exprCxt); exprCxt.setInputSourceType(0, *it); builder.getExprRewriter().setCodeSetUpAlways(true); Projection &destProj = builder.rewriteProjection(proj); destProj.initializeProjection(cxt); create(factoryCxt, destProj); } exprCxt.getInputSourceRef(0).resolveAs<CursorRef>().updateAll(cxt); return *(ALLOC_NEW(cxt.getAllocator()) ContainerRowScanner( handlerSet, rowArray, NULL)); } ContainerRowScanner::HandlerSet& SQLContainerImpl::ScannerHandlerFactory::create( FactoryContext &cxt, const Projection &proj) const { if (factoryFunc_ == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return factoryFunc_(cxt, proj); } void SQLContainerImpl::ScannerHandlerFactory::setFactoryFunc(FactoryFunc func) { if (factoryFunc_ != NULL) { } factoryFunc_ = func; } SQLContainerImpl::ScannerHandlerFactory::ScannerHandlerFactory() : factoryFunc_(NULL) { } SQLContainerImpl::BaseRegistrar::BaseRegistrar( const BaseRegistrar &subRegistrar) throw() : factory_(NULL) { try { subRegistrar(); } catch (...) { assert(false); } } void SQLContainerImpl::BaseRegistrar::operator()() const { assert(false); } SQLContainerImpl::BaseRegistrar::BaseRegistrar() throw() : factory_(&ScannerHandlerFactory::getInstanceForRegistrar()) { } template<SQLExprs::ExprType T, typename E> void SQLContainerImpl::BaseRegistrar::addExprVariants() const { SQLExprs::VariantsRegistrarBase<ExprVariantTraits>::add<T, E>(); } template<typename S> void SQLContainerImpl::BaseRegistrar::addScannerVariants() const { ScannerHandlerFactory::getInstanceForRegistrar().setFactoryFunc( SQLExprs::VariantsRegistrarBase<ScannerVariantTraits>::add<0, S>()); } template<typename S, size_t Begin, size_t End> void SQLContainerImpl::BaseRegistrar::addScannerVariants() const { ScannerHandlerFactory::getInstanceForRegistrar().setFactoryFunc( SQLExprs::VariantsRegistrarBase<ScannerVariantTraits>::add<0, S, Begin, End>()); } template<typename V> SQLContainerImpl::BaseRegistrar::ScannerVariantTraits::ObjectType& SQLContainerImpl::BaseRegistrar::ScannerVariantTraits::create( ContextType &cxt, const CodeType &code) { V *handler = ALLOC_NEW(cxt.first->getAllocator()) V(*cxt.first, code); cxt.second->getEntry<V::ROW_ARRAY_TYPE>() = ContainerRowScanner::createHandlerEntry(*handler); return *cxt.second; } const SQLContainerImpl::BaseRegistrar SQLContainerImpl::DefaultRegistrar::REGISTRAR_INSTANCE((DefaultRegistrar())); void SQLContainerImpl::DefaultRegistrar::operator()() const { typedef SQLCoreExprs::Functions Functions; addExprVariants<SQLType::EXPR_ID, IdExpression>(); addExprVariants<SQLType::EXPR_COLUMN, ColumnExpression>(); addExprVariants< SQLType::OP_LT, ComparisonExpression<Functions::Lt> >(); addExprVariants< SQLType::OP_LE, ComparisonExpression<Functions::Le> >(); addExprVariants< SQLType::OP_GT, ComparisonExpression<Functions::Gt> >(); addExprVariants< SQLType::OP_GE, ComparisonExpression<Functions::Ge> >(); addExprVariants< SQLType::OP_EQ, ComparisonExpression<Functions::Eq> >(); addExprVariants< SQLType::OP_NE, ComparisonExpression<Functions::Ne> >(); addScannerVariants<ScannerHandlerBase>(); } SQLContainerImpl::SearchResult::SearchResult(util::StackAllocator &alloc) : normalEntry_(alloc), mvccEntry_(alloc) { } inline bool SQLContainerImpl::SearchResult::isEmpty() const{ return ( normalEntry_.isEntryEmpty() && mvccEntry_.isEntryEmpty()); } inline size_t SQLContainerImpl::SearchResult::getSize() const{ return ( normalEntry_.getEntrySize() + mvccEntry_.getEntrySize()); } inline SQLContainerImpl::SearchResult::Entry& SQLContainerImpl::SearchResult::getEntry(bool onMvcc){ return (onMvcc ? mvccEntry_ : normalEntry_); } inline const SQLContainerImpl::SearchResult::Entry& SQLContainerImpl::SearchResult::getEntry(bool onMvcc) const{ return (onMvcc ? mvccEntry_ : normalEntry_); } inline SQLContainerImpl::SearchResult::OIdListRef SQLContainerImpl::SearchResult::getOIdListRef(bool forRowArray) { return OIdListRef( &normalEntry_.getOIdList(forRowArray), &mvccEntry_.getOIdList(forRowArray)); } SQLContainerImpl::SearchResult::Entry::Entry(util::StackAllocator &alloc) : rowOIdList_(alloc), rowArrayOIdList_(alloc) { } inline bool SQLContainerImpl::SearchResult::Entry::isEntryEmpty() const { return (rowOIdList_.empty() && rowArrayOIdList_.empty()); } inline size_t SQLContainerImpl::SearchResult::Entry::getEntrySize() const { return (rowOIdList_.size() + rowArrayOIdList_.size()); } inline SQLContainerImpl::SearchResult::OIdList& SQLContainerImpl::SearchResult::Entry::getOIdList(bool forRowArray) { return (forRowArray ? rowArrayOIdList_ : rowOIdList_); } inline const SQLContainerImpl::SearchResult::OIdList& SQLContainerImpl::SearchResult::Entry::getOIdList(bool forRowArray) const { return (forRowArray ? rowArrayOIdList_ : rowOIdList_); } inline void SQLContainerImpl::SearchResult::Entry::swap(Entry &another) { rowOIdList_.swap(another.rowOIdList_); rowArrayOIdList_.swap(another.rowArrayOIdList_); } SQLContainerImpl::CursorScope::CursorScope( OpContext &cxt, CursorImpl &cursor) : cursor_(cursor), txn_(CursorImpl::prepareTransactionContext(cxt)), txnSvc_(CursorImpl::getTransactionService(cxt)), containerAutoPtr_( cxt.getAllocator(), getContainer( txn_, cxt, getStoreLatch(txn_, cxt, latch_), cursor_.location_, cursor_.containerExpired_, cursor_.containerType_)), resultSet_(prepareResultSet( cxt, txn_, checkContainer( cxt, containerAutoPtr_.get(), cursor_.location_, cursor_.schemaVersionId_), rsGuard_, cursor_)), partialExecCount_((resultSet_ == NULL ? 0 : resultSet_->getPartialExecuteCount())) { try { initialize(cxt); } catch (...) { clear(true); throw; } } SQLContainerImpl::CursorScope::~CursorScope() { try { clear(false); } catch (...) { assert(false); } } TransactionContext& SQLContainerImpl::CursorScope::getTransactionContext() { return txn_; } ResultSet& SQLContainerImpl::CursorScope::getResultSet() { assert(resultSet_ != NULL); return *resultSet_; } int64_t SQLContainerImpl::CursorScope::getStartPartialExecCount() { return partialExecCount_; } uint64_t SQLContainerImpl::CursorScope::getElapsedNanos() { return watch_.elapsedNanos(); } void SQLContainerImpl::CursorScope::initialize(OpContext &cxt) { static_cast<void>(cxt); watch_.start(); BaseContainer *container = containerAutoPtr_.get(); cursor_.container_ = container; cursor_.containerExpired_ = (container == NULL); cursor_.resultSetId_ = findResultSetId(resultSet_); cursor_.lastPartitionId_ = txn_.getPartitionId(); cursor_.lastDataStore_ = (container == NULL ? NULL : container->getDataStore()); cursor_.latchTarget_ = LatchTarget(&cursor_); cursor_.latchHolder_.reset(&cursor_.latchTarget_); if (container == NULL) { return; } cursor_.containerType_ = container->getContainerType(); cursor_.schemaVersionId_ = container->getVersionId(); cursor_.initializeScanRange(txn_, *container); cursor_.initializeRowArray(txn_, *container); DataStore *dataStore = container->getDataStore(); ObjectManager *objectManager = dataStore->getObjectManager(); cursor_.frontFieldCache_ = UTIL_MAKE_LOCAL_UNIQUE( cursor_.frontFieldCache_, BaseObject, txn_.getPartitionId(), *objectManager); } void SQLContainerImpl::CursorScope::clear(bool force) { if (containerAutoPtr_.get() == NULL) { return; } assert(cursor_.container_ != NULL); cursor_.destroyRowArray(); cursor_.frontFieldCache_.reset(); cursor_.container_ = NULL; clearResultSet(force); } void SQLContainerImpl::CursorScope::clearResultSet(bool force) { if (resultSet_ == NULL) { return; } bool closeable = (force || resultSet_->isRelease()); if (!closeable && cursor_.resultSetHolder_.isEmpty()) { assert(txnSvc_ != NULL); assert(cursor_.lastPartitionId_ != UNDEF_PARTITIONID); try { cursor_.resultSetHolder_.assign( txnSvc_->getResultSetHolderManager(), cursor_.lastPartitionId_, cursor_.resultSetId_); } catch (...) { cursor_.resultSetLost_ = true; closeable = true; } } if (closeable) { resultSet_->setResultType(RESULT_ROWSET); resultSet_->setPartialMode(false); cursor_.resultSetId_ = UNDEF_RESULTSETID; cursor_.resultSetPreserving_ = false; cursor_.resultSetHolder_.release(); cursor_.lastPartitionId_ = UNDEF_PARTITIONID; cursor_.lastDataStore_ = NULL; cursor_.destroyUpdateRowIdHandler(); } rsGuard_.reset(); resultSet_ = NULL; } const DataStore::Latch* SQLContainerImpl::CursorScope::getStoreLatch( TransactionContext &txn, OpContext &cxt, util::LocalUniquePtr<DataStore::Latch> &latch) { if (!cxt.getExtContext().isOnTransactionService()) { return NULL; } latch = UTIL_MAKE_LOCAL_UNIQUE( latch, DataStore::Latch, txn, txn.getPartitionId(), CursorImpl::getDataStore(cxt), CursorImpl::getClusterService(cxt)); return latch.get(); } BaseContainer* SQLContainerImpl::CursorScope::getContainer( TransactionContext &txn, OpContext &cxt, const DataStore::Latch *latch, const ContainerLocation &location, bool expired, ContainerType type) { if (latch == NULL || location.type_ != SQLType::TABLE_CONTAINER || expired) { return NULL; } DataStore *dataStore = CursorImpl::getDataStore(cxt); const PartitionId partitionId = txn.getPartitionId(); const ContainerType requiredType = (type == UNDEF_CONTAINER ? ANY_CONTAINER : type); try { return dataStore->getContainer( txn, partitionId, location.id_, requiredType); } catch (UserException &e) { if ((e.getErrorCode() == GS_ERROR_DS_CONTAINER_UNEXPECTEDLY_REMOVED || e.getErrorCode() == GS_ERROR_DS_DS_CONTAINER_EXPIRED) && location.expirable_) { return NULL; } throw; } } BaseContainer* SQLContainerImpl::CursorScope::checkContainer( OpContext &cxt, BaseContainer *container, const ContainerLocation &location, SchemaVersionId schemaVersionId) { if (container == NULL && (location.type_ != SQLType::TABLE_CONTAINER || location.expirable_)) { return NULL; } CursorImpl::checkInputInfo(cxt, *container); GetContainerPropertiesHandler handler; if (schemaVersionId == UNDEF_SCHEMAVERSIONID) { handler.checkContainerExistence(container); } else { handler.checkContainerSchemaVersion(container, schemaVersionId); } if (location.partitioningVersionId_ >= 0 && container->getAttribute() == CONTAINER_ATTR_SUB && location.partitioningVersionId_ < container->getTablePartitioningVersionId()) { GS_THROW_USER_ERROR( GS_ERROR_SQL_DML_EXPIRED_SUB_CONTAINER_VERSION, "Table schema cache mismatch partitioning version, actual=" << container->getTablePartitioningVersionId() << ", cache=" << location.partitioningVersionId_); } return container; } ResultSet* SQLContainerImpl::CursorScope::prepareResultSet( OpContext &cxt, TransactionContext &txn, BaseContainer *container, util::LocalUniquePtr<ResultSetGuard> &rsGuard, const CursorImpl &cursor) { if (container == NULL) { return NULL; } DataStore *dataStore = CursorImpl::getDataStore(cxt); assert(dataStore != NULL); TransactionService *txnSvc = CursorImpl::getTransactionService(cxt); assert(txnSvc != NULL); txnSvc->getResultSetHolderManager().closeAll(txn, *dataStore); const int64_t emNow = CursorImpl::getEventContext(cxt)->getHandlerStartMonotonicTime(); if (cursor.closed_) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } if (cursor.resultSetLost_) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_INPUT, ""); } ResultSet *resultSet; if (cursor.resultSetId_ == UNDEF_RESULTSETID) { const bool noExpire = true; resultSet = dataStore->createResultSet( txn, container->getContainerId(), container->getVersionId(), emNow, NULL, noExpire); resultSet->setUpdateIdType(ResultSet::UPDATE_ID_NONE); } else { resultSet = dataStore->getResultSet(txn, cursor.resultSetId_); } if (resultSet == NULL) { GS_THROW_USER_ERROR(GS_ERROR_DS_DS_RESULT_ID_INVALID, ""); } rsGuard = UTIL_MAKE_LOCAL_UNIQUE( rsGuard, ResultSetGuard, txn, *dataStore, *resultSet); return resultSet; } ResultSetId SQLContainerImpl::CursorScope::findResultSetId( ResultSet *resultSet) { if (resultSet == NULL) { return UNDEF_RESULTSETID; } return resultSet->getId(); } SQLContainerImpl::MetaScanHandler::MetaScanHandler( OpContext &cxt, CursorImpl &cursor, const Projection &proj) : cxt_(cxt), cursor_(cursor), proj_(proj) { } void SQLContainerImpl::MetaScanHandler::operator()( TransactionContext &txn, const MetaProcessor::ValueList &valueList) { util::StackAllocator &alloc = txn.getDefaultAllocator(); VarContext &varCxt = cxt_.getVarContext(); VarContext::Scope varScope(varCxt); const uint32_t outIndex = cursor_.getOutputIndex(); TupleListWriter &writer= cxt_.getWriter(outIndex); writer.next(); TupleValue value; uint32_t pos = 0; for (Expression::Iterator it(proj_); it.exists(); it.next()) { const Value &srcValue = valueList[it.get().getCode().getColumnPos()]; ContainerValueUtils::toTupleValue(alloc, srcValue, value, true); CursorImpl::writeValueAs<TupleTypes::TYPE_ANY>( writer, cxt_.getWriterColumn(outIndex, pos), value); pos++; } } util::ObjectPool< SQLContainerImpl::TupleUpdateRowIdHandler::Shared, util::Mutex> SQLContainerImpl::TupleUpdateRowIdHandler:: sharedPool_(util::AllocatorInfo( ALLOCATOR_GROUP_SQL_WORK, "updateRowIdHandlerPool")); SQLContainerImpl::TupleUpdateRowIdHandler::TupleUpdateRowIdHandler( const OpContext::Source &cxtSrc, RowId maxRowId) : shared_(UTIL_OBJECT_POOL_NEW(sharedPool_) Shared(cxtSrc, maxRowId)) { } SQLContainerImpl::TupleUpdateRowIdHandler::~TupleUpdateRowIdHandler() { try { close(); } catch (...) { assert(false); } } void SQLContainerImpl::TupleUpdateRowIdHandler::close() { if (shared_ == NULL) { return; } bool noRef; { util::LockGuard<util::Mutex> guard(shared_->mutex_); shared_->cxt_.reset(); assert(shared_->refCount_ > 0); noRef = (--shared_->refCount_ == 0); } if (noRef) { UTIL_OBJECT_POOL_DELETE(sharedPool_, shared_); } shared_ = NULL; } bool SQLContainerImpl::TupleUpdateRowIdHandler::isUpdated() { if (shared_ == NULL || shared_->cxt_.get() == NULL) { return false; } return shared_->updated_; } void SQLContainerImpl::TupleUpdateRowIdHandler::setUpdated() { if (shared_ == NULL || shared_->cxt_.get() == NULL) { return; } shared_->updated_ = true; } void SQLContainerImpl::TupleUpdateRowIdHandler::operator()( RowId rowId, uint64_t id, UpdateOperation op) { if (shared_ == NULL) { return; } util::LockGuard<util::Mutex> guard(shared_->mutex_); if (shared_->cxt_.get() == NULL) { return; } shared_->updated_ = true; if (rowId > shared_->maxRowId_ && (op == ResultSet::UPDATE_OP_UPDATE_NORMAL_ROW || op == ResultSet::UPDATE_OP_UPDATE_MVCC_ROW)) { return; } OpContext &cxt = *shared_->cxt_; const IdStoreColumnList &columnList = shared_->columnList_; const uint32_t index = shared_->rowIdStoreIndex_; { TupleListWriter &writer = cxt.getWriter(index); writer.next(); WritableTuple tuple = writer.get(); SQLValues::ValueUtils::writeValue<IdValueTag>( tuple, columnList[ID_COLUMN_POS], static_cast<IdValueTag::ValueType>(id)); SQLValues::ValueUtils::writeValue<OpValueTag>( tuple, columnList[OP_COLUMN_POS], static_cast<OpValueTag::ValueType>(op)); } cxt.releaseWriterLatch(index); } bool SQLContainerImpl::TupleUpdateRowIdHandler::apply( OIdTable &oIdTable, uint64_t limit) { if (shared_ == NULL || shared_->cxt_.get() == NULL) { return true; } OpContext &cxt = *shared_->cxt_; const IdStoreColumnList &columnList = shared_->columnList_; const uint32_t index = shared_->rowIdStoreIndex_; const uint32_t extraIndex = shared_->extraStoreIndex_; cxt.closeLocalWriter(index); bool extra = false; { uint64_t rest = std::max<uint64_t>(limit, 1); TupleListReader &reader = cxt.getLocalReader(index); for (; reader.exists(); reader.next(), --rest) { if (rest <= 0) { extra = true; break; } const uint64_t id = static_cast<uint64_t>( SQLValues::ValueUtils::readCurrentValue<IdValueTag>( reader, columnList[ID_COLUMN_POS])); const UpdateOperation op = static_cast<UpdateOperation>( SQLValues::ValueUtils::readCurrentValue<OpValueTag>( reader, columnList[OP_COLUMN_POS])); oIdTable.update(op, id); } shared_->updated_ = false; } if (extra) { cxt.createLocalTupleList(extraIndex); copyRowIdStore(cxt, index, extraIndex, columnList); cxt.closeLocalWriter(extraIndex); } cxt.closeLocalTupleList(index); cxt.createLocalTupleList(index); if (extra) { copyRowIdStore(cxt, extraIndex, index, columnList); cxt.closeLocalTupleList(extraIndex); } cxt.releaseWriterLatch(index); const bool finished = !extra; return finished; } SQLContainerImpl::TupleUpdateRowIdHandler* SQLContainerImpl::TupleUpdateRowIdHandler::share(util::StackAllocator &alloc) { assert(shared_ != NULL); return ALLOC_NEW(alloc) TupleUpdateRowIdHandler(*shared_); } SQLContainerImpl::TupleUpdateRowIdHandler::TupleUpdateRowIdHandler( Shared &shared) : shared_(&shared) { shared_->refCount_++; } uint32_t SQLContainerImpl::TupleUpdateRowIdHandler::createRowIdStore( util::LocalUniquePtr<OpContext> &cxt, const OpContext::Source &cxtSrc, IdStoreColumnList &columnList, uint32_t &extraStoreIndex) { cxt = UTIL_MAKE_LOCAL_UNIQUE(cxt, OpContext, cxtSrc); const size_t columnCount = sizeof(columnList) / sizeof(*columnList); const TupleColumnType baseTypeList[columnCount] = { IdValueTag::COLUMN_TYPE, OpValueTag::COLUMN_TYPE }; util::Vector<TupleColumnType> typeList( baseTypeList, baseTypeList + columnCount, cxt->getAllocator()); const uint32_t index = cxt->createLocal(&typeList); extraStoreIndex = cxt->createLocal(&typeList); const TupleList::Info &info = cxt->createLocalTupleList(index).getInfo(); info.getColumns(columnList, columnCount); return index; } void SQLContainerImpl::TupleUpdateRowIdHandler::copyRowIdStore( OpContext &cxt, uint32_t srcIndex, uint32_t destIndex, const IdStoreColumnList &columnList) { const size_t columnCount = sizeof(columnList) / sizeof(*columnList); TupleListReader &reader = cxt.getLocalReader(srcIndex); TupleListWriter &writer = cxt.getWriter(destIndex); for (; reader.exists(); reader.next()) { writer.next(); WritableTuple tuple = writer.get(); for (size_t i = 0; i < columnCount; i++) { SQLValues::ValueUtils::writeAny( tuple, columnList[i], SQLValues::ValueUtils::readCurrentAny( reader, columnList[i])); } } } SQLContainerImpl::TupleUpdateRowIdHandler::Shared::Shared( const OpContext::Source &cxtSrc, RowId maxRowId) : refCount_(1), rowIdStoreIndex_(createRowIdStore( cxt_, cxtSrc, columnList_, extraStoreIndex_)), maxRowId_(maxRowId), updated_(false) { } SQLContainerImpl::OIdTable::OIdTable(const Source &source) : allocManager_(*source.allocManager_), allocRef_(allocManager_, *source.baseAlloc_), alloc_(allocRef_.get()), large_(source.large_), mode_(source.mode_), category_(-1) { assert(mode_ != MergeMode::END_MODE); for (size_t i = 0; i < SUB_TABLE_COUNT; i++) { const bool mapOrdering = (mode_ != MergeMode::MODE_MIXED); if (mapOrdering) { subTables_[i].treeMap_ = ALLOC_NEW(alloc_) TreeGroupMap(alloc_); } else { subTables_[i].hashMap_ = ALLOC_NEW(alloc_) HashGroupMap( 0, GroupMapHasher(), GroupMapPred(), alloc_); } } } bool SQLContainerImpl::OIdTable::isEmpty() const { for (size_t i = 0; i < SUB_TABLE_COUNT; i++) { if (!subTables_[i].isSubTableEmpty()) { return false; } } return true; } void SQLContainerImpl::OIdTable::addAll(const SearchResult &result) { for (size_t i = 0; i < 2; i++) { const bool onMvcc = (i != 0); addAll(result.getEntry(onMvcc), onMvcc); } } void SQLContainerImpl::OIdTable::addAll( const SearchResultEntry &entry, bool onMvcc) { prepareToAdd(entry); const SwitcherOption option = toSwitcherOption(onMvcc); AddAllOp op(entry); (op.*Switcher(option).resolve<AddAllOp>())(option); } void SQLContainerImpl::OIdTable::popAll( SearchResult &result, uint64_t limit, uint32_t rowArraySize) { assert(result.isEmpty()); SearchResultEntry &entry = result.getEntry(false); bool onMvcc; popAll(entry, onMvcc, limit, rowArraySize); if (onMvcc) { entry.swap(result.getEntry(true)); } } void SQLContainerImpl::OIdTable::popAll( SearchResultEntry &entry, bool &onMvcc, uint64_t limit, uint32_t rowArraySize) { assert(entry.isEntryEmpty()); onMvcc = false; for (;;) { const SwitcherOption option = toSwitcherOption(onMvcc); PopAllOp op(entry, limit, rowArraySize); (op.*Switcher(option).resolve<PopAllOp>())(option); if (!entry.isEntryEmpty() || onMvcc) { break; } onMvcc = !onMvcc; } } void SQLContainerImpl::OIdTable::update( ResultSet::UpdateOperation op, OId oId) { switch (op) { case ResultSet::UPDATE_OP_UPDATE_NORMAL_ROW: add(oId, false); break; case ResultSet::UPDATE_OP_UPDATE_MVCC_ROW: add(oId, true); break; case ResultSet::UPDATE_OP_REMOVE_ROW: remove(oId, true); remove(oId, false); break; case ResultSet::UPDATE_OP_REMOVE_ROW_ARRAY: removeRa(oId, true); removeRa(oId, false); break; case ResultSet::UPDATE_OP_REMOVE_CHUNK: removeChunk(oId, true); removeChunk(oId, false); break; } } void SQLContainerImpl::OIdTable::readAll( SearchResult &result, uint64_t limit, bool large, MergeMode::Type mode, uint32_t rowArraySize, Reader &reader) { assert(result.isEmpty()); SwitcherOption option; option.onLarge_ = large; option.mode_ = mode; uint64_t rest = limit; for (size_t i = 0; i < 2; i++) { const bool onMvcc = (i == 0); option.onMvcc_ = onMvcc; SearchResultEntry &entry = result.getEntry(onMvcc); ReadAllOp op(entry, rest, rowArraySize, reader); (op.*Switcher(option).resolve<ReadAllOp>())(option); rest -= std::min<uint64_t>(getEntrySize(entry, rowArraySize), rest); } } void SQLContainerImpl::OIdTable::load(Reader &reader) { for (size_t i = 0; i < 2; i++) { const bool onMvcc = (i == 0); const SwitcherOption option = toSwitcherOption(onMvcc); LoadOp op(reader); (op.*Switcher(option).resolve<LoadOp>())(option); } } void SQLContainerImpl::OIdTable::save(Writer &writer) { for (size_t i = 0; i < 2; i++) { const bool onMvcc = (i == 0); const SwitcherOption option = toSwitcherOption(onMvcc); SaveOp op(writer); (op.*Switcher(option).resolve<SaveOp>())(option); } } size_t SQLContainerImpl::OIdTable::getTotalAllocationSize() { return alloc_.getTotalSize(); } void SQLContainerImpl::OIdTable::add(OId oId, bool onMvcc) { prepareToAdd(oId); const bool forRa = isForRaWithMode(false, mode_); const SwitcherOption option = toSwitcherOption(onMvcc); AddOp op(oId, forRa); (op.*Switcher(option).resolve<AddOp>())(option); } void SQLContainerImpl::OIdTable::remove(OId oId, bool onMvcc, bool forRa) { const SwitcherOption option = toSwitcherOption(onMvcc); RemoveOp op(oId, forRa); (op.*Switcher(option).resolve<RemoveOp>())(option); } void SQLContainerImpl::OIdTable::removeRa(OId oId, bool onMvcc) { const bool forRa = true; remove(oId, onMvcc, forRa); } void SQLContainerImpl::OIdTable::removeChunk(OId oId, bool onMvcc) { const SwitcherOption option = toSwitcherOption(onMvcc); RemoveChunkOp op(oId); (op.*Switcher(option).resolve<RemoveChunkOp>())(option); } template<bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> void SQLContainerImpl::OIdTable::readAllDetail( SearchResultEntry &entry, uint64_t limit, uint32_t rowArraySize, Reader &reader) { uint64_t rest = limit; bool forRa; Code code; while (rest > 0 && readTopElement<Mvcc, Large, Mode>(reader, forRa, code)) { OIdList &oIdList = entry.getOIdList(isForRaWithMode<Mode>(forRa)); const size_t prevSize = oIdList.size(); const Code lastMasked = CodeUtils::toMaskedCode<Large>(code); do { oIdList.push_back(CodeUtils::codeToOId<Large>(code)); } while (readNextElement<Large, Mode>(reader, forRa, lastMasked, code)); rest -= std::min<uint64_t>(getEntrySize( forRa, (oIdList.size() - prevSize), rowArraySize), rest); } } template<bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> void SQLContainerImpl::OIdTable::loadDetail( typename MapByMode<Mode>::Type &map, Reader &reader) { bool forRa; Code code; while (readTopElement<Mvcc, Large, Mode>(reader, forRa, code)) { prepareToAdd(CodeUtils::codeToOId<Large>(code)); ElementSet &elemSet = insertGroup(map, CodeUtils::toGroup<Large>(code), forRa); ElementList &list = elemSet.elems_; assert(list.empty()); const Code lastMasked = CodeUtils::toMaskedCode<Large>(code); do { list.push_back(CodeUtils::toElement<Large>(code)); } while (readNextElement<Large, Mode>(reader, forRa, lastMasked, code)); } } template<bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> void SQLContainerImpl::OIdTable::saveDetail( typename MapByMode<Mode>::Type &map, Writer &writer) { typedef typename MapByMode<Mode>::Type Map; typedef typename Map::iterator MapIterator; if (map.empty()) { return; } const Element category = resolveCategory(); for (MapIterator mapIt = map.begin(); mapIt != map.end(); ++mapIt) { writeGroupHead<Mvcc, Large, Mode>( writer, mapIt->second.isForRa(), mapIt->first); ElementList &list = mapIt->second.elems_; for (ElementList::iterator it = list.begin(); it != list.end(); ++it) { writer.writeCode( CodeUtils::toCode<Mvcc, Large>(mapIt->first, *it, category)); } } } inline bool SQLContainerImpl::OIdTable::isForRaWithMode( bool forRa, MergeMode::Type mode) { return (mode == MergeMode::MODE_ROW_ARRAY || forRa); } template<SQLContainerUtils::ScanMergeMode::Type Mode> inline bool SQLContainerImpl::OIdTable::isForRaWithMode(bool forRa) { return (Mode == MergeMode::MODE_ROW_ARRAY || forRa); } template<SQLContainerUtils::ScanMergeMode::Type Mode> inline bool SQLContainerImpl::OIdTable::isRaMerging(bool forRa) { return (Mode == MergeMode::MODE_MIXED_MERGING && !forRa); } template<bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> inline bool SQLContainerImpl::OIdTable::readTopElement( Reader &reader, bool &forRa, Code &code) { if (!reader.exists()) { return false; } bool withHead = false; forRa = (Mode == MergeMode::MODE_ROW_ARRAY); code = reader.getCode(); Code lastMasked = CodeUtils::toMaskedCode<Large>(code); for (;;) { if (Mvcc && !CodeUtils::isOnMvcc(code)) { return false; } assert(!Mvcc == !CodeUtils::isOnMvcc(code)); if (Mode != MergeMode::MODE_ROW_ARRAY && CodeUtils::isGroupHead<Large>(code)) { if (Mode == MergeMode::MODE_MIXED_MERGING) { forRa |= CodeUtils::isRaHead<Large>(code); } reader.next(); if (!reader.exists()) { return false; } code = reader.getCode(); const Code masked = CodeUtils::toMaskedCode<Large>(code); if (masked == lastMasked) { withHead = true; } else { if (Mode == MergeMode::MODE_MIXED_MERGING) { forRa = false; } lastMasked = masked; withHead = false; } continue; } assert(!CodeUtils::isGroupHead<Large>(code)); if (Mode != MergeMode::MODE_ROW_ARRAY && !withHead) { forRa = true; } if (Mode == MergeMode::MODE_MIXED_MERGING && forRa) { code = CodeUtils::toRaCode(code); } return true; } } template<bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> inline bool SQLContainerImpl::OIdTable::readNextElement( Reader &reader, bool forRa, Code lastMasked, Code &code) { Code prevCode = code; for (;;) { reader.next(); if (!reader.exists()) { return false; } code = reader.getCode(); if (CodeUtils::toMaskedCode<Large>(code) != lastMasked) { return false; } assert(!CodeUtils::isGroupHead<Large>(code)); if (Mode == MergeMode::MODE_MIXED_MERGING && forRa) { code = CodeUtils::toRaCode(code); if (code == prevCode) { prevCode = code; continue; } } return true; } } template<bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> inline void SQLContainerImpl::OIdTable::writeGroupHead( Writer &writer, bool forRa, Group group) { if (Mode == MergeMode::MODE_ROW_ARRAY || (Mode != MergeMode::MODE_MIXED_MERGING && forRa)) { return; } Code code; if (Mode == MergeMode::MODE_MIXED_MERGING && forRa) { code = CodeUtils::toGroupHead<Mvcc, Large, true>(group); } else { assert(!forRa); code = CodeUtils::toGroupHead<Mvcc, Large, false>(group); } writer.writeCode(code); } template<bool Large, bool Ordering> void SQLContainerImpl::OIdTable::addAllDetail( typename MapByOrdering<Ordering>::Type &map, const SearchResultEntry &entry) { { const bool forRa = false; const OIdList &list = entry.getOIdList(forRa); addAllDetail<Large, Ordering>(map, list, isForRaWithMode(forRa, mode_)); } { const bool forRa = true; const OIdList &list = entry.getOIdList(forRa); addAllDetail<Large, Ordering>(map, list, forRa); } } template<bool Large, bool Ordering> void SQLContainerImpl::OIdTable::addAllDetail( typename MapByOrdering<Ordering>::Type &map, const OIdList &list, bool forRa) { if (forRa) { for (OIdList::const_iterator it = list.begin(); it != list.end(); ++it) { addRaDetail<Large, Ordering>(map, *it); } } else { for (OIdList::const_iterator it = list.begin(); it != list.end(); ++it) { addDetail<Large, Ordering>(map, *it); } } } template<bool Large, bool Ordering> inline void SQLContainerImpl::OIdTable::addDetail( typename MapByOrdering<Ordering>::Type &map, OId oId, bool forRa) { if (forRa) { addRaDetail<Large, Ordering>(map, oId); } else { addDetail<Large, Ordering>(map, oId); } } template<bool Large, bool Ordering> inline void SQLContainerImpl::OIdTable::addDetail( typename MapByOrdering<Ordering>::Type &map, OId oId) { ElementSet &elemSet = insertGroup(map, CodeUtils::oIdToGroup<Large>(oId), false); if (elemSet.isForRa()) { insertElement(elemSet, CodeUtils::oIdToRaElement<Large>(oId)); } else if (insertElement(elemSet, CodeUtils::oIdToElement<Large>(oId)) && !elemSet.acceptRows()) { elementSetToRa(elemSet); } } template<bool Large, bool Ordering> inline void SQLContainerImpl::OIdTable::addRaDetail( typename MapByOrdering<Ordering>::Type &map, OId oId) { ElementSet &elemSet = insertGroup(map, CodeUtils::oIdToGroup<Large>(oId), true); if (!elemSet.isForRa()) { elementSetToRa(elemSet); } insertElement(elemSet, CodeUtils::oIdToRaElement<Large>(oId)); } template<bool Large, bool Ordering> void SQLContainerImpl::OIdTable::popAllDetail( typename MapByOrdering<Ordering>::Type &map, SearchResultEntry &entry, uint64_t limit, uint32_t rowArraySize) { typedef typename MapByOrdering<Ordering>::Type Map; typedef typename Map::iterator MapIterator; if (map.empty()) { return; } const Element category = resolveCategory(); uint64_t rest = limit; for (MapIterator mapIt = map.begin(); mapIt != map.end();) { if (rest <= 0) { break; } const bool forRa = mapIt->second.isForRa(); OIdList &oIdList = entry.getOIdList(forRa); const size_t prevSize = oIdList.size(); ElementList &list = mapIt->second.elems_; for (ElementList::iterator it = list.begin(); it != list.end(); ++it) { oIdList.push_back( CodeUtils::toOId<Large>(mapIt->first, *it, category)); } MapIterator lastIt = mapIt; ++mapIt; map.erase(lastIt); rest -= std::min<uint64_t>(getEntrySize( forRa, (oIdList.size() - prevSize), rowArraySize), rest); } } template<bool Large, bool Ordering> void SQLContainerImpl::OIdTable::removeDetail( typename MapByOrdering<Ordering>::Type &map, OId oId, bool forRa) { typedef typename MapByOrdering<Ordering>::Type Map; typedef typename Map::iterator MapIterator; MapIterator mapIt = map.find(CodeUtils::oIdToGroup<Large>(oId)); if (mapIt == map.end()) { return; } ElementSet &elemSet = mapIt->second; if (mapIt->second.isForRa()) { if (!forRa) { return; } } else { if (forRa) { elementSetToRa(elemSet); } } const Element elem = (mapIt->second.isForRa() ? CodeUtils::oIdToRaElement<Large>(oId) : CodeUtils::oIdToElement<Large>(oId)); if (eraseElement(elemSet, elem) && elemSet.elems_.empty()) { map.erase(mapIt); } } template<bool Large, bool Ordering> void SQLContainerImpl::OIdTable::removeChunkDetail( typename MapByOrdering<Ordering>::Type &map, OId oId) { typedef typename MapByOrdering<Ordering>::Type Map; typedef typename Map::iterator MapIterator; MapIterator mapIt = map.find(CodeUtils::oIdToGroup<Large>(oId)); if (mapIt == map.end()) { return; } map.erase(mapIt); } void SQLContainerImpl::OIdTable::elementSetToRa(ElementSet &elemSet) { ElementList &list = elemSet.elems_; ElementList::iterator it = list.begin(); if (it != list.end()) { *it = CodeUtils::toRaElement(*it); ElementList::iterator next = it; while ((++next) != list.end()) { const Element elem = CodeUtils::toRaElement(*next); if (elem != *it) { *(++it) = elem; } } list.erase((++it), list.end()); } elemSet.setForRa(); } template<typename Map> inline SQLContainerImpl::OIdTable::ElementSet& SQLContainerImpl::OIdTable::insertGroup(Map &map, Group group, bool forRa) { typename Map::iterator mapIt = map.find(group); if (mapIt == map.end()) { ElementSet &elemSet = map.insert(std::make_pair( group, ElementSet(alloc_, forRa))).first->second; elemSet.elems_.reserve(ELEMENT_SET_ROWS_CAPACITY); return elemSet; } return mapIt->second; } inline bool SQLContainerImpl::OIdTable::insertElement( ElementSet &elemSet, Element elem) { ElementList &list = elemSet.elems_; ElementList::iterator it = std::lower_bound(list.begin(), list.end(), elem); if (it == list.end() || *it != elem) { list.insert(it, elem); return true; } return false; } inline bool SQLContainerImpl::OIdTable::eraseElement( ElementSet &elemSet, Element elem) { ElementList &list = elemSet.elems_; ElementList::iterator it = std::lower_bound(list.begin(), list.end(), elem); if (it != list.end() && *it == elem) { list.erase(it); return true; } return false; } void SQLContainerImpl::OIdTable::prepareToAdd(const SearchResultEntry &entry) { if (category_ >= 0) { return; } for (size_t i = 0; i < 2; i++) { const bool forRa = (i != 0); const OIdList &oIdList = entry.getOIdList(forRa); if (!oIdList.empty()) { prepareToAdd(oIdList.front()); break; } } } void SQLContainerImpl::OIdTable::prepareToAdd(OId oId) { if (category_ >= 0) { return; } category_ = static_cast<int64_t>(CodeUtils::oIdToCategory(oId)); } SQLContainerImpl::OIdTable::TreeGroupMap& SQLContainerImpl::OIdTable::getGroupMap(bool onMvcc, const util::TrueType&) { TreeGroupMap *map = subTables_[(onMvcc ? 1 : 0)].treeMap_; assert(map != NULL); return *map; } SQLContainerImpl::OIdTable::HashGroupMap& SQLContainerImpl::OIdTable::getGroupMap(bool onMvcc, const util::FalseType&) { HashGroupMap *map = subTables_[(onMvcc ? 1 : 0)].hashMap_; assert(map != NULL); return *map; } SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::resolveCategory() { if (category_ < 0) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return static_cast<Element>(category_); } SQLContainerImpl::OIdTable::SwitcherOption SQLContainerImpl::OIdTable::toSwitcherOption(bool onMvcc) { SwitcherOption option; option.onMvcc_ = onMvcc; option.onLarge_ = large_; option.mode_ = mode_; option.table_ = this; return option; } uint64_t SQLContainerImpl::OIdTable::getEntrySize( const SearchResultEntry &entry, uint32_t rowArraySize) { uint64_t size = 0; for (size_t i = 0; i < 2; i++) { const bool forRa = (i != 0); size += getEntrySize(forRa, entry.getOIdList(forRa).size(), rowArraySize); } return size; } uint64_t SQLContainerImpl::OIdTable::getEntrySize( bool forRa, size_t elemCount, uint32_t rowArraySize) { return static_cast<uint64_t>(forRa ? rowArraySize : 1) * elemCount; } SQLContainerImpl::OIdTable::Source::Source() : allocManager_(NULL), baseAlloc_(NULL), large_(false), mode_(MergeMode::END_MODE) { } SQLContainerImpl::OIdTable::Source SQLContainerImpl::OIdTable::Source::ofContext( OpContext &cxt, MergeMode::Type mode) { Source source; source.allocManager_ = &cxt.getAllocatorManager(); source.baseAlloc_ = &cxt.getAllocator().base(); source.large_ = detectLarge(cxt.getExtContext().getResourceSet()->getDataStore()); source.mode_ = mode; return source; } bool SQLContainerImpl::OIdTable::Source::detectLarge(DataStore *dataStore) { if (dataStore == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } ObjectManager *objectManager = dataStore->getObjectManager(); if (objectManager == NULL) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } const uint32_t chunkSize = objectManager->getChunkSize(); const uint32_t chunkExpSize = util::nextPowerBitsOf2(chunkSize); if (chunkSize != (static_cast<uint32_t>(1) << chunkExpSize)) { assert(false); GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return OIdBitUtils::isLargeChunkMode(chunkExpSize); } SQLContainerImpl::OIdTable::Reader::Reader( BaseReader &base, const TupleColumnList &columnList) : base_(base), column_(columnList.front()) { } inline bool SQLContainerImpl::OIdTable::Reader::exists() { return base_.exists(); } inline void SQLContainerImpl::OIdTable::Reader::next() { base_.next(); } inline SQLContainerImpl::OIdTable::Code SQLContainerImpl::OIdTable::Reader::getCode() { typedef SQLValues::Types::Long TypeTag; return static_cast<Code>( SQLValues::ValueUtils::readCurrentValue<TypeTag>(base_, column_)); } SQLContainerImpl::OIdTable::Writer::Writer( BaseWriter &base, const TupleColumnList &columnList) : base_(base), column_(columnList.front()) { } inline void SQLContainerImpl::OIdTable::Writer::writeCode(Code code) { typedef SQLValues::Types::Long TypeTag; base_.next(); WritableTuple tuple = base_.get(); SQLValues::ValueUtils::writeValue<TypeTag>( tuple, column_, static_cast<TypeTag::ValueType>(code)); } SQLContainerImpl::OIdTable::SwitcherOption::SwitcherOption() : onMvcc_(false), onLarge_(false), mode_(MergeMode::END_MODE), table_(NULL) { } SQLContainerImpl::OIdTable& SQLContainerImpl::OIdTable::SwitcherOption::getTable() const { assert(table_ != NULL); return *table_; } SQLContainerImpl::OIdTable::Switcher::Switcher(const SwitcherOption &option) : option_(option) { } template<typename Op> typename SQLContainerImpl::OIdTable::Switcher::template OpTraits<Op>::FuncType SQLContainerImpl::OIdTable::Switcher::resolve() const { typedef typename Op::SwitcherTraitsType::MvccFilter FilterType; if (option_.onMvcc_ && FilterType::OPTION_SPECIFIC) { return resolveDetail<Op, FilterType::template At<true>::VALUE>(); } else { return resolveDetail<Op, FilterType::template At<false>::VALUE>(); } } template<typename Op, bool Mvcc> typename SQLContainerImpl::OIdTable::Switcher::template OpTraits<Op>::FuncType SQLContainerImpl::OIdTable::Switcher::resolveDetail() const { if (option_.onLarge_) { return resolveDetail<Op, Mvcc, true>(); } else { return resolveDetail<Op, Mvcc, false>(); } } template<typename Op, bool Mvcc, bool Large> typename SQLContainerImpl::OIdTable::Switcher::template OpTraits<Op>::FuncType SQLContainerImpl::OIdTable::Switcher::resolveDetail() const { typedef typename Op::SwitcherTraitsType::ModeFilter FilterType; switch (option_.mode_) { case MergeMode::MODE_MIXED: return resolveDetail<Op, Mvcc, Large, FilterType::template At< MergeMode::MODE_MIXED>::VALUE>(); case MergeMode::MODE_MIXED_MERGING: return resolveDetail<Op, Mvcc, Large, FilterType::template At< MergeMode::MODE_MIXED_MERGING>::VALUE>(); default: assert(option_.mode_ == MergeMode::MODE_ROW_ARRAY); return resolveDetail<Op, Mvcc, Large, FilterType::template At< MergeMode::MODE_ROW_ARRAY>::VALUE>(); } } template< typename Op, bool Mvcc, bool Large, SQLContainerUtils::ScanMergeMode::Type Mode> typename SQLContainerImpl::OIdTable::Switcher::template OpTraits<Op>::FuncType SQLContainerImpl::OIdTable::Switcher::resolveDetail() const { typedef OpFuncTraits<Mvcc, Large, Mode> FuncTraitsType; return &Op::template execute<FuncTraitsType>; } SQLContainerImpl::OIdTable::ReadAllOp::ReadAllOp( SearchResultEntry &entry, uint64_t limit, uint32_t rowArraySize, Reader &reader) : entry_(entry), limit_(limit), rowArraySize_(rowArraySize), reader_(reader) { } template<typename Traits> void SQLContainerImpl::OIdTable::ReadAllOp::execute( const SwitcherOption &option) const { static_cast<void>(option); readAllDetail<Traits::ON_MVCC, Traits::ON_LARGE, Traits::MERGE_MODE>( entry_, limit_, rowArraySize_, reader_); } SQLContainerImpl::OIdTable::LoadOp::LoadOp(Reader &reader) : reader_(reader) { } template<typename Traits> void SQLContainerImpl::OIdTable::LoadOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.loadDetail< Traits::ON_MVCC, Traits::ON_LARGE, Traits::MERGE_MODE>( table.getGroupMap(option.onMvcc_, MapOrderingType()), reader_); } SQLContainerImpl::OIdTable::SaveOp::SaveOp(Writer &writer) : writer_(writer) { } template<typename Traits> void SQLContainerImpl::OIdTable::SaveOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.saveDetail< Traits::ON_MVCC, Traits::ON_LARGE, Traits::MERGE_MODE>( table.getGroupMap(option.onMvcc_, MapOrderingType()), writer_); } SQLContainerImpl::OIdTable::AddAllOp::AddAllOp(const SearchResultEntry &entry) : entry_(entry) { } template<typename Traits> void SQLContainerImpl::OIdTable::AddAllOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.addAllDetail<Traits::ON_LARGE, Traits::MAP_ORDERING>( table.getGroupMap(option.onMvcc_, MapOrderingType()), entry_); } SQLContainerImpl::OIdTable::PopAllOp::PopAllOp( SearchResultEntry &entry, uint64_t limit, uint32_t rowArraySize) : entry_(entry) { } template<typename Traits> void SQLContainerImpl::OIdTable::PopAllOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.popAllDetail<Traits::ON_LARGE, Traits::MAP_ORDERING>( table.getGroupMap(option.onMvcc_, MapOrderingType()), entry_, limit_, rowArraySize_); } SQLContainerImpl::OIdTable::AddOp::AddOp(OId oId, bool forRa) : oId_(oId), forRa_(forRa) { } template<typename Traits> void SQLContainerImpl::OIdTable::AddOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.addDetail<Traits::ON_LARGE, Traits::MAP_ORDERING>( table.getGroupMap(option.onMvcc_, MapOrderingType()), oId_, forRa_); } SQLContainerImpl::OIdTable::RemoveOp::RemoveOp(OId oId, bool forRa) : oId_(oId), forRa_(forRa) { } template<typename Traits> void SQLContainerImpl::OIdTable::RemoveOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.removeDetail<Traits::ON_LARGE, Traits::MAP_ORDERING>( table.getGroupMap(option.onMvcc_, MapOrderingType()), oId_, forRa_); } SQLContainerImpl::OIdTable::RemoveChunkOp::RemoveChunkOp(OId oId) : oId_(oId) { } template<typename Traits> void SQLContainerImpl::OIdTable::RemoveChunkOp::execute( const SwitcherOption &option) const { typedef typename Traits::MapOrderingType MapOrderingType; OIdTable &table = option.getTable(); table.removeChunkDetail<Traits::ON_LARGE, Traits::MAP_ORDERING>( table.getGroupMap(option.onMvcc_, MapOrderingType()), oId_); } template<bool Large> inline OId SQLContainerImpl::OIdTable::CodeUtils::toOId( Group group, Element elem, Element category) { typedef OIdConstants<Large> SubConstants; return (static_cast<Code>(group) << SubConstants::GROUP_TO_OID_CHUNK_BIT) | (static_cast<Code>(elem & OIdConstantsBase::ELEMENT_NON_USER_MASK) << OIdConstantsBase::ELEMENT_TO_OID_OFFSET_BIT) | OIdConstantsBase::MAGIC_NUMBER | category | (elem & OIdConstantsBase::USER_MASK); } template<bool Large> inline OId SQLContainerImpl::OIdTable::CodeUtils::codeToOId(Code code) { typedef OIdConstants<Large> SubConstants; return ((code & SubConstants::CODE_GROUP_MASK) << CODE_TO_OID_CHUNK_BIT) | ((code & SubConstants::CODE_OFFSET_MASK) << OIdConstantsBase::CODE_TO_OID_OFFSET_BIT) | OIdConstantsBase::MAGIC_NUMBER | (code & OIdConstantsBase::CATEGORY_USER_MASK); } template<bool Large> inline SQLContainerImpl::OIdTable::Group SQLContainerImpl::OIdTable::CodeUtils::oIdToGroup(OId oId) { typedef OIdConstants<Large> SubConstants; return static_cast<Group>(oId >> SubConstants::GROUP_TO_OID_CHUNK_BIT); } template<bool Large> inline SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::CodeUtils::oIdToElement(OId oId) { typedef OIdConstants<Large> SubConstants; return static_cast<Element>( ((oId & SubConstants::OID_OFFSET_MASK) >> OIdConstantsBase::ELEMENT_TO_OID_OFFSET_BIT) | (oId & OIdConstantsBase::USER_MASK)); } template<bool Large> inline SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::CodeUtils::oIdToRaElement(OId oId) { typedef OIdConstants<Large> SubConstants; return static_cast<Element>( ((oId & SubConstants::OID_OFFSET_MASK) >> OIdConstantsBase::ELEMENT_TO_OID_OFFSET_BIT)); } inline SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::CodeUtils::oIdToCategory(OId oId) { return static_cast<Element>(oId & OIdConstantsBase::CATEGORY_MASK); } template<bool Mvcc, bool Large> inline SQLContainerImpl::OIdTable::Code SQLContainerImpl::OIdTable::CodeUtils::toCode( Group group, Element elem, Element category) { typedef OIdConstants<Large> SubConstants; return (Mvcc ? CODE_MVCC_FLAG : 0) | (static_cast<Code>(group) << SubConstants::GROUP_TO_CODE_BIT) | SubConstants::CODE_BODY_FLAG | (static_cast<Code>(elem & OIdConstantsBase::ELEMENT_NON_USER_MASK) << OIdConstantsBase::ELEMENT_TO_CODE_OFFSET_BIT) | category | (elem & OIdConstantsBase::USER_MASK); } template<bool Large> inline SQLContainerImpl::OIdTable::Code SQLContainerImpl::OIdTable::CodeUtils::toMaskedCode(Code code) { typedef OIdConstants<Large> SubConstants; return (code & SubConstants::CODE_MVCC_GROUP_MASK); } inline SQLContainerImpl::OIdTable::Code SQLContainerImpl::OIdTable::CodeUtils::toRaCode(Code code) { return (code & OIdConstantsBase::CODE_NON_USER_MASK); } template<bool Mvcc, bool Large, bool ForRa> inline SQLContainerImpl::OIdTable::Code SQLContainerImpl::OIdTable::CodeUtils::toGroupHead(Group group) { typedef OIdConstants<Large> SubConstants; return (Mvcc ? CODE_MVCC_FLAG : 0) | (static_cast<Code>(group) << SubConstants::GROUP_TO_CODE_BIT) | (ForRa ? SubConstants::CODE_RA_FLAG : 0); } template<bool Large> inline bool SQLContainerImpl::OIdTable::CodeUtils::isGroupHead(Code code) { typedef OIdConstants<Large> SubConstants; return ((code & SubConstants::CODE_BODY_FLAG) == 0); } template<bool Large> inline bool SQLContainerImpl::OIdTable::CodeUtils::isRaHead(Code code) { typedef OIdConstants<Large> SubConstants; return ((code & SubConstants::CODE_RA_FLAG) != 0); } inline bool SQLContainerImpl::OIdTable::CodeUtils::isOnMvcc(Code code) { UTIL_STATIC_ASSERT(sizeof(Code) == sizeof(SignedCode)); UTIL_STATIC_ASSERT(std::numeric_limits<SignedCode>::is_signed); return static_cast<SignedCode>(code) < 0; } template<bool Large> inline SQLContainerImpl::OIdTable::Group SQLContainerImpl::OIdTable::CodeUtils::toGroup(Code code) { typedef OIdConstants<Large> SubConstants; return static_cast<Group>( ((code & SubConstants::CODE_GROUP_MASK) >> SubConstants::GROUP_TO_CODE_BIT)); } template<bool Large> inline SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::CodeUtils::toElement(Code code) { typedef OIdConstants<Large> SubConstants; return static_cast<Element>( ((code & SubConstants::CODE_OFFSET_MASK) >> OIdConstantsBase::ELEMENT_TO_CODE_OFFSET_BIT) | (code & OIdConstantsBase::USER_MASK)); } inline SQLContainerImpl::OIdTable::Element SQLContainerImpl::OIdTable::CodeUtils::toRaElement(Element elem) { return (elem & OIdConstantsBase::ELEMENT_NON_USER_MASK); } inline SQLContainerImpl::OIdTable::ElementSet::ElementSet( util::StackAllocator &alloc, bool forRa) : rowsRest_((forRa ? 0 : ELEMENT_SET_ROWS_CAPACITY)) , elems_(alloc) { } inline bool SQLContainerImpl::OIdTable::ElementSet::isForRa() const { return (rowsRest_ <= 0); } inline void SQLContainerImpl::OIdTable::ElementSet::setForRa() { rowsRest_ = 0; } inline bool SQLContainerImpl::OIdTable::ElementSet::acceptRows() { assert(!isForRa()); return (--rowsRest_ > 0); } SQLContainerImpl::OIdTable::SubTable::SubTable() : treeMap_(NULL), hashMap_(NULL) { } bool SQLContainerImpl::OIdTable::SubTable::isSubTableEmpty() const { if (treeMap_ != NULL && !treeMap_->empty()) { return false; } if (hashMap_ != NULL && !hashMap_->empty()) { return false; } return true; } SQLContainerImpl::RowIdFilter::RowIdFilter( SQLOps::OpAllocatorManager &allocManager, util::StackAllocator::BaseAllocator &baseAlloc, RowId maxRowId) : allocManager_(allocManager), allocRef_(allocManager_, baseAlloc), alloc_(allocRef_.get()), maxRowId_(maxRowId), rowIdBits_(alloc_), readOnly_(false) { } inline bool SQLContainerImpl::RowIdFilter::accept(RowId rowId) { if (rowId > maxRowId_) { return false; } if (readOnly_) { return (rowIdBits_.find(rowId) == rowIdBits_.end()); } else { return rowIdBits_.insert(rowId).second; } } void SQLContainerImpl::RowIdFilter::load( OpContext::Source &cxtSrc, uint32_t input) { OpContext cxt(cxtSrc); load(cxt.getLocalReader(input)); } uint32_t SQLContainerImpl::RowIdFilter::save(OpContext::Source &cxtSrc) { OpContext cxt(cxtSrc); const uint32_t columnCount = BITS_STORE_COLUMN_COUNT; const util::Vector<TupleColumnType> typeList( Constants::COLUMN_TYPES, Constants::COLUMN_TYPES + columnCount, cxt.getAllocator()); const uint32_t output = cxt.createLocal(&typeList); cxt.createLocalTupleList(output); save(cxt.getWriter(output)); cxt.closeLocalWriter(output); cxt.releaseWriterLatch(output); return output; } void SQLContainerImpl::RowIdFilter::load(TupleListReader &reader) { BitsStoreColumnList columnList; getBitsStoreColumnList(columnList); BitSet::OutputCursor cursor(rowIdBits_); for (; reader.exists(); reader.next()) { cursor.next(BitSet::CodedEntry( SQLValues::ValueUtils::readCurrentValue<BitsKeyTag>( reader, columnList[BITS_KEY_COLUMN_POS]), SQLValues::ValueUtils::readCurrentValue<BitsValueTag>( reader, columnList[BITS_VALUE_COLUMN_POS]))); } } void SQLContainerImpl::RowIdFilter::save(TupleListWriter &writer) { BitsStoreColumnList columnList; getBitsStoreColumnList(columnList); BitSet::InputCursor cursor(rowIdBits_); for (BitSet::CodedEntry entry; cursor.next(entry);) { writer.next(); WritableTuple tuple = writer.get(); SQLValues::ValueUtils::writeValue<BitsKeyTag>( tuple, columnList[BITS_KEY_COLUMN_POS], entry.first); SQLValues::ValueUtils::writeValue<BitsValueTag>( tuple, columnList[BITS_VALUE_COLUMN_POS], entry.second); } } void SQLContainerImpl::RowIdFilter::setReadOnly() { readOnly_ = true; } void SQLContainerImpl::RowIdFilter::getBitsStoreColumnList( BitsStoreColumnList &columnList) { const uint32_t count = BITS_STORE_COLUMN_COUNT; UTIL_STATIC_ASSERT(sizeof(columnList) / sizeof(*columnList) == count); TupleList::Info info; info.columnCount_ = count; info.columnTypeList_ = Constants::COLUMN_TYPES; info.getColumns(columnList, info.columnCount_); } const TupleColumnType SQLContainerImpl::RowIdFilter::Constants::COLUMN_TYPES[ BITS_STORE_COLUMN_COUNT] = { BitsKeyTag::COLUMN_TYPE, BitsValueTag::COLUMN_TYPE }; void SQLContainerImpl::ContainerValueUtils::toContainerValue( util::StackAllocator &alloc, const TupleValue &src, Value &dest) { switch (src.getType()) { case TupleTypes::TYPE_BOOL: dest.set(!!ValueUtils::getValue<int8_t>(src)); break; case TupleTypes::TYPE_BYTE: dest.set(ValueUtils::getValue<int8_t>(src)); break; case TupleTypes::TYPE_SHORT: dest.set(ValueUtils::getValue<int16_t>(src)); break; case TupleTypes::TYPE_INTEGER: dest.set(ValueUtils::getValue<int32_t>(src)); break; case TupleTypes::TYPE_LONG: dest.set(ValueUtils::getValue<int64_t>(src)); break; case TupleTypes::TYPE_FLOAT: dest.set(ValueUtils::getValue<float>(src)); break; case TupleTypes::TYPE_DOUBLE: dest.set(ValueUtils::getValue<double>(src)); break; case TupleTypes::TYPE_TIMESTAMP: dest.setTimestamp(ValueUtils::getValue<int64_t>(src)); break; case TupleTypes::TYPE_STRING: { const TupleString::BufferInfo &str = TupleString(src).getBuffer(); char8_t *addr = const_cast<char8_t*>(str.first); const uint32_t size = static_cast<uint32_t>(str.second); dest.set(alloc, addr, size); } break; case TupleTypes::TYPE_BLOB: { util::XArray<char8_t> buf(alloc); { TupleValue::LobReader reader(src); const void *data; size_t size; while (reader.next(data, size)) { const size_t offset = buf.size(); buf.resize(offset + size); memcpy(&buf[offset], data, size); } } { const uint32_t size = static_cast<uint32_t>(buf.size()); dest.set(alloc, buf.data(), size); } } break; case TupleTypes::TYPE_NULL: dest.setNull(); break; default: GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Unexpected parameter value type"); } } bool SQLContainerImpl::ContainerValueUtils::toTupleValue( util::StackAllocator &alloc, const Value &src, TupleValue &dest, bool failOnUnsupported) { switch (src.getType()) { case COLUMN_TYPE_STRING: dest = SyntaxTree::makeStringValue( alloc, reinterpret_cast<const char8_t*>(src.data()), src.size()); break; case COLUMN_TYPE_BOOL: dest = TupleValue(src.getBool()); break; case COLUMN_TYPE_BYTE: dest = TupleValue(src.getByte()); break; case COLUMN_TYPE_SHORT: dest = TupleValue(src.getShort()); break; case COLUMN_TYPE_INT: dest = TupleValue(src.getInt()); break; case COLUMN_TYPE_LONG: dest = TupleValue(src.getLong()); break; case COLUMN_TYPE_FLOAT: dest = TupleValue(src.getFloat()); break; case COLUMN_TYPE_DOUBLE: dest = TupleValue(src.getDouble()); break; case COLUMN_TYPE_TIMESTAMP: dest = ValueUtils::toAnyByTimestamp(src.getTimestamp()); break; case COLUMN_TYPE_BLOB: { TupleValue::VarContext varCxt; varCxt.setStackAllocator(&alloc); dest = SyntaxTree::makeBlobValue(varCxt, src.data(), src.size()); break; } default: dest = TupleValue(); if (COLUMN_TYPE_NULL){ break; } if (!failOnUnsupported) { return false; } GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, "Unsupported value type"); } return true; } TupleColumnType SQLContainerImpl::ContainerValueUtils::toTupleColumnType( ContainerColumnType src, bool nullable) { return SQLValues::TypeUtils::setNullable( SQLValues::TypeUtils::filterColumnType(toRawTupleColumnType(src)), nullable); } TupleColumnType SQLContainerImpl::ContainerValueUtils::toRawTupleColumnType( ContainerColumnType src) { TupleColumnType dest; switch (ValueProcessor::getSimpleColumnType(src)) { case COLUMN_TYPE_STRING: dest = TupleTypes::TYPE_STRING; break; case COLUMN_TYPE_BOOL: dest = TupleTypes::TYPE_BOOL; break; case COLUMN_TYPE_BYTE: dest = TupleTypes::TYPE_BYTE; break; case COLUMN_TYPE_SHORT: dest = TupleTypes::TYPE_SHORT; break; case COLUMN_TYPE_INT: dest = TupleTypes::TYPE_INTEGER; break; case COLUMN_TYPE_LONG: dest = TupleTypes::TYPE_LONG; break; case COLUMN_TYPE_FLOAT: dest = TupleTypes::TYPE_FLOAT; break; case COLUMN_TYPE_DOUBLE: dest = TupleTypes::TYPE_DOUBLE; break; case COLUMN_TYPE_TIMESTAMP: dest = TupleTypes::TYPE_TIMESTAMP; break; case COLUMN_TYPE_GEOMETRY: dest = TupleTypes::TYPE_GEOMETRY; break; case COLUMN_TYPE_BLOB: dest = TupleTypes::TYPE_BLOB; break; case COLUMN_TYPE_ANY: dest = TupleTypes::TYPE_ANY; break; default: assert(false); return TupleColumnType(); } if (ValueProcessor::isArray(src)) { dest = static_cast<TupleColumnType>(dest | TupleTypes::TYPE_MASK_ARRAY); } return dest; } bool SQLContainerImpl::ContainerValueUtils::toContainerColumnType( TupleColumnType src, ContainerColumnType &dest, bool failOnError) { switch (src) { case TupleTypes::TYPE_STRING: dest = COLUMN_TYPE_STRING; break; case TupleTypes::TYPE_BOOL: dest = COLUMN_TYPE_BOOL; break; case TupleTypes::TYPE_BYTE: dest = COLUMN_TYPE_BYTE; break; case TupleTypes::TYPE_SHORT: dest = COLUMN_TYPE_SHORT; break; case TupleTypes::TYPE_INTEGER: dest = COLUMN_TYPE_INT; break; case TupleTypes::TYPE_LONG: dest = COLUMN_TYPE_LONG; break; case TupleTypes::TYPE_FLOAT: dest = COLUMN_TYPE_FLOAT; break; case TupleTypes::TYPE_DOUBLE: dest = COLUMN_TYPE_DOUBLE; break; case TupleTypes::TYPE_TIMESTAMP: dest = COLUMN_TYPE_TIMESTAMP; break; case TupleTypes::TYPE_GEOMETRY: dest = COLUMN_TYPE_GEOMETRY; break; case TupleTypes::TYPE_BLOB: dest = COLUMN_TYPE_BLOB; break; case TupleTypes::TYPE_ANY: dest = COLUMN_TYPE_ANY; break; default: dest = ContainerColumnType(); if (failOnError) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL, ""); } return false; } return true; } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genPredExpr( util::StackAllocator &alloc, const Query &query) { typedef Query::QueryAccessor QueryAccessor; return genPredExpr(alloc, QueryAccessor::findWhereExpr(query), NULL); } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genPredExpr( util::StackAllocator &alloc, const BoolExpr *src, bool *unresolved) { typedef Query::BoolExprAccessor BoolExprAccessor; static_cast<void>(unresolved); if (src == NULL) { return genConstExpr(alloc, ValueUtils::toAnyByBool(true)); } const BoolExpr::BoolTerms &argList = BoolExprAccessor::getOperands(*src); const Expr *unaryExpr = BoolExprAccessor::getUnary(*src); BoolExpr::Operation opType = BoolExprAccessor::getOpType(*src); SQLType::Id type; switch (opType) { case BoolExpr::AND: type = SQLType::EXPR_AND; break; case BoolExpr::OR: type = SQLType::EXPR_OR; break; case BoolExpr::NOT: { SyntaxExprRefList *destArgList = genExprList(alloc, &argList, NULL, 1); SyntaxExpr expr(alloc); expr.op_ = SQLType::OP_NOT; expr.left_ = (*destArgList)[0]; return expr; } case BoolExpr::UNARY: { util::XArray<const Expr*> srcExprList(alloc); srcExprList.push_back(unaryExpr); SyntaxExprRefList *destExprList = genExprList(alloc, &srcExprList, NULL, 1); return *(*destExprList)[0]; } default: GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, ""); } { const size_t minArgCount = 2; const size_t maxArgCount = std::numeric_limits<size_t>::max(); SyntaxExpr expr(alloc); expr.op_ = type; expr.next_ = genExprList(alloc, &argList, NULL, minArgCount, maxArgCount); return expr; } } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genPredExpr( util::StackAllocator &alloc, const Expr *src, bool *unresolved) { typedef Query::ExprAccessor ExprAccessor; assert(unresolved != NULL); if (src == NULL) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, ""); } switch (ExprAccessor::getType(*src)) { case Expr::VALUE: { TupleValue value; ContainerValueUtils::toTupleValue( alloc, *ExprAccessor::getValue(*src), value, false); return genConstExpr(alloc, value); } case Expr::EXPR: { SQLType::Id type = SQLType::START_EXPR; switch (ExprAccessor::getOp(*src)) { case Expr::NE: type = SQLType::OP_NE; break; case Expr::EQ: type = SQLType::OP_EQ; break; case Expr::LT: type = SQLType::OP_LT; break; case Expr::LE: type = SQLType::OP_LE; break; case Expr::GT: type = SQLType::OP_GT; break; case Expr::GE: type = SQLType::OP_GE; break; default: break; } if (type != SQLType::START_EXPR) { SyntaxExprRefList *argList = genExprList( alloc, ExprAccessor::getArgList(*src), unresolved, 2); SyntaxExpr expr(alloc); expr.op_ = type; expr.left_ = (*argList)[0]; expr.right_ = (*argList)[1]; return expr; } bool negative = false; switch (ExprAccessor::getOp(*src)) { case Expr::BETWEEN: type = SQLType::EXPR_BETWEEN; break; case Expr::NOTBETWEEN: type = SQLType::EXPR_BETWEEN; negative = true; break; default: break; } if (type != SQLType::START_EXPR) { SyntaxExpr expr(alloc); expr.op_ = type; expr.next_ = genExprList( alloc, ExprAccessor::getArgList(*src), unresolved, 3); if (negative) { SyntaxExpr *left = ALLOC_NEW(alloc) SyntaxExpr(expr); expr = SyntaxExpr(alloc); expr.op_ = SQLType::OP_NOT; expr.left_ = left; } return expr; } return genUnresolvedLeafExpr(alloc, unresolved); } case Expr::COLUMN: { SyntaxExpr expr(alloc); expr.op_ = SQLType::EXPR_COLUMN; expr.inputId_ = 0; expr.columnId_ = ExprAccessor::getColumnId(*src); expr.columnType_ = ContainerValueUtils::toTupleColumnType( ExprAccessor::getExprColumnType(*src), src->isNullable()); expr.autoGenerated_ = true; return expr; } case Expr::NULLVALUE: return genConstExpr(alloc, TupleValue()); case Expr::BOOL_EXPR: return genPredExpr( alloc, static_cast<const BoolExpr*>(src), unresolved); default: return genUnresolvedLeafExpr(alloc, unresolved); } } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genUnresolvedTopExpr( util::StackAllocator &alloc) { SyntaxExpr expr(alloc); expr.op_ = SQLType::OP_EQ; for (size_t i = 0; i < 2; i++) { SyntaxExpr *argExpr = ALLOC_NEW(alloc) SyntaxExpr(alloc); argExpr->op_ = SQLType::FUNC_RANDOM; (i == 0 ? expr.left_ : expr.right_) = argExpr; } return expr; } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genUnresolvedLeafExpr( util::StackAllocator &alloc, bool *unresolved) { if (unresolved != NULL) { *unresolved = true; } return genConstExpr(alloc, TupleValue()); } SQLContainerImpl::SyntaxExpr SQLContainerImpl::TQLTool::genConstExpr( util::StackAllocator &alloc, const TupleValue &value) { SyntaxExpr expr(alloc); expr.op_ = SQLType::EXPR_CONSTANT; expr.value_ = value; return expr; } template<typename T> SQLContainerImpl::SyntaxExprRefList* SQLContainerImpl::TQLTool::genExprList( util::StackAllocator &alloc, const util::XArray<T*> *src, bool *unresolved, size_t argCount) { return genExprList(alloc, src, unresolved, argCount, argCount); } template<typename T> SQLContainerImpl::SyntaxExprRefList* SQLContainerImpl::TQLTool::genExprList( util::StackAllocator &alloc, const util::XArray<T*> *src, bool *unresolved, size_t minArgCount, size_t maxArgCount) { if (src == NULL || !(minArgCount <= src->size() && src->size() <= maxArgCount)) { GS_THROW_USER_ERROR(GS_ERROR_SQL_PROC_INTERNAL_INVALID_OPTION, ""); } SyntaxExprRefList *dest = ALLOC_NEW(alloc) SyntaxExprRefList(alloc); for (typename util::XArray<T*>::const_iterator it = src->begin(); it != src->end(); ++it) { bool unresolvedLocal = false; SyntaxExpr expr = genPredExpr(alloc, *it, &unresolvedLocal); if (unresolved == NULL) { if (unresolvedLocal) { expr = genUnresolvedTopExpr(alloc); } } else { *unresolved |= unresolvedLocal; } dest->push_back(ALLOC_NEW(alloc) SyntaxExpr(expr)); } return dest; }
27.973007
83
0.741436
[ "vector" ]
46cf657b5b8e3054001752e598d37f5bf152a356
2,962
cpp
C++
src/SACSegmentation.cpp
FloatingObjectSegmentation/Test2
f55ec186e5f64accc325aeada56f06f32e686f96
[ "MIT" ]
1
2022-03-03T04:57:44.000Z
2022-03-03T04:57:44.000Z
src/SACSegmentation.cpp
FloatingObjectSegmentation/Test2
f55ec186e5f64accc325aeada56f06f32e686f96
[ "MIT" ]
null
null
null
src/SACSegmentation.cpp
FloatingObjectSegmentation/Test2
f55ec186e5f64accc325aeada56f06f32e686f96
[ "MIT" ]
null
null
null
#include "SACSegmentation.hpp" #include <iostream> #include <vector> #include <string> #include <liblas/liblas.hpp> #include <pcl/io/pcd_io.h> #include <pcl/search/search.h> #include <pcl/search/kdtree.h> #include <pcl/features/normal_3d.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/ModelCoefficients.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> using namespace std; pcl::PointCloud <pcl::PointXYZRGB>::Ptr SACSegmentation::computeSegmentation(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cld) { // copy to appropriate form pcl::PointCloud<pcl::PointXYZ>::Ptr cloud; cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr (new pcl::PointCloud<pcl::PointXYZ>); copyPointCloud(*cld, *cloud); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZ> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (0.01); seg.setInputCloud (cloud); seg.segment (*inliers, *coefficients); if (inliers->indices.size () == 0) { PCL_ERROR ("Could not estimate a planar model for the given dataset."); return NULL; } std::cerr << "Model coefficients: " << coefficients->values[0] << " " << coefficients->values[1] << " " << coefficients->values[2] << " " << coefficients->values[3] << std::endl; std::cerr << "Model inliers: " << inliers->indices.size () << std::endl; for (size_t i = 0; i < inliers->indices.size (); ++i) std::cerr << inliers->indices[i] << " " << cloud->points[inliers->indices[i]].x << " " << cloud->points[inliers->indices[i]].y << " " << cloud->points[inliers->indices[i]].z << std::endl; pcl::PointCloud<pcl::PointXYZRGB> ret; // Fill in the cloud data ret.width = inliers->indices.size(); // This means that the point cloud is "unorganized" ret.height = 1; // (i.e. not a depth map) ret.is_dense = false; ret.points.resize(inliers->indices.size()); for (int i = 0; i < inliers->indices.size(); i++) { ret.points[i].x = cloud->points[inliers->indices[i]].x; ret.points[i].y = cloud->points[inliers->indices[i]].y; ret.points[i].z = cloud->points[inliers->indices[i]].z; } pcl::PointCloud<pcl::PointXYZRGB>::Ptr retPtr; retPtr = pcl::PointCloud<pcl::PointXYZRGB>::Ptr (new pcl::PointCloud<pcl::PointXYZRGB>); copyPointCloud(ret, *retPtr); return retPtr; }
36.121951
127
0.608035
[ "object", "vector", "model" ]
46d985b9c9d12fe385cf427b04b6405319a3917e
12,389
cc
C++
src/fcst/source/contribs/DAE_solver.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
24
2016-10-04T20:49:55.000Z
2022-03-12T19:07:10.000Z
src/fcst/source/contribs/DAE_solver.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
3
2016-09-05T10:17:36.000Z
2016-12-11T18:23:06.000Z
src/fcst/source/contribs/DAE_solver.cc
jeremyjiezhou/Learn-PyTorch
7e4404609bacd2ec796f6ca3ea118e8e34ab4a22
[ "MIT" ]
9
2016-12-11T22:15:03.000Z
2020-11-21T13:51:05.000Z
//--------------------------------------------------------------------------- // $Id: DAE_solver.cc 2605 2014-08-15 03:36:44Z secanell $ // // Copyright (C) 2011 by Jason Boisvert, University of Saskatchewan // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include "DAE_solver.h" #include <iostream> using namespace FuelCell::ApplicationCore; void FuelCell::ApplicationCore::DAE_dummy_guess (double &/*x*/, double /*z*/[], double /*y*/[], double /*df*/[]) { } //------------------------------------------------------------------------------ void FuelCell::ApplicationCore::for_to_c_matrix(int rows, int cols, double *fmat, double **cmat) { int k=0; for (int i=0; i < cols; i++) { for (int j=0; j < rows; j++) { cmat[j][i] = fmat[k++]; } } } //------------------------------------------------------------------------------ void FuelCell::ApplicationCore::c_to_for_matrix(int rows, int cols, double ** cmat, double *fmat) { int k=0; for (int i=0; i < cols; i++) { for (int j=0; j < rows; j++) { fmat[k++] = cmat[j][i]; } } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ DAESolver::DAESolver (int m_comp, int ny, int m[], double a, double b, double zeta[], void (*fsub)(double &, double [], double [], double []), void (*dfsub)(double &, double [], double [], double []), void (*gsub)(int &, double [], double &), void (*dgsub)(int &, double [], double []), void (*guess)(double &, double [], double [], double [])): set_zeta(false), set_ltol(false), set_tol(false), linear(false), set_collpnts(false), set_intialmeshsize(false), set_ispace(false), set_fspace(false), use_old_fspace(false), output_level(1), set_fixpnt(false), set_solvercontrol(false), DAE_index(0), use_cont(false) //Assign Parameters { //Set info for DAE this->set_prob_size(m_comp,ny,m); //Set the boundary points this->set_boundary_points(a,b); //set side conditions int mcomp=0; // sum of orders for(int i = 0; i < this->num_ODEs; i ++) { mcomp += this->ODEs_Orders[i]; } this->set_side_conditions(mcomp,zeta); //Set the user supplied functions this->set_fsub(fsub); this->set_dfsub(dfsub); this->set_gsub(gsub); this->set_dgsub(dgsub); this->set_guess(guess); } //------------------------------------------------------------------------------ void DAESolver::set_prob_size(int num_ODEs, int num_Alg_Const, int * ODEs_Orders) { this->num_ODEs = num_ODEs; this->num_Alg_Const = num_Alg_Const; this->ODEs_Orders = ODEs_Orders; } //------------------------------------------------------------------------------ void DAESolver::set_boundary_points(int a, int b) { this->a=a; this->b=b; } //------------------------------------------------------------------------------ void DAESolver::set_side_conditions(int zeta_size, double *zeta) { this->zeta=zeta; this->set_zeta=true; this->zeta_size = zeta_size; } //------------------------------------------------------------------------------ void DAESolver::set_fsub(void (*fsub)(double &, double [], double [], double [])) { this->DAE_fsub = fsub; } //------------------------------------------------------------------------------ void DAESolver::set_dfsub(void (*dfsub)(double &, double [], double [], double [])) { this->DAE_dfsub=dfsub; } //------------------------------------------------------------------------------ void DAESolver::set_gsub(void (*gsub)(int &, double [], double &)) { this->DAE_gsub=gsub; } //------------------------------------------------------------------------------ void DAESolver::set_dgsub(void (*dgsub)(int &, double [], double [])) { this->DAE_dgsub=dgsub; } //------------------------------------------------------------------------------ void DAESolver::set_guess(void (*guess)(double &, double [], double [], double [])) { if (guess == NULL) { this->have_guess = false; this->DAE_guess = &DAE_dummy_guess; } else { this->have_guess = true; this->DAE_guess=guess; } } //------------------------------------------------------------------------------ void DAESolver::set_tolerance(int ltol_size, int *ltol, double *tol) { // attempt to get user supplied tolerances if( ltol != NULL && tol != NULL ) { this->ltol = ltol; this->set_ltol = true; this->tol = tol; this->set_tol = true; this->ltol_size = ltol_size; } else { int mcomp=0; // sum of orders for(int i = 0; i < this->num_ODEs; i ++) { mcomp += this->ODEs_Orders[i]; } int *tmp_ltol = new int[mcomp]; double *tmp_tol = new double[mcomp]; //populate ltol int k=0; for(int i = 0; i < this->num_ODEs; i ++) { for (int j=0; j < this->ODEs_Orders[i]; j++) { tmp_ltol[k] = k+1; tmp_tol[k] = 1E-6; k++; } } this->ltol = tmp_ltol; this->set_ltol = true; this->tol = tmp_tol; this->set_tol = true; this->ltol_size=mcomp; delete [] tmp_ltol; delete [] tmp_tol; } } //------------------------------------------------------------------------------ void DAESolver::set_linear(void) { this->linear=true; } //------------------------------------------------------------------------------ void DAESolver::set_collocation_points(int pnts) { this->collpnts = pnts; this->set_collpnts = true; } //------------------------------------------------------------------------------ void DAESolver::set_initial_mesh_size(int pnts) { this->intialmeshsize = pnts; this->set_intialmeshsize = true; } //------------------------------------------------------------------------------ void DAESolver::set_integer_space(int ispace_size) { //Ensure we do not have more than one copy of fspace in memory if(this->set_ispace == true) { //FcstUtilities::log << "Cleaning ispace" << std::endl; delete [] this->ispace; this->set_ispace = false; this->ispace_size = 0; } if(ispace_size > 0) { this->ispace_size = ispace_size; } else { int mcomp = 0; for(int i = 0; i < this->num_ODEs; i ++) mcomp += this->ODEs_Orders[i]; this->ispace_size = mcomp * 1000000; } int *tmp_ispace = new int[this->ispace_size]; this->ispace = tmp_ispace; this->set_ispace = true; } //------------------------------------------------------------------------------ void DAESolver::set_float_space(int fspace_size, double *fspace) { double *tmp_fspace; //Ensure we do not have more than one copy of fspace in memory if(this->set_fspace == true) { //FcstUtilities::log << "Cleaning fspace" << std::endl; delete [] this->fspace; this->set_fspace = false; this->fspace_size = 0; } if (fspace != NULL) { this->use_old_fspace=true; tmp_fspace = fspace; } else if(fspace_size > 0) { this->fspace_size = fspace_size; tmp_fspace = new double[this->fspace_size]; } else { int mcomp = 0; for(int i = 0; i < this->num_ODEs; i ++) mcomp += this->ODEs_Orders[i]; this->fspace_size = mcomp * 10000000; tmp_fspace = new double[this->fspace_size]; } this->fspace = tmp_fspace; this->set_fspace = true; } //------------------------------------------------------------------------------ void DAESolver::set_output(int level) { if (level >= -1 && level <= 1) this->output_level = level; else level = 0; } //------------------------------------------------------------------------------ void DAESolver::set_fixpnts(int fixpnt_size, double *fixpnt) { if(fixpnt != NULL) { this->fixpnt = fixpnt; this->fixpnt_size = fixpnt_size; } else { double *tmp_fixpnt = new double [1]; this->fixpnt = tmp_fixpnt; this->fixpnt_size = 0; //delete [] tmp_fixpnt; } this->set_fixpnt=true; } //------------------------------------------------------------------------------ void DAESolver::set_solver_control(int control) { this->solvercontrol = control; this->set_solvercontrol = true; } //------------------------------------------------------------------------------ void DAESolver::set_DAE_index(int index) { if (index >= 0 && index <= 2) this->DAE_index = index; else this->DAE_index = 0; } //------------------------------------------------------------------------------ void DAESolver::use_simple_cont(void) { this->ipar[8]=2; this->ipar[2]= this->get_size_final_mesh() -1; this->use_cont=true; } //------------------------------------------------------------------------------ void DAESolver::set_ipar(void) { int *tmp_ipar = new int[12]; //initialize for (int i=0; i < 12; i++) tmp_ipar[i] = 0; //linear if (this->linear == false) tmp_ipar[0] = 1; //collocation points if (this->set_collpnts == true) tmp_ipar[1] = this->collpnts; // initial mesh size if (this->set_intialmeshsize == true) tmp_ipar[2] = this->intialmeshsize; // ltol size tmp_ipar[3] = this->ltol_size; //fspace size tmp_ipar[4] = this->fspace_size; // ipsace size tmp_ipar[5] = this->ispace_size; // output control tmp_ipar[6] = this->output_level; // continuation if (this->use_old_fspace) { tmp_ipar[7] = 2; tmp_ipar[8] = 2; } else { tmp_ipar[7] = 0; if (this->have_guess == false) tmp_ipar[8] = 0; else tmp_ipar[8] = 1; } // solver control if(this->set_solvercontrol == true) tmp_ipar[9] = this->solvercontrol; //fixpoints tmp_ipar[10] = this->fixpnt_size; //dae index tmp_ipar[11] = this->DAE_index; this->ipar = tmp_ipar; //delete [] tmp_ipar; } //------------------------------------------------------------------------------ int DAESolver::DAE_solve(void) { if (this->set_ltol == false && this->set_tol == false) this->set_tolerance(); if (this->set_ispace == false) this->set_integer_space(); if (this->set_fspace == false) this->set_float_space(); if (this->set_fixpnt == false) this->set_fixpnts(); if (this->use_cont == false) this->set_ipar(); //get parameters and arrays int ncomp = this->num_ODEs; int ny = this->num_Alg_Const; int *m = this->ODEs_Orders; double aleft = this->a; double bright = this->b; double *zeta = this->zeta; int *ipar = this->ipar; int *ltol = this->ltol; double *tol = this->tol; double *fixpnt = this->fixpnt; int *ispace = this->ispace; double *fspace = this->fspace; int iflag=0; fsub_ptr fsub = this->DAE_fsub; gsub_ptr gsub = this->DAE_gsub; dgsub_ptr dgsub = this->DAE_dgsub; guess_ptr guess = this->DAE_guess; dfsub_ptr dfsub = this->DAE_dfsub; if (omp_get_thread_num() > 19) std::out_of_range("ptr_DAE_object is out of range, modify to run more threads"); coldae_(ncomp, ny, m, aleft, bright, zeta, ipar, ltol, tol, fixpnt, ispace, fspace, iflag, fsub, dfsub, gsub, dgsub, guess); return iflag; } //------------------------------------------------------------------------------ void DAESolver::DAE_solution(double x, double z[], double y[]) { int *ispace = this->ispace; double *fspace = this->fspace; appsln_(x,z,y,fspace,ispace); } //------------------------------------------------------------------------------ int *DAESolver::return_integer_space(void) { return (this->ispace); } //------------------------------------------------------------------------------ double *DAESolver::return_float_space(void) { return (this->fspace); } //------------------------------------------------------------------------------ void DAESolver::get_copy_final_mesh (double *mesh) { int npts = this->get_size_final_mesh(); for (int i=0; i < npts; i++) { mesh[i] = this->fspace[i]; } } //------------------------------------------------------------------------------ void DAESolver::clear_mem(void) { delete [] this->ispace; delete [] this->fspace; delete [] this->ipar; } // ----------------------------------------------------------------------------- // //------------------------------------------------------------------------------ // // void DAESolver::operator delete (void *p) // { // DAESolver *tmp = (DAESolver *)p; // tmp->clear_mem(); // // } //------------------------------------------------------------------------------
24.630219
112
0.49544
[ "mesh" ]
46da57e6b1b07323b3c21a96ee6b3aec7cbeaeb8
2,154
cpp
C++
src/Systems/camerasystem.cpp
NotBjoggisAtAll/Tomato-Engine
c13d071fdc311634a58243f000f8c5d6731f1218
[ "MIT" ]
1
2021-01-06T21:13:19.000Z
2021-01-06T21:13:19.000Z
src/Systems/camerasystem.cpp
NotBjoggisAtAll/Tomato-Engine
c13d071fdc311634a58243f000f8c5d6731f1218
[ "MIT" ]
null
null
null
src/Systems/camerasystem.cpp
NotBjoggisAtAll/Tomato-Engine
c13d071fdc311634a58243f000f8c5d6731f1218
[ "MIT" ]
null
null
null
#include "camerasystem.h" #include "world.h" #include "GSL/matrix4x4.h" #include "Components/camera.h" #include "Components/transform.h" void CameraSystem::tick(float /*deltaTime*/) { for(const auto& entity : entities_) { Camera* camera = getWorld()->getComponent<Camera>(entity).value(); Transform* transform = getWorld()->getComponent<Transform>(entity).value(); gsl::Matrix4x4 yawMatrix; gsl::Matrix4x4 pitchMatrix; pitchMatrix.rotateX(camera->pitch_); yawMatrix.rotateY(camera->yaw_); camera->viewMatrix_ = pitchMatrix * yawMatrix; if(camera->isInUse_) { transform->position_ -= camera->forward_ * camera->speed_; camera->viewMatrix_.translate(-transform->position_); } updateFrustum(camera); } } void CameraSystem::updateFrustum(Camera* camera) { gsl::Matrix4x4 vpMatrix = camera->projectionMatrix_ * camera->viewMatrix_; gsl::Vector3D col1(vpMatrix[0], vpMatrix[2], vpMatrix[2]); gsl::Vector3D col2(vpMatrix[4], vpMatrix[5], vpMatrix[6]); gsl::Vector3D col3(vpMatrix[8], vpMatrix[9], vpMatrix[10]); gsl::Vector3D col4(vpMatrix[12], vpMatrix[13], vpMatrix[14]); camera->frustum_[0].normal_ = col4 + col1; camera->frustum_[1].normal_ = col4 - col1; camera->frustum_[2].normal_ = col4 - col2; camera->frustum_[3].normal_ = col4 + col2; camera->frustum_[4].normal_ = col4 - col3; camera->frustum_[5].normal_ = col3; camera->frustum_[0].distance_ = vpMatrix[15] + vpMatrix[3]; camera->frustum_[1].distance_ = vpMatrix[15] - vpMatrix[3]; camera->frustum_[2].distance_ = vpMatrix[15] - vpMatrix[7]; camera->frustum_[3].distance_ = vpMatrix[15] + vpMatrix[7]; camera->frustum_[4].distance_ = vpMatrix[15] - vpMatrix[11]; camera->frustum_[5].distance_ = vpMatrix[11]; for (unsigned int i = 0; i < 6; ++i) { float magnitude = 1.0f / camera->frustum_[i].normal_.length(); camera->frustum_[i].normal_ = camera->frustum_[i].normal_ * magnitude; camera->frustum_[i].distance_ = camera->frustum_[i].distance_ * magnitude; } }
35.9
83
0.652275
[ "transform" ]
46e08ab3d4dbb7030a82e6668c17b64e6cceeafd
3,125
cpp
C++
app/src/logic/GameManager.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
app/src/logic/GameManager.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
app/src/logic/GameManager.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include <algorithm> #include <optional> #include <stdexcept> #include <thread> #include <mutex> #include "GameManager.hpp" #include "debug.hpp" #include "stringTools.hpp" #include "Process.hpp" namespace Logic { GameManager::GameManager(const std::vector<Model::PieceColor>* const colorsInGame, const std::chrono::high_resolution_clock::time_point* const lastMsgReceivedPtr) : colorsInGame(colorsInGame), agent(state, ownColor, lastMsgReceivedPtr) {} void GameManager::setColor(const Model::PlayerColor& color) { ownColor = color; } const Model::PlayerColor& GameManager::getPlayerColor() const { return ownColor; } void GameManager::handleResults(const App::ResultMsg& message) const { #ifdef DEBUG const Util::Process proc = Util::Process(); std::cout << "Score: "; if (ownColor == Model::PlayerColor::BLUE) { std::cout << Util::Print::Text::bold(std::to_string(message.score[0])) << " : " << std::to_string(message.score[1]); } else { std::cout << std::to_string(message.score[0]) << " : " << Util::Print::Text::bold(std::to_string(message.score[1])); } std::cout << '\n' << state << '\n' << '\n'; proc.printSystemStatus(); #endif } void GameManager::updateWithMemento(const App::MementoMsg& memento) { if (state.initialPiece == -1) { state.initialPiece = static_cast<int>(memento.startPiece); } if (memento.currentTurn > 0) { state.update(memento.lastMove); while (state.getTurn() < 100 && state.getCurrentPieceColor() != memento.currentColor) { state.update(std::nullopt); } agent.setInvalidColors(this->colorsInGame); #ifdef DEBUG std::cout << Util::Print::Text::bold("Colors in Game: "); for (const Model::PieceColor& color : *colorsInGame) { std::cout << color << " "; } std::cout << '\n' << Util::Print::Text::bold("Available Moves: ") << state.getPossibleMoves().size() << std::endl; #endif } } const Model::Move* GameManager::moveRequest() { moveRequestGuard.lock(); SearchResult result = agent.find(); const Util::Process proc = Util::Process(); const double usedMemory = static_cast<double>(proc.virtualMemory()) / 1'000'000; #ifdef DEBUG agent.log(); #endif std::thread cleanUpWorker([&usedMemory, this] { if (usedMemory > 1100) { const double percentage = (usedMemory - 1100) / 10000 * 15; // 15% per 100 MB > 1100 MB => 1400MB used -> 300 > 1100 -> 45% of cache is freed for reuse state.freeMemory(percentage); } else { state.freeMemory(0); } agent.clean(); moveRequestGuard.unlock(); }); cleanUpWorker.detach(); return result.move; } const Model::GameState& GameManager::getManagedState() const { return state; } }
31.565657
242
0.57824
[ "vector", "model" ]
46e1326e984be6abfa15c11eaaf26c7494355d4a
770
cpp
C++
conf/IniHelper.cpp
jjzhang166/winutil1
fba80821c415e26afb2c63d8d3a423d6ff43b6b4
[ "MIT" ]
4
2015-09-05T05:28:30.000Z
2019-05-16T08:45:36.000Z
conf/IniHelper.cpp
ph0ly/winutil
fba80821c415e26afb2c63d8d3a423d6ff43b6b4
[ "MIT" ]
null
null
null
conf/IniHelper.cpp
ph0ly/winutil
fba80821c415e26afb2c63d8d3a423d6ff43b6b4
[ "MIT" ]
null
null
null
#define DLL_EXPORTS #include "IniHelper.h" #include <windows.h> NAMESPACE_PH0LY_BEGIN(conf) IniHelper::IniHelper(void) { } IniHelper::~IniHelper(void) { } std::vector<std::string> IniHelper::GetChildren(std::string strPath, std::string strNode) { std::vector<std::string> tmp; return tmp; } std::vector<std::string> IniHelper::GetProfileSectionNodes(std::string strPath, std::string strNode) { std::vector<std::string> tmp; DWORD dwNumber = 1024*1024; char * pBuf = new char[dwNumber]; DWORD dwRead = GetPrivateProfileSectionA(strNode.data(), pBuf, dwNumber, strPath.data()); char * p = pBuf; for (size_t i=0; i<dwRead; i++) { if (pBuf[i] == 0) { tmp.push_back(p); p += strlen(p); p++; } } delete[] pBuf; return tmp; } NAMESPACE_PH0LY_END
19.25
100
0.688312
[ "vector" ]
46e270e52c9693f63368537f61be73beb1648032
1,803
cpp
C++
boboleetcode/Play-Leetcode-master/0473-Matchsticks-to-Square/cpp-0473/main3.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2019-03-20T17:05:59.000Z
2019-10-15T07:56:45.000Z
boboleetcode/Play-Leetcode-master/0473-Matchsticks-to-Square/cpp-0473/main3.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0473-Matchsticks-to-Square/cpp-0473/main3.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/matchsticks-to-square/description/ /// Author : liuyubobobo /// Time : 2018-08-28 #include <iostream> #include <numeric> #include <vector> #include <cassert> using namespace std; /// Memory Search /// /// Time Complexity: O(n*2^n) /// Space Complexity: O(2^n) class Solution { private: int all, side; public: bool makesquare(vector<int>& nums) { if(nums.size() == 0) return false; int total = accumulate(nums.begin(), nums.end(), 0); if(total % 4) return false; sort(nums.begin(), nums.end(), greater<int>()); all = (1 << nums.size()) - 1; side = total / 4; vector<int> sum(all + 1, -1); vector<int> dp(all + 1, -1); // -1 - unvisited, 0 - false, 1 - true return dfs(nums, 0, dp, sum); } private: bool dfs(const vector<int>& nums, int state, vector<int>& dp, vector<int>& sum){ if(state == all) return true; if(dp[state] != -1) return dp[state]; int left = getSum(nums, state, sum) % side; for(int i = 0; i < nums.size() ; i ++) if((state & (1 << i)) == 0 && left + nums[i] <= side && dfs(nums, state | (1 << i), dp, sum)) return dp[state] = 1; return dp[state] = 0; } int getSum(const vector<int>& nums, int state, vector<int>& sum){ if(sum[state] != -1) return sum[state]; if(state == 0) return sum[state] = 0; for(int i = 0; i < nums.size() ; i ++) if(state & (1 << i)) return sum[state] = nums[i] + getSum(nums, state - (1 << i), sum); assert(false); return -1; } }; int main() { return 0; }
22.5375
83
0.494176
[ "vector" ]