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
c744a16041c2466d3839a37fbee2bf86887bf4e1
11,720
cpp
C++
src/authorizer/local/authorizer.cpp
maselvaraj/mesos
dba04cd8ed9ed514b0782a1f27655728dd9ea478
[ "Apache-2.0" ]
null
null
null
src/authorizer/local/authorizer.cpp
maselvaraj/mesos
dba04cd8ed9ed514b0782a1f27655728dd9ea478
[ "Apache-2.0" ]
null
null
null
src/authorizer/local/authorizer.cpp
maselvaraj/mesos
dba04cd8ed9ed514b0782a1f27655728dd9ea478
[ "Apache-2.0" ]
1
2022-01-28T01:17:36.000Z
2022-01-28T01:17:36.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "authorizer/local/authorizer.hpp" #include <string> #include <vector> #include <mesos/mesos.hpp> #include <mesos/authorizer/acls.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <process/process.hpp> #include <process/protobuf.hpp> #include <stout/foreach.hpp> #include <stout/option.hpp> #include <stout/path.hpp> #include <stout/protobuf.hpp> #include <stout/try.hpp> #include "common/parse.hpp" using process::Failure; using process::Future; using process::dispatch; using std::string; using std::vector; namespace mesos { namespace internal { struct GenericACL { ACL::Entity subjects; ACL::Entity objects; }; class LocalAuthorizerProcess : public ProtobufProcess<LocalAuthorizerProcess> { public: LocalAuthorizerProcess(const ACLs& _acls) : ProcessBase(process::ID::generate("authorizer")), acls(_acls) {} virtual void initialize() { // TODO(arojas): Remove the following two if blocks once // ShutdownFramework reaches the end of deprecation cycle // which started with 0.27.0. if (acls.shutdown_frameworks_size() > 0 && acls.teardown_frameworks_size() > 0) { LOG(WARNING) << "ACLs defined for both ShutdownFramework and " << "TeardownFramework; only the latter will be used"; return; } // Move contents of `acls.shutdown_frameworks` to // `acls.teardown_frameworks` if (acls.shutdown_frameworks_size() > 0) { LOG(WARNING) << "ShutdownFramework ACL is deprecated; please use " << "TeardownFramework"; foreach (const ACL::ShutdownFramework& acl, acls.shutdown_frameworks()) { ACL::TeardownFramework* teardown = acls.add_teardown_frameworks(); teardown->mutable_principals()->CopyFrom(acl.principals()); teardown->mutable_framework_principals()->CopyFrom( acl.framework_principals()); } } acls.clear_shutdown_frameworks(); } Future<bool> authorized(const authorization::Request& request) { vector<GenericACL> acls_; switch (request.action()) { case authorization::REGISTER_FRAMEWORK_WITH_ROLE: for (const ACL::RegisterFramework& acl : acls.register_frameworks()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.roles(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::TEARDOWN_FRAMEWORK_WITH_PRINCIPAL: for (const ACL::TeardownFramework& acl : acls.teardown_frameworks()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.framework_principals(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::RUN_TASK_WITH_USER: for (const ACL::RunTask& acl : acls.run_tasks()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.users(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::RESERVE_RESOURCES_WITH_ROLE: for (const ACL::ReserveResources& acl : acls.reserve_resources()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.roles(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::UNRESERVE_RESOURCES_WITH_PRINCIPAL: for (const ACL::UnreserveResources& acl : acls.unreserve_resources()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.reserver_principals(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::CREATE_VOLUME_WITH_ROLE: for (const ACL::CreateVolume& acl : acls.create_volumes()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.roles(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::DESTROY_VOLUME_WITH_PRINCIPAL: for (const ACL::DestroyVolume& acl : acls.destroy_volumes()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.creator_principals(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::SET_QUOTA_WITH_ROLE: for (const ACL::SetQuota& acl : acls.set_quotas()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.roles(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::DESTROY_QUOTA_WITH_PRINCIPAL: for (const ACL::RemoveQuota& acl : acls.remove_quotas()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.quota_principals(); acls_.push_back(acl_); } return authorized(request, acls_); break; case authorization::UPDATE_WEIGHTS_WITH_ROLE: for (const ACL::UpdateWeights& acl : acls.update_weights()) { GenericACL acl_; acl_.subjects = acl.principals(); acl_.objects = acl.roles(); acls_.push_back(acl_); } return authorized(request, acls_); break; default: LOG(WARNING) << "Authorization request for action '" << request.action() << "' is not defined and therefore not authorized"; return false; break; } UNREACHABLE(); } private: Future<bool> authorized( const authorization::Request& request, const vector<GenericACL>& acls) { ACL::Entity subject; if (request.subject().has_value()) { subject.add_values(request.subject().value()); subject.set_type(mesos::ACL::Entity::SOME); } else { subject.set_type(mesos::ACL::Entity::ANY); } ACL::Entity object; if (request.object().has_value()) { object.add_values(request.object().value()); object.set_type(mesos::ACL::Entity::SOME); } else { object.set_type(mesos::ACL::Entity::ANY); } for (const GenericACL& acl : acls) { if (matches(subject, acl.subjects) && matches(object, acl.objects)) { return allows(subject, acl.subjects) && allows(object, acl.objects); } } return this->acls.permissive(); // None of the ACLs match. } // Match matrix: // // -----------ACL---------- // // SOME NONE ANY // -------|-------|-------|------- // | SOME | Yes/No| Yes | Yes // | -------|-------|-------|------- // Request NONE | No | Yes | No // | -------|-------|-------|------- // | ANY | No | Yes | Yes // -------|-------|-------|------- bool matches(const ACL::Entity& request, const ACL::Entity& acl) { // NONE only matches with NONE. if (request.type() == ACL::Entity::NONE) { return acl.type() == ACL::Entity::NONE; } // ANY matches with ANY or NONE. if (request.type() == ACL::Entity::ANY) { return acl.type() == ACL::Entity::ANY || acl.type() == ACL::Entity::NONE; } if (request.type() == ACL::Entity::SOME) { // SOME matches with ANY or NONE. if (acl.type() == ACL::Entity::ANY || acl.type() == ACL::Entity::NONE) { return true; } // SOME is allowed if the request values are a subset of ACL // values. foreach (const string& value, request.values()) { bool found = false; foreach (const string& value_, acl.values()) { if (value == value_) { found = true; break; } } if (!found) { return false; } } return true; } return false; } // Allow matrix: // // -----------ACL---------- // // SOME NONE ANY // -------|-------|-------|------- // | SOME | Yes/No| No | Yes // | -------|-------|-------|------- // Request NONE | No | Yes | No // | -------|-------|-------|------- // | ANY | No | No | Yes // -------|-------|-------|------- bool allows(const ACL::Entity& request, const ACL::Entity& acl) { // NONE is only allowed by NONE. if (request.type() == ACL::Entity::NONE) { return acl.type() == ACL::Entity::NONE; } // ANY is only allowed by ANY. if (request.type() == ACL::Entity::ANY) { return acl.type() == ACL::Entity::ANY; } if (request.type() == ACL::Entity::SOME) { // SOME is allowed by ANY. if (acl.type() == ACL::Entity::ANY) { return true; } // SOME is not allowed by NONE. if (acl.type() == ACL::Entity::NONE) { return false; } // SOME is allowed if the request values are a subset of ACL // values. foreach (const string& value, request.values()) { bool found = false; foreach (const string& value_, acl.values()) { if (value == value_) { found = true; break; } } if (!found) { return false; } } return true; } return false; } ACLs acls; }; Try<Authorizer*> LocalAuthorizer::create(const ACLs& acls) { Authorizer* local = new LocalAuthorizer(acls); return local; } Try<Authorizer*> LocalAuthorizer::create(const Parameters& parameters) { Option<string> acls; foreach (const Parameter& parameter, parameters.parameter()) { if (parameter.key() == "acls") { acls = parameter.value(); } } if (acls.isNone()) { return Error("No ACLs for default authorizer provided"); } Try<ACLs> acls_ = flags::parse<ACLs>(acls.get()); if (acls_.isError()) { return Error("Contents of 'acls' parameter could not be parsed into a " "valid ACLs object"); } return LocalAuthorizer::create(acls_.get()); } LocalAuthorizer::LocalAuthorizer(const ACLs& acls) : process(new LocalAuthorizerProcess(acls)) { spawn(process); } LocalAuthorizer::~LocalAuthorizer() { if (process != NULL) { terminate(process); wait(process); delete process; } } process::Future<bool> LocalAuthorizer::authorized( const authorization::Request& request) { typedef Future<bool> (LocalAuthorizerProcess::*F)( const authorization::Request&); return dispatch( process, static_cast<F>(&LocalAuthorizerProcess::authorized), request); } } // namespace internal { } // namespace mesos {
28.038278
80
0.583874
[ "object", "vector" ]
c7458eeda8320d58a5b8d914f4bfd67128852257
906
cpp
C++
Arrays/FindAllNumbersDisappearedInAnArray448.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Arrays/FindAllNumbersDisappearedInAnArray448.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Arrays/FindAllNumbersDisappearedInAnArray448.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// Given an array nums of n integers where nums[i] is in the range [1, n], // return an array of all the integers in the range [1, n] that do not appear in nums. // Example 1: // Input: nums = [4,3,2,7,8,2,3,1] // Output: [5,6] // Example 2: // Input: nums = [1,1] // Output: [2] // Constraints: // n == nums.length // 1 <= n <= 105 // 1 <= nums[i] <= n // Follow up: Could you do it without extra space and in O(n) runtime? // You may assume the returned list does not count as extra space. class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> ans; for(int num : nums){ if(nums[abs(num) - 1] > 0) nums[abs(num) - 1] *= -1; } for(int i = 0; i < nums.size(); i++) if(nums[i] > 0) ans.push_back(i+1); return ans; } };
27.454545
87
0.519868
[ "vector" ]
c74788d1de47e954a5ac650d915834b2c7ef6959
3,492
cc
C++
src/drivers/DriverManager.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/drivers/DriverManager.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/drivers/DriverManager.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /* \file DriverManager.cc \brief Implementation of Drivermanager class. \author Meteorological Visualisation Section, ECMWF Started: Jan 2004 */ #include <DriverManager.h> #include "BasicGraphicsObject.h" using namespace magics; DriverManager::DriverManager() {} DriverManager::~DriverManager() { clearDrivers(); } void DriverManager::print(ostream& out) const { out << "DriverManager"; } void DriverManager::dispatch(BasicGraphicsObject* object) const { if (!object) return; for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) (*object).redisplay(*(*driver)); } void DriverManager::dispatch(BaseDriver::ModeFunction mode, const SelectionMode& properties) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) ((*driver)->*mode)(properties); } void DriverManager::dispatch(BaseDriver::ControlFunction mode, bool control) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) ((*driver)->*mode)(control); } void DriverManager::dispatch(void (BaseDriver::*mode)()) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) ((*driver)->*mode)(); } void DriverManager::dispatch(void (MagicsEvent::*notify)(MagicsObserver&), MagicsEvent& event) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) (event.*notify)(*(*driver)); } void DriverManager::dispatch(BaseDriver::InputEventFunction mode, MtInputEvent* event) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) ((*driver)->*mode)(event); } void DriverManager::openDrivers() const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) (*(*driver)).open(); } void DriverManager::closeDrivers() const { const_iterator driver = begin(); for (; driver != end(); ++driver) if (!(*(*driver)).disable()) (*(*driver)).close(); } void DriverManager::clearDrivers() { for (const_iterator driver = begin(); driver != end(); ++driver) delete *driver; clear(); } void DriverManager::setDriversWidth(double width) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) (*(*driver)).setXDeviceLength(width); } void DriverManager::setOutputWidth(double width) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) { // double width = (*(*driver)).getWidth(); (*(*driver)).setWidth(width); } } void DriverManager::setDriversHeight(double height) const { for (const_iterator driver = begin(); driver != end(); ++driver) if (!(*(*driver)).disable()) (*(*driver)).setYDeviceLength(height); }
31.178571
102
0.626861
[ "object" ]
c748adcbb022f824a921af34725e29d37a7fda14
9,260
hxx
C++
com/ole32/stg/props/nffmstm.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/stg/props/nffmstm.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/stg/props/nffmstm.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef _NFFMSTM_HXX_ #define _NFFMSTM_HXX_ #include <propstm.hxx> class CNtfsStream; class CNtfsUpdateStreamForPropStg; //+---------------------------------------------------------------------------- // // Class: CNFFMappedStream // // This class is used by CNtfsStream, and implements the IMappedStream // interface for use on NFF (NTFS Flat-File) files. The mapping // exposed by this implementation is robust, in that updates to the // underlying stream are atomic (though not durable until flushed). // // This atomicity is accomplished by using stream renaming (which is only // supported in NTFS5). When this mapping is written to the underlying // NTFS files, it is written to a second stream (the "update" stream), // rather than the original stream. When Flush is called, // the update stream is renamed over the original stream. In order to // make NTFS stream renaming atomic, the overwritten stream must be // truncated first to have zero length. The the overall flush operation // is: truncate the original stream, rename the update stream over // the original stream, and optionally create a new update stream to be // ready for the next write. // // When the original stream is truncated, the update stream is then // considered master. So if there is a crash before the truncate, then // the original stream, with the original data, is master. If there is // a crash after the truncate but before the rename, then the update stream // is considered master. In this case, on the next open, the update stream // is either renamed over the zero-length original (if opening for write), // or the update stream is simply used as is (if opening for read). // // If the file isn't on an NTFS5 volume, so stream renaming isn't supported, // we just use the original stream unconditionally and there is no robustness. // // To accomplish all of this, this class works with two stream handles, // the original and the update. The original is the stream handle held // by the parent CNtfsStream. The update stream handle must behave like all other // stream handles, wrt USN, oplock, timestamps, etc (see CNtfsStream). // So the update stream is wrapped in a CNtfsStream too, but a special // one - the CNtfsUpdateStreamForPropStg derivation. An instance of this // CNtfsUpdateStreamForPropStg class is maintained by here (by CNFFMappedStream). // // // // +-------------+ +------------------+ // | |------->| | // | CNtfsStream | | CNFFMappedStream | // | |<-------| | // +-------------+ +------------------+ // | | +------------------------------+ // | | | | // | +----->| CNtfsUpdateStreamForPropStg | // V | : public CNtfsStream | // Original | | // NTFS +------------------------------+ // Stream | // | // V // Updated // NTFS // Stream // //+---------------------------------------------------------------------------- class CNFFMappedStream : public IMappedStream #if DBG , public IStorageTest // For testing only #endif { // Constructors public: CNFFMappedStream( CNtfsStream *pnffstm ); ~CNFFMappedStream(); // ------------- // IMappedStream // ------------- public: STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); STDMETHODIMP_(VOID) Open(IN NTPROP np, OUT LONG *phr); STDMETHODIMP_(VOID) Close(OUT LONG *phr); STDMETHODIMP_(VOID) ReOpen(IN OUT VOID **ppv, OUT LONG *phr); STDMETHODIMP_(VOID) Quiesce(VOID); STDMETHODIMP_(VOID) Map(IN BOOLEAN fCreate, OUT VOID **ppv); STDMETHODIMP_(VOID) Unmap(IN BOOLEAN fFlush, IN OUT VOID **ppv); STDMETHODIMP_(VOID) Flush(OUT LONG *phr); STDMETHODIMP_(ULONG) GetSize(OUT LONG *phr); STDMETHODIMP_(VOID) SetSize(IN ULONG cb, IN BOOLEAN fPersistent, IN OUT VOID **ppv, OUT LONG *phr); STDMETHODIMP_(NTSTATUS) Lock(IN BOOLEAN fExclusive); STDMETHODIMP_(NTSTATUS) Unlock(VOID); STDMETHODIMP_(VOID) QueryTimeStamps(OUT STATPROPSETSTG *pspss, BOOLEAN fNonSimple) const; STDMETHODIMP_(BOOLEAN) QueryModifyTime(OUT LONGLONG *pll) const; STDMETHODIMP_(BOOLEAN) QuerySecurity(OUT ULONG *pul) const; STDMETHODIMP_(BOOLEAN) IsWriteable(VOID) const; STDMETHODIMP_(BOOLEAN) IsModified(VOID) const; STDMETHODIMP_(VOID) SetModified(OUT LONG *phr); STDMETHODIMP_(HANDLE) GetHandle(VOID) const; #if DBG STDMETHODIMP_(BOOLEAN) SetChangePending(BOOLEAN fChangePending); STDMETHODIMP_(BOOLEAN) IsNtMappedStream(VOID) const; #endif // ------------ // IStorageTest // ------------ public: #if DBG STDMETHOD(UseNTFS4Streams)( BOOL fUseNTFS4Streams ); STDMETHOD(GetFormatVersion)(WORD *pw); STDMETHOD(SimulateLowMemory)( BOOL fSimulate ); STDMETHOD_(LONG, GetLockCount)(); STDMETHOD(IsDirty)(); #endif // ----------------------------- // Public, non-interface methods // ----------------------------- public: inline BOOL IsMapped(); inline ULONG SizeOfMapping(); void Read( void *pv, ULONG ulOffset, ULONG *pcbCopy ); void Write( const void *pv, ULONG ulOffset, ULONG *pcbCopy ); HRESULT Init( HANDLE hStream ); HRESULT ShutDown(); // ---------------- // Internal Methods // ---------------- private: void InitMappedStreamMembers(); void BeginUsingUpdateStream(); void EndUsingUpdateStream(); void BeginUsingLatestStream(); void EndUsingLatestStream(); HRESULT WriteMappedStream(); enum enumCREATE_NEW_UPDATE_STREAM { CREATE_NEW_UPDATE_STREAM = 1, DONT_CREATE_NEW_UPDATE_STREAM = 2 }; inline HRESULT CreateUpdateStreamIfNecessary(); HRESULT ReplaceOriginalWithUpdate( enumCREATE_NEW_UPDATE_STREAM CreateNewUpdateStream ); HRESULT OpenUpdateStream( BOOL fCreate ); HRESULT RollForwardIfNecessary(); // -------------- // Internal state // -------------- private: // Containing stream (i.e., we're an embedded object in this CNtfsStream) CNtfsStream *_pnffstm; // Are we using global reserved memory? BOOL _fLowMem:1; // Does the mapped stream have unflushed changes? BOOL _fMappedStreamDirty:1; #if DBG // Should we pretent that CoTaskMemAlloc fails? BOOL _fSimulateLowMem:1; #endif // Is the latest data in _pstmUpdate? BOOL _fUpdateStreamHasLatest:1; // Have we already called the RollForwardIfNecessary method? BOOL _fCheckedForRollForward:1; // Is this an NTFS5 volume? BOOL _fStreamRenameSupported:1; // The current mapping BYTE *_pbMappedStream; // The size of the buffer referred to by _pbMappedStream ULONG _cbMappedStream; // The size of the underlying stream that _pbMappedStream represents ULONG _cbMappedStreamActual; // Cookie used in PrOnMappedStreamEvent VOID *_pMappedStreamOwner; // Count of calls to BeginUsingUpdateStream unmatched by a call to // EndUsingUpdateStream USHORT _cUpdateStreamInUse; // Count of calls to BeginUsingLatestStream unmatched by a call to // EndUsingLatestStream USHORT _cLatestStreamInUse; // The Update stream. CNtfsUpdateStreamForPropStg *_pstmUpdate; }; // class CNFFMappedStream inline CNFFMappedStream::CNFFMappedStream( CNtfsStream *pnffstm ) { _pnffstm = pnffstm; _pstmUpdate = NULL; _fUpdateStreamHasLatest = FALSE; IFDBG( _fSimulateLowMem = FALSE ); InitMappedStreamMembers(); } inline BOOL CNFFMappedStream::IsMapped() { return( NULL != _pbMappedStream ); } inline ULONG CNFFMappedStream::SizeOfMapping() { return( _cbMappedStream ); } #endif // #ifndef _NFFMSTM_HXX_
35.478927
108
0.553456
[ "object" ]
c75468b4c94603f29cc03d10d49a3eac0013777b
18,472
cpp
C++
src/bt_node/environment_model.cpp
tum-phoenix/drive_ros_custom_behavior_trees
1485a5bda8e6a5df38082f3e992e20e9ecd42068
[ "MIT" ]
1
2019-11-12T12:34:42.000Z
2019-11-12T12:34:42.000Z
src/bt_node/environment_model.cpp
tum-phoenix/drive_ros_custom_behavior_trees
1485a5bda8e6a5df38082f3e992e20e9ecd42068
[ "MIT" ]
null
null
null
src/bt_node/environment_model.cpp
tum-phoenix/drive_ros_custom_behavior_trees
1485a5bda8e6a5df38082f3e992e20e9ecd42068
[ "MIT" ]
null
null
null
#include "bt_node/environment_model.h" #include "drive_ros_msgs/ObstacleEnvironment.h" #include "drive_ros_msgs/PedestrianEnvironment.h" #include "drive_ros_msgs/TrafficMarkEnvironment.h" #include "drive_ros_msgs/Lane.h" #include "drive_ros_msgs/TrajectoryMetaInput.h" #include "drive_ros_msgs/value_definitions.h" #include "general.h" #include <math.h> #include <map> extern float min_sign_react_distance; extern float max_sign_react_distance; extern float max_start_box_distance; extern float max_bridge_speed; extern float general_max_speed; extern float break_distance_safety_factor; extern float intersection_max_obj_distance; extern bool priority_road; extern bool force_stop; extern bool overtaking_forbidden_zone; extern bool express_way; extern bool on_bridge; extern int intersection_turn_indication; extern float speed_limit; extern float current_velocity; extern std::string mode; namespace EnvModel { //Working copy of the most recently received message. Only to be used in the environment_model.cpp!!! drive_ros_msgs::EnvironmentModel env_msg; //true when currently in pedestrian tracking "mode" and there was a pedestrian on the track at some point //set to false when no crosswalk is in sight bool pedestrian_on_track = false; bool was_pedestrian_on_track() { return pedestrian_on_track; } float get_traffic_mark_distance(int id) { for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == id) return env_msg.traffic_marks[i].track_distance; } return -1; } float object_min_lane_distance(int lane) { float shortest_distance = 100000; for(int i = 0; i < env_msg.obstacles.size(); i++) { if(env_msg.obstacles[i].obj_lane.obj_lane == lane && env_msg.obstacles[i].obj_track_distance < shortest_distance && env_msg.obstacles[i].obj_track_distance > 0) shortest_distance = env_msg.obstacles[i].obj_track_distance; } return shortest_distance; } bool f_barred_area_left_distance = false; float v_barred_area_left_distance; float barred_area_left_distance() { if(f_barred_area_left_distance) return v_barred_area_left_distance; float d = -1; for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == MARKING_BARRED_AREA_LEFT && (d == -1 || env_msg.traffic_marks[i].track_distance < d)) d = env_msg.traffic_marks[i].track_distance; } v_barred_area_left_distance = d; f_barred_area_left_distance = true; return d; } bool arrived_at_parking_spot() { //Collect all constraints std::vector<float> constraint_distances; for(int i = 0; i < env_msg.obstacles.size(); i++) { if(env_msg.obstacles[i].obj_lane.obj_lane == drive_ros_msgs::Lane::RIGHT_SIDE) constraint_distances.push_back(env_msg.obstacles[i].obj_track_distance); } for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == MARKING_PARKING_SPOT_BLOCKED && env_msg.traffic_marks[i].obj_lane.obj_lane == drive_ros_msgs::Lane::RIGHT_SIDE) constraint_distances.push_back(env_msg.traffic_marks[i].track_distance); } //Sort them in ascending distance order std::sort(constraint_distances.begin(), constraint_distances.end(), std::greater<float>()); //Try to find a parking spot for(int i = 0; i < constraint_distances.size() - 1; i++) { if(constraint_distances[i + 1] - constraint_distances[i] > 0.85) { return constraint_distances[i + 1] - 1.0 < 0.2; } } return false; } bool f_barred_area_right_distance = false; float v_barred_area_right_distance; float barred_area_right_distance() { if(f_barred_area_right_distance) return v_barred_area_right_distance; float d = -1; for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == MARKING_BARRED_AREA_RIGHT && (d == -1 || env_msg.traffic_marks[i].track_distance < d)) d = env_msg.traffic_marks[i].track_distance; } if(d == -1) d = get_traffic_mark_distance(SIGN_YIELD_ONCOMING_TRAFFIC); v_barred_area_right_distance = d; f_barred_area_right_distance = true; return d; } bool f_pass_by_on_right_distance = false; float v_pass_by_on_right_distance; float pass_by_on_right_distance() { if(f_pass_by_on_right_distance) return v_pass_by_on_right_distance; float d = get_traffic_mark_distance(SIGN_PASS_BY_ON_RIGHT); v_pass_by_on_right_distance = d; f_pass_by_on_right_distance = true; return d; } bool intersection_no_object() { for(int i = 0; i < env_msg.obstacles.size(); i++) { if(abs(env_msg.obstacles[i].obj_lateral_offset) < intersection_max_obj_distance) { return false; } } return true; } bool intersection_no_object_right() { for(int i = 0; i < env_msg.obstacles.size(); i++) { if(env_msg.obstacles[i].obj_lateral_offset > -0.4 && env_msg.obstacles[i].obj_lateral_offset < intersection_max_obj_distance) { return false; } } return true; } float break_distance_to(float target_speed) { if(target_speed < current_velocity) return break_distance_safety_factor * 0.5 * (current_velocity - target_speed) * (current_velocity - target_speed) / 4; else return 0.1; } float current_break_distance() { return break_distance_to(0) + 0.1; } bool f_crosswalk_distance = false; float v_crosswalk_distance; float crosswalk_distance() { if(f_crosswalk_distance) return v_crosswalk_distance; float cd = get_traffic_mark_distance(MARKING_CROSSWALK); float pd = get_traffic_mark_distance(PEDESTRIAN); float sd = get_traffic_mark_distance(SIGN_CROSSWALK); v_crosswalk_distance = fmax(fmax(cd, pd), sd); f_crosswalk_distance = true; return v_crosswalk_distance; } bool f_start_line_distance = false; float v_start_line_distance; float start_line_distance() { if(f_start_line_distance) return v_start_line_distance; v_start_line_distance = get_traffic_mark_distance(MARKING_START_LINE); f_start_line_distance = true; return v_start_line_distance; } bool f_parking_sign_distance = false; float v_parking_sign_distance; float parking_sign_distance() { if(f_parking_sign_distance) return v_parking_sign_distance; v_parking_sign_distance = get_traffic_mark_distance(SIGN_PARKING); f_parking_sign_distance = true; return v_parking_sign_distance; } bool f_in_sharp_turn = false; bool v_in_sharp_turn; bool in_sharp_turn() { if(f_in_sharp_turn) return v_in_sharp_turn; for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == SIGN_SHARP_TURN_LEFT || env_msg.traffic_marks[i].id == SIGN_SHARP_TURN_RIGHT) if(env_msg.traffic_marks[i].track_distance < 0.5) { v_in_sharp_turn = true; f_in_sharp_turn = true; return true; } } v_in_sharp_turn = false; f_in_sharp_turn = true; return false; } bool f_in_very_sharp_turn = false; bool v_in_very_sharp_turn; bool in_very_sharp_turn() { if(f_in_very_sharp_turn) return v_in_very_sharp_turn; for(int i = 0; i < env_msg.traffic_marks.size(); i++) { if(env_msg.traffic_marks[i].id == SIGN_VERY_SHARP_TURN_LEFT || env_msg.traffic_marks[i].id == SIGN_VERY_SHARP_TURN_RIGHT) if(env_msg.traffic_marks[i].track_distance < 0.5) { v_in_very_sharp_turn = true; f_in_very_sharp_turn = true; return true; } } v_in_very_sharp_turn = false; f_in_very_sharp_turn = true; return false; } bool start_box_was_closed = false; bool start_box_open() { if(!start_box_was_closed && ((env_msg.front_distance == 0 ? 10000 : env_msg.front_distance) < max_start_box_distance)) { start_box_was_closed = true; ROS_INFO("Start box detected"); } return start_box_was_closed && (env_msg.front_distance > max_start_box_distance); } bool object_on_lane(int lane) { for(int i = 0; i < env_msg.obstacles.size(); i++) { if(env_msg.obstacles[i].obj_lane.obj_lane == lane) return true; } return false; } bool f_crosswalk_clear = false; bool v_crosswalk_clear; bool crosswalk_clear() { if(f_crosswalk_clear) return v_crosswalk_clear; bool flag = true; for(int i = 0; i < env_msg.obstacles.size(); i++) { if(env_msg.obstacles[i].obj_lane.obj_lane == drive_ros_msgs::Lane::LEFT || env_msg.obstacles[i].obj_lane.obj_lane == drive_ros_msgs::Lane::RIGHT) if(env_msg.obstacles[i].obj_track_distance > crosswalk_distance() - 0.1 && env_msg.obstacles[i].obj_track_distance < crosswalk_distance() + 0.6) flag = false; } v_crosswalk_clear = flag; f_crosswalk_clear = true; return flag; } int get_current_lane() { return env_msg.current_lane; } bool f_pedestrians_on_track = false; int v_pedestrians_on_track; int pedestrians_on_track() { if(f_pedestrians_on_track) return v_pedestrians_on_track; int c = 0; for(int i = 0; i < env_msg.pedestrians.size(); i++) { if(env_msg.pedestrians[i].obj_lane.obj_lane < 2) c++; } v_pedestrians_on_track = c; f_pedestrians_on_track = true; } bool f_intersection_immediately_upfront = false; bool v_intersection_immediately_upfront; bool intersection_immediately_upfront() { if(f_intersection_immediately_upfront) return v_intersection_immediately_upfront; float yd = get_traffic_mark_distance(MARKING_CROSSING_YIELD); float sd = get_traffic_mark_distance(MARKING_CROSSING_STOP); float id = get_traffic_mark_distance(MARKING_INTERSECTION); float distance = fmin(fmin(yd == -1 ? 10000 : yd, sd == -1 ? 10000 : sd), id == -1 ? 10000 : id); float intersect_dist = distance == 10000 ? -1 : distance; bool b = (intersect_dist == -1) ? false : intersect_dist < current_break_distance(); v_intersection_immediately_upfront = b; f_intersection_immediately_upfront = true; return b; } int num_of_pedestrians() { return env_msg.pedestrians.size(); } float to_real_speed(int s) { return (s / 10) / 3.6; } void subscriber_callback(const drive_ros_msgs::EnvironmentModel &msg) { env_msg = msg; //Pedestrian tracking if(crosswalk_distance() == -1) { pedestrian_on_track = false; } else { if(!pedestrian_on_track) { for(int i = 0; i < msg.pedestrians.size(); i++) { if(msg.pedestrians[i].obj_lane.obj_lane < 2) { pedestrian_on_track = true; break; } } } } //Check for global sign flags to be set if(!mode.compare("OBSTACLES")) { for(int i = 0; i < msg.traffic_marks.size(); i++) { switch(msg.traffic_marks[i].id) { case SIGN_SPEED_ZONE_10: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(10))) { speed_limit = to_real_speed(10); } break; case SIGN_SPEED_ZONE_20: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(20))) { speed_limit = to_real_speed(20); } break; case SIGN_SPEED_ZONE_30: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(30))) { speed_limit = to_real_speed(30); } break; case SIGN_SPEED_ZONE_40: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(40))) { speed_limit = to_real_speed(40); } break; case SIGN_SPEED_ZONE_50: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(50))) { speed_limit = to_real_speed(50); } break; case SIGN_SPEED_ZONE_60: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(60))) { speed_limit = to_real_speed(60); } break; case SIGN_SPEED_ZONE_70: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(70))) { speed_limit = to_real_speed(70); } break; case SIGN_SPEED_ZONE_80: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(80))) { speed_limit = to_real_speed(80); } break; case SIGN_SPEED_ZONE_90: if(msg.traffic_marks[i].track_distance < break_distance_to(to_real_speed(90))) { speed_limit = to_real_speed(90); } break; case SIGN_SPEED_ZONE_END: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { speed_limit = 100; } break; case SIGN_TURN_LEFT: intersection_turn_indication = drive_ros_msgs::TrajectoryMetaInput::TURN_LEFT; break; case SIGN_TURN_RIGHT: intersection_turn_indication = drive_ros_msgs::TrajectoryMetaInput::TURN_RIGHT; break; case MARKING_ARROW_LEFT: intersection_turn_indication = drive_ros_msgs::TrajectoryMetaInput::TURN_LEFT; break; case MARKING_ARROW_RIGHT: intersection_turn_indication = drive_ros_msgs::TrajectoryMetaInput::TURN_RIGHT; break; case SIGN_PRIORITY_ROAD: priority_road = true; break; case SIGN_GIVE_WAY: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { priority_road = false; express_way = false; } break; case MARKING_CROSSING_YIELD: priority_road = false; express_way = false; break; case SIGN_STOP: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { force_stop = true; priority_road = false; //Maybe the express_way_end was not detected... express_way = false; } break; case MARKING_CROSSING_STOP: force_stop = true; priority_road = false; //Maybe the express_way_end was not detected... express_way = false; break; case SIGN_NO_PASSING_ZONE: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { overtaking_forbidden_zone = true; } break; case SIGN_NO_PASSING_ZONE_END: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { overtaking_forbidden_zone = false; } break; case SIGN_EXPRESSWAY_BEGIN: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { express_way = true; //Should increase robustness, esp. at falsely detected intersections. priority_road = true; } break; case SIGN_EXPRESSWAY_END: if(msg.traffic_marks[i].track_distance < min_sign_react_distance) { express_way = false; priority_road = true; } break; case SIGN_STEEP_INCLINE: if(msg.traffic_marks[i].track_distance < break_distance_to(max_bridge_speed)) { on_bridge = true; } break; case SIGN_STEEP_DECLINE: //We can already drive faster again when we are starting to leave the bridge. on_bridge = false; break; default: break; //All other signs are used differently, e.g. by asking for them directly. These were just passive states. } } } //Invalidate all previously computed data f_barred_area_left_distance = false; f_barred_area_right_distance = false; f_pass_by_on_right_distance = false; f_crosswalk_distance = false; f_start_line_distance = false; f_parking_sign_distance = false; f_in_sharp_turn = false; f_in_very_sharp_turn = false; f_crosswalk_clear = false; f_pedestrians_on_track = false; f_intersection_immediately_upfront = false; } }
40.331878
162
0.588891
[ "vector" ]
c7575fe5af9d5b5d07e771ad1109e07d66978953
920
hpp
C++
shadow/algorithm/detect_yolo.hpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
20
2017-07-04T11:22:47.000Z
2022-01-16T03:58:32.000Z
shadow/algorithm/detect_yolo.hpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
2
2017-12-03T13:07:39.000Z
2021-01-13T11:11:52.000Z
shadow/algorithm/detect_yolo.hpp
junluan/shadow
067d1c51d7c38bc1c985008a2e2e1599bbf11a8c
[ "Apache-2.0" ]
10
2017-09-30T05:06:30.000Z
2020-11-13T05:43:44.000Z
#ifndef SHADOW_ALGORITHM_DETECT_YOLO_HPP_ #define SHADOW_ALGORITHM_DETECT_YOLO_HPP_ #include "method.hpp" #include "core/network.hpp" namespace Shadow { class DetectYOLO final : public Method { public: DetectYOLO() = default; void Setup(const std::string& model_file) override; void Predict(const cv::Mat& im_mat, const RectF& roi, VecBoxF* boxes, std::vector<VecPointF>* Gpoints) override; private: void Process(const VecFloat& in_data, std::vector<VecBoxF>* Gboxes); void ConvertDetections(float* data, const float* biases, int out_h, int out_w, VecBoxF* boxes); Network net_; VecFloat in_data_; VecFloat biases_; std::string in_str_; VecString out_str_; int batch_, in_num_, in_c_, in_h_, in_w_; int num_classes_, num_km_, version_; float threshold_, nms_threshold_; }; } // namespace Shadow #endif // SHADOW_ALGORITHM_DETECT_YOLO_HPP_
24.210526
80
0.720652
[ "vector" ]
c768a057f2f5380752304963f8d2792e8e0c1b4e
11,985
hpp
C++
src/xalanc/XPath/XPathExecutionContextDefault.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
src/xalanc/XPath/XPathExecutionContextDefault.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
src/xalanc/XPath/XPathExecutionContextDefault.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680) #define XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/XPath/XPathDefinitions.hpp> #include <xalanc/Include/XalanObjectCache.hpp> #include <xalanc/Include/XalanVector.hpp> #include <xalanc/XalanDOM/XalanDOMString.hpp> // Base class include file. #include <xalanc/XPath/XPathExecutionContext.hpp> #include <xalanc/PlatformSupport/XalanDOMStringCache.hpp> #include <xalanc/XPath/MutableNodeRefList.hpp> #include <xalanc/XPath/XalanQNameByValue.hpp> namespace XALAN_CPP_NAMESPACE { class DOMSupport; class XPathEnvSupport; class XalanQName; /** * A basic implementation of the class XPathExecutionContext. */ class XALAN_XPATH_EXPORT XPathExecutionContextDefault : public XPathExecutionContext { public: typedef XalanVector<XalanNode*> CurrentNodeStackType; typedef XalanVector<const NodeRefListBase*> ContextNodeListStackType; /** * Construct an XPathExecutionContextDefault object * * @param theXPathEnvSupport XPathEnvSupport class instance * @param theDOMSupport DOMSupport class instance * @param theXobjectFactory factory class instance for XObjects * @param theCurrentNode current node in the source tree * @param theContextNodeList node list for current context * @param thePrefixResolver pointer to prefix resolver to use */ XPathExecutionContextDefault( XPathEnvSupport& theXPathEnvSupport, DOMSupport& theDOMSupport, XObjectFactory& theXObjectFactory, XalanNode* theCurrentNode = 0, const NodeRefListBase* theContextNodeList = 0, const PrefixResolver* thePrefixResolver = 0); /** * Construct an XPathExecutionContextDefault object * * @param theXPathEnvSupport XPathEnvSupport class instance * @param theXObjectFactory factory class instance for XObjects * @param theCurrentNode current node in the source tree * @param theContextNodeList node list for current context * @param thePrefixResolver pointer to prefix resolver to use */ explicit XPathExecutionContextDefault( MemoryManager& theManager, XalanNode* theCurrentNode = 0, const NodeRefListBase* theContextNodeList = 0, const PrefixResolver* thePrefixResolver = 0); static XPathExecutionContextDefault* create( MemoryManager& theManager, XalanNode* theCurrentNode = 0, const NodeRefListBase* theContextNodeList = 0, const PrefixResolver* thePrefixResolver = 0); virtual ~XPathExecutionContextDefault(); /** * Get the XPathEnvSupport instance. * * @return a pointer to the instance. */ XPathEnvSupport* getXPathEnvSupport() const { return m_xpathEnvSupport; } /** * Set the XPathEnvSupport instance. * * @param theSupport a reference to the instance to use. */ void setXPathEnvSupport(XPathEnvSupport* theSupport) { m_xpathEnvSupport = theSupport; } /** * Set the DOMSupport instance. * * @param theDOMSupport a reference to the instance to use. */ void setDOMSupport(DOMSupport* theDOMSupport) { m_domSupport = theDOMSupport; } /** * Set the XObjectFactory instance. * * @param theFactory a reference to the instance to use. */ void setXObjectFactory(XObjectFactory* theXObjectFactory) { m_xobjectFactory = theXObjectFactory; } /** * Get a reference to the scratch QNameByValue instance. * * @return A reference to a QNameByValue instance. */ XalanQNameByValue& getScratchQName() const { return m_scratchQName; } virtual void doFormatNumber( double number, const XalanDOMString& pattern, const XalanDecimalFormatSymbols* theDFS, XalanDOMString& theResult, const XalanNode* context = 0, const Locator* locator = 0); // These interfaces are inherited from XPathExecutionContext... virtual void reset(); virtual XalanNode* getCurrentNode() const; virtual void pushCurrentNode(XalanNode* theCurrentNode); virtual void popCurrentNode(); virtual bool isNodeAfter( const XalanNode& node1, const XalanNode& node2) const; virtual void pushContextNodeList(const NodeRefListBase& theList); virtual void popContextNodeList(); virtual const NodeRefListBase& getContextNodeList() const; virtual size_type getContextNodeListLength() const; virtual size_type getContextNodeListPosition(const XalanNode& contextNode) const; virtual bool elementAvailable(const XalanQName& theQName) const; virtual bool elementAvailable( const XalanDOMString& theName, const Locator* locator) const; virtual bool functionAvailable(const XalanQName& theQName) const; virtual bool functionAvailable( const XalanDOMString& theName, const Locator* locator) const; virtual const XObjectPtr extFunction( const XalanDOMString& theNamespace, const XalanDOMString& functionName, XalanNode* context, const XObjectArgVectorType& argVec, const Locator* locator); virtual XalanDocument* parseXML( MemoryManager& theManager, const XalanDOMString& urlString, const XalanDOMString& base, ErrorHandler* theErrorHandler = 0) const; virtual MutableNodeRefList* borrowMutableNodeRefList(); virtual bool returnMutableNodeRefList(MutableNodeRefList* theList); virtual MutableNodeRefList* createMutableNodeRefList(MemoryManager& theManager) const; virtual XalanDOMString& getCachedString(); virtual bool releaseCachedString(XalanDOMString& theString); virtual void getNodeSetByKey( XalanNode* context, const XalanQName& qname, const XalanDOMString& ref, const Locator* locator, MutableNodeRefList& nodelist); virtual void getNodeSetByKey( XalanNode* context, const XalanDOMString& name, const XalanDOMString& ref, const Locator* locator, MutableNodeRefList& nodelist); virtual const XObjectPtr getVariable( const XalanQName& name, const Locator* locator = 0); virtual const PrefixResolver* getPrefixResolver() const; virtual void setPrefixResolver(const PrefixResolver* thePrefixResolver); virtual const XalanDOMString* getNamespaceForPrefix(const XalanDOMString& prefix) const; virtual const XalanDOMString& findURIFromDoc(const XalanDocument* owner) const; virtual const XalanDOMString& getUnparsedEntityURI( const XalanDOMString& theName, const XalanDocument& theDocument) const; virtual XalanDocument* getSourceDocument(const XalanDOMString& theURI) const; virtual void setSourceDocument( const XalanDOMString& theURI, XalanDocument* theDocument); virtual void formatNumber( double number, const XalanDOMString& pattern, XalanDOMString& theResult, const XalanNode* context = 0, const Locator* locator = 0); virtual void formatNumber( double number, const XalanDOMString& pattern, const XalanDOMString& dfsName, XalanDOMString& theResult, const XalanNode* context = 0, const Locator* locator = 0); // These interfaces are inherited from ExecutionContext... virtual void problem( eSource source, eClassification classification, const XalanDOMString& msg, const Locator* locator, const XalanNode* sourceNode); virtual void problem( eSource source, eClassification classification, const XalanDOMString& msg, const XalanNode* sourceNode); virtual void error( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const Locator* locator = 0) const; virtual void warn( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const Locator* locator = 0) const; virtual void message( const XalanDOMString& msg, const XalanNode* sourceNode = 0, const Locator* locator = 0) const; virtual bool shouldStripSourceNode(const XalanText& node); protected: typedef XalanObjectCache< MutableNodeRefList, DefaultCacheCreateFunctorMemMgr<MutableNodeRefList>, DeleteFunctor<MutableNodeRefList>, ClearCacheResetFunctor<MutableNodeRefList> > NodeListCacheType; enum { eNodeListCacheListSize = 50 }; struct ContextNodeListPositionCache { ContextNodeListPositionCache() : m_node(0), m_index(0) { } void clear() { if (m_node != 0) { m_node = 0; } } const XalanNode* m_node; size_type m_index; }; XPathEnvSupport* m_xpathEnvSupport; DOMSupport* m_domSupport; CurrentNodeStackType m_currentNodeStack; ContextNodeListStackType m_contextNodeListStack; const PrefixResolver* m_prefixResolver; XalanDOMString m_currentPattern; NodeListCacheType m_nodeListCache; XalanDOMStringCache m_stringCache; mutable ContextNodeListPositionCache m_cachedPosition; mutable XalanQNameByValue m_scratchQName; static const NodeRefList s_dummyList; }; } #endif // XPATHEXECUTIONCONTEXTDEFAULT_HEADER_GUARD_1357924680
28.467933
84
0.609846
[ "object" ]
c7705b7294d0e8182a3c059ce71d144c8bcbdc01
593
cpp
C++
Leetcode/1000-2000/1727. Largest Submatrix With Rearrangements/1727.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1727. Largest Submatrix With Rearrangements/1727.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/1000-2000/1727. Largest Submatrix With Rearrangements/1727.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int largestSubmatrix(vector<vector<int>>& matrix) { const int n = matrix[0].size(); int ans = 0; vector<int> hist(n); for (const auto& row : matrix) { // accumulate the histogram if possible for (int i = 0; i < n; ++i) hist[i] = row[i] == 0 ? 0 : hist[i] + 1; // get sorted histogram vector<int> sortedHist(hist); sort(begin(sortedHist), end(sortedHist)); // greedily calculate the answer for (int i = 0; i < n; ++i) ans = max(ans, sortedHist[i] * (n - i)); } return ans; } };
23.72
53
0.543002
[ "vector" ]
c7723daa88905396058a5631fa9447dbc54aebbe
2,224
cpp
C++
sources/dir_analyze.cpp
dyndtikj/4-boost-fs
7349c9f7e249241d16e649cfa33e2aa59d1344b8
[ "MIT" ]
null
null
null
sources/dir_analyze.cpp
dyndtikj/4-boost-fs
7349c9f7e249241d16e649cfa33e2aa59d1344b8
[ "MIT" ]
null
null
null
sources/dir_analyze.cpp
dyndtikj/4-boost-fs
7349c9f7e249241d16e649cfa33e2aa59d1344b8
[ "MIT" ]
null
null
null
// Copyright 2021 <geraldy12319@gamil.com> #include <dir_analyze.hpp> Analyzer::Analyzer(const std::string& path) { if (!path.empty()) { boost::system::error_code err; if (fs::exists(path, err)) { file_path = path; } else { throw fs::filesystem_error("Nothing exist at the path", err); } } else { file_path = fs::current_path(); } const std::regex pattern( "^(balance_)\\d\\d\\d\\d\\d\\d\\d\\d_\\d\\d\\d\\d\\d\\d\\d\\d"); for (const auto& dir : fs::directory_iterator(file_path)) { if (fs::is_directory(dir.path())) { for (const auto& file : fs::directory_iterator{dir.path()}) { if (fs::is_regular_file(file) && (file.path().extension() == ".txt") && (std::regex_match(file.path().stem().string(), pattern))) { pathArr.push_back(file.path()); nameAccounts.insert(file.path().stem().string().substr(8, 8)); } } } } } void Analyzer::Files_Info(std::ostream& out) const{ for (const auto& path : pathArr) { out << std::left << std::setw(10) << path.parent_path().filename().string() << " " << path.filename().string() << '\n'; } } std::stringstream Analyzer::Account_to_str(const fs::path& elem, const size_t& n) const{ std::stringstream ss; ss << "broker: " << std::left << std::setw(8) << elem.parent_path().filename().string() << " | account: " << elem.stem().string().substr(8, 8) << " | files: " << std::setw(3) << n << " | lastdate: " << elem.stem().string().substr(17, 8); return ss; } void Analyzer::Accounts_Stats(std::ostream& out) const{ for (const auto & el : nameAccounts) { std::vector<fs::path> temp; size_t n = 0; for (const auto& i : pathArr) { if (el == i.stem().string().substr(8, 8)) { n++; temp.push_back(i); } } auto recent = std::max_element( temp.begin(), temp.end(), [](const fs::path& lhs, const fs::path& rhs) { return lhs.stem().string().substr(17, 8) < rhs.stem().string().substr(17, 8); }); out << Account_to_str(*recent, n).str() << std::endl; } } Analyzer::~Analyzer() = default;
31.323944
80
0.546763
[ "vector" ]
c7811d2958e52de65b16743f750ef5e39169ddc6
710
cpp
C++
6 star Problem Solving/Algorithms/Greedy/Largest Permutation.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
6
2021-04-26T17:09:54.000Z
2021-07-08T17:36:16.000Z
6 star Problem Solving/Algorithms/Greedy/Largest Permutation.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
null
null
null
6 star Problem Solving/Algorithms/Greedy/Largest Permutation.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void largestPermutation(int k, vector<int> &arr) { int l=arr.size(),a[l+1]={0},r=0; for(int i=0;i<l;i++) a[arr[i]]=i; while(k>0 && r<l) { if(arr[r]!=l-r) { arr[a[l-r]]=arr[r]; a[arr[r]]=a[l-r]; arr[r]=l-r; a[l-r]=r; k--; } ++r; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n,k; cin>>n>>k; vector<int> arr(n,0); for (int i = 0; i < n; i++) cin>>arr[i]; largestPermutation(k, arr); for (size_t i = 0; i < n; i++) cout << arr[i]<<" "; return 0; }
20.285714
50
0.423944
[ "vector" ]
c78429fec2bfb503ee44e7fa0eadab23c75d5610
6,438
cpp
C++
src/ie_terrain.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
1
2017-09-21T16:53:27.000Z
2017-09-21T16:53:27.000Z
src/ie_terrain.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
null
null
null
src/ie_terrain.cpp
wtkooa/imagine
105695085b369825b70ff3ca4b0076f8ce15c957
[ "MIT" ]
null
null
null
//___|"ie_terrain.cpp"|_________________________________________________________ // // Project: Imagine: 3D Environment Engine // Version: 0.1.0 // Author: David Lipps // License: MIT License // // Copyright (c) 2017 David E Lipps //______________________________________________________________________________ #include "ie_terrain.h" #include <cmath> #include <iostream> #include <glm/gtc/noise.hpp> #include <glm/mat4x2.hpp> #include <glm/vec3.hpp> #include <glm/gtx/vector_angle.hpp> #include "ie_config.h" #include "ie_packages.h" ie::TerrainGenerator::TerrainGenerator(void) { clear(); generateTerrain(); } ie::TerrainGenerator::TerrainGenerator(short d) { clear(); generateTerrain(d, unitSize); } ie::TerrainGenerator::TerrainGenerator(short d, float u) { generateTerrain(d, u); } void ie::TerrainGenerator::clear(void) { name = "Terrain"; dim = 100; unitSize = 1; vertices.clear(); colors.clear(); blends.clear(); indices.clear(); textures.clear(); shininess = 1; ambient = glm::vec3(1.0f, 1.0f, 1.0f); diffuse = glm::vec3(0.0f, 0.0f, 0.0f); specular = glm::vec3(0.0f, 0.0f, 0.0f); emission = glm::vec3(0.0f, 0.0f, 0.0f); } void ie::TerrainGenerator::generateTerrain() {generateTerrain(dim, unitSize);} void ie::TerrainGenerator::generateTerrain(short d, float u) { clear(); dim = d; unitSize = u; for (short z = 0; z < dim; z++) { for (short x = 0; x < dim; x++) { glm::vec4 vert(x * unitSize, 0.0f, z * unitSize, 1.0f); glm::vec3 color(0.0f , 0.0f, 0.0f); glm::vec3 normal(0.0f, 1.0f, 0.0f); glm::uvec2 blend(99, 0); vertices.push_back(vert); colors.push_back(color); normals.push_back(normal); blends.push_back(blend); } } for (short z = 0; z < (dim - 1); z++) { for (short x = 0; x < (dim - 1); x++) { unsigned int n = (z * dim) + x; unsigned int v1 = n; unsigned int v2 = (n + dim); unsigned int v3 = (n + dim + 1); unsigned int v4 = (n + 1); indices.push_back(glm::ivec4(v1, v2, v3, 0)); indices.push_back(glm::ivec4(v3, v4, v1, 0)); } } } void ie::TerrainGenerator::applyPerlin(float seed, float res, float range) { float hackyOffset = 0.001; range /= 2.0f; for (short z = 0; z < dim; z++) { for (short x = 0; x < dim; x++) { unsigned int n = (z * dim) + x; glm::vec3 perlVec((float(x) + hackyOffset) / res, float(seed) + hackyOffset, (float(z) + hackyOffset) / res); vertices[n].y = glm::perlin(perlVec) * range; } } calcFaceNormals(); } void ie::TerrainGenerator::calcFaceNormals(void) { faceNormals.clear(); for (short z = 0; z < (dim - 1); z++) { for (short x = 0; x < (dim - 1); x++) { unsigned int n = (z * dim) + x; glm::vec3 v1(vertices[n].x, vertices[n].y, vertices[n].z); glm::vec3 v2(vertices[n+dim].x, vertices[n+dim].y, vertices[n+dim].z); glm::vec3 v3(vertices[n+dim+1].x, vertices[n+dim+1].y, vertices[n+dim+1].z); glm::vec3 v4(vertices[n+1].x, vertices[n+1].y, vertices[n+1].z); glm::vec3 n1 = glm::normalize(cross((v2-v1), (v3-v1))); glm::vec3 n2 = glm::normalize(cross((v3-v1), (v4-v1))); faceNormals.push_back(n1); faceNormals.push_back(n2); } } smoothNormals(); } void ie::TerrainGenerator::smoothNormals(void) { normals.clear(); for (unsigned int n = 0; n < dim * dim; n++) { normals.push_back(glm::vec3()); } for (unsigned int face = 0; face < indices.size(); face++) { unsigned int vert = indices[face].x; normals[vert] += faceNormals[face]; vert = indices[face].y; normals[vert] += faceNormals[face]; vert = indices[face].z; normals[vert] += faceNormals[face]; } for (unsigned int n = 0; n < dim * dim; n++) { normals[n] = glm::normalize(normals[n]); } } void ie::TerrainGenerator::applyDemoBlends(void) { short octalSize = (dim / 8); unsigned int blendAmount = dim * dim; for (unsigned int nBlend = 0; nBlend < blendAmount; nBlend++) { blends[nBlend] = glm::uvec2(0, 0); } for (short z = 0; z < dim; z++) { for (short x = 0; x < dim; x++) { unsigned int n = (z * dim) + x; short octal = short(x / octalSize); blends[n] = setBlendValue(blends[n], octal, 49); } } for (short z = 0; z < dim; z++) { for (short x = 0; x < dim; x++) { unsigned int n = (z * dim) + x; short octal = short(z / octalSize); blends[n] = setBlendValue(blends[n], octal, 49); } } } glm::uvec2 ie::TerrainGenerator::setBlendValue(glm::uvec2 blend, short tex, short value) { tex = 7 - tex; if (tex < 4) { blend.y += value * std::pow(100, tex); } else { tex -= 4; blend.x += value * std::pow(100, tex); } return blend; } void ie::TerrainGenerator::addTexture(std::string filepath, std::string filename) { if (textures.size() < ie::MAX_TERRAIN_TEXTURES) { TexturePackage texture; texture.filepath = filepath; texture.filename = filename; texture.type = BUMP_MAP; texture.mipmapped = true; texture.anisotropy = true; texture.repeating = true; textures.push_back(texture); } else { std::cout << "Warning: Max terrian texture capacity (" << ie::MAX_TERRAIN_TEXTURES << ") already reached." << std::endl; } } ie::TerrainPackage ie::TerrainGenerator::wrapTerrainPackage(void) { ie::TerrainPackage package; package.name = name; package.dim = dim; package.unitSize = unitSize; package.vertices = vertices; package.normals = normals; package.colors = colors; package.blends = blends; package.indices = indices; package.textures = textures; package.shininess = shininess; package.ambient = ambient; package.diffuse = diffuse; package.emission = emission; return package; } void ie::TerrainGenerator::setName(std::string n) {name = n;} void ie::TerrainGenerator::setDim(short d) {dim = d;} void ie::TerrainGenerator::setShininess(float s) {shininess = s;} void ie::TerrainGenerator::setAmbient(glm::vec3 a) {ambient = a;} void ie::TerrainGenerator::setDiffuse(glm::vec3 d) {diffuse = d;} void ie::TerrainGenerator::setSpecular(glm::vec3 s) {specular = s;} void ie::TerrainGenerator::setEmission(glm::vec3 e) {emission = e;}
24.953488
82
0.60438
[ "3d" ]
c78a96e0b67780c4a16e5b41c9a626b0f3240ea1
1,369
cc
C++
cpp/src/ow/lemonadeChange.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2019-10-17T08:34:55.000Z
2019-10-17T08:34:55.000Z
cpp/src/ow/lemonadeChange.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2020-05-24T08:32:13.000Z
2020-05-24T08:32:13.000Z
cpp/src/ow/lemonadeChange.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
null
null
null
#include "test.h" /** Question no 860 easy Lemonade Change * Author : Li-Han, Chen; 陳立瀚 * Date : 14th, March, 2020 * Source : https://leetcode.com/problems/lemonade-change/ * * At a lemonade stand, each lemonade costs $5. * * Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). * * Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. * You must provide the correct change to each customer, so that the net transaction is that the customer pays $5. * * Note that you don't have any change in hand at first. * * Return true if and only if you can provide every customer with correct change. * */ /** Solution * Runtime 12 ms MeMory 8.6 MB; * faster than 97.13%, less than 100.00% * O(n) ; O(1) */ bool lemonadeChange(std::vector<int>& bills) { std::vector<int> chg(3, 0); for (auto item: bills) { switch (item) { case 5: chg[0]++; break; case 10: if (chg[0] == 0) return false; chg[0]--; chg[1]++; break; default: if (chg[1] == 0 ) { if (chg[0]<3) return false; chg[0]-=3; } else { if (chg[0] == 0) return false; chg[0]--; chg[1]--; } chg[2]++; break; } } return true; }
24.890909
114
0.563185
[ "vector" ]
c791f4a832e5924f910f29503615c3ea0fa87c6a
986
cpp
C++
125_backpack-ii/backpack-ii.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
2
2016-07-30T01:25:06.000Z
2017-10-07T12:30:24.000Z
125_backpack-ii/backpack-ii.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
null
null
null
125_backpack-ii/backpack-ii.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
null
null
null
/* @Copyright:LintCode @Author: taoleetju @Problem: http://www.lintcode.com/problem/backpack-ii @Language: C++ @Datetime: 16-06-08 05:13 */ class Solution { public: /** * @param m: An integer m denotes the size of a backpack * @param A & V: Given n items with size A[i] and value V[i] * @return: The maximum value */ int backPackII(int m, vector<int> A, vector<int> V) { vector<int> prev(m+1,0), cur(m+1, 0); if(A.empty()|| m<=0|| V.empty()|| A.size()!=V.size()) return 0; int j=0; for(; j<= m; j++){ if(A[0]<=j) prev[j] = V[0]; } for(int i=1; i<A.size(); i++){ for(int j=0; j<=m; j++){ if(A[i]<=j) cur[j] = max(V[i]+ prev[j-A[i]], prev[j]); else cur[j] = prev[j]; } prev = cur; } return prev[m]; } };
26.648649
65
0.423935
[ "vector" ]
c798f2849e7a21d36214679a17aa78586a0e7286
11,871
cpp
C++
cpp/serving/tabular_model.cpp
meta-soul/MetaSpore
e6fbc12c6a3139df76c87215b16f9dba65962ec7
[ "Apache-2.0" ]
32
2022-03-30T10:24:00.000Z
2022-03-31T16:19:15.000Z
cpp/serving/tabular_model.cpp
meta-soul/MetaSpore
e6fbc12c6a3139df76c87215b16f9dba65962ec7
[ "Apache-2.0" ]
null
null
null
cpp/serving/tabular_model.cpp
meta-soul/MetaSpore
e6fbc12c6a3139df76c87215b16f9dba65962ec7
[ "Apache-2.0" ]
3
2022-03-30T10:28:57.000Z
2022-03-30T11:37:39.000Z
// // Copyright 2022 DMetaSoul // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <common/logger.h> #include <serving/converters.h> #include <serving/dense_feature_extraction_model.h> #include <serving/feature_extraction_model_input.h> #include <serving/ort_model.h> #include <serving/sparse_embedding_bag_model.h> #include <serving/sparse_feature_extraction_model.h> #include <serving/sparse_lookup_model.h> #include <serving/tabular_model.h> #include <serving/threadpool.h> #include <filesystem> #include <boost/algorithm/string.hpp> #include <fmt/format.h> namespace metaspore::serving { namespace fs = std::filesystem; struct SparseModelUnit { SparseFeatureExtractionModel fe_model; SparseLookupModel lookup_model; SparseEmbeddingBagModel emb_model; std::unique_ptr<Converter> fe_to_lookup_converter; }; class TabularModelContext { public: std::vector<SparseModelUnit> sparse_models; DenseFeatureExtractionModel dense_model; std::unique_ptr<Converter> dense_fe_to_ort_converter; OrtModel ort_model; // inputs of crt model is unique set of inputs of all Fe models std::vector<std::string> inputs_; }; TabularModel::TabularModel() { context_ = std::make_unique<TabularModelContext>(); } TabularModel::TabularModel(TabularModel &&) = default; TabularModel::~TabularModel() = default; awaitable_status TabularModel::load(std::string dir_path) { auto s = co_await boost::asio::co_spawn( Threadpools::get_background_threadpool(), [this, &dir_path]() -> awaitable_status { // load a ctr model // 1. find all subdirs prefixed with "sparse_" and load fe/lookup models in them fs::path root_dir(dir_path); if (!fs::is_directory(root_dir)) { co_return absl::NotFoundError( fmt::format("TabularModel cannot find dir {}", dir_path)); } bool dense_loaded = false; for (auto const &dir_entry : fs::directory_iterator{root_dir}) { if (!dir_entry.is_directory()) { // find if dense schema exist and load it if (dir_entry.path().filename() == "dense_schema.txt") { CO_AWAIT_AND_CO_RETURN_IF_STATUS_NOT_OK( context_->dense_model.load(root_dir.string())); context_->dense_fe_to_ort_converter = std::make_unique<DenseFEToOrtConverter>( context_->dense_model.input_names()); std::copy(context_->dense_model.input_names().begin(), context_->dense_model.input_names().end(), std::back_inserter(context_->inputs_)); } continue; } auto dir_name = dir_entry.path().filename(); // begin to load components of sparse models if (boost::contains(dir_name.string(), "sparse")) { SparseModelUnit unit; int component_loaded = 0; // load sparse model for (auto const &sparse_dir_entry : fs::directory_iterator{dir_entry}) { spdlog::info("find path {} under {}", sparse_dir_entry.path().string(), dir_entry.path().string()); if (!sparse_dir_entry.is_directory() && sparse_dir_entry.path().filename() == "combine_schema.txt") { spdlog::info("Loading sparse fe model from {}", dir_entry.path().string()); // load sparse fe model CO_AWAIT_AND_CO_RETURN_IF_STATUS_NOT_OK( unit.fe_model.load(dir_entry.path().string())); component_loaded ^= 0b1; std::copy(unit.fe_model.input_names().begin(), unit.fe_model.input_names().end(), std::back_inserter(context_->inputs_)); } else if (sparse_dir_entry.path().filename().string() == "embedding_table") { spdlog::info("Loading sparse lookup model from {}", dir_entry.path().string()); // load lookup model CO_AWAIT_AND_CO_RETURN_IF_STATUS_NOT_OK( unit.lookup_model.load(dir_entry.path().string())); unit.fe_to_lookup_converter = std::make_unique<SparseFEToLookupConverter>(); component_loaded ^= 0b10; } else if (!sparse_dir_entry.is_directory() && sparse_dir_entry.path().filename() == "model.onnx") { spdlog::info("Loading sparse embedding bag model from {}", dir_entry.path().string()); // load sparse emebdding bag model CO_AWAIT_AND_CO_RETURN_IF_STATUS_NOT_OK( unit.emb_model.load(dir_entry.path().string())); component_loaded ^= 0b100; } } if (component_loaded != 0b111) { co_return absl::NotFoundError( fmt::format("TabularModel with a sparse component under {} requires a " "combine_schema.txt file, an embedding_table dir and a " "model.onnx file to initialize, component loaded {:#b}", dir_name.string(), component_loaded)); } context_->sparse_models.emplace_back(std::move(unit)); } else if (boost::contains(dir_name.string(), "dense")) { // load dense ort model if (!dense_loaded) { CO_AWAIT_AND_CO_RETURN_IF_STATUS_NOT_OK( context_->ort_model.load(dir_entry.path())); dense_loaded = true; } else { spdlog::error("TabularModel cannot support more than one dense model"); co_return absl::UnimplementedError( "TabularModel cannot support more than one dense model"); } } } if (context_->sparse_models.empty() && !context_->dense_fe_to_ort_converter) { auto msg = fmt::format( "TabularModel requires at least one fe model while loading from {}", dir_path); spdlog::error(msg); co_return absl::NotFoundError(msg); } if (!dense_loaded) { auto msg = fmt::format("TabularModel requires an onnx model under {}/dense/", dir_path); spdlog::error(msg); co_return absl::NotFoundError(msg); } // get unique input names from all sparse/fe models as the inputs of TabularModel std::sort(context_->inputs_.begin(), context_->inputs_.end()); auto last = std::unique(context_->inputs_.begin(), context_->inputs_.end()); context_->inputs_.erase(last, context_->inputs_.end()); spdlog::info("TabularModel loaded from {}, required inputs [{}], " "producing outputs [{}]", dir_path, fmt::join(context_->inputs_, ", "), fmt::join(this->output_names(), ", ")); co_return absl::OkStatus(); }, boost::asio::use_awaitable); co_return s; } std::unique_ptr<FeatureExtractionModelInput> get_input(ModelBase &fe_model, const FeatureExtractionModelInput *input) { auto out = std::make_unique<FeatureExtractionModelInput>(); for (const auto &name : fe_model.input_names()) { auto find = input->feature_tables.find(name); if (find == input->feature_tables.end()) { spdlog::error("Fe model required input {} not found"); return nullptr; } out->feature_tables[name] = find->second; } return out; } awaitable_result<std::unique_ptr<OrtModelOutput>> TabularModel::do_predict(std::unique_ptr<FeatureExtractionModelInput> input) { // firstly execute sparse fe and lookup // set all output to ort input auto *fe_input = input.get(); auto ort_in = std::make_unique<OrtModelInput>(); for (auto &unit : context_->sparse_models) { auto sub_input = get_input(unit.fe_model, fe_input); if (!sub_input) { co_return absl::NotFoundError("Input not found for sparse fe model"); } CO_ASSIGN_RESULT_OR_CO_RETURN_NOT_OK(auto fe_result, unit.fe_model.do_predict(std::move(sub_input))); auto lookup_in = std::make_unique<SparseLookupModelInput>(); CALL_AND_CO_RETURN_IF_STATUS_NOT_OK( unit.fe_to_lookup_converter->convert_input(std::move(fe_result), lookup_in.get())); CO_ASSIGN_RESULT_OR_CO_RETURN_NOT_OK(auto lookup_result, unit.lookup_model.do_predict(std::move(lookup_in))); CO_ASSIGN_RESULT_OR_CO_RETURN_NOT_OK(auto emb_ort_result, unit.emb_model.do_predict(std::move(lookup_result))); // merge embedding bag output to ort_in for (auto &[name, v] : emb_ort_result->outputs) { if (!ort_in->inputs.emplace(name, OrtModelInput::Value{.value = std::move(v)}).second) { co_return absl::AlreadyExistsError( fmt::format("Sparse Embedding produced duplicated output {}", name)); } } } // secondly execute dense fe if it exists // and set all output to ort input if (context_->dense_fe_to_ort_converter) { auto sub_input = get_input(context_->dense_model, fe_input); if (!sub_input) { co_return absl::NotFoundError("Input not found for dense fe model"); } CO_ASSIGN_RESULT_OR_CO_RETURN_NOT_OK( auto fe_result, context_->dense_model.do_predict(std::move(sub_input))); CO_RETURN_IF_STATUS_NOT_OK( context_->dense_fe_to_ort_converter->convert_input(std::move(fe_result), ort_in.get())); } // finally execute ort model prediction CO_ASSIGN_RESULT_OR_CO_RETURN_NOT_OK(auto final_result, context_->ort_model.do_predict(std::move(ort_in))); co_return final_result; } std::string TabularModel::info() const { return ""; } const std::vector<std::string> &TabularModel::input_names() const { return context_->inputs_; } const std::vector<std::string> &TabularModel::output_names() const { return context_->ort_model.output_names(); } } // namespace metaspore::serving
46.920949
100
0.56499
[ "vector", "model" ]
c79a4277b218472a732b5784c778cedcb797d693
13,898
cpp
C++
libraries/nodes/src/SoftmaxLayerNode.cpp
siddu1998/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2018-11-08T06:19:31.000Z
2018-11-08T06:19:31.000Z
libraries/nodes/src/SoftmaxLayerNode.cpp
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
null
null
null
libraries/nodes/src/SoftmaxLayerNode.cpp
vishnoitanuj/ELL
993d5370f0f7a274e8dfd8f43220c792be46f314
[ "MIT" ]
1
2019-12-19T10:02:48.000Z
2019-12-19T10:02:48.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: SoftmaxLayerNode.cpp (nodes) // Authors: Chuck Jacobs // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "SoftmaxLayerNode.h" #include "BroadcastFunctionNode.h" #include "ConstantNode.h" namespace ell { namespace nodes { namespace { // // Function objects for separate phases // template <typename ValueType> class FindMaxFunction { public: FindMaxFunction(emitters::IRFunctionEmitter& function) { auto valueType = emitters::GetVariableType<ValueType>(); _accumValueVar = function.Variable(valueType, "maxAccumValue"); Reset(function); } void Reset(emitters::IRFunctionEmitter& function) { function.Store(_accumValueVar, function.Literal(-(std::numeric_limits<ValueType>::max()))); } emitters::LLVMValue Compile(emitters::IRFunctionEmitter& function, emitters::LLVMValue x) { function.If(emitters::TypedComparison::greaterThanFloat, x, function.Load(_accumValueVar), [this, x](emitters::IRFunctionEmitter& function) { function.Store(_accumValueVar, x); }); return nullptr; } emitters::LLVMValue GetMaxValue(emitters::IRFunctionEmitter& function) const { return function.Load(_accumValueVar); } private: emitters::LLVMValue _accumValueVar; }; template <typename ValueType> class ComputeEulerAndSumFunction { public: ComputeEulerAndSumFunction(emitters::IRFunctionEmitter& function, emitters::LLVMValue maxValue) : _maxValue(maxValue) { auto valueType = emitters::GetVariableType<ValueType>(); _accumValueVar = function.Variable(valueType, "eulerSumAccumValue"); _expFunc = function.GetModule().GetRuntime().GetExpFunction<ValueType>(); Reset(function); } void Reset(emitters::IRFunctionEmitter& function) { function.StoreZero(_accumValueVar); } emitters::LLVMValue Compile(emitters::IRFunctionEmitter& function, emitters::LLVMValue x) { const auto plusFloat = emitters::TypedOperator::addFloat; const auto minusFloat = emitters::TypedOperator::subtractFloat; auto valueMinusMax = function.Operator(minusFloat, x, _maxValue); auto eulerVal = function.Call(_expFunc, { valueMinusMax }); function.OperationAndUpdate(_accumValueVar, plusFloat, eulerVal); return eulerVal; } emitters::LLVMValue GetEulerSum(emitters::IRFunctionEmitter& function) const { return function.Load(_accumValueVar); } private: emitters::LLVMFunction _expFunc; emitters::LLVMValue _maxValue; emitters::LLVMValue _accumValueVar; }; template <typename ValueType> class NormalizeOutputFunction { public: NormalizeOutputFunction(emitters::IRFunctionEmitter& function, emitters::LLVMValue sum) : _sum(sum) { } void Reset(emitters::IRFunctionEmitter& function) { } emitters::LLVMValue Compile(emitters::IRFunctionEmitter& function, emitters::LLVMValue x) { const auto divideFloat = emitters::TypedOperator::divideFloat; return function.Operator(divideFloat, x, _sum); } public: emitters::LLVMValue _sum; }; } // end anonymous namespace template <typename ValueType> SoftmaxLayerNode<ValueType>::SoftmaxLayerNode(const model::OutputPort<ValueType>& input, const predictors::neural::SoftmaxLayer<ValueType>& layer) : NeuralNetworkLayerNode<SoftmaxLayerNode<ValueType>, predictors::neural::SoftmaxLayer<ValueType>, ValueType>(input, layer) { } template <typename ValueType> void SoftmaxLayerNode<ValueType>::Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function) { emitters::LLVMValue pInput = compiler.EnsurePortEmitted(input); emitters::LLVMValue pOutput = compiler.EnsurePortEmitted(output); emitters::LLVMValue prevInputDimensionOffset = nullptr; emitters::LLVMValue prevOutputDimensionOffset = nullptr; // Compute max value FindMaxFunction<ValueType> findMax(function); EmitComputeDimensionLoop(compiler, function, 0, this->GetInputMemoryLayout(), this->GetOutputMemoryLayout(), pInput, pOutput, prevInputDimensionOffset, prevOutputDimensionOffset, findMax); auto maxValue = findMax.GetMaxValue(function); // Compute sum and scale output ComputeEulerAndSumFunction<ValueType> computeEuler(function, maxValue); EmitComputeDimensionLoop(compiler, function, 0, this->GetInputMemoryLayout(), this->GetOutputMemoryLayout(), pInput, pOutput, prevInputDimensionOffset, prevOutputDimensionOffset, computeEuler); auto eulerSum = computeEuler.GetEulerSum(function); // normalize output NormalizeOutputFunction<ValueType> normalizeOutput(function, eulerSum); EmitComputeDimensionLoop(compiler, function, 0, this->GetOutputMemoryLayout(), pOutput, prevOutputDimensionOffset, normalizeOutput); } template <typename ValueType> template <typename FunctionType> void SoftmaxLayerNode<ValueType>::EmitComputeDimensionLoop(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function, size_t dimension, const model::PortMemoryLayout& inputLayout, const model::PortMemoryLayout& outputLayout, emitters::LLVMValue pInput, emitters::LLVMValue pOutput, emitters::LLVMValue prevInputDimensionOffset, emitters::LLVMValue prevOutputDimensionOffset, FunctionType& f) const { // Note: It should be easy to unroll the last K levels by putting a real loop here when dimension < k // Or, instead of unrolling, vectorizing --- if broadcastDimension = 1, let secondaryValue be a vector and load it one loop previous const auto numDimensions = this->NumInputDimensions(); auto&& inputStride = inputLayout.GetStride(); auto&& inputOffset = inputLayout.GetOffset(); auto&& inputSize = inputLayout.GetActiveSize(); auto&& outputStride = outputLayout.GetStride(); auto&& outputOffset = outputLayout.GetOffset(); function.For(inputSize[dimension], [dimension, numDimensions, inputStride, inputOffset, inputLayout, outputStride, outputOffset, outputLayout, pInput, pOutput, prevInputDimensionOffset, prevOutputDimensionOffset, &f, &compiler, this](emitters::IRFunctionEmitter& function, emitters::LLVMValue i) { auto loopIndex = function.LocalScalar(i); // Calculate the offset within this dimension = (loopIndex + offset[dimension]) auto thisInputDimensionInternalOffset = loopIndex + inputOffset[dimension]; auto thisOutputDimensionInternalOffset = loopIndex + outputOffset[dimension]; // Calculate the total offset from beginning of memory: // * if in the outermost loop, the offset into this dimension // * otherwise, the offset into this dimension plus the previous offset scaled by the previous dimension's stride auto thisInputDimensionOffset = function.LocalScalar(); auto thisOutputDimensionOffset = function.LocalScalar(); if (dimension == 0) { assert(prevInputDimensionOffset == nullptr); assert(prevOutputDimensionOffset == nullptr); thisInputDimensionOffset = thisInputDimensionInternalOffset; thisOutputDimensionOffset = thisOutputDimensionInternalOffset; } else { auto scaledInputDimensionOffset = prevInputDimensionOffset * function.LocalScalar<int>(inputStride[dimension]); thisInputDimensionOffset = scaledInputDimensionOffset + thisInputDimensionInternalOffset; auto scaledOutputDimensionOffset = prevOutputDimensionOffset * function.LocalScalar<int>(outputStride[dimension]); thisOutputDimensionOffset = scaledOutputDimensionOffset + thisOutputDimensionInternalOffset; } if (dimension < numDimensions - 1) { // Recursive call to emit nested loop EmitComputeDimensionLoop(compiler, function, dimension + 1, inputLayout, outputLayout, pInput, pOutput, thisInputDimensionOffset, thisOutputDimensionOffset, f); } else { // We're in the innermost loop --- compute the value auto inputValue = function.ValueAt(pInput, thisInputDimensionOffset); auto outputValue = f.Compile(function, inputValue); if (outputValue != nullptr) { function.SetValueAt(pOutput, thisOutputDimensionOffset, outputValue); } } }); } // In-place version template <typename ValueType> template <typename FunctionType> void SoftmaxLayerNode<ValueType>::EmitComputeDimensionLoop(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function, size_t dimension, const model::PortMemoryLayout& inputLayout, emitters::LLVMValue pInput, emitters::LLVMValue prevInputDimensionOffsetValue, FunctionType& f) const { // Note: It should be easy to unroll the last K levels by putting a real loop here when dimension < k // Or, instead of unrolling, vectorizing --- if broadcastDimension = 1, let secondaryValue be a vector and load it one loop previous const auto numDimensions = this->NumInputDimensions(); auto&& inputStride = inputLayout.GetStride(); auto&& inputOffset = inputLayout.GetOffset(); auto&& inputSize = inputLayout.GetActiveSize(); auto input = function.LocalArray(pInput); auto prevInputDimensionOffset = function.LocalScalar(prevInputDimensionOffsetValue); function.For(inputSize[dimension], [dimension, numDimensions, inputOffset, inputStride, inputLayout, input, prevInputDimensionOffset, &f, &compiler, this](emitters::IRFunctionEmitter& function, emitters::LLVMValue i) { auto loopIndex = function.LocalScalar(i); // Calculate the offset within this dimension = (loopIndex + offset[dimension]) auto thisInputDimensionInternalOffset = loopIndex + inputOffset[dimension]; // Calculate the total offset from beginning of memory: // * if in the outermost loop, the offset into this dimension // * otherwise, the offset into this dimension plus the previous offset scaled by the previous dimension's stride auto thisInputDimensionOffset = function.LocalScalar(); if (dimension == 0) { assert(!prevInputDimensionOffset.IsValid()); thisInputDimensionOffset = thisInputDimensionInternalOffset; } else { auto scaledInputDimensionOffset = prevInputDimensionOffset * inputStride[dimension]; thisInputDimensionOffset = scaledInputDimensionOffset + thisInputDimensionInternalOffset; } if (dimension < numDimensions - 1) { // Recursive call to emit nested loop EmitComputeDimensionLoop(compiler, function, dimension + 1, inputLayout, input, thisInputDimensionOffset, f); } else { // We're in the innermost loop --- compute the value emitters::IRLocalScalar inputValue = input[thisInputDimensionOffset]; auto outputValue = f.Compile(function, inputValue); if (outputValue != nullptr) { input[thisInputDimensionOffset] = outputValue; } } }); } template <typename ValueType> void SoftmaxLayerNode<ValueType>::Copy(model::ModelTransformer& transformer) const { const auto& newPortElements = transformer.GetCorrespondingInputs(this->_input); auto newNode = transformer.AddNode<SoftmaxLayerNode<ValueType>>(newPortElements, this->_layer); transformer.MapNodeOutput(this->_output, newNode->output); } // Explicit specialization template class SoftmaxLayerNode<float>; template class SoftmaxLayerNode<double>; } // nodes } // ell
48.256944
305
0.605195
[ "vector", "model" ]
c79bb4fac9bef3585e32aae31020490783d09fa1
16,863
cpp
C++
Test/simple_reconstruct.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
Test/simple_reconstruct.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
Test/simple_reconstruct.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file simple_reconstruct.cpp Simple reconstruction program to illustrate use of various DB components \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 09/16/2005 */ #include <list> #include <iostream> #include <iterator> #include <VSOptions.hpp> #include <VSDatabase.hpp> #include <VSDBFactory.hpp> #include <VSDBParameterTable.hpp> #include <VSSimDB.hpp> #include <VSSimDBTables.hpp> #include <VSOTelescopeArray.hpp> #include <VSReconstruction.hpp> #include <VSTestTimer.hpp> using namespace VERITAS; using namespace Physics; struct ChannelInfo { ChannelInfo(): valid(false), vec() { } bool valid; Vec3D vec; }; typedef std::list<VSReconstruction::Chi2MapElement> Chi2Map; int main(int argc, char** argv) { std::string progname(*argv); VSOptions options(argc,argv,true); // -------------------------------------------------------------------------- // Options // -------------------------------------------------------------------------- VSDBFactory::configure(&options); #if 0 std::ostringstream stream; stream << "/tmp/rng_state_uid" << getuid() << ".dat"; std::string rngstatefile(stream.str()); options.findWithValue("rng_state_file",rngstatefile, "Set random number generator state file"); #endif bool print_usage = false; int exit_code = EXIT_SUCCESS; if(options.find("h","Print this message") != VSOptions::FS_NOT_FOUND) print_usage=true; if(options.find("help", "Print this message") != VSOptions::FS_NOT_FOUND) print_usage=true; bool single_event_mode = false; unsigned event_no = 0; if(options.findWithValue("ev",event_no, "Process only one event, writing details of chi^2 " "grid search. Number of event to process should be " "given as an argument to this option") != VSOptions::FS_NOT_FOUND)single_event_mode = true; unsigned max_events = 0; options.findWithValue("max_events",max_events, "Maximum number of events to process, or zero to " "process all events"); double plate_scale = 1.0; options.findWithValue("platescale",plate_scale, "Set the plate scale correction " "(1.0 gives no correction)"); std::vector<unsigned> scope_suppress_id; options.findWithValue("scope_suppress",scope_suppress_id, "Comma separated list of telescope numbers to " "suppress in analysis"); double fov = 3.5; options.findWithValue("fov",fov, "Set the camera field of view"); unsigned l1_pe = 6; options.findWithValue("l1_pe",l1_pe, "Set the L1 trigger level in PE"); unsigned l2_mult = 3; options.findWithValue("l2_mult",l2_mult, "Set the L2 trigger multiplicity in channels"); bool l2_force = false; if(options.find("l2_force", "Force L2 trigger on all telescopes when L3 " "trigger occurs") != VSOptions::FS_NOT_FOUND) l2_force = true; unsigned l3_mult = 2; options.findWithValue("l3_mult",l3_mult, "Set the L3 trigger multiplicity in telescopes"); unsigned cleaning_pe = unsigned(floor(0.1878*10*3.0)); options.findWithValue("cleaning_pe",cleaning_pe, "Set the cleaning level in PE"); // -------------------------------------------------------------------------- // Get the database and table names from the command line arguments // -------------------------------------------------------------------------- argc--,argv++; if (argc!=2) { print_usage=true; exit_code=EXIT_FAILURE; } if(print_usage) { std::cerr << "Usage: " << progname << " [options] database table_name" << std::endl << "Options:" << std::endl; options.printUsage(std::cerr); return exit_code; } std::string database(*argv); argc--; argv++; std::string tablename(*argv); argc--; argv++; // -------------------------------------------------------------------------- // Create the database // -------------------------------------------------------------------------- VSDatabase* db = VSDBFactory::getInstance()->createVSDB(); if(db->useDatabase(database) < 0) { std::cerr << "Could not connect to database " << database << std::endl; return EXIT_FAILURE; }; VSSimDB db_sim(db); VSDBParameterTable db_param(db); // -------------------------------------------------------------------------- // Get the table parameters from the DB // -------------------------------------------------------------------------- VSSimDBTableParam* param; param = db_sim.getDataTableByName(tablename); if(!param) { std::cerr << "Could not get information for table " << tablename << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Get the definition of the array from the database // -------------------------------------------------------------------------- VSOTelescopeArray array; array.readFromDatabase(db, param->fOpticsID); std::vector<bool> scope_suppress; std::vector<std::vector<ChannelInfo> > channel_info; std::vector<unsigned> max_channel; scope_suppress.resize(array.numTelescopes()); channel_info.resize(array.numTelescopes()); max_channel.resize(array.numTelescopes()); for(std::vector<unsigned>::const_iterator iid=scope_suppress_id.begin(); iid!=scope_suppress_id.end(); iid++) if(*iid<scope_suppress.size())scope_suppress[*iid]=true; for(unsigned iscope=0;iscope<array.numTelescopes();iscope++) { unsigned nvalid=0; unsigned npix=array.telescope(iscope)->numPixels(); channel_info[iscope].resize(npix); for(unsigned ipix=0;ipix<npix; ipix++) { channel_info[iscope][ipix].vec = array.telescope(iscope)->pixel(ipix)->incomingSkyVectorAtZenith(plate_scale); double theta = acos(channel_info[iscope][ipix].vec * Vec3D(0,0,-1)); if(theta <= fov/2/180*M_PI) { max_channel[iscope]=ipix; channel_info[iscope][ipix].valid=true; nvalid++; } } if(npix==0) { max_channel[iscope] = 0xFFFFFFFFU; } std::cerr << progname << ": scope " << iscope << " has " << nvalid << " pixels (max id:" << max_channel[iscope] << ')' << std::endl; } // -------------------------------------------------------------------------- // Set up the reconstruction // -------------------------------------------------------------------------- VSReconstruction::ScopeSpecs scopes; for(unsigned iscope=0;iscope<array.numTelescopes();iscope++) { VSCORSIKATelescopeSpec scope; scope.scope_num = iscope; scope.scope_x = array.telescope(iscope)->pos().x/100; scope.scope_y = array.telescope(iscope)->pos().y/100; scope.scope_z = array.telescope(iscope)->pos().z/100; scope.scope_r = array.telescope(iscope)->aperture()/100; scopes.push_back(scope); } VSReconstruction reconstruction(scopes); // -------------------------------------------------------------------------- // Get a list of all (or single, if requested) complete events // -------------------------------------------------------------------------- std::string tablename_ev = std::string(VSIMDB_TABLE_PREFIX_DATA) +tablename + std::string(VSIMDB_TABLE_POSTFIX_EVENTS); std::string tablename_tel = std::string(VSIMDB_TABLE_PREFIX_DATA) +tablename + std::string(VSIMDB_TABLE_POSTFIX_SCOPES); std::string tablename_pe = std::string(VSIMDB_TABLE_PREFIX_DATA) +tablename + std::string(VSIMDB_TABLE_POSTFIX_PES); std::string ev_condition = "EventComplete=1"; if(single_event_mode) ev_condition += " AND EventID=" + VSDataConverter::toString(event_no); else if(max_events!=0) ev_condition += " AND EventID<" + VSDataConverter::toString(max_events); VSDBStatement* stmt = db->createSelectQuery(tablename_ev, ev_condition, "*", VSDatabase::FLAG_NO_BUFFER); if(!stmt) { std::cerr << progname << ": could no query table: " << tablename_ev << std::endl; return EXIT_FAILURE; } VSSimDBEventData event; std::list<VSSimDBEventData> events; stmt->bindToResult(event.fEventID); stmt->bindToResult(event.fTargetZenithRad); stmt->bindToResult(event.fTargetAzimuthRad); stmt->bindToResult(event.fPrimaryZenithRad); stmt->bindToResult(event.fPrimaryAzimuthRad); stmt->bindToResult(event.fPrimaryCoreEastM); stmt->bindToResult(event.fPrimaryCoreNorthM); stmt->bindToResult(event.fPrimaryCoreUpASLM); stmt->bindToResult(event.fNumHitScopes); stmt->bindToResult(event.fEventComplete); if(stmt->execute() < 0) { std::cerr << progname << ": error executing query on: " << tablename_ev << std::endl; return EXIT_FAILURE; } VSTestTimer<VSTimerCoreIA32> timer_query; VSTestTimer<VSTimerCoreIA32> timer_reconstruction; timer_query.start(); while(stmt->retrieveNextRow())events.push_back(event); timer_query.stop(); delete stmt; std::cerr << progname << ": loaded " << events.size() << " event headers in " << timer_query << " seconds" << std::endl; // -------------------------------------------------------------------------- // Create the database queries and bind variables // -------------------------------------------------------------------------- VSDBStatement* stmt_tel = db->createSelectQuery(tablename_tel, "EventID=?", "ScopeID,ScopeZenithRad,ScopeAzimuthRad"); if(!stmt_tel) { std::cerr << progname << ": could no query table: " << tablename_tel << std::endl; return EXIT_FAILURE; } VSDBStatement* stmt_pix = db->createQuery(std::string("SELECT PixelID,COUNT(PixelID) FROM ") + tablename_pe + std::string(" WHERE EventID=? AND ScopeID=? " "AND PixelID<=? GROUP BY PixelID")); if(!stmt_pix) { std::cerr << progname << ": could no query table: " << tablename_pe << std::endl; return EXIT_FAILURE; } uint32_t event_id; uint16_t scope_id; float scope_zn; float scope_az; uint32_t max_pixel_id; uint32_t pixel_id; uint32_t pe_count; stmt_tel->bindToParam(event_id); stmt_tel->bindToResult(scope_id); stmt_tel->bindToResult(scope_zn); stmt_tel->bindToResult(scope_az); stmt_pix->bindToParam(event_id); stmt_pix->bindToParam(scope_id); stmt_pix->bindToParam(max_pixel_id); stmt_pix->bindToResult(pixel_id); stmt_pix->bindToResult(pe_count); // -------------------------------------------------------------------------- // Query database and reconstruct events // -------------------------------------------------------------------------- std::vector<std::vector<std::pair<uint32_t, uint32_t> > > data; data.resize(array.numTelescopes()); for(unsigned iscope=0;iscope<array.numTelescopes();iscope++) data[iscope].reserve(max_channel[scope_id]+1); std::vector<double> scopes_zn; std::vector<double> scopes_az; scopes_az.resize(array.numTelescopes()); scopes_zn.resize(array.numTelescopes()); std::vector<VSReconstruction::GridSpecs> grid; grid.push_back(VSReconstruction::GridSpecs(fov/2.0,0.100)); grid.push_back(VSReconstruction::GridSpecs(fov/20.0,0.010)); grid.push_back(VSReconstruction::GridSpecs(fov/200.0,0.001)); timer_query.reset(); unsigned ntrig_ev = 0; for(std::list<VSSimDBEventData>::const_iterator ievent = events.begin(); ievent!=events.end(); ievent++) { unsigned ntrig_l3 = 0; std::vector<bool> scopes_l2; scopes_l2.resize(array.numTelescopes()); event_id = ievent->fEventID; for(unsigned iscope=0;iscope<array.numTelescopes();iscope++) data[iscope].clear(); timer_query.start(); if(stmt_tel->execute()<0) { std::cerr << progname << ": error executing query on: " << tablename_tel << std::endl; return EXIT_FAILURE; } while(stmt_tel->retrieveNextRow()) { if(scope_suppress[scope_id])continue; uint32_t ntrig_l2 = 0; max_pixel_id = max_channel[scope_id]; scopes_zn[scope_id] = scope_zn; scopes_az[scope_id] = scope_az; if(stmt_pix->execute()<0) { std::cerr << progname << ": error executing query on: " << tablename_pe << std::endl; return EXIT_FAILURE; } while(stmt_pix->retrieveNextRow()) { if((pixel_id<channel_info[scope_id].size())&& (!channel_info[scope_id][pixel_id].valid))continue; if(pe_count>=l1_pe)ntrig_l2++; if(pe_count>=cleaning_pe) data[scope_id]. push_back(std::make_pair<uint32_t,uint32_t>(pixel_id, pe_count)); } if(ntrig_l2>=l2_mult) { ntrig_l3++; scopes_l2[scope_id]=true; } } timer_query.stop(); #ifndef NO_OUTPUT if(!single_event_mode) std::cout << ievent->fEventID << ' ' << ievent->fTargetZenithRad << ' ' << ievent->fTargetAzimuthRad << ' ' << ievent->fPrimaryZenithRad << ' ' << ievent->fPrimaryAzimuthRad << ' ' << ievent->fPrimaryCoreEastM << ' ' << ievent->fPrimaryCoreNorthM << ' ' << ievent->fPrimaryCoreUpASLM << ' ' << ntrig_l3; #endif if(ntrig_l3>=l3_mult) { #ifndef NO_OUTPUT if(!single_event_mode) std::cout << ' ' << 1; #endif // ****************************************************************** // R E C O N S T R U C T I O N // ****************************************************************** timer_reconstruction.start(); Vec3D axis(0,0,-1); axis.Rotate(Vec3D(-ievent->fTargetZenithRad,0,0)); axis.Rotate(Vec3D(0,0,-ievent->fTargetAzimuthRad)); VSReconstruction::Ray optical_axis(axis.x, axis.y); unsigned nray = 0; VSReconstruction::AllScopeRays array_rays; array_rays.resize(array.numTelescopes()); for(unsigned iscope=0;iscope<array.numTelescopes();iscope++) { unsigned npix = data[iscope].size(); if((npix==0)||((l2_force==false)&&(scopes_l2[iscope]==false))) continue; array_rays[iscope].reserve(npix); Vec3D scope_rotation(-scopes_zn[iscope],0,0); scope_rotation &= Vec3D(0,0,-scopes_az[iscope]); for(unsigned ipix=0;ipix<npix;ipix++) { unsigned ipixel = data[iscope][ipix].first; unsigned npe = data[iscope][ipix].second; Vec3D r; if(ipixel<channel_info[iscope].size()) r=channel_info[iscope][ipixel].vec; else { const VSOTelescope* scope = array.telescope(iscope); int hexid = ipixel; Vec3D pos; nh_to_xy(&hexid, &pos.x, &pos.z); if(scope->pixelParity())pos.x=-pos.x; pos.x *= scope->pixelSpacing(); pos.z *= scope->pixelSpacing(); pos.y = 0; pos.Rotate(scope->focalPlaneRotion()); VSOPixel* pixel = new VSOPixel(scope, hexid, hexid, false, pos); r = pixel->incomingSkyVectorAtZenith(plate_scale); } r.Rotate(scope_rotation); array_rays[iscope] .push_back(VSReconstruction::Ray(r.x, r.y, npe)); nray++; } } VSReconstruction::MinimizationResults res; if(single_event_mode) { Chi2Map chi2map; reconstruction.gridSearch(array_rays, optical_axis, grid, res, std::back_insert_iterator<Chi2Map>(chi2map)); for(Chi2Map::iterator i = chi2map.begin(); i!=chi2map.end(); i++) { Vec3D p(i->ec_x, i->ec_y, i->ec_z); p.Rotate(Vec3D(0,0,ievent->fTargetAzimuthRad)); p.Rotate(Vec3D(ievent->fTargetZenithRad,0,0)); double x_fp = p.y/p.z/M_PI*180; double y_fp = p.x/p.z/M_PI*180; std::cout << x_fp << ' ' << y_fp << ' ' << i->chi2 << ' ' << i->ec_x << ' ' << i->ec_y << ' ' << i->ec_z << ' ' << i->rc_x << ' ' << i->rc_y << ' ' << i->rc_z << std::endl; } } else { reconstruction.gridSearch(array_rays, optical_axis, grid, res); } timer_reconstruction.stop(); #ifndef NO_OUTPUT if(!single_event_mode) std::cout << ' ' << nray << ' ' << res.chi2 << ' ' << res.weight << ' ' << atan2(sqrt(res.ec_x*res.ec_x+res.ec_y*res.ec_y),-res.ec_z)*180/M_PI << ' ' << atan2(res.ec_x,res.ec_y)*180/M_PI << ' ' << res.rc_x << ' ' << res.rc_y << ' ' << res.rc_z << ' ' << res.chi2_curv_l << ' ' << res.chi2_curv_w; #endif ntrig_ev++; } else { #ifndef NO_OUTPUT if(!single_event_mode) std::cout << ' ' << 0; #endif } #ifndef NO_OUTPUT if(!single_event_mode) std::cout << std::endl; #endif } std::cerr << progname << ": " << events.size() << " events read in " << timer_query << " seconds" << std::endl; std::cerr << progname << ": " << ntrig_ev << " triggering events reconstructed in " << timer_reconstruction << " seconds" << std::endl; }
28.678571
84
0.585246
[ "vector" ]
c79c0e75c33529fe2016bc498fc252a6d826886e
3,479
cpp
C++
tests/test_index_merger.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
6
2020-10-13T11:30:53.000Z
2021-12-03T15:50:15.000Z
tests/test_index_merger.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
null
null
null
tests/test_index_merger.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
3
2020-10-13T11:30:55.000Z
2021-12-02T14:29:42.000Z
#include "v2/index_merger.h" #include <numeric> #include <omp.h> #include <cstring> #include <ctime> #include <timer.h> #include <iomanip> #include "aux_utils.h" #include "utils.h" #ifndef _WINDOWS #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #endif template<typename T> void run(const char* disk_in, const std::vector<std::string>& mem_in, const char* disk_out, const char* deleted_tags, const uint32_t ndims, diskann::Distance<T>* dist, const uint32_t beam_width, const uint32_t range, const uint32_t l_index, const float alpha, const uint32_t maxc) { std::cout << "Instantiating IndexMerger\n"; diskann::IndexMerger<T> merger(disk_in, mem_in, disk_out, deleted_tags, ndims, dist, beam_width, range, l_index, alpha, maxc); std::cout << "Starting merge\n"; merger.merge(); std::cout << "Finished merging\n"; } int main(int argc, char** argv) { if (argc < 13) { std::cout << "Correct usage: " << argv[0] << " <type[int8/uint8/float]> <disk_in> <disk_out> <deleted_tags_file>" << " <ndims> <beam_width> <range> <L_index> <alpha> <maxc> " "<tmp_working_folder> <mem_index_1> <mem_index_2> .." << std::endl; exit(-1); } std::cout.setf(std::ios::unitbuf); int arg_no = 1; std::string index_type = argv[arg_no++]; // assert(index_type == std::string("float")); const char* disk_in = argv[arg_no++]; std::cout << "Input SSD-DiskANN: " << disk_in << "\n"; const char* disk_out = argv[arg_no++]; std::cout << "Output SSD-DiskANN: " << disk_out << "\n"; const char* delete_list_file = argv[arg_no++]; std::cout << "Deleted tags file : " << delete_list_file << "\n"; uint32_t data_dim = (uint32_t) atoi(argv[arg_no++]); std::cout << "Data dim : " << data_dim << "\n"; uint32_t beam_width = (uint32_t) atoi(argv[arg_no++]); std::cout << "Beam Width : " << beam_width << "\n"; uint32_t range = (uint32_t) atoi(argv[arg_no++]); std::cout << "Range (max out-degree) : " << range << "\n"; uint32_t L_index = (uint32_t) atoi(argv[arg_no++]); std::cout << "L-index : " << L_index << "\n"; float alpha = atof(argv[arg_no++]); std::cout << "alpha : " << alpha << "\n"; uint32_t maxc = (uint32_t) atoi(argv[arg_no++]); std::cout << "max-C : " << maxc << "\n"; TMP_FOLDER = argv[arg_no++]; std::cout << "Working folder : " << TMP_FOLDER << "\n"; std::vector<std::string> mem_in; while (arg_no < argc) { const char* cur_mem_in = argv[arg_no++]; std::cout << "Mem-DiskANN index #" << mem_in.size() + 1 << " : " << cur_mem_in << "\n"; mem_in.emplace_back(cur_mem_in); } if (index_type == std::string("float")) { diskann::DistanceL2 dist_cmp; run<float>(disk_in, mem_in, disk_out, delete_list_file, data_dim, &dist_cmp, beam_width, range, L_index, alpha, maxc); } else if (index_type == std::string("uint8")) { diskann::DistanceL2UInt8 dist_cmp; run<uint8_t>(disk_in, mem_in, disk_out, delete_list_file, data_dim, &dist_cmp, beam_width, range, L_index, alpha, maxc); } else if (index_type == std::string("int8")) { diskann::DistanceL2Int8 dist_cmp; run<int8_t>(disk_in, mem_in, disk_out, delete_list_file, data_dim, &dist_cmp, beam_width, range, L_index, alpha, maxc); } else { std::cout << "Unsupported type : " << index_type << "\n"; } std::cout << "Exiting\n"; }
36.621053
80
0.61052
[ "vector" ]
c7a5c03ac58a80a9a9807edfbc0fd60a714529df
37,865
cc
C++
src/core/alien/index_manager/IndexManager.cc
cedricga91/alien
2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0
[ "Apache-2.0" ]
8
2021-09-30T08:29:44.000Z
2022-02-23T18:39:32.000Z
src/core/alien/index_manager/IndexManager.cc
cedricga91/alien
2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0
[ "Apache-2.0" ]
42
2021-07-01T17:32:05.000Z
2022-03-03T14:53:56.000Z
src/core/alien/index_manager/IndexManager.cc
cedricga91/alien
2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0
[ "Apache-2.0" ]
9
2021-09-28T12:59:32.000Z
2022-03-18T06:35:01.000Z
/* * Copyright 2020 IFPEN-CEA * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include <algorithm> #include <list> #include <map> #include <utility> #include <vector> #include <arccore/message_passing/BasicSerializeMessage.h> #include <arccore/message_passing/ISerializeMessageList.h> #include <arccore/message_passing/Messages.h> #include <arccore/message_passing_mpi/MpiMessagePassingMng.h> #include <arccore/message_passing_mpi/MpiSerializeMessageList.h> #include <alien/index_manager/IAbstractFamily.h> #include <alien/index_manager/IndexManager.h> #include <alien/utils/Precomp.h> #include <alien/utils/Trace.h> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Alien { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ struct IndexManager::EntryLocalId { explicit EntryLocalId(Alien::Integer size) : m_is_defined(size, false) {} void reserveLid(const Integer count) { m_defined_lids.reserve(m_defined_lids.size() + count); } [[nodiscard]] bool isDefinedLid(const Integer localId) const { return m_is_defined[localId]; } void defineLid(const Integer localId, const Integer pos) { m_is_defined[localId] = true; Alien::add(m_defined_lids, std::make_pair(localId, pos)); } void undefineLid(const Integer localId) { m_is_defined[localId] = false; for (Integer i = 0; i < m_defined_lids.size(); ++i) { if (m_defined_lids[i].first == localId) { m_defined_lids[i] = m_defined_lids.back(); m_defined_lids.resize(m_defined_lids.size() - 1); return; } } throw FatalErrorException( A_FUNCINFO, "Inconsistent state : cannot find id to remove"); } [[nodiscard]] const UniqueArray<std::pair<Integer, Integer>>& definedLids() const { return m_defined_lids; } void freeDefinedLids() { Alien::freeData(m_defined_lids); std::vector<bool>().swap(m_is_defined); } std::vector<bool> m_is_defined; UniqueArray<std::pair<Integer, Integer>> m_defined_lids; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ struct IndexManager::EntrySendRequest { EntrySendRequest() = default; ~EntrySendRequest() = default; EntrySendRequest(const EntrySendRequest& esr) : count(esr.count) {} Arccore::Ref<Arccore::MessagePassing::ISerializeMessage> comm; Integer count = 0; void operator=(const EntrySendRequest&) = delete; }; /*---------------------------------------------------------------------------*/ struct IndexManager::EntryRecvRequest { EntryRecvRequest() = default; ~EntryRecvRequest() = default; explicit EntryRecvRequest(const EntrySendRequest& err) {} Arccore::Ref<Arccore::MessagePassing::ISerializeMessage> comm; UniqueArray<Int64> ids; void operator=(const EntryRecvRequest&) = delete; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IndexManager::IndexManager( Alien::IMessagePassingMng* parallelMng, Alien::ITraceMng* traceMng) : m_parallel_mng(parallelMng) , m_trace_mng(traceMng) , m_local_owner(0) , m_state(Undef) , m_verbose(false) , m_local_entry_count(0) , m_global_entry_count(0) , m_global_entry_offset(0) , m_local_removed_entry_count(0) , m_global_removed_entry_count(0) , m_max_null_index_opt(false) { this->init(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ IndexManager::~IndexManager() { this->init(); } /*---------------------------------------------------------------------------*/ void IndexManager::init() { m_local_owner = m_parallel_mng->commRank(); m_state = Initialized; m_local_entry_count = 0; m_global_entry_count = 0; m_global_entry_offset = 0; m_local_removed_entry_count = 0; m_global_removed_entry_count = 0; // Destruction des structure de type entry for (auto& m_entrie : m_entries) { delete m_entrie; } m_entries.clear(); m_abstract_families.clear(); } /*---------------------------------------------------------------------------*/ void IndexManager::setVerboseMode(bool verbose) { m_verbose = verbose; } /*---------------------------------------------------------------------------*/ ScalarIndexSet IndexManager::buildEntry( const String& name, const IAbstractFamily* family, const Integer kind) { if (m_state != Initialized) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); for (auto* e : m_entries) { if (name == e->getName()) throw FatalErrorException(A_FUNCINFO, "Already defined entry"); } const Integer uid = m_entries.size(); m_entry_families[uid] = family; auto* entry = new ScalarIndexSet(name, uid, this, kind); m_entries.push_back(entry); return *entry; } /*---------------------------------------------------------------------------*/ void IndexManager::defineIndex(const ScalarIndexSet& entry, ConstArrayView<Integer> localIds) { if (m_state != Initialized) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); const Integer uid = entry.getUid(); const auto* family = m_entry_families[uid]; auto entry_local_ids = std::make_shared<EntryLocalId>(family->maxLocalId()); m_entry_local_ids[uid] = entry_local_ids; auto owners = family->owners(localIds); entry_local_ids->reserveLid(localIds.size()); for (Integer i = 0, is = localIds.size(); i < is; ++i) { const Integer localId = localIds[i]; if (not entry_local_ids->isDefinedLid(localId)) { // nouvelle entrée if (owners[i] == m_local_owner) { entry_local_ids->defineLid( localId, +(m_local_removed_entry_count + m_local_entry_count++)); } else { entry_local_ids->defineLid( localId, -(m_global_removed_entry_count + (++m_global_entry_count))); } } } } /*---------------------------------------------------------------------------*/ void IndexManager::removeIndex(const ScalarIndexSet& entry, ConstArrayView<Integer> localIds) { if (m_state != Initialized) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); const Integer uid = entry.getUid(); const auto* family = m_entry_families[uid]; auto entry_local_ids = m_entry_local_ids[uid]; const auto owners = family->owners(localIds); for (Integer localId : localIds) { if (entry_local_ids->isDefinedLid(localId)) { entry_local_ids->undefineLid(localId); if (owners[localId] == m_local_owner) { --m_local_entry_count; ++m_local_removed_entry_count; } else { --m_global_entry_count; ++m_global_removed_entry_count; } } } } /*---------------------------------------------------------------------------*/ void IndexManager::prepare() { EntryIndexMap entry_index; begin_prepare(entry_index); if (m_parallel_mng->commSize() > 1) { begin_parallel_prepare(entry_index); end_parallel_prepare(entry_index); } else { sequential_prepare(entry_index); } end_prepare(entry_index); } /*---------------------------------------------------------------------------*/ void IndexManager::begin_prepare(EntryIndexMap& entry_index) { if (m_state != Initialized) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); Integer total_size = 0; for (auto* entry : m_entries) { auto entry_local_ids = m_entry_local_ids[entry->getUid()]; total_size += entry_local_ids->definedLids().size(); } entry_index.reserve(total_size); for (auto* entry : m_entries) { const Integer entry_uid = entry->getUid(); const auto* family = m_entry_families[entry_uid]; const Integer entry_kind = entry->getKind(); auto entry_local_ids = m_entry_local_ids[entry_uid]; const auto& lids = entry_local_ids->definedLids(); for (Integer i = 0, is = lids.size(); i < is; ++i) { const Integer item_localid = lids[i].first; auto item = family->item(item_localid); entry_index.push_back(InternalEntryIndex{ entry_uid, entry_kind, item.uniqueId(), item_localid, lids[i].second, item.owner() }); } entry_local_ids->freeDefinedLids(); } m_entry_local_ids.clear(); // Tri par défaut std::sort(entry_index.begin(), entry_index.end(), [](const InternalEntryIndex& a, const InternalEntryIndex& b) { if (a.m_entry_kind != b.m_entry_kind) return a.m_entry_kind < b.m_entry_kind; else if (a.m_item_uid != b.m_item_uid) return a.m_item_uid < b.m_item_uid; else return a.m_entry_uid < b.m_entry_uid; }); ALIEN_ASSERT( ((Integer)entry_index.size() == m_local_entry_count + m_global_entry_count), ("Inconsistent global size")); } /*---------------------------------------------------------------------------*/ void IndexManager::end_prepare(EntryIndexMap& entryIndex) { // Calcul de la taille des indices par entrée std::map<Integer, Integer> count_table; for (auto& i : entryIndex) { count_table[i.m_entry_uid]++; } auto isOwn = [&](const InternalEntryIndex& i) -> bool { return i.m_item_owner == m_local_owner; }; // Dimensionnement des buffers de chaque entrée for (auto* entry : m_entries) { const Integer uid = entry->getUid(); const Integer size = count_table[uid]; auto& all_items = m_entry_all_items[uid]; auto& all_indices = m_entry_all_indices[uid]; all_items.resize(size); all_indices.resize(size); Integer own_i = 0; Integer ghost_i = size; for (auto& i : entryIndex) { if (i.m_entry_uid == uid) { const Integer local_id = i.m_item_localid; const Integer index = i.m_item_index; const bool is_own = isOwn(i); if (is_own) { all_items[own_i] = local_id; all_indices[own_i] = index; ++own_i; } else { --ghost_i; all_items[ghost_i] = local_id; all_indices[ghost_i] = index; } } } const Integer own_size = own_i; ALIEN_ASSERT((own_i == ghost_i), ("Not merged insertion")); m_entry_own_items[uid] = ConstArrayView<Integer>(own_size, &all_items[0]); m_entry_own_indices[uid] = ConstArrayView<Integer>(own_size, &all_indices[0]); } m_state = Prepared; if (m_verbose) { alien_info([&] { cout() << "Entry ordering :"; for (auto* entry : m_entries) { cout() << "\tEntry '" << entry->getName() << "' placed at rank " << entry->getUid() << " with " << getOwnLocalIds(*entry).size() << " local / " << getAllLocalIds(*entry).size() << " global indexes "; } cout() << "Total local Entry indexes = " << m_local_entry_count; }); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ struct IndexManager::ParallelRequests { // Structure pour accumuler et structurer la collecte de l'information typedef std::map<Integer, EntrySendRequest> SendRequestByEntry; typedef std::map<Integer, SendRequestByEntry> SendRequests; SendRequests sendRequests; // Table des requetes exterieures (reçoit les uid et renverra les EntryIndex finaux) typedef std::list<EntryRecvRequest> RecvRequests; RecvRequests recvRequests; Alien::Ref<ISerializeMessageList> messageList; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void IndexManager::begin_parallel_prepare(EntryIndexMap& entry_index) { ALIEN_ASSERT((m_parallel_mng->commSize() > 1), ("Parallel mode expected")); /* Algorithme: * 1 - listing des couples Entry-Item non locaux * 2 - Envoi vers les propriétaires des items non locaux * 3 - Prise en compte éventuelle de nouvelles entrées * 4 - Nommage locales * 5 - Retour vers demandeurs des EntryIndex non locaux * 6 - Finalisation de la numérotation (table reindex) */ parallel = std::make_shared<ParallelRequests>(); // 1 - Comptage des Items non locaux for (auto& entryIndex : entry_index) { const Integer item_owner = entryIndex.m_item_owner; if (item_owner != m_local_owner) { parallel->sendRequests[item_owner][entryIndex.m_entry_uid].count++; } } // Liste de synthèse des messages (emissions / réceptions) parallel->messageList = Arccore::MessagePassing::mpCreateSerializeMessageListRef(m_parallel_mng); // Contruction de la table de communications + préparation des messages d'envoi UniqueArray<Integer> sendToDomains(2 * m_parallel_mng->commSize(), 0); for (auto i = parallel->sendRequests.begin(); i != parallel->sendRequests.end(); ++i) { const Integer destDomainId = i->first; auto& requests = i->second; for (auto& j : requests) { EntrySendRequest& request = j.second; const Integer entryImpl = j.first; const String nameString = m_entries[entryImpl]->getName(); // Données pour receveur sendToDomains[2 * destDomainId + 0] += 1; sendToDomains[2 * destDomainId + 1] += request.count; // Construction du message du EntrySendRequest request.comm = Arccore::MessagePassing::Mpi::BasicSerializeMessage::create( MessageRank(m_parallel_mng->commRank()), MessageRank(destDomainId), Arccore::MessagePassing::ePointToPointMessageType::MsgSend); parallel->messageList->addMessage(request.comm.get()); auto sbuf = request.comm->serializer(); sbuf->setMode(Alien::ISerializer::ModeReserve); // phase préparatoire sbuf->reserve(nameString); // Chaine de caractère du nom de l'entrée sbuf->reserveInteger(1); // Nb d'item sbuf->reserve(Alien::ISerializer::DT_Int64, request.count); // Les uid sbuf->allocateBuffer(); // allocation mémoire sbuf->setMode(Alien::ISerializer::ModePut); sbuf->put(nameString); sbuf->put(request.count); } } // 2 - Accumulation des valeurs à demander for (auto& entryIndex : entry_index) { const Integer entryImpl = entryIndex.m_entry_uid; const Integer item_owner = entryIndex.m_item_owner; const Int64 item_uid = entryIndex.m_item_uid; if (item_owner != m_local_owner) parallel->sendRequests[item_owner][entryImpl].comm->serializer()->put(item_uid); } // Réception des annonces de demandes (les nombres d'entrée + taille) UniqueArray<Integer> recvFromDomains(2 * m_parallel_mng->commSize()); Arccore::MessagePassing::mpAllToAll(m_parallel_mng, sendToDomains, recvFromDomains, 2); for (Integer isd = 0, nsd = m_parallel_mng->commSize(); isd < nsd; ++isd) { Integer recvCount = recvFromDomains[2 * isd + 0]; while (recvCount-- > 0) { auto recvMsg = Arccore::MessagePassing::Mpi::BasicSerializeMessage::create( MessageRank(m_parallel_mng->commRank()), MessageRank(isd), Arccore::MessagePassing::ePointToPointMessageType::MsgReceive); parallel->recvRequests.push_back(EntryRecvRequest()); EntryRecvRequest& recvRequest = parallel->recvRequests.back(); recvRequest.comm = recvMsg; parallel->messageList->addMessage(recvMsg.get()); } } // Traitement des communications parallel->messageList->processPendingMessages(); parallel->messageList->waitMessages(Arccore::MessagePassing::WaitAll); parallel->messageList.reset(); // delete parallel->messageList; // parallel->messageList = NULL; // Destruction propre // Pour les réponses vers les demandeurs parallel->messageList = Arccore::MessagePassing::mpCreateSerializeMessageListRef(m_parallel_mng); // 3 - Réception et mise en base local des demandes for (auto i = parallel->recvRequests.begin(); i != parallel->recvRequests.end(); ++i) { auto& recvRequest = *i; String nameString; Integer uidCount; { // Traitement des arrivées auto sbuf = recvRequest.comm->serializer(); sbuf->setMode(Alien::ISerializer::ModeGet); sbuf->get(nameString); uidCount = sbuf->getInteger(); recvRequest.ids.resize(uidCount); sbuf->getSpan(recvRequest.ids); ALIEN_ASSERT((uidCount == recvRequest.ids.size()), ("Inconsistency detected")); #ifndef NO_USER_WARNING #ifdef _MSC_VER #pragma message("CHECK: optimisable ?") #else #warning "CHECK: optimisable ?" #endif #endif /* Si on est sûr que les entrées et l'item demandées doivent * toujours exister (même les pires cas), on peut faire * l'indexation locale avant et envoyer immédiatement (via un * buffer; dans la présente boucle) la réponse. */ // Reconstruction de l'entrée à partir du nom auto lookup = std::find_if(m_entries.begin(), m_entries.end(), [&](ScalarIndexSet* s) { return s->getName() == nameString; }); // Si pas d'entrée de ce côté => système défectueux ? if (lookup == m_entries.end()) throw FatalErrorException("Non local Entry Requested : degenerated system ?"); auto* currentEntry = *lookup; const Integer entry_uid = currentEntry->getUid(); // Passage de l'uid à l'item associé (travaille sur place : pas de recopie) ArrayView<Int64> ids = recvRequest.ids; const auto* family = m_entry_families[entry_uid]; const Integer entry_kind = currentEntry->getKind(); UniqueArray<Int32> lids(ids.size()); family->uniqueIdToLocalId(lids, ids); // Vérification d'intégrité : toutes les entrées demandées sont définies localement auto owners = family->owners(lids); for (Integer j = 0; j < uidCount; ++j) { const Integer current_item_lid = lids[j]; const Int64 current_item_uid = ids[j]; const Integer current_item_owner = owners[j]; if (current_item_owner != m_local_owner) { throw FatalErrorException("Non local EntryIndex requested"); } InternalEntryIndex lookup_entry{ entry_uid, entry_kind, current_item_uid, current_item_lid, 0, current_item_owner }; // Recherche de la liste triée par défaut auto lookup2 = std::lower_bound(entry_index.begin(), entry_index.end(), lookup_entry, [](const InternalEntryIndex& a, const InternalEntryIndex& b) { if (a.m_entry_kind != b.m_entry_kind) return a.m_entry_kind < b.m_entry_kind; else if (a.m_item_uid != b.m_item_uid) return a.m_item_uid < b.m_item_uid; else return a.m_entry_uid < b.m_entry_uid; }); if ((lookup2 == entry_index.end()) || !(*lookup2 == lookup_entry)) throw FatalErrorException("Not locally defined entry requested"); // Mise en place de la pre-valeur retour [avant renumérotation locale] (EntryIndex // écrit sur un Int64) ids[j] = lookup2->m_item_index; } } { // Préparation des retours auto dest = recvRequest.comm->destination(); // Attention à l'ordre bizarre auto orig = recvRequest.comm->source(); // de SerializeMessage recvRequest.comm.reset(); recvRequest.comm = Arccore::MessagePassing::Mpi::BasicSerializeMessage::create( orig, dest, Arccore::MessagePassing::ePointToPointMessageType::MsgSend); parallel->messageList->addMessage(recvRequest.comm.get()); auto sbuf = recvRequest.comm->serializer(); sbuf->setMode(Alien::ISerializer::ModeReserve); // phase préparatoire sbuf->reserve(nameString); // Chaine de caractère du nom de l'entrée sbuf->reserveInteger(1); // Nb d'item sbuf->reserveInteger(uidCount); // Les index sbuf->allocateBuffer(); // allocation mémoire sbuf->setMode(Alien::ISerializer::ModePut); sbuf->put(nameString); sbuf->put(uidCount); } } // 4 - Indexation locale /* La politique naive ici appliquée est de numéroter tous les * (Entry,Item) locaux d'abord. */ // Calcul de des offsets globaux sur Entry (via les tailles locales) UniqueArray<Integer> allLocalSizes(m_parallel_mng->commSize()); UniqueArray<Integer> myLocalSize(1); myLocalSize[0] = m_local_entry_count; Arccore::MessagePassing::mpAllGather(m_parallel_mng, myLocalSize, allLocalSizes); // Mise à jour du contenu des entrées m_global_entry_offset = 0; for (Integer i = 0; i < m_parallel_mng->commRank(); ++i) { m_global_entry_offset += allLocalSizes[i]; } // Calcul de la taille global d'indexation (donc du système associé) m_global_entry_count = 0; for (Integer i = 0; i < m_parallel_mng->commSize(); ++i) { m_global_entry_count += allLocalSizes[i]; } } /*---------------------------------------------------------------------------*/ void IndexManager::end_parallel_prepare(EntryIndexMap& entry_index) { ALIEN_ASSERT((m_parallel_mng->commSize() > 1), ("Parallel mode expected")); { // Table de ré-indexation (EntryIndex->Integer) Alien::UniqueArray<Integer> entry_reindex(m_local_entry_count); Alien::fill(entry_reindex, -1); // valeur de type Erreur par défaut // C'est ici et uniquement ici qu'est matérialisé l'ordre des entrées Integer currentEntryIndex = m_global_entry_offset; // commence par l'offset local for (auto& i : entry_index) { if (i.m_item_owner == m_local_owner) { // Numérotation locale ! const Integer newIndex = currentEntryIndex++; ALIEN_ASSERT(newIndex >= 0, "Invalid local id"); entry_reindex[i.m_item_index] = newIndex; // Table de translation i.m_item_index = newIndex; } } // 5 - Envoie des retours (EntryIndex globaux) for (auto& recvRequest : parallel->recvRequests) { auto sbuf = recvRequest.comm->serializer(); for (auto id : recvRequest.ids) { sbuf->putInteger(entry_reindex[id]); // Via la table de réindexation } } } // Table des buffers de retour typedef std::list<Alien::Ref<Alien::ISerializeMessage>> ReturnedRequests; ReturnedRequests returnedRequests; // Acces rapide aux buffers connaissant le proc emetteur et le nom d'une entrée /* Car on ne peut tager les buffers donc l'entrée reçue dans un buffer est non * déterminée * surtout si 2 domaines se communiquent plus d'une entrée */ typedef std::map<Integer, EntrySendRequest*> SubFastReturnMap; typedef std::map<String, SubFastReturnMap> FastReturnMap; FastReturnMap fastReturnMap; // Préparation des réceptions [sens inverse] for (auto i = parallel->sendRequests.begin(); i != parallel->sendRequests.end(); ++i) { const Integer destDomainId = i->first; auto& requests = i->second; for (auto& j : requests) { auto& request = j.second; const Integer entryImpl = j.first; const String nameString = m_entries[entryImpl]->getName(); // On ne peut pas associer directement le message à cette entrée // : dans le cas d'échange multiple il n'y pas de garantie d'arrivée // à la bonne place // delete request.comm; // request.comm = NULL; request.comm.reset(); auto msg = Arccore::MessagePassing::Mpi::BasicSerializeMessage::create( MessageRank(m_parallel_mng->commRank()), MessageRank(destDomainId), Arccore::MessagePassing::ePointToPointMessageType::MsgReceive); returnedRequests.push_back(msg); parallel->messageList->addMessage(msg.get()); fastReturnMap[nameString][destDomainId] = &request; } } // Traitement des communications parallel->messageList->processPendingMessages(); parallel->messageList->waitMessages(Arccore::MessagePassing::WaitAll); parallel->messageList.reset(); // 6 - Traitement des réponses // Association aux EntrySendRequest du buffer correspondant for (auto& returnedRequest : returnedRequests) { auto& message = returnedRequest; auto origDomainId = message->destination().value(); auto sbuf = message->serializer(); sbuf->setMode(Alien::ISerializer::ModeGet); String nameString; sbuf->get(nameString); ALIEN_ASSERT( (fastReturnMap[nameString][origDomainId] != nullptr), ("Inconsistency detected")); auto& request = *fastReturnMap[nameString][origDomainId]; request.comm = returnedRequest; // Reconnection pour accès rapide depuis l'EntrySendRequest #ifdef ALIEN_DEBUG_ASSERT const Integer idCount = sbuf.getInteger(); ALIEN_ASSERT((request.count == idCount), ("Inconsistency detected")); #else const Integer idCount = sbuf->getInteger(); ALIEN_ASSERT((request.count == idCount), ("Inconsistency detected")); #endif } // Distribution des reponses // Par parcours dans ordre initial (celui de la demande) for (auto& entry : entry_index) { const Integer item_owner = entry.m_item_owner; if (item_owner != m_local_owner) { const Integer entryImpl = entry.m_entry_uid; auto& request = parallel->sendRequests[item_owner][entryImpl]; ALIEN_ASSERT((request.count > 0), ("Unexpected empty request")); --request.count; auto sbuf = request.comm->serializer(); const Integer newIndex = sbuf->getInteger(); entry.m_item_index = newIndex; } } } /*---------------------------------------------------------------------------*/ void IndexManager::sequential_prepare(EntryIndexMap& entry_index) { ALIEN_ASSERT((m_parallel_mng->commSize() <= 1), ("Sequential mode expected")); ALIEN_ASSERT((m_global_entry_count == 0), ("Unexpected global entries (%d)", m_global_entry_count)); // Très similaire à la section parallèle : // 4 - Indexation locale /* La politique naive ici appliquée est de numéroter tous les * (Entry,Item) locaux d'abord. */ // Mise à jour du contenu des entrées // C'est ici et uniquement ici qu'est matérialisé l'ordre des entrées Integer currentEntryIndex = 0; // commence par l'offset local for (auto i = entry_index.begin(); i != entry_index.end(); ++i) { ALIEN_ASSERT((i->m_item_owner == m_local_owner), ("Item cannot be non-local for sequential mode")); // Numérotation locale only ! const Integer newIndex = currentEntryIndex++; i->m_item_index = newIndex; } m_global_entry_count = m_local_entry_count; } /*---------------------------------------------------------------------------*/ UniqueArray<Integer> IndexManager::getIndexes(const ScalarIndexSet& entry) const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); const IAbstractFamily& family = entry.getFamily(); UniqueArray<Integer> allIds(family.maxLocalId(), nullIndex()); const ConstArrayView<Integer> allIndices = getAllIndexes(entry); const ConstArrayView<Integer> allLocalIds = getAllLocalIds(entry); const Integer size = allIndices.size(); for (Integer i = 0; i < size; ++i) allIds[allLocalIds[i]] = allIndices[i]; return allIds; } /*---------------------------------------------------------------------------*/ UniqueArray2<Integer> IndexManager::getIndexes(const VectorIndexSet& entries) const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); Integer max_family_size = 0; for (Integer i = 0; i < entries.size(); ++i) { // controles uniquement en première passe ALIEN_ASSERT( (entries[i].manager() == this), ("Incompatible entry from another manager")); const auto& entry = entries[i]; const IAbstractFamily& family = entry.getFamily(); max_family_size = std::max(max_family_size, family.maxLocalId()); } UniqueArray2<Integer> allIds; Alien::allocateData(allIds, max_family_size, entries.size()); Alien::fill(allIds, nullIndex()); for (Integer i = 0; i < entries.size(); ++i) { const auto& entry = entries[i]; const ConstArrayView<Integer> allIndices = getAllIndexes(entry); const ConstArrayView<Integer> allLocalIds = getAllLocalIds(entry); const Integer size = allIndices.size(); for (Integer j = 0; j < size; ++j) allIds[allLocalIds[j]][i] = allIndices[i]; } return allIds; } /*---------------------------------------------------------------------------*/ void IndexManager::stats(Integer& globalSize, Integer& minLocalIndex, Integer& localSize) const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); globalSize = m_global_entry_count; minLocalIndex = m_global_entry_offset; localSize = m_local_entry_count; } /*---------------------------------------------------------------------------*/ Integer IndexManager::globalSize() const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); return m_global_entry_count; } /*---------------------------------------------------------------------------*/ Integer IndexManager::minLocalIndex() const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); return m_global_entry_offset; } /*---------------------------------------------------------------------------*/ Integer IndexManager::localSize() const { if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); return m_local_entry_count; } /*---------------------------------------------------------------------------*/ ScalarIndexSet IndexManager::buildScalarIndexSet(const String& name, ConstArrayView<Integer> localIds, const IAbstractFamily& family, Integer kind, eKeepAlive alive) { alien_debug([&] { cout() << "IndexManager: build scalar index set '" << name << "', kind=" << kind; }); ScalarIndexSet en = buildEntry(name, addNewAbstractFamily(&family, alive), kind); defineIndex(en, localIds); return en; } /*---------------------------------------------------------------------------*/ ScalarIndexSet IndexManager::buildScalarIndexSet( const String& name, const IAbstractFamily& family, Integer kind, eKeepAlive alive) { alien_debug([&] { cout() << "IndexManager: build scalar index set '" << name << "', kind=" << kind; }); auto localIds = family.allLocalIds(); ScalarIndexSet en = buildEntry(name, addNewAbstractFamily(&family, alive), kind); defineIndex(en, localIds.view()); return en; } /*---------------------------------------------------------------------------*/ IndexManager::VectorIndexSet IndexManager::buildVectorIndexSet(const String& name, ConstArrayView<Integer> localIds, const IAbstractFamily& family, const UniqueArray<Integer>& kind, eKeepAlive alive) { alien_debug([&] { cout() << "IndexManager: build vector index set '" << name << "', size=" << kind.size(); }); const Integer size = kind.size(); VectorIndexSet ens(size); const auto* f = addNewAbstractFamily(&family, alive); for (Integer i = 0; i < size; ++i) { ens[i] = buildEntry(Alien::format("{0}[{1}]", name, i), f, kind[i]); defineIndex(ens[i], localIds); } return ens; } /*---------------------------------------------------------------------------*/ IndexManager::VectorIndexSet IndexManager::buildVectorIndexSet(const String& name, const IAbstractFamily& family, const UniqueArray<Integer>& kind, eKeepAlive alive) { alien_debug([&] { cout() << "IndexManager: build vector index set '" << name << "', size=" << kind.size(); }); auto localIds = family.allLocalIds(); const Integer size = kind.size(); VectorIndexSet ens(size); const auto* f = addNewAbstractFamily(&family, alive); for (Integer i = 0; i < size; ++i) { ens[i] = buildEntry(Alien::format("{0}[{1}]", name, i), f, kind[i]); defineIndex(ens[i], localIds.view()); } return ens; } /*---------------------------------------------------------------------------*/ const IAbstractFamily* IndexManager::addNewAbstractFamily(const IAbstractFamily* family, eKeepAlive alive) { auto finder = m_abstract_families.find(family); if (finder == m_abstract_families.end()) // La famille n'est pas stockée, nouvelle famille { if (alive == eKeepAlive::DontClone) { m_abstract_families[family] = std::shared_ptr<IAbstractFamily>(); return family; } else { auto clone = std::shared_ptr<IAbstractFamily>(family->clone()); m_abstract_families[family] = clone; // On remplace les familles des entrées for (auto& f : m_entry_families) { if (f.second == family) f.second = clone.get(); } return clone.get(); } } else // La famille est connue { if (finder->second) // Si clone, on le renvoit return finder->second.get(); else { // Sinon, on crée éventuellement le clone if (alive == eKeepAlive::DontClone) { return family; } else { auto clone = std::shared_ptr<IAbstractFamily>(family->clone()); m_abstract_families[family] = clone; // On remplace les familles des entrées for (auto& f : m_entry_families) { if (f.second == family) f.second = clone.get(); } return clone.get(); } } } } /*---------------------------------------------------------------------------*/ ConstArrayView<Integer> IndexManager::getOwnIndexes(const ScalarIndexSet& entry) const { ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); auto it = m_entry_own_indices.find(entry.getUid()); return it->second; } /*---------------------------------------------------------------------------*/ ConstArrayView<Integer> IndexManager::getOwnLocalIds(const ScalarIndexSet& entry) const { ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); auto it = m_entry_own_items.find(entry.getUid()); return it->second; } /*---------------------------------------------------------------------------*/ ConstArrayView<Integer> IndexManager::getAllIndexes(const ScalarIndexSet& entry) const { ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); auto it = m_entry_all_indices.find(entry.getUid()); return it->second; } /*---------------------------------------------------------------------------*/ ConstArrayView<Integer> IndexManager::getAllLocalIds(const ScalarIndexSet& entry) const { ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); auto it = m_entry_all_items.find(entry.getUid()); return it->second; } /*---------------------------------------------------------------------------*/ const IAbstractFamily& IndexManager::getFamily(const ScalarIndexSet& entry) const { ALIEN_ASSERT((entry.manager() == this), ("Incompatible entry from another manager")); if (m_state != Prepared) throw FatalErrorException(A_FUNCINFO, "Inconsistent state"); auto it = m_entry_families.find(entry.getUid()); return *(it->second); } /*---------------------------------------------------------------------------*/ void IndexManager::setMaxNullIndexOpt(bool flag) { m_max_null_index_opt = flag; alien_debug(flag, [&] { cout() << "IndexManager: null index optimized enabled"; }); } /*---------------------------------------------------------------------------*/ Integer IndexManager::nullIndex() const { ALIEN_ASSERT((m_state == Prepared), ("nullIndex is valid only in Prepared state")); if (m_max_null_index_opt) return m_global_entry_offset + m_local_entry_count; else return -1; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // namespace Alien /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
34.174188
116
0.608953
[ "vector" ]
c7ae6de36b7ab8d34d88666e6795226cd07d0a84
7,572
cpp
C++
StringUtils.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
18
2017-01-28T14:18:44.000Z
2020-04-29T00:05:10.000Z
StringUtils.cpp
GPUOpen-Archive/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
1
2019-02-09T18:00:53.000Z
2019-02-09T18:00:53.000Z
StringUtils.cpp
GPUOpen-Tools/common-src-ShaderUtils
545195d74ff0758f74ebf9a8b4c541f9390a1df7
[ "MIT" ]
5
2018-04-29T09:46:06.000Z
2019-11-01T23:11:27.000Z
//===================================================================== // Copyright 2007-2016 (c), Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file StringUtils.cpp /// //===================================================================== //===================================================================== // $Id: //devtools/main/Common/Src/ShaderUtils/StringUtils.cpp#4 $ // // Last checkin: $DateTime: 2016/04/18 06:01:26 $ // Last edited by: $Author: AMD Developer Tools Team //===================================================================== #include <cstring> #include "StringUtils.h" size_t StringUtils::SplitStringIntoLines(const std::string& strString, std::vector<std::string>& vLines, bool bTrimLines) { size_t nLineBegin = 0; size_t nLineEnd = 0; do { nLineEnd = strString.find('\n', nLineBegin); std::string strLine(strString, nLineBegin, nLineEnd - nLineBegin); if (bTrimLines) { TrimString(strLine); } vLines.push_back(strLine); nLineBegin = nLineEnd + 1; } while (nLineEnd != std::string::npos); return vLines.size(); } void StringUtils::TrimString(std::string& strString) { const char* pszWhiteSpace = " \t\r\n"; size_t nStartPos = strString.find_first_not_of(pszWhiteSpace); if ((nStartPos == std::string::npos)) { strString = ""; } else { size_t nEndPos = strString.find_last_not_of(pszWhiteSpace); strString = strString.substr(nStartPos, nEndPos + 1); } } size_t StringUtils::FindFunctionEntryInString(const std::string& strFunctionEntry, const std::string& strSource) { std::vector<std::string> lines; size_t nLines = StringUtils::SplitStringIntoLines(strSource, lines); int scopeLevel = 0; // The algorithm to find the function definition goes as follows: // 1. Scan the source line by line to find the function name. // 2. If the function name is found, this line contains the function definition only if // the scope level is equal to 0 (at the top level). // 3. Use the open and closing brackets to compute the scope level. // 4. Skip C and C++ comments as necessary. // Note we don't take account for preprocessing yet. bool bCommentLine = false; for (size_t i = 0; i < nLines; ++i) { std::string line(lines[ i ]); //-------------------- HANDLING C comment blocks ----------------------------- size_t foundEndComment = line.find("*/"); if (bCommentLine && std::string::npos != foundEndComment) { bCommentLine = false; line.erase(0, foundEndComment + 2); // chop out the string until the */ tag } if (bCommentLine) { // this entire line is part of the C comment line, skip it continue; } // let's chop out the substring in between all C comment tags(/* and */) bool bLoop = true; while (bLoop) { bLoop = false; size_t foundStartComment = line.find("/*"); if (std::string::npos != foundStartComment) { foundEndComment = line.find("*/", foundStartComment + 2); if (std::string::npos != foundEndComment) { // chop out the string from /* till */ tags line.erase(foundStartComment, foundEndComment - foundStartComment + 2); bLoop = true; } else { bCommentLine = true; // chop out the string from the /* tag till the end of the line line.erase(foundStartComment); } } } //--------------- END OF HANDLING C comment blocks --------------------------- size_t foundComment = line.find("//"); if (std::string::npos != foundComment) { // chop out the C++ comment block line.erase(foundComment); } if (line.empty()) { continue; } size_t startPos = 0; size_t foundFunction = std::string::npos; // loop over the line once for each time the func name appears. // here's an exmaple of a problematic line: "HS_CONTROL_POINT_OUTPUT HS( InputPatch<VS_OUTPUT_HS_INPUT, 3> inputPatch," while ((foundFunction = line.find(strFunctionEntry, startPos)) != std::string::npos) { // the func name was found, but it may be a substring of a different string // need to make sure the character before and after are expected // preceeding character: if (((foundFunction == 0) || // func name is the first word on the line OR (foundFunction > 0 && line.at(foundFunction - 1) == ' ')) && // preceding character is a space // following character: ((line.length() == foundFunction + strFunctionEntry.length()) || // function name ends at end of line OR (strchr(" (", line.at(foundFunction + strFunctionEntry.length())) != NULL))) // char after func name is space or '(' { // make sure we calculate the scope level prior to the function name at the same line size_t foundOpenBracket = line.find_first_of("{", startPos); // count the open bracket prior to the function name and update the scope level while (std::string::npos != foundOpenBracket && foundOpenBracket < foundFunction) { ++scopeLevel; foundOpenBracket = line.find_first_of("{", foundOpenBracket + 1); } size_t foundCloseBracket = line.find_first_of("}", startPos); // count the closing bracket prior to the function name and update the scope level while (std::string::npos != foundCloseBracket && foundCloseBracket < foundFunction) { --scopeLevel; foundCloseBracket = line.find_first_of("}", foundCloseBracket + 1); } // the function name is at the top level so it must be the function definition and not a call to the function if (0 == scopeLevel) { // this is the function definition, because it is at the top scope level return (i + 1); } } // update the start position so we don't match the same funcname instance again startPos = foundFunction + 1; } size_t foundOpenBracket = line.find_first_of("{", startPos); // count the open bracket and update the scope level while (std::string::npos != foundOpenBracket) { ++scopeLevel; foundOpenBracket = line.find_first_of("{", foundOpenBracket + 1); } size_t foundCloseBracket = line.find_first_of("}", startPos); // count the closing bracket and update the scope level while (std::string::npos != foundCloseBracket) { --scopeLevel; foundCloseBracket = line.find_first_of("}", foundCloseBracket + 1); } } return 0; }
36.57971
149
0.529054
[ "vector" ]
c7af58f0cdd330cff73baf7d3c157a33d62e3cba
4,916
hpp
C++
external_libraries/vexcl/vexcl/sparse/product.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
external_libraries/vexcl/vexcl/sparse/product.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
external_libraries/vexcl/vexcl/sparse/product.hpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
#ifndef VEXCL_SPARSE_PRODUCT_HPP #define VEXCL_SPARSE_PRODUCT_HPP /* The MIT License Copyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/sparse/product.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Sparse matrix-vector product terminal. */ #include <vexcl/operations.hpp> namespace vex { namespace sparse { struct matrix_vector_product_terminal {}; typedef vector_expression< typename boost::proto::terminal< matrix_vector_product_terminal >::type > matrix_vector_product_expression; template <class Matrix, class Vector> struct matrix_vector_product : matrix_vector_product_expression { const Matrix &A; typename boost::proto::result_of::as_child<const Vector, vector_domain>::type x; matrix_vector_product(const Matrix &A, const Vector &x) : A(A), x(boost::proto::as_child(x)) {} }; } // namespace sparse namespace traits { template <> struct is_vector_expr_terminal< sparse::matrix_vector_product_terminal > : std::true_type {}; template <class Matrix, class Vector> struct terminal_is_value< sparse::matrix_vector_product<Matrix, Vector> > : std::true_type {}; template <class Matrix, class Vector> struct terminal_preamble< sparse::matrix_vector_product<Matrix, Vector> > { static void get(backend::source_generator &src, const sparse::matrix_vector_product<Matrix, Vector> &term, const backend::command_queue &q, const std::string &prm_name, detail::kernel_generator_state_ptr state) { term.A.terminal_preamble(term.x, src, q, prm_name, state); } }; template <class Matrix, class Vector> struct local_terminal_init< sparse::matrix_vector_product<Matrix, Vector> > { static void get(backend::source_generator &src, const sparse::matrix_vector_product<Matrix, Vector> &term, const backend::command_queue &q, const std::string &prm_name, detail::kernel_generator_state_ptr state) { term.A.local_terminal_init(term.x, src, q, prm_name, state); } }; template <class Matrix, class Vector> struct kernel_param_declaration< sparse::matrix_vector_product<Matrix, Vector> > { static void get(backend::source_generator &src, const sparse::matrix_vector_product<Matrix, Vector> &term, const backend::command_queue &q, const std::string &prm_name, detail::kernel_generator_state_ptr state) { term.A.kernel_param_declaration(term.x, src, q, prm_name, state); } }; template <class Matrix, class Vector> struct partial_vector_expr< sparse::matrix_vector_product<Matrix, Vector> > { static void get(backend::source_generator &src, const sparse::matrix_vector_product<Matrix, Vector> &term, const backend::command_queue &q, const std::string &prm_name, detail::kernel_generator_state_ptr state) { term.A.partial_vector_expr(term.x, src, q, prm_name, state); } }; template <class Matrix, class Vector> struct kernel_arg_setter< sparse::matrix_vector_product<Matrix, Vector> > { static void set(const sparse::matrix_vector_product<Matrix, Vector> &term, backend::kernel &kernel, unsigned part, size_t index_offset, detail::kernel_generator_state_ptr state) { term.A.kernel_arg_setter(term.x, kernel, part, index_offset, state); } }; template <class Matrix, class Vector> struct expression_properties< sparse::matrix_vector_product<Matrix, Vector> > { static void get(const sparse::matrix_vector_product<Matrix, Vector> &term, std::vector<backend::command_queue> &queue_list, std::vector<size_t> &partition, size_t &size ) { term.A.expression_properties(term.x, queue_list, partition, size); } }; } // namespace traits } // namespace vex #endif
35.883212
84
0.7262
[ "vector" ]
c7b8fc45699e075f9b3f5b1edb7ccbf8e5077cb4
636
hpp
C++
Source/Ilum/Editor/Editor.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
11
2022-01-09T05:32:56.000Z
2022-03-28T06:35:16.000Z
Source/Ilum/Editor/Editor.hpp
LavenSun/IlumEngine
94841e56af3c5214f04e7a94cb7369f4935c5788
[ "MIT" ]
null
null
null
Source/Ilum/Editor/Editor.hpp
LavenSun/IlumEngine
94841e56af3c5214f04e7a94cb7369f4935c5788
[ "MIT" ]
1
2021-11-20T15:39:03.000Z
2021-11-20T15:39:03.000Z
#pragma once #include "Utils/PCH.hpp" #include "Engine/Subsystem.hpp" #include "Panel.hpp" #include "Scene/Entity.hpp" namespace Ilum { class Editor : public TSubsystem<Editor> { public: Editor(Context *context); ~Editor() = default; virtual bool onInitialize() override; virtual void onPreTick() override; virtual void onTick(float delta_time) override; virtual void onPostTick() override; virtual void onShutdown() override; void select(Entity entity); Entity getSelect(); private: std::vector<scope<Panel>> m_panels; Entity m_select_entity; std::string m_scene_path = ""; }; } // namespace Ilum
15.512195
48
0.718553
[ "vector" ]
c7bbb0d30ca6b44e1adfa7d5770b4abd4c86cdf1
9,533
hpp
C++
sdk/include/XWordLayer.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/XWordLayer.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/XWordLayer.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
#pragma once #include "xbxbase.h" #include "xworddatasvr.hpp" namespace Hxsoft{ namespace XFrame{ namespace XOffice {namespace XWord { #define TShiftState int #define ssCtrl 0x0001 #define ssShift 0x0008 #define ssAlt 0x0004 #define TWordState DWORD #define TWordState_Normal 0x00000000 #define TWordState_Selecting 0x00000001 #define TWordState_Readonly 0x00010000 #define STI_TEXTCOLOR 0x00000200 #define STI_TEXTBKCOLOR 0x00000400 #define STI_BKCOLOR 0x00000800 class XWordLayer : public xbObject { public: class XWordDocumentBlock; struct XWordBlockExtentInfo { //in args int startx; int endx; HDC hPaintDC; //out args int cx; int cy; int rows; int rowheight; int xPosLast; int nFitFirstRow; LPTSTR pStr; int nStrLen; int * pDx; std::vector<int> nFits; std::vector<int> nZWFits; std::vector<int> nLens; XWordBlockExtentInfo():hPaintDC(0),cx(0),cy(0),rows(0),rowheight(0),xPosLast(0),nFitFirstRow(0),pStr(NULL),nStrLen(0),pDx(NULL){} ~XWordBlockExtentInfo(){if(hPaintDC && pDx) delete pDx;} }; struct XWordBlock { int m_nCssStyle; DWORD m_dwOption; XWordDataBase * m_pContent; XWordBlock * m_pBlockParent; std::vector<XWordBlock * >* m_pChilds; DWORD dwPositin; int x; int y; int width; int height; RECT m_AreaRect; RECT m_ContentRect; //operate XWordBlock():m_nCssStyle(-1),m_dwOption(0),dwPositin(0),x(0),y(0),width(0),height(0),m_pContent(NULL), m_pBlockParent(NULL),m_pChilds(new std::vector<XWordBlock * >) { ::SetRect(&m_AreaRect,0,0,0,0); ::SetRect(&m_ContentRect,0,0,0,0); }; ~XWordBlock() { if(m_pChilds) { for(int i=0;i<(int)m_pChilds->size();i++) { delete (*m_pChilds)[i]; } delete m_pChilds; } } public: XWordDocumentBlock * GetDocumentBlock(); virtual XWordBlock * CreateWordBlock(XWordDataBase * pWordDataBase); public: virtual int AdjustExtent(); virtual int CalcContentRect(); virtual bool CalcExtent(XWordBlockExtentInfo &extentInfo); public: virtual int DoDraw(HDC hPaintDC,POINT ptOffset); virtual int DoDrawBackGround(HDC hPaintDC,POINT ptOffset); virtual int LoadData(XWordDataBase * m_pContent,bool bLoadChild=true); virtual bool GetRects(std::vector<RECT> & rects); public: int GetIndexFromParent(); XWordBlock * GetPirorTextBlock(); XWordBlock * GetNextTextBlock(); public: bool BlockIsSelected(XWordBlock * pStartBlock,XWordBlock * pEndBlock); }; struct XWordSpanBlock : public XWordBlock { virtual bool GetRects(std::vector<RECT> & rects); }; struct XWordSpanNullBlock : public XWordSpanBlock { }; struct XWordTextBlock : public XWordSpanBlock { int* m_pDx; int m_nRowHeight; XWordTextBlock():m_pDx(NULL),m_nRowHeight(0){}; ~XWordTextBlock(){if(m_pDx) delete m_pDx;} virtual bool CalcExtent(XWordBlockExtentInfo &extentInfo); virtual int GetFitedWidth(int startChar,int nFited); }; class XWordSpanControlBlock:public XWordSpanBlock { virtual bool CalcExtent(XWordBlockExtentInfo &extentInfo); }; struct XWordParagraphRowInfo { struct RowBlock { XWordBlock * pBlock; int nStartCharPos; int nFited; int nStartX; int nLen; int nRowheight; int nZWFited; }; std::vector<RowBlock> m_rowBlocks; int nRowHeight; int nBala; }; class XWordContentParagraph:public XWordBlock { public: virtual int AdjustExtent(); virtual bool GetRects(std::vector<RECT> & rects); }; class XWordControlParagraph:public XWordContentParagraph { public: int DoDraw(HDC hPaintDC,POINT ptOffset); }; class XWordParagraphBlock:public XWordContentParagraph { public: std::vector<XWordParagraphRowInfo> m_rowInfos; virtual int AdjustExtent(); public: virtual int DoDraw(HDC hPaintDC,POINT ptOffset); virtual int DoDraw(HDC hPaintDC,POINT ptOffset,int & nStartRow, int & nHeight); }; class XWordChapterBlock:public XWordBlock { public: virtual int AdjustExtent(); virtual bool GetRects(std::vector<RECT> & rects); }; class XWordDocumentBlock:public XWordBlock { public: XWordDocumentBlock():m_pLayer(NULL){}; XWordDocumentBlock(XWordLayer * pLayer):m_pLayer(pLayer){}; public: XWordLayer * m_pLayer; public: virtual int AdjustExtent(); }; struct XWordCursorInfo { int nRow; int nCol; //int nBlock; //int nPosChar; int XPosCursur; int YPosCursur; int CursorHeight; //bool bControlParagraph; //XWordBlock * m_pParagraphBlock; }; struct XWordSelection { //XWordBlock * pStartBlock; //int nStartPosChar; //XWordBlock * pEndBlock; //int nEndPosChar; int nStartRow; int nStartCol; int nEndRow; int nEndCol; bool bSelection; bool blast; }; public: XWordLayer(void); ~XWordLayer(void); public: XWordDataSvr* m_pWordData; XWordDocumentBlock * m_pWordDocumentBlock; class XWordSheetSvr * m_pSheetSvr; public: RECT m_rcPage; RECT m_rcPageContent; RECT m_rcPageMargin; public: TWordState m_State; public: int FOptions; RECT FRect; public: XWordCursorInfo m_CursorInfo; public: virtual int DoDraw(HDC hPaintDC,RECT * pDrawRect=NULL); int CalcContentPageRect(int nPage,RECT * pDrawRect, RECT &rc); public: XWordBlock * GetObjectAtPoint(POINT pt,XWordParagraphRowInfo::RowBlock * &pRowBlock); public: int PosBlockIndex(int &y,std::vector<XWordBlock * > * pItems); int PosRowIndex(int &y,std::vector<XWordParagraphRowInfo> * pItems,int nStartRow=0); int PosCharIndex(int x,XWordParagraphRowInfo* pRowInfo,int &nPosChar,int &posX); int PosCharIndexEx(int x,XWordParagraphRowInfo* pRowInfo,int &nPosChar,int &posX,int &nCol); bool CalcCursorInfo(XWordCursorInfo & CursorInfo,int nRow,int nCol); bool CalcCursorInfoEx(XWordCursorInfo & CursorInfo,XWordBlock * pBlock,int nPosChar); bool CalcCursorInfoAtPoint(POINT pt,XWordCursorInfo & CursorInfo); void InitCursorInfo(XWordCursorInfo &cursorInfo){::ZeroMemory(&cursorInfo,sizeof(XWordCursorInfo));} void ShowCurrentCaret(bool bShow); int GetColCount(int nRow); int GetRowCount(); bool CalcLeftCursorInfo(XWordCursorInfo & CursorInfo); bool CalcRightCursorInfo(XWordCursorInfo & CursorInfo); bool CalcUpCursorInfo(XWordCursorInfo & CursorInfo); bool CalcDownCursorInfo(XWordCursorInfo & CursorInfo); int GetPageOfBlock(XWordBlock * pBlock,int nPosChar); int GetPageOfParagraph(XWordParagraphBlock * pParagraph,int nParaRow); int CalcParagraphRow(int nRow,XWordParagraphBlock * &pPara,int &nParaRow); int CalcBlockCol(XWordParagraphBlock * pPara,int nParaRow,int nCol,int &nBlock,int &nCharPos,bool bRight = false); XWordBlock * GetBlock(int nRow,int nCol); XWordParagraphBlock * GetParagraphByRow(int nRow); XWordParagraphRowInfo::RowBlock * GetRowBlock(int nRow,int nCol); int RemoveBlock(XWordBlock * pBlock); int GetBlockRowCol(XWordBlock * pBlock,int &nStartRow,int &nStartCol,int &nEndRow,int &nEndCol); int GetChaterRow(XWordBlock * pChater); int GetChaterRowCount(XWordBlock * pChater); int GetParahraphRow(XWordBlock * pParahraph); int GetParahraphRowCount(XWordBlock * pParahraph); public: int BlockCmp(XWordBlock * pFirst,XWordBlock* pTwo); public: XWordSelection m_Selection; void InitSelection(XWordSelection &WordSelection){ZeroMemory(&WordSelection,sizeof(XWordSelection));} bool BlockIsSelected(XWordBlock * pBlock,XWordBlock * pStartBlock,XWordBlock * pEndBlock); bool AdjustSelection(XWordCursorInfo & CursorInfo,TShiftState state); bool CursorInfoInSelection(XWordCursorInfo & CursorInfo); bool StandOnlySelection(XWordSelection &Selection); bool StandOnlySelection(XWordSelection &Selection,XWordBlock * &pStartBlockEx,XWordBlock * &pEndBlockEx); int GetBlockAndCharPos(int nRow,int nCol,XWordBlock * &pBlock,int &nCharPos,bool bRight=false); bool StandOnlyToPara(int nRow,int nCol); bool MerginPara(XWordParagraphBlock * pDestPara,XWordParagraphBlock * pSrcPara); public: bool DeleteChar(XWordCursorInfo & CursorInfo); bool BackDeleteChar(XWordCursorInfo & CursorInfo); bool InsertChar(XWordCursorInfo & CursorInfo,TCHAR chr); public: void SetFontBold(); void SetFontItalic(); void SetFontUnderline(); void SetFont(LOGFONT &logFont,COLORREF color); bool ChooseFontDlg(); bool ChooseColorDlg(DWORD flag); void SetColor(COLORREF color, DWORD flag); void SetAlign(DWORD flag); public: int m_nPage; POINT m_ptScroll; CXScrollBar * GetHScrollBar(); CXScrollBar * GetVScrollBar(); void WMVScroll(UINT nSBCode, UINT nPos, HWND hWndCtl); void WMHScroll(UINT nSBCode, UINT nPos, HWND hWndCtl); void WMWheel(POINT point,UINT_PTR fwKeys, short zDelta); int CalcScrollBar(int Value, int ScrollCode, int ScrollBar, int Pos); void ModifyScrollBar(int ScrollBar, int ScrollCode, int Pos); void UpdateScrollPos(int ScrollBar); int ScrollBarMin(int ScrollBar); int ScrollBarMax(int ScrollBar); int PageUp(int ScrollBar); int PageDown(int ScrollBar); int GetTotalHeight(); int GetMaxScrollExtent(int ScrollBar); bool ClampInView(const XWordCursorInfo & CursorInfo); public: int CalcPages(); bool GetFirstRowOfPage(int nPage,int & nParaRow,XWordContentParagraph * & pParaBlockEx); bool DoDrawPage(HDC hPaintDC,int nPage,POINT ptOffset); int SetFRect(RECT &rc); public: int DoPaste(); int DoCopy(); int DoCut(); }; }}}}
29.152905
132
0.731564
[ "vector" ]
c7c376fd3fd53fe451abbe79c09c5a0e4d39704a
3,796
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/algorithms/distance/distance_geo_pl_pl.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2017, Oracle and/or its affiliates. // Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_distance_geographic_pl_l #endif //#include <boost/geometry/core/srs.hpp> #include <boost/test/included/unit_test.hpp> #include "test_distance_geo_common.hpp" typedef bg::cs::geographic<bg::degree> cs_type; typedef bg::model::point<double, 2, cs_type> point_type; typedef bg::model::multi_point<point_type> multi_point_type; namespace services = bg::strategy::distance::services; typedef bg::default_distance_result<point_type>::type return_type; typedef bg::srs::spheroid<double> stype; // Strategies for point-point distance typedef bg::strategy::distance::andoyer<stype> andoyer; typedef bg::strategy::distance::thomas<stype> thomas; typedef bg::strategy::distance::vincenty<stype> vincenty; //=========================================================================== template <typename Strategy> inline bg::default_distance_result<point_type>::type pp_distance(std::string const& wkt1, std::string const& wkt2, Strategy const& strategy) { point_type p1, p2; bg::read_wkt(wkt1, p1); bg::read_wkt(wkt2, p2); return bg::distance(p1, p2, strategy); } //=========================================================================== template <typename Strategy> void test_distance_multipoint_point(Strategy const& strategy) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "multipoint/point distance tests" << std::endl; #endif typedef test_distance_of_geometries<multi_point_type, point_type> tester; tester::apply("mp-p-01", "MULTIPOINT(1 1,1 2,2 3)", "POINT(0 0)", pp_distance("POINT(0 0)","POINT(1 1)",strategy), strategy); tester::apply("mp-p-01", "MULTIPOINT(0 0,0 2,2 0,2 2)", "POINT(1.1 1.1)", pp_distance("POINT(1.1 1.1)","POINT(2 2)",strategy), strategy); } //=========================================================================== template <typename Point, typename Strategy> void test_empty_input_pointlike_linear(Strategy const& strategy) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << "testing on empty inputs... " << std::flush; #endif bg::model::multi_point<Point> multipoint_empty; Point point_empty; Point point = from_wkt<Point>("POINT(0 0)"); // 1st geometry is empty test_empty_input(multipoint_empty, point, strategy); // 2nd geometry is empty test_empty_input(point, multipoint_empty, strategy); // both geometries are empty test_empty_input(multipoint_empty, point_empty, strategy); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "done!" << std::endl; #endif } //=========================================================================== //=========================================================================== //=========================================================================== BOOST_AUTO_TEST_CASE( test_all_point_segment ) { test_distance_multipoint_point(vincenty()); test_distance_multipoint_point(thomas()); test_distance_multipoint_point(andoyer()); test_empty_input_pointlike_linear<point_type>(vincenty()); test_empty_input_pointlike_linear<point_type>(thomas()); test_empty_input_pointlike_linear<point_type>(andoyer()); }
32.724138
78
0.59589
[ "geometry", "model" ]
c7d21cc019c0a892e11b936bbe8f6baf077f7f06
861
hpp
C++
Main course/Homework4/Problem1/Header files/Repository.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem1/Header files/Repository.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem1/Header files/Repository.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
#pragma once #include "MovingAverager.hpp" #include "PeriodicSampler.hpp" // Repository is the single place where Subscribers will // be stored. A Repository has ownership of the Subscribers // stored inside it. // The only way to access the available Subscribers in the // repository is via the Subscriber's unique id. // id's are guaranteed to be unique class Repository { public: Repository() = default; Repository(const Repository&); Repository& operator=(const Repository&); ~Repository(); // add registers a new Subscriber in the Repository void add(const Averager*); // get returns a Subscriber in the Repository if a // Subscriber with the given id exists. // Returns nullptr otherwise Averager* get(const std::string& id) const; private: std::vector<Averager*> subscribers; void copy(const Repository&); void deleteSubscribers(); };
26.090909
59
0.749129
[ "vector" ]
c7d7ed814e0d869b4de0647390bd639381820093
10,585
cpp
C++
isis/src/qisis/objs/Footprint2DView/Footprint2DView.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/qisis/objs/Footprint2DView/Footprint2DView.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/qisis/objs/Footprint2DView/Footprint2DView.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
/** * @file * $Date$ * $Revision$ * * Unless noted otherwise, the portions of Isis written by the USGS are * public domain. See individual third-party library and package descriptions * for intellectual property information, user agreements, and related * information. * * Although Isis has been used by the USGS, no warranty, expressed or * implied, is made by the USGS as to the accuracy and functioning of such * software and related material nor shall the fact of distribution * constitute any such warranty, and no responsibility is assumed by the * USGS in connection therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html * in a browser or see the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include "IsisDebug.h" #include "Footprint2DView.h" #include <QAction> #include <QDockWidget> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDropEvent> #include <QItemSelectionModel> #include <QList> #include <QSize> #include <QSizePolicy> #include <QStatusBar> #include <QToolBar> #include <QBoxLayout> #include <QHBoxLayout> #include <QMainWindow> #include <QVBoxLayout> #include <QWidget> #include <QWidgetAction> #include "ControlPoint.h" #include "Cube.h" #include "Image.h" #include "ImageFileListWidget.h" #include "MosaicGraphicsView.h" #include "MosaicSceneWidget.h" #include "ProjectItem.h" #include "ProjectItemModel.h" #include "Shape.h" #include "ToolPad.h" namespace Isis { /** * Constructor. * * @param parent Pointer to parent QWidget */ Footprint2DView::Footprint2DView(Directory *directory, QWidget *parent) : AbstractProjectItemView(parent) { QStatusBar *statusBar = new QStatusBar(this); m_sceneWidget = new MosaicSceneWidget(statusBar, true, false, directory, this); m_sceneWidget->getScene()->installEventFilter(this); m_sceneWidget->setAcceptDrops(false); MosaicGraphicsView *graphicsView = m_sceneWidget->getView(); graphicsView->installEventFilter(this); graphicsView->setAcceptDrops(false); connect( internalModel(), SIGNAL( itemAdded(ProjectItem *) ), this, SLOT( onItemAdded(ProjectItem *) ) ); connect( internalModel(), SIGNAL( itemRemoved(ProjectItem *) ), this, SLOT( onItemRemoved(ProjectItem *) ) ); connect(m_sceneWidget, SIGNAL(queueSelectionChanged() ), this, SLOT(onQueueSelectionChanged() ) ); // Pass on Signals emitted from ControlNetTool, through the MosaicSceneWidget // TODO 2016-09-09 TLS Design: Use a proxy model instead of signals? connect(m_sceneWidget, SIGNAL(modifyControlPoint(ControlPoint *)), this, SIGNAL(modifyControlPoint(ControlPoint *))); connect(m_sceneWidget, SIGNAL(deleteControlPoint(ControlPoint *)), this, SIGNAL(deleteControlPoint(ControlPoint *))); connect(m_sceneWidget, SIGNAL(createControlPoint(double, double)), this, SIGNAL(createControlPoint(double, double))); connect(m_sceneWidget, SIGNAL(mosCubeClosed(Image *)), this, SLOT(onMosItemRemoved(Image *))); // Pass on redrawMeasure signal from Directory, so the control measures are redrawn on all // the footprints. connect(this, SIGNAL(redrawMeasures()), m_sceneWidget->getScene(), SLOT(update())); QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom); QHBoxLayout *viewlayout = new QHBoxLayout(); layout->addWidget(statusBar); m_fileListWidget = new ImageFileListWidget(directory); m_fileListWidget->setWindowTitle( tr("File List") ); m_fileListWidget->setObjectName( m_fileListWidget->windowTitle() ); QDockWidget *imageFileListdock = new QDockWidget( m_fileListWidget->windowTitle() ); imageFileListdock->setObjectName(imageFileListdock->windowTitle()); imageFileListdock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); imageFileListdock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); imageFileListdock->setWidget(m_fileListWidget); m_window = new QMainWindow(); m_window->addDockWidget(Qt::LeftDockWidgetArea, imageFileListdock, Qt::Vertical); m_window->setCentralWidget(m_sceneWidget); viewlayout->addWidget(m_window); layout->addLayout(viewlayout); setLayout(layout); m_permToolBar = new QToolBar("Standard Tools", 0); m_permToolBar->setObjectName("permToolBar"); m_permToolBar->setIconSize(QSize(22, 22)); //toolBarLayout->addWidget(m_permToolBar); m_activeToolBar = new QToolBar("Active Tool", 0); m_activeToolBar->setObjectName("activeToolBar"); m_activeToolBar->setIconSize(QSize(22, 22)); //toolBarLayout->addWidget(m_activeToolBar); m_toolPad = new ToolPad("Tool Pad", 0); m_toolPad->setObjectName("toolPad"); //toolBarLayout->addWidget(m_toolPad); m_sceneWidget->addToPermanent(m_permToolBar); m_sceneWidget->addTo(m_activeToolBar); m_sceneWidget->addTo(m_toolPad); m_activeToolBarAction = new QWidgetAction(this); m_activeToolBarAction->setDefaultWidget(m_activeToolBar); setAcceptDrops(true); QSizePolicy policy = sizePolicy(); policy.setHorizontalPolicy(QSizePolicy::Expanding); policy.setVerticalPolicy(QSizePolicy::Expanding); setSizePolicy(policy); } /** * Destructor */ Footprint2DView::~Footprint2DView() { delete m_fileListWidget; delete m_window; delete m_permToolBar; delete m_activeToolBar; delete m_toolPad; m_permToolBar = 0; m_activeToolBar = 0; m_toolPad = 0; } /** * Returns the suggested size for the widget. * * @return @b QSize The size */ QSize Footprint2DView::sizeHint() const { return QSize(800, 600); } /** * Accessor for the MosaicSceneWidget */ MosaicSceneWidget *Footprint2DView::mosaicSceneWidget() { return m_sceneWidget; } /** * Event filter to filter out drag and drop events. * * @param[in] watched (QObject *) The object being filtered * @param[in] event (QEvent *) The event * * @return @b bool True if the event was intercepted */ bool Footprint2DView::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::DragEnter) { dragEnterEvent( static_cast<QDragEnterEvent *>(event) ); return true; } else if (event->type() == QEvent::DragMove) { dragMoveEvent( static_cast<QDragMoveEvent *>(event) ); return true; } else if (event->type() == QEvent::Drop) { dropEvent( static_cast<QDropEvent *>(event) ); return true; } return AbstractProjectItemView::eventFilter(watched, event); } /** * Slot to connect to the itemAdded signal from the model. If the * item is an image it adds it to the scene. * * @param[in] item (ProjectItem *) The item */ void Footprint2DView::onItemAdded(ProjectItem *item) { if (!item || (!item->isImage() && !item->isShape())) { return; } //TODO 2016-09-09 TLS Handle Shapes-Create image from shape since qmos only handles images? // Still don't know if shape should inherit from image or contain an image? // Image *image; ImageList images; if (item->isShape()) { //TEMPORARY UNTIL SHAPE IS FIXED TO HOLD IMAGE, once Shape holds image go back to old code // previous to 10-21-16 image = new Image(item->shape()->cube()); } else if (item->isImage()) { image = item->image(); } images.append(image); m_sceneWidget->addImages(images); m_fileListWidget->addImages(&images); if (!m_imageItemMap.value(image)) { m_imageItemMap.insert(image, item); } } /** * Slot at removes the mosaic item and corresponding image file list item when a cube is closed * using the Close Cube context menu. * * @param image The image that was closed and needs to be removed */ void Footprint2DView::onMosItemRemoved(Image *image) { if (image) { ImageList images; images.append(image); m_sceneWidget->removeImages(images); m_fileListWidget->removeImages(&(images)); if ( m_imageItemMap.value( image ) ) { m_imageItemMap.remove( image ); } } } /** * Slot to connect to the itemRemoved signal from the model. If the item is an image it removes it * from the scene. * * @param[in] item (ProjectItem *) The item to be removed */ void Footprint2DView::onItemRemoved(ProjectItem *item) { if (!item) { return; } if (item->isImage()) { ImageList images; images.append(item->image()); m_sceneWidget->removeImages(images); m_fileListWidget->removeImages(&(images)); if ( m_imageItemMap.value( item->image() ) ) { m_imageItemMap.remove( item->image()); } } } /** * Slot to connect to the queueSelectionChanged signal from a * MosiacSceneWidget. Updates the selection in the model. */ void Footprint2DView::onQueueSelectionChanged() { ImageList selectedImages = m_sceneWidget->selectedImages(); if (selectedImages.isEmpty() ) { return; } Image *currentImage = selectedImages.first(); internalModel()->selectionModel()->clear(); if ( ProjectItem *item = m_imageItemMap.value(currentImage) ) { internalModel()->selectionModel()->setCurrentIndex(item->index(), QItemSelectionModel::Select); } foreach (Image *image, selectedImages) { if ( ProjectItem *item = m_imageItemMap.value(image) ) { internalModel()->selectionModel()->select(item->index(), QItemSelectionModel::Select); } } } /** * Returns a list of actions for the permanent tool bar. * * @return @b QList<QAction*> The actions */ QList<QAction *> Footprint2DView::permToolBarActions() { return m_permToolBar->actions(); } /** * Returns a list of actions for the active tool bar. * * @return @b QList<QAction*> The actions */ QList<QAction *> Footprint2DView::activeToolBarActions() { QList<QAction *> actions; actions.append(m_activeToolBarAction); return actions; } /** * Returns a list of actions for the tool pad. * * @return @b QList<QAction*> The actions */ QList<QAction *> Footprint2DView::toolPadActions() { return m_toolPad->actions(); } }
29.816901
101
0.680775
[ "object", "shape", "model" ]
939e2d5a524533868e8ab0e519318ec5dcb047db
3,277
hh
C++
src/ui/viewmodels/OverlayViewModel.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
71
2018-04-15T13:02:43.000Z
2022-03-26T11:19:18.000Z
src/ui/viewmodels/OverlayViewModel.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
309
2018-04-15T12:10:59.000Z
2022-01-22T20:13:04.000Z
src/ui/viewmodels/OverlayViewModel.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
17
2018-04-17T16:09:31.000Z
2022-03-04T08:49:03.000Z
#ifndef RA_UI_OVERLAY_VIEWMODEL_H #define RA_UI_OVERLAY_VIEWMODEL_H #include "PopupViewModelBase.hh" #include "RA_Interface.h" namespace ra { namespace ui { namespace viewmodels { class OverlayViewModel : public PopupViewModelBase { public: enum class State { Hidden, FadeIn, Visible, FadeOutRequested, FadeOut, }; State CurrentState() const noexcept { return m_nState; } /// <summary> /// Begins the animation cycle. /// </summary> void BeginAnimation() override; /// <summary> /// Updates the image to render. /// </summary> bool UpdateRenderImage(double fElapsed) override; /// <summary> /// Causes the cached render image to be rebuilt. /// </summary> void RebuildRenderImage() noexcept { m_bSurfaceStale = true; } /// <summary> /// Releases the memory used to cache the render image. /// </summary> void DestroyRenderImage() noexcept { m_bSurfaceStale = false; m_pSurface.reset(); } /// <summary> /// Determines whether the animation cycle has started. /// </summary> bool IsAnimationStarted() const noexcept override { return (m_fAnimationProgress >= 0.0); } /// <summary> /// Determines whether the animation cycle has completed. /// </summary> bool IsAnimationComplete() const noexcept override { return (m_nState == State::Hidden); } void ProcessInput(const ControllerInput& pInput); void Resize(int nWidth, int nHeight); void Activate(); void Deactivate(); class PageViewModel : public ViewModelBase { public: /// <summary> /// The <see cref="ModelProperty" /> for the page title. /// </summary> static const StringModelProperty TitleProperty; /// <summary> /// Gets the page title to display. /// </summary> const std::wstring& GetTitle() const { return GetValue(TitleProperty); } /// <summary> /// Sets the page title to display. /// </summary> void SetTitle(const std::wstring& sValue) { SetValue(TitleProperty, sValue); } virtual void Refresh() = 0; virtual bool Update(_UNUSED double fElapsed) noexcept(false) { return false; } virtual bool ProcessInput(const ControllerInput& pInput) = 0; virtual void Render(ra::ui::drawing::ISurface& pSurface, int nX, int nY, int nWidth, int nHeight) const = 0; }; PageViewModel& CurrentPage() const { return *m_vPages.at(m_nSelectedPage); } private: void PopulatePages(); void CreateRenderImage(); void RefreshOverlay(); State m_nState = State::Hidden; bool m_bSurfaceStale = false; enum class NavButton { None, Up, Down, Left, Right, Confirm, Cancel, Quit, }; NavButton m_nCurrentButton = NavButton::None; std::chrono::steady_clock::time_point m_tCurrentButtonPressed; std::vector<std::unique_ptr<PageViewModel>> m_vPages; gsl::index m_nSelectedPage = 0; double m_fAnimationProgress = -1.0; static _CONSTANT_VAR INOUT_TIME = 0.4; }; } // namespace viewmodels } // namespace ui } // namespace ra #endif // !RA_UI_OVERLAY_VIEWMODEL_H
24.825758
116
0.633201
[ "render", "vector" ]
93a21638773bfbe8e24400638daa571dae3fc8d0
742
cpp
C++
chap13/Exer13_56.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap13/Exer13_56.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap13/Exer13_56.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
// Warning: this is for verification. It has run time error. // The problem lies in line 28. #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl; using std::vector; class Foo { public: Foo() = default; Foo(const vector<int> &v) : data(v) {} Foo(const Foo &f) : data(f.data) {} Foo sorted() &&; Foo sorted() const &; private: vector<int> data; }; Foo Foo::sorted() && { sort(data.begin(),data.end()); return *this; } Foo Foo::sorted() const & { Foo ret(*this); cout << "Foo sorted() const & is called." << endl; return ret.sorted(); // recursive call, infinite loop } int main() { Foo f = Foo({1,2,3,4}); // f is an lvalue f.sorted(); return 0; }
20.611111
60
0.595687
[ "vector" ]
93acbb4987aa534e5484c2b643abb1b2e625bdf9
3,472
cpp
C++
src/openIMUdata.cpp
akira215/OpenIMUdriver
1d67b53c0c2870c7e9fff24247e82821aaff05f1
[ "MIT" ]
null
null
null
src/openIMUdata.cpp
akira215/OpenIMUdriver
1d67b53c0c2870c7e9fff24247e82821aaff05f1
[ "MIT" ]
null
null
null
src/openIMUdata.cpp
akira215/OpenIMUdriver
1d67b53c0c2870c7e9fff24247e82821aaff05f1
[ "MIT" ]
null
null
null
#include "openIMUdata.h" #include <json.hpp> #include <fstream> // std::ifstream #include <iostream> #include <cstring> //memcpy using json = nlohmann::json; OpenIMUdata::OpenIMUdata() { } OpenIMUdata::~OpenIMUdata() { clearData(); } void OpenIMUdata::clearData(){ // delete old objects for (IMUData* el : _data_vector) { delete el; el=nullptr; } _data_vector.clear(); _data_map.clear(); } void OpenIMUdata::setPacketType(std::string& packetType){ // read a JSON file std::ifstream i(CONFIG_FILE); json j; i >> j; for(const auto& packetDesc : j[USER_MESSAGES][OUTPUT_PACKETS] ){ if(packetDesc["name"]==packetType){ // delete old objects clearData(); // create new data vector for(const auto& payloadDesc : packetDesc["payload"] ){ std::cout << payloadDesc <<std::endl; IMUData* newItem = new IMUData(); newItem->name = payloadDesc["name"]; newItem->unit = payloadDesc["unit"]; newItem->setType(payloadDesc["type"]); //newItem->setSize(payloadDesc["type"]); std::cout << newItem->name << " type: " << newItem->type << " size: "<< newItem->size <<std::endl; // Store in 2 containers _data_vector.push_back(newItem); _data_map[newItem->name] = newItem; } } } //std::cout << "json" << j[USER_MESSAGES][OUTPUT_PACKETS] <<std::endl; } void OpenIMUdata::newData(std::string& data){ //auto it = data.begin(); const char* str = data.c_str(); for (IMUData* el : _data_vector) { //std::memcpy(value, &(*it), el->size); //el->setValue(&(*it)); //std::advance(it, el->size); el->setValue(str); str += el->size; std::cout << el->name << ": "; std::visit([](const auto &x) { std::cout << x; }, el->value); std::cout << " " << el->unit << std::endl; } /* std::memcpy(&timeITOW, &(*it), sizeof(timeITOW)); std::cout << "timeITOW: " << timeITOW << "ms"; std::advance(it,sizeof(timeITOW)); std::memcpy(&time, &(*it), sizeof(time)); std::cout << " - time: " << time << "s"; std::advance(it,sizeof(time)); std::memcpy(&roll, &(*it), sizeof(roll)); std::cout << " - roll: " << roll << "rad"; std::advance(it,sizeof(roll)); std::memcpy(&pitch, &(*it), sizeof(pitch)); std::cout << " - pitch: " << pitch << "rad"; std::advance(it,sizeof(pitch)); std::cout << "\r"; */ } void OpenIMUdata::error(const std::string& msg){ std::cout << msg <<std::endl; } /* "type": "uint32", "name": "timeITOW", "unit": "msec" }, { "type": "double", "name": "time", "unit": "s" }, { "type": "float", "name": "roll", "unit": "rad" }, { "type": "float", "name": "pitch", "unit": "rad" }, { "type": "float", "name": "xRate", "unit": "rad/s" }, { "type": "float", "name": "yRate", "unit": "rad/s" }, { "type": "float", "name": "zRate", "unit": "rad/s" }, { "type": "float", "name": "xAccel", "unit": "m/s/s" }, { "type": "float", "name": "yAccel", "unit": "m/s/s" }, { "type": "float", "name": "zAccel", "unit": "m/s/s" }, { "type": "uint8", "name": "opMode", "unit": "unitless" }, { "type": "uint8", "name": "linAccSw", "unit": "unitless" }, { "type": "uint8", "name": "turnSw", "unit": "unitless" } ], */
20.790419
71
0.516705
[ "vector" ]
93c6e8b70401f1774a537e41a1d5a5cfccd20cf8
15,328
cpp
C++
src/ga.cpp
btnkij/VehicleRouting
0defcea8ae346ce160326f2480cdcafdc9e4f4e8
[ "Apache-2.0" ]
1
2021-04-16T04:44:49.000Z
2021-04-16T04:44:49.000Z
src/ga.cpp
btnkij/VehicleRouting
0defcea8ae346ce160326f2480cdcafdc9e4f4e8
[ "Apache-2.0" ]
null
null
null
src/ga.cpp
btnkij/VehicleRouting
0defcea8ae346ce160326f2480cdcafdc9e4f4e8
[ "Apache-2.0" ]
null
null
null
#include "ga.h" #include <iostream> #include <ctime> #include <cassert> #include <memory> #include <algorithm> #include <numeric> #include <thread> #include <unordered_set> #include "problem.h" #include "loss_metrics.h" #include "genetic_coding.h" #include "cws.h" #include "util.h" namespace VRP { LossMetrics EvaluateTrip( Plan::const_iterator& entry, const Plan::const_iterator& end, const Vehicle& veh, const bool verbose) { assert(entry->type == 0); static std::vector<int> path; if (verbose) { std::cout << "{" << R"("serve":[)"; path.clear(); } LossMetrics loss; int pre = veh.depot; for (; ; ++entry) { int cur = entry->cid; if (verbose) { std::cout << problem.nodeID[cur]; problem.getPath(pre, cur, path); path.pop_back(); } loss.dist += problem.dis[pre][cur]; loss.time += problem.dis[pre][cur] / veh.speed; loss.load += problem.customers[cur].demand; pre = cur; if (problem.customers[cur].twbeg > 0) { loss.time = std::max(loss.time, problem.customers[cur].twbeg); } if (problem.customers[cur].twend > 0) { double twViolation = 0; twViolation = std::max(twViolation, problem.customers[cur].twbeg - loss.time); twViolation = std::max(twViolation, loss.time - problem.customers[cur].twend); loss.penalty += twViolation; } loss.time += problem.customers[cur].serviceTime; if (std::next(entry) == end || std::next(entry)->type != 0 //|| entry->back || loss.load + problem.customers[std::next(entry)->cid].demand > veh.maxLoad ) { loss.maxLoad += veh.maxLoad; loss.dist += problem.dis[cur][veh.depot]; loss.time += problem.dis[cur][veh.depot] / veh.speed; loss.penalty += std::max(0., loss.load - veh.maxLoad); break; } if (verbose) { std::cout << ","; } } ++entry; if (verbose) { problem.getPath(pre, veh.depot, path); std::cout << "]," << R"("route":[)"; for (auto it = path.begin(); it != path.end(); ++it) { if (it != path.begin())std::cout << ","; std::cout << problem.nodeID[*it]; } std::cout << "]," << R"("distance":)" << loss.dist << R"(,"time":)" << loss.time << R"(,"load":)" << loss.load << "}"; } return loss; } LossMetrics EvaluateJourney( Plan::const_iterator& entry, const Plan::const_iterator& end, const bool verbose) { assert(entry->type == 1); if (verbose) { std::cout << "{" << R"("vid":)" << problem.vehicleID[entry->vtype] << R"(,"trips":[)"; } LossMetrics loss; const Vehicle& veh = problem.vehicles[entry->vtype]; auto it = std::next(entry); while (it != end && it->type == 0) { if (verbose && it != std::next(entry)) { std::cout << ","; } loss.Update(EvaluateTrip(it, end, veh, verbose)); } if (veh.maxMileage > 0) { loss.penalty += std::max(0., loss.dist - veh.maxMileage); } if (Vehicle::workTime > 0) { loss.penalty += std::max(0., loss.time - Vehicle::workTime); } if (verbose) { std::cout << "]" << R"(,"distance":)" << loss.dist << R"(,"time":)" << loss.time << R"(,"loadFactor":)" << loss.LoadFactor() << "}"; } entry = it; return loss; } LossMetrics EvaluatePlan(const Plan& plan, const bool verbose) { assert(plan.begin()->type == 1); LossMetrics loss; if (verbose) { std::cout << R"({"plan":[)"; } auto entry = plan.begin(); while (entry != plan.end()) { if (verbose && entry != plan.begin()) { std::cout << ","; } loss.Merge(EvaluateJourney(entry, plan.end(), verbose)); } if (verbose) { std::cout << R"(],"distance":)" << loss.dist << R"(,"time":)" << loss.time << R"(,"loadFactor":)" << loss.LoadFactor() << "}" << std::endl; } return loss; } void MicrobeCrossover(Genome& parent, Genome& child) { auto x = std::next(parent.plan.begin(), randint(0, parent.plan.size())); std::rotate(parent.plan.begin(), x, parent.plan.end()); x = parent.plan.begin(); auto y = std::next(x, randint(1, parent.plan.size())); std::unordered_set<int> vis; for (auto it = x; it != y; ++it) { if (it->type == 0) vis.insert(it->cid); else child.num[it->vtype]++; } for (auto it = child.plan.begin(); it != child.plan.end(); ) { auto nxt = std::next(it); if (it->type == 0 && vis.count(it->cid)) { child.plan.erase(it); } else if (it->type == 1) { if (problem.vehicles[it->vtype].count != -1 && child.num[it->vtype] > problem.vehicles[it->vtype].count) { child.num[it->vtype]--; child.plan.erase(it); } else if (it != child.plan.begin()) { auto pre = std::prev(it); if (pre->type == 1) { child.num[pre->vtype]--; child.plan.erase(pre); } } } it = nxt; } child.plan.insert(child.plan.end(), x, y); child.RemoveSpareVehicles(); child.Evaluate(); } Genome Crossover(const Genome& parent1, const Genome& parent2) { auto x = std::next(parent1.plan.begin(), randint(0, parent1.plan.size() - 1)); int y = randint(1, parent1.plan.size()); std::unordered_set<int> vis; Genome child; child.num.resize(problem.nVehicle); auto it = x; for (int i = 0; i < y; i++) { if (it == parent1.plan.end()) { it = parent1.plan.begin(); } child.plan.push_back(*it); if (it->type == 0) vis.insert(it->cid); else child.num[it->vtype]++; ++it; } for (it = parent2.plan.begin(); it != parent2.plan.end(); ++it) { if (it->type == CUSTOMER) { if (!vis.count(it->cid)) { child.plan.push_back(*it); } } else { if (std::next(it) == parent2.plan.end() && child.plan.front().type == VEHICLE) { break; } if (child.plan.back().type == VEHICLE) { child.num[child.plan.back().vtype]--; child.plan.pop_back(); } if (problem.vehicles[it->vtype].count == -1 || child.num[it->vtype] < problem.vehicles[it->vtype].count) { child.plan.push_back(*it); child.num[it->vtype]++; } } } child.RemoveSpareVehicles(); child.Evaluate(); return child; } void ReinsertRoute(Genome& genome) { int cid = randint(0, problem.nCustomer - 1); auto g = std::find_if(genome.plan.begin(), genome.plan.end(), [cid](Gene& g) { return g.type == 0 && g.cid == cid; }); auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size())); genome.plan.insert(x, *g); genome.plan.erase(g); genome.RemoveSpareVehicles(); genome.Evaluate(); } void SwapRoute(Genome& genome) { auto p = randpair(0, problem.nCustomer - 1); auto c1 = std::find_if(genome.plan.begin(), genome.plan.end(), [p](Gene& g) { return g.type == 0 && g.cid == p.first; }); auto c2 = std::find_if(genome.plan.begin(), genome.plan.end(), [p](Gene& g) { return g.type == 0 && g.cid == p.second; }); std::swap(c1->cid, c2->cid); genome.Evaluate(); } void RotateRoute(Genome& genome) { auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size() - 1)); std::rotate(genome.plan.begin(), x, genome.plan.end()); auto p = randpair(0, genome.plan.size() - 1); int m = randint(p.first, p.second); x = std::next(genome.plan.begin(), p.first); auto y = std::next(x, m - p.first); auto z = std::next(y, p.second - m); std::rotate(x, y, z); genome.RemoveSpareVehicles(); genome.Evaluate(); } void ReverseRoute(Genome& genome) { auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size() - 1)); std::rotate(genome.plan.begin(), x, genome.plan.end()); x = genome.plan.begin(); auto y = std::next(x, randint(1, genome.plan.size())); std::reverse(x, y); genome.RemoveSpareVehicles(); genome.Evaluate(); } void RemoveVehicle(Genome& genome) { auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size() - 1)); std::rotate(genome.plan.begin(), x, genome.plan.end()); auto it = std::find_if(genome.plan.begin(), genome.plan.end(), [](Gene& g) { return g.type == VEHICLE; }); genome.num[it->vtype]--; genome.plan.erase(it); genome.Evaluate(); } void InsertVehicle(Genome& genome) { int vtype = randint(0, problem.nVehicle - 1); if (problem.vehicles[vtype].count == -1 || genome.num[vtype] < problem.vehicles[vtype].count) { auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size())); genome.num[vtype]++; genome.plan.insert(x, Gene::VehicleGene(vtype)); genome.RemoveSpareVehicles(); genome.Evaluate(); } } void ChangeVehicle(Genome& genome) { auto x = std::next(genome.plan.begin(), randint(0, genome.plan.size() - 1)); std::rotate(genome.plan.begin(), x, genome.plan.end()); auto it = std::find_if(genome.plan.begin(), genome.plan.end(), [](Gene& g) { return g.type == VEHICLE; }); int vtype = randint(0, problem.nVehicle - 1); if (problem.vehicles[vtype].count == -1 || genome.num[vtype] < problem.vehicles[vtype].count) { genome.num[vtype]++; genome.num[it->vtype]--; it->vtype = vtype; genome.Evaluate(); } } Genome MutateRoute(const Genome& genome) { int k = randint(0, 3); auto tmp = genome; switch (k) { case 0: SwapRoute(tmp); break; case 1: RotateRoute(tmp); break; case 2: ReverseRoute(tmp); break; case 3: ReinsertRoute(tmp); break; } return tmp; } Genome MutateVehicle(const Genome& genome) { auto tmp = genome; int k = randint(0, 2); switch (k) { case 0: InsertVehicle(tmp); break; case 1: RemoveVehicle(tmp); break; case 2: ChangeVehicle(tmp); break; } return tmp; } void Finetune(Genome& genome) { auto best = genome; // re-insert for (int k = 0; k < 3; k++) { auto tmp = genome; ReinsertRoute(tmp); if (tmp < best)best = tmp; } // swap for (int k = 0; k < 3; k++) { auto tmp = genome; SwapRoute(tmp); if (tmp < best)best = tmp; } // reverse for (int k = 0; k < 3; k++) { auto tmp = genome; ReverseRoute(tmp); if (tmp < best)best = tmp; } // change vehicle for (int k = 0; k < 3; k++) { auto tmp = genome; ChangeVehicle(tmp); if (tmp < best)best = tmp; } if (best < genome) genome = best; } inline void Genome::Evaluate() { FindEntry(); auto loss = EvaluatePlan(plan); this->loss = loss.Result(std::accumulate(num.begin(), num.end(), 0)); } Genome RandomGenome() { std::vector<int> route(problem.nCustomer); std::iota(route.begin(), route.end(), 0); randshuffle(route.begin(), route.end()); Genome genome; genome.num.assign(problem.nVehicle, 0); int vtype = randint(0, problem.nVehicle - 1); genome.plan.push_back(Gene::VehicleGene(vtype)); genome.num[vtype]++; for (int cid : route) { if (!genome.plan.empty() && genome.plan.rbegin()->type != 1 && randprob() < 0.1) { vtype = randint(0, problem.nVehicle - 1); if (problem.vehicles[vtype].count == -1 || genome.num[vtype] < problem.vehicles[vtype].count) { genome.plan.push_back(Gene::VehicleGene(vtype)); genome.num[vtype]++; } } genome.plan.push_back(Gene::CustomerGene(cid)); } genome.Evaluate(); //genome.Finetune(); return genome; } Population::Population() { population.reserve(popsize * 4); for (int i = 0; i < popsize; i++) { population.push_back(RandomGenome()); } bestIndiv = *std::min_element(population.begin(), population.end()); } void Population::Select() { int nElite = int(popsize * eliteRate); auto mid = population.begin() + nElite; auto end = population.begin() + popsize; std::nth_element(population.begin(), mid, population.end()); for (int i = int(population.size() - 1); i >= popsize; i--) { int j = randint(nElite, popsize); if (population[i] < population[j] || randprob() < 0.2) { population[j] = population[i]; } } population.erase(end, population.end()); } const Genome& Population::BestIndiv()const { return bestIndiv; } void HGA(int maxiter, const bool verbose) { constexpr int n = 4; // number of populations constexpr double migrationRate = 0.2; int nMigration = int(Population::popsize * migrationRate); // the number of individuals to migrate clock_t startTime, endTime; if (verbose) { std::cout << "begin optimizing" << "\n\n"; startTime = clock(); } srand(std::time(nullptr)); Genome best; best.loss.first = INF; std::unique_ptr<Population[]> pops(new Population[n]); pops[0].population.push_back(CWS()); // CWS constructed individual std::unique_ptr<std::thread[]> threads(new std::thread[n]); for (int step = 0; step < maxiter; ) { int stepsize = std::min(15, maxiter - step); for (int k = 0; k < n; k++) { threads[k] = std::thread([](Population* cur, int nGeneration) { srand((unsigned)std::time(nullptr) + (unsigned)cur * 23333U); for (int step = 0; step < nGeneration; ++step) { for (int i = 0; i < Population::popsize; i++) { if (randprob() > Population::mutationRate) continue; int j = randint(0, Population::popsize - 1); auto child = Crossover(cur->population[i], cur->population[j]); while (randprob() < Population::mutationRate) { cur->population.push_back(MutateRoute(child)); } if (child.plan.size() - problem.nCustomer > 1) { while (randprob() < Population::mutationRate) { cur->population.push_back(MutateVehicle(child)); } } cur->population.push_back(child); } cur->Select(); for (int i = 0; i < Population::popsize; i++) { if (randprob() < Population::finetuneRate) { Finetune(cur->population[i]); } } } }, &pops[k], stepsize); } step += stepsize; for (int k = 0; k < n; k++) { threads[k].join(); } // migrate if (step % 15 == 0) { for (int i = 0; i < n; i++) { auto& x = pops[i].population; auto midx = x.begin() + nMigration; std::nth_element(x.begin(), midx, x.end()); int j = 0; if (j >= 2)j = randint(2, n - 2); if (j >= i)j++; auto& y = pops[j].population; y.insert(y.end(), x.begin(), midx); } for (int i = 2; i < n; i++) { pops[i].Select(); int j = i % 2; auto beg = pops[i].population.begin(); pops[j].population.insert(pops[j].population.end(), beg, beg + nMigration); } for (int i = 0; i < 2; i++) { pops[i].Select(); } } // update solution for (int k = 0; k < n; k++) { auto cur = &pops[k]; cur->bestIndiv = *std::min_element(cur->population.begin(), cur->population.end()); } if (verbose) { std::cout << "step " << step << ":\n"; for (int i = 0; i < n; i++) { std::cout << "pop#" << i << ": " << "penalty=" << pops[i].BestIndiv().loss.first << ", cost=" << pops[i].BestIndiv().loss.second << "\n"; } } } for (int i = 0; i < n; i++) { if (pops[i].BestIndiv() < best) { best = pops[i].BestIndiv(); } } if (verbose) { endTime = clock(); double runTime = (double(endTime) - startTime) / CLOCKS_PER_SEC; std::cout << "\ntime consumption: " << runTime << " sec\n" << std::endl; } best.FindEntry(); EvaluatePlan(best.plan, true); } }
24.100629
108
0.575874
[ "vector" ]
93c8581986ad7abb84d4ac5d2cefd8fe24f55d55
447
cpp
C++
C++/problem0566.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0566.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0566.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int m = nums.size(); int n = nums[0].size(); if (m * n != r * c) { return nums; } vector<vector<int>> ans(r, vector<int>(c, 0)); for (int i = 0; i < m * n; ++i) { ans[i / c][i % c] = nums[i / n][i % n]; } return ans; } };
21.285714
80
0.404922
[ "vector" ]
93cb2472f013908ce3db0a65b3bbb80637ddbf1f
3,356
cc
C++
soa/service/testing/test_endpoint_accept_speed.cc
etnrlz/rtbkit
0d9cd9e2ee2d7580a27453ad0a2d815410d87091
[ "Apache-2.0" ]
737
2015-01-04T01:40:46.000Z
2022-03-07T10:09:23.000Z
service/testing/test_endpoint_accept_speed.cc
leobispo/soa
57eeddd841157250232004af9a4d69b487c43ae3
[ "Apache-2.0" ]
56
2015-01-05T16:01:03.000Z
2020-06-22T19:02:37.000Z
service/testing/test_endpoint_accept_speed.cc
leobispo/soa
57eeddd841157250232004af9a4d69b487c43ae3
[ "Apache-2.0" ]
329
2015-01-01T06:54:27.000Z
2022-02-12T22:21:02.000Z
/* endpoint_test.cc Jeremy Barnes, 31 January 2011 Copyright (c) 2011 Datacratic. All rights reserved. Tests for the endpoints. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "soa/service/http_endpoint.h" #include "soa/service/active_endpoint.h" #include "soa/service/passive_endpoint.h" #include <sys/socket.h> #include "jml/utils/guard.h" #include "jml/arch/exception_handler.h" #include "jml/utils/testing/watchdog.h" #include "jml/utils/testing/fd_exhauster.h" #include "test_connection_error.h" #include "ping_pong.h" #include <poll.h> #include "jml/utils/exc_assert.h" using namespace std; using namespace ML; using namespace Datacratic; void runAcceptSpeedTest() { string connectionError; PassiveEndpointT<SocketTransport> acceptor("acceptor"); acceptor.onMakeNewHandler = [&] () { return ML::make_std_sp(new PongConnectionHandler(connectionError)); }; int port = acceptor.init(); cerr << "port = " << port << endl; BOOST_CHECK_EQUAL(acceptor.numConnections(), 0); int nconnections = 100; Date before = Date::now(); vector<int> sockets; /* Open all the connections */ for (unsigned i = 0; i < nconnections; ++i) { int s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) throw Exception("socket"); //cerr << "i = " << i << " s = " << s << " sockets.size() = " // << sockets.size() << endl; struct sockaddr_in addr = { AF_INET, htons(port), { INADDR_ANY } }; //cerr << "before connect on " << s << endl; int res = connect(s, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)); //cerr << "after connect on " << s << endl; if (res == -1) { cerr << "connect error: " << strerror(errno) << endl; close(s); } else { sockets.push_back(s); } } /* Write to each and get a response back. This makes sure that all are open. */ for (unsigned i = 0; i < sockets.size(); ++i) { int s = sockets[i]; int res = write(s, "hello", 5); ExcAssertEqual(res, 5); char buf[16]; res = read(s, buf, 16); ExcAssertEqual(res, 4); if (res > 0) { ExcAssertEqual(string(buf, buf + res), "Hi!!"); } } Date after = Date::now(); BOOST_CHECK_LT(after.secondsSince(before), 1); BOOST_CHECK_EQUAL(sockets.size(), nconnections); BOOST_CHECK_EQUAL(acceptor.numConnections(), nconnections); acceptor.closePeer(); for (unsigned i = 0; i < sockets.size(); ++i) { close(sockets[i]); } acceptor.shutdown(); } BOOST_AUTO_TEST_CASE( test_accept_speed ) { BOOST_REQUIRE_EQUAL(TransportBase::created, TransportBase::destroyed); BOOST_REQUIRE_EQUAL(ConnectionHandler::created, ConnectionHandler::destroyed); Watchdog watchdog(50.0); int ntests = 1; //ntests = 1000; // stress test for (unsigned i = 0; i < ntests; ++i) { runAcceptSpeedTest(); } BOOST_CHECK_EQUAL(TransportBase::created, TransportBase::destroyed); BOOST_CHECK_EQUAL(ConnectionHandler::created, ConnectionHandler::destroyed); }
25.618321
84
0.597735
[ "vector" ]
93d432a1b39c05347a8b044ceb3d334aa9456cec
77,017
cpp
C++
libcamera/QualcommCameraHardware.cpp
LineageOS/android_device_motorola_motus
5caaed648a23faa3827c8cd8534b17c58913d594
[ "Apache-2.0" ]
1
2017-07-13T21:19:09.000Z
2017-07-13T21:19:09.000Z
libcamera/QualcommCameraHardware.cpp
LineageOS/android_device_motorola_motus
5caaed648a23faa3827c8cd8534b17c58913d594
[ "Apache-2.0" ]
null
null
null
libcamera/QualcommCameraHardware.cpp
LineageOS/android_device_motorola_motus
5caaed648a23faa3827c8cd8534b17c58913d594
[ "Apache-2.0" ]
3
2016-01-23T15:04:55.000Z
2017-07-31T22:05:04.000Z
/* ** Copyright 2008, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** Based on KalimochoAz's HTC Click source code ** ** Ported to the MB501 by Turl and Firesnatch */ // NOTE VERSION_C #define REVISION_C "RC7009.1." #define LOG_NDEBUG 0 #define LOG_TAG "QualcommCameraHardware" #include <utils/Log.h> #include "QualcommCameraHardware.h" #include <utils/threads.h> #include <binder/MemoryHeapPmem.h> #include <utils/String16.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <math.h> #if HAVE_ANDROID_OS #include <linux/android_pmem.h> #endif #include <linux/ioctl.h> #include "raw2jpeg.h" #define LIKELY(exp) __builtin_expect(!!(exp), 1) #define UNLIKELY(exp) __builtin_expect(!!(exp), 0) extern "C" { #include "exifwriter.h" #include <fcntl.h> #include <time.h> #include <pthread.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <termios.h> #include <assert.h> #include <stdlib.h> #include <ctype.h> #include <signal.h> #include <errno.h> #include <sys/mman.h> #include <sys/time.h> #include <stdlib.h> #include <poll.h> #include "msm_camera.h" // Cliq XT kernel #define REVISION "0.5" // init for Cliq XT #define THUMBNAIL_WIDTH_STR "192" #define THUMBNAIL_HEIGHT_STR "144" // if not set, set them to the following #define THUMBNAIL_WIDTH 192 #define THUMBNAIL_HEIGHT 144 // actual px for snapshoting #define DEFAULT_PICTURE_WIDTH 2560 #define DEFAULT_PICTURE_HEIGHT 1920 #define THUMBNAIL_BUFFER_SIZE (THUMBNAIL_WIDTH * THUMBNAIL_HEIGHT * 3/2) #define DEFAULT_PREVIEW_SETTING 2 #define DEFAULT_FRAMERATE 15 #define PREVIEW_SIZE_COUNT (sizeof(preview_sizes)/sizeof(preview_size_type)) #define NOT_FOUND -1 #define LOG_PREVIEW false #include <dlfcn.h> void* (*LINK_cam_conf)(void *data); } // extern "C" static int exif_table_numEntries = 0; #define MAX_EXIF_TABLE_ENTRIES 7 exif_tags_info_t exif_data[MAX_EXIF_TABLE_ENTRIES]; struct preview_size_type { int width; int height; }; static preview_size_type preview_sizes[] = { { 480, 320 }, // HVGA { 352, 288 }, // CIF { 320, 240 }, // QVGA { 176, 144 }, // QCIF }; static int attr_lookup(const struct str_map *const arr, const char *name) { if (name) { const struct str_map *trav = arr; while (trav->desc) { if (!strcmp(trav->desc, name)) return trav->val; trav++; } } return NOT_FOUND; } static const char* attr_lookup(const struct dstr_map *const arr, const char *name) { if (name) { const struct dstr_map *trav = arr; while (trav->desc) { if (!strcmp(trav->desc, name)) return trav->val; trav++; } } return '\0'; } #define INIT_VALUES_FOR(parm) do { \ if (!parm##_values) { \ parm##_values = (char *)malloc(sizeof(parm)/ \ sizeof(parm[0])*30); \ char *ptr = parm##_values; \ const TYPESTRMAP *trav; \ for (trav = parm; trav->desc; trav++) { \ int len = strlen(trav->desc); \ strcpy(ptr, trav->desc); \ ptr += len; \ *ptr++ = ','; \ } \ *--ptr = 0; \ } \ } while(0) // from aeecamera.h static const str_map whitebalance[] = { { "minus1", CAMERA_WB_MIN_MINUS_1 }, { "auto", CAMERA_WB_AUTO }, { "custom", CAMERA_WB_CUSTOM }, { "incandescent", CAMERA_WB_INCANDESCENT }, { "fluorescent", CAMERA_WB_FLUORESCENT }, { "daylight", CAMERA_WB_DAYLIGHT }, { "cloudy", CAMERA_WB_CLOUDY_DAYLIGHT }, { "twilight", CAMERA_WB_TWILIGHT }, { "shade", CAMERA_WB_SHADE }, { "maxplus1", CAMERA_WB_MAX_PLUS_1 }, { NULL, 0 } }; static char *whitebalance_values; // from camera_effect_t static const str_map effect[] = { { "minus1", 0 }, /* This list must match aeecamera.h */ { "none", CAMERA_EFFECT_OFF }, //CAMERA_EFFECT_OFF { "b/w", CAMERA_EFFECT_MONO }, { "negative", CAMERA_EFFECT_NEGATIVE }, { "solarize", CAMERA_EFFECT_SOLARIZE }, { "pastel", 5 /*CAMERA_EFFECT_PASTEL*/ }, { "mosaic", 6 /*CAMERA_EFFECT_MOSAIC*/ }, { "resize", 7 /*CAMERA_EFFECT_RESIZE*/ }, { "sepia", CAMERA_EFFECT_SEPIA }, { "posterize", CAMERA_EFFECT_POSTERIZE }, { "whiteboard", CAMERA_EFFECT_WHITEBOARD }, { "blackboard", CAMERA_EFFECT_BLACKBOARD }, { "aqua", CAMERA_EFFECT_AQUA }, { "masplus", 13 /*CAMERA_EFFECT_MAX_PLUS_1*/ }, { NULL, 0 } }; static char *effect_values; // from qcamera/common/camera.h static const str_map antibanding[] = { { "off", CAMERA_ANTIBANDING_OFF }, { "60hz", CAMERA_ANTIBANDING_60HZ }, { "50hz", CAMERA_ANTIBANDING_50HZ }, { "auto", CAMERA_ANTIBANDING_AUTO }, { "max", 4 /*CAMERA_ANTIBANDING_MAX*/ }, { NULL, 0 } }; static char *antibanding_values; static const str_map flashmode[] = { { "off", LED_MODE_OFF }, { "auto", LED_MODE_AUTO }, { "on", LED_MODE_ON }, { "torch", LED_MODE_TORCH }, { NULL, 0 } }; static char *flashmode_values; static const str_map picturesize[] = { { "2560x1920", 0 },// max res, cannot zoom { "2048x1536", 2 },// 2 ok, 3 broken { "1600x1200", 4 },// 4 ok, 5 broken { "1280x960", 6 }, // 6 ok, 7 broken { "640x480", 11 }, // 11 ok, 12 broken { "480x320", 8 }, // 8 ok, 9 broken { "320x240", 11 }, // 11 ok, 12 broken { "352x288", 10 }, // 10 ok, 11 broken { "176x144", 16 }, // 16 ok, 17 broken { NULL, 0 } }; static char *picturesize_values; static const dstr_map reducesize[] = { { "2560x1920", "2048x1536" }, { "2048x1536", "1600x1200" }, { "1600x1200", "1280x960" }, { "1280x960" , "480x320" }, { "640x480" , "320x240" }, { "480x320" , "640x480" }, { "320x240" , "352x288" }, { "352x288" , "176x144" }, { "176x144" , NULL }, { NULL, 0 } }; static char *reducesize_values; // round to the next power of two static inline unsigned clp2(unsigned x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } namespace android { static Mutex singleton_lock; static bool singleton_releasing; static Condition singleton_wait; static void receive_camframe_callback(struct msm_frame_t *frame); static int camerafd; static int fd_frame; // zoom-related variables static int32_t mMaxZoom = -1; static bool zoomSupported = false; static int32_t prevzoom = 0; struct msm_frame_t *frameA; bool bFramePresent; pthread_t w_thread; pthread_t jpegThread; void *opencamerafd(void *arg) { camerafd = open(MSM_CAMERA_CONTROL, O_RDWR); if (camerafd < 0) LOGE("Camera control %s open failed: %s!", MSM_CAMERA_CONTROL, strerror(errno)); else LOGV("opening %s fd: %d", MSM_CAMERA_CONTROL, camerafd); return NULL; } QualcommCameraHardware::QualcommCameraHardware() : mParameters(), mPreviewHeight(-1), mPreviewWidth(-1), mRawHeight(-1), mRawWidth(-1), mCameraRunning(false), mPreviewInitialized(false), mRawInitialized(false), mFrameThreadRunning(false), mSnapshotThreadRunning(false), mReleasedRecordingFrame(false), mNotifyCb(0), mDataCb(0), mDataCbTimestamp(0), mCallbackCookie(0), mMsgEnabled(0), mPreviewFrameSize(0), mRawSize(0), mCameraControlFd(-1), mAutoFocusThreadRunning(false), mAutoFocusFd(-1), mInPreviewCallback(false), mCameraRecording(false), mCurZoom(0) { LOGV("constructor E"); if((pthread_create(&w_thread, NULL, opencamerafd, NULL)) != 0) { LOGE("Camera open thread creation failed"); } memset(&mDimension, 0, sizeof(mDimension)); memset(&mCrop, 0, sizeof(mCrop)); mAFenabled = false; LOGV("constructor X"); } void QualcommCameraHardware::initDefaultParameters() { CameraParameters p; LOGV("initDefaultParameters E"); preview_size_type *ps = &preview_sizes[DEFAULT_PREVIEW_SETTING]; p.setPreviewSize(ps->width, ps->height); p.setPreviewFrameRate(DEFAULT_FRAMERATE); p.setPreviewFormat(CameraParameters::PIXEL_FORMAT_YUV420SP); // informative p.setPictureFormat(CameraParameters::PIXEL_FORMAT_JPEG); // informative p.set("jpeg-quality", "90"); // default quality p.set("jpeg-thumbnail-width", THUMBNAIL_WIDTH_STR); // informative p.set("jpeg-thumbnail-height", THUMBNAIL_HEIGHT_STR); // informative p.set("jpeg-thumbnail-quality", "40"); p.setPictureSize(DEFAULT_PICTURE_WIDTH, DEFAULT_PICTURE_HEIGHT); p.set(CameraParameters::KEY_ANTIBANDING, CameraParameters::ANTIBANDING_OFF); p.set(CameraParameters::KEY_EFFECT, CameraParameters::EFFECT_NONE); p.set(CameraParameters::KEY_WHITE_BALANCE, CameraParameters::WHITE_BALANCE_AUTO); p.set(CameraParameters::KEY_FLASH_MODE, CameraParameters::FLASH_MODE_AUTO); p.set(CameraParameters::KEY_FOCUS_MODE, CameraParameters::FOCUS_MODE_AUTO); // This will happen only once in the lifetime of the mediaserver process. // We do not free the _values arrays when we destroy the camera object. #define TYPESTRMAP str_map INIT_VALUES_FOR(antibanding); INIT_VALUES_FOR(effect); INIT_VALUES_FOR(whitebalance); INIT_VALUES_FOR(flashmode); INIT_VALUES_FOR(picturesize); #undef TYPESTRMAP #define TYPESTRMAP dstr_map INIT_VALUES_FOR(reducesize); p.set(CameraParameters::KEY_SUPPORTED_ANTIBANDING, antibanding_values); p.set(CameraParameters::KEY_SUPPORTED_EFFECTS, effect_values); p.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE, whitebalance_values); p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES, "320x240,640x480,1280x960,1600x1200,2048x1536,2560x1920"); p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES, "176x144,320x240,352x288,480x320"); p.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, flashmode_values); p.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES, "auto"); // zoom parameters p.set(CameraParameters::KEY_ZOOM_SUPPORTED, "true"); p.set(CameraParameters::KEY_ZOOM, "0"); p.set(CameraParameters::KEY_MAX_ZOOM, 11); p.set(CameraParameters::KEY_ZOOM_RATIOS, "100,150,175,200,225,250,275,300,325,350,375,400"); if (setParameters(p) != NO_ERROR) { LOGE("Failed to set default parameters?!"); } LOGV("initDefaultParameters X"); } void QualcommCameraHardware::setCallbacks(notify_callback notify_cb, data_callback data_cb, data_callback_timestamp data_cb_timestamp, void* user) { Mutex::Autolock lock(mLock); mNotifyCb = notify_cb; mDataCb = data_cb; mDataCbTimestamp = data_cb_timestamp; mCallbackCookie = user; } void QualcommCameraHardware::enableMsgType(int32_t msgType) { Mutex::Autolock lock(mLock); LOGV("enableMsgType(%d)", msgType); mMsgEnabled |= msgType; } void QualcommCameraHardware::disableMsgType(int32_t msgType) { Mutex::Autolock lock(mLock); LOGD("DisableMsgType( %d )", msgType); mMsgEnabled &= ~msgType; } bool QualcommCameraHardware::msgTypeEnabled(int32_t msgType) { Mutex::Autolock lock(mLock); LOGD("msgTypeEnabled( %d )", msgType); return (mMsgEnabled & msgType); } #define ROUND_TO_PAGE(x) (((x)+0xfff)&~0xfff) void QualcommCameraHardware::startCamera() { LOGV("startCamera E"); libmmcamera_target = ::dlopen("libmm-qcamera-tgt.so", RTLD_NOW); LOGV("loading libmm-qcamera-tgt at %p", libmmcamera_target); if (!libmmcamera_target) { LOGE("FATAL ERROR: could not dlopen libmm-qcamera_target.so: %s", dlerror()); return; } *(void **)&LINK_cam_conf = ::dlsym(libmmcamera_target, "cam_conf"); /* The control thread is in libcamera itself. */ LOGV("pthread_join on control thread"); if (pthread_join(w_thread, NULL) != 0) { LOGE("Camera open thread exit failed"); return; } // Opened camerafd in thread mCameraControlFd = fd_frame = camerafd; if (fd_frame < 0) { LOGE("cam_frame_click: cannot open %s: %s", MSM_CAMERA_CONTROL, strerror(errno)); } else { if ((pthread_create(&mCamConfigThread, NULL, LINK_cam_conf, NULL)) != 0) LOGE("Config thread creation failed!"); else LOGV("Config thread created successfully"); } // init this in order to avoid false preview displays bFramePresent = false; LOGV("startCamera X"); } status_t QualcommCameraHardware::dump(int fd, const Vector<String16>& args) const { const size_t SIZE = 256; char buffer[SIZE]; String8 result; // Dump internal primitives. result.append("QualcommCameraHardware::dump"); snprintf(buffer, 255, "preview width(%d) x height (%d)\n", mPreviewWidth, mPreviewHeight); result.append(buffer); snprintf(buffer, 255, "raw width(%d) x height (%d)\n", mRawWidth, mRawHeight); result.append(buffer); snprintf(buffer, 255, "preview frame size(%d), raw size (%d), jpeg size (%d) " "and jpeg max size (%d)\n", mPreviewFrameSize, mRawSize, mJpegSize, mJpegMaxSize); result.append(buffer); write(fd, result.string(), result.size()); // Dump internal objects. if (mPreviewHeap != 0) { mPreviewHeap->dump(fd, args); } if (mRawHeap != 0) { mRawHeap->dump(fd, args); } if (mJpegHeap != 0) { mJpegHeap->dump(fd, args); } mParameters.dump(fd, args); return NO_ERROR; } bool QualcommCameraHardware::reg_unreg_buf(int camfd, int width, int height, msm_frame_t *frame, msm_pmem_t pmem_type, unsigned char unregister, unsigned char active) { uint32_t y_size; struct msm_pmem_info_t pmemBuf; uint32_t ioctl_cmd; int ioctlRetVal; memset(&pmemBuf, 0, sizeof(pmemBuf)); pmemBuf.type = pmem_type; pmemBuf.fd = frame->fd; pmemBuf.vaddr = (unsigned long *)frame->buffer; pmemBuf.y_off = (frame->y_off + 3) & ~3; // aligned to 4 pmemBuf.cbcr_off = (frame->cbcr_off + 3) & ~3; pmemBuf.active = active; ioctl_cmd = unregister ? MSM_CAM_IOCTL_UNREGISTER_PMEM : MSM_CAM_IOCTL_REGISTER_PMEM; if ((ioctlRetVal = ioctl(camfd, ioctl_cmd, &pmemBuf)) < 0) { LOGE("reg_unreg_buf: MSM_CAM_IOCTL_(UN)REGISTER_PMEM ioctl failed %d", ioctlRetVal); return false; } return true; } void QualcommCameraHardware::native_register_preview_bufs( int camfd, void *pDim, struct msm_frame_t *frame, unsigned char active) { cam_ctrl_dimension_t *dimension = (cam_ctrl_dimension_t *)pDim; reg_unreg_buf(camfd, dimension->display_width, dimension->display_height, frame, MSM_PMEM_OUTPUT2, false, active); } void QualcommCameraHardware::native_unregister_preview_bufs( int camfd, void *pDim, struct msm_frame_t *frame) { cam_ctrl_dimension_t *dimension = (cam_ctrl_dimension_t *)pDim; reg_unreg_buf(camfd, dimension->display_width, dimension->display_height, frame, MSM_PMEM_OUTPUT2, true, true); } static bool native_get_maxzoom(int camfd, void *pZm) { LOGV("native_get_maxzoom E"); struct msm_ctrl_cmd_t ctrlCmd; int32_t *pZoom = (int32_t *)pZm; ctrlCmd.type = CAMERA_GET_PARM_MAXZOOM; ctrlCmd.timeout_ms = 5000; ctrlCmd.length = sizeof(int32_t); ctrlCmd.value = pZoom; if (ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_get_maxzoom: ioctl fd %d error %s", camfd, strerror(errno)); return false; } LOGV("MaxZoom value is %d", *(int32_t *)ctrlCmd.value); memcpy(pZoom, (int32_t *)ctrlCmd.value, sizeof(int32_t)); LOGV("native_get_maxzoom X"); return true; } static bool native_set_afmode(int camfd, isp3a_af_mode_t af_type) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_SET_PARM_AUTO_FOCUS; ctrlCmd.length = sizeof(int); ctrlCmd.value = (void *) &af_type; if (ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_set_afmode: MSM_CAM_IOCTL_CTRL_COMMAND fd %d error %s", camfd, strerror(errno)); return false; } return true; } static int native_get_af_result(int camfd) { int ret; struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = 0; ctrlCmd.length = 0; ctrlCmd.value = NULL; ctrlCmd.status = 0; errno = 0; ret = ioctl(camfd, MSM_CAM_IOCTL_AF_CTRL, &ctrlCmd); if (ret < 0) { if (errno == ETIMEDOUT) LOGE("native_get_af_result: ioctl timedout\n"); else LOGE("native_get_af_result: ioctl failed. ioctl return %d, errno = %d\n", ret, errno); return 1; } LOGV("af_result: %d\n", ctrlCmd.status); if (ctrlCmd.status == 1) return 0; // focus passed else return 1; // focus failed } // need to snapshot static bool native_cancel_afmode(int camfd, int af_fd) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_AUTO_FOCUS_CANCEL; ctrlCmd.length = 0; ctrlCmd.value = NULL; if (ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_cancel_afmode: MSM_CAM_IOCTL_CTRL_COMMAND fd %d error %s", camfd, strerror(errno)); return false; } return true; } static bool native_start_preview(int camfd) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_START_PREVIEW; ctrlCmd.length = 0; ctrlCmd.value = NULL; if (ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_start_preview: MSM_CAM_IOCTL_CTRL_COMMAND fd %d error %s", camfd, strerror(errno)); return false; } return true; } static bool native_get_picture(int camfd, common_crop_t *crop) { LOGV("native_get_picture E"); struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.length = sizeof(common_crop_t); ctrlCmd.value = crop; if(ioctl(camfd, MSM_CAM_IOCTL_GET_PICTURE, &ctrlCmd) < 0) { LOGE("native_get_picture: MSM_CAM_IOCTL_GET_PICTURE fd %d error %s", camfd, strerror(errno)); return false; } LOGV("crop: in1_w %d", crop->in1_w); LOGV("crop: in1_h %d", crop->in1_h); LOGV("crop: out1_w %d", crop->out1_w); LOGV("crop: out1_h %d", crop->out1_h); LOGV("crop: in2_w %d", crop->in2_w); LOGV("crop: in2_h %d", crop->in2_h); LOGV("crop: out2_w %d", crop->out2_w); LOGV("crop: out2_h %d", crop->out2_h); LOGV("crop: update %d", crop->update_flag); LOGV("native_get_picture status after ioctl %d", ctrlCmd.status); LOGV("native_get_picture X"); return true; } static bool native_stop_preview(int camfd) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_STOP_PREVIEW; ctrlCmd.length = 0; if(ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_stop_preview: ioctl fd %d error %s", camfd, strerror(errno)); return false; } return true; } static bool native_start_snapshot(int camfd) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_START_SNAPSHOT; ctrlCmd.length = 0; if(ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_start_snapshot: ioctl fd %d error %s", camfd, strerror(errno)); return false; } return true; } static bool native_stop_snapshot (int camfd) { struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = CAMERA_STOP_SNAPSHOT; ctrlCmd.length = 0; if (ioctl(camfd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) { LOGE("native_stop_snapshot: ioctl fd %d error %s", camfd, strerror(errno)); return false; } return true; } void *jpeg_encoder_thread( void *user ) { LOGD("jpeg_encoder_thread E"); sp<QualcommCameraHardware> obj = QualcommCameraHardware::getInstance(); if (obj != 0) { obj->runJpegEncodeThread(user); } else LOGW("not starting frame thread: the object went away!"); LOGD("jpeg_encoder_thread X"); return NULL; } static bool mJpegThreadRunning = false; bool QualcommCameraHardware::native_jpeg_encode(void) { int jpeg_quality = mParameters.getInt("jpeg-quality"); if (jpeg_quality >= 0) { LOGV("native_jpeg_encode, current jpeg main img quality = %d", jpeg_quality); } int thumbnail_quality = mParameters.getInt("jpeg-thumbnail-quality"); if (thumbnail_quality >= 0) { LOGV("native_jpeg_encode, current jpeg thumbnail quality = %d", thumbnail_quality); } int rotation = mParameters.getInt("rotation"); if (rotation >= 0) { LOGV("native_jpeg_encode, rotation = %d", rotation); } setGpsParameters(); mDimension.filler7 = 2560; mDimension.filler8 = 1920; int ret = !pthread_create(&jpegThread, NULL, jpeg_encoder_thread, NULL); if (ret) mJpegThreadRunning = true; return true; } bool QualcommCameraHardware::native_set_dimension(cam_ctrl_dimension_t *value) { LOGV("native_set_dimension: EX"); return native_set_parm(CAMERA_SET_PARM_DIMENSION, sizeof(cam_ctrl_dimension_t), value); } bool QualcommCameraHardware::native_set_parm( cam_ctrl_type type, uint16_t length, void *value) { int rc = true; struct msm_ctrl_cmd_t ctrlCmd; ctrlCmd.timeout_ms = 5000; ctrlCmd.type = (uint16_t)type; ctrlCmd.length = length; ctrlCmd.value = value; LOGV("native_set_parm: type: %d, length=%d", type, length); rc = ioctl(mCameraControlFd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd); if(rc < 0 || ctrlCmd.status != CAM_CTRL_SUCCESS) { LOGE("ioctl error. camfd=%d, type=%d, length=%d, rc=%d, ctrlCmd.status=%d, %s", mCameraControlFd, type, length, rc, ctrlCmd.status, strerror(errno)); return false; } return true; } static void handler(int sig, siginfo_t *siginfo, void *context) { pthread_exit(NULL); } // Set transfer preview meanwhile new preview is captured static void *prev_frame_click(void *user) { while (true) { usleep(100); if(bFramePresent) { if(LOG_PREVIEW) LOGV("PREVIEW ARRIVED !!!!!!"); receive_camframe_callback(frameA); bFramePresent=false; } } return NULL; } // customized camframe_callback function based on reassembled libmmcamera.so // Routine coded by fn.fyodor and corrected by KalimochoAz static void *cam_frame_click(void *data) { LOGV("Entering cam_frame_click"); frameA = (msm_frame_t *)data; struct sigaction act; pthread_mutex_t mutex_camframe = PTHREAD_MUTEX_INITIALIZER; struct timeval timeout; fd_set readfds; int ret; // found in assembled codes of all libmmcamera memset(&readfds, 0, sizeof(readfds)); act.sa_sigaction = &handler; act.sa_flags = SA_SIGINFO; if (sigaction(SIGUSR1, &act, NULL) != 0) { LOGE("sigaction in cam_frame failed"); pthread_exit(NULL); } FD_ZERO(&readfds); FD_SET(fd_frame, &readfds); while (true) { timeout.tv_sec = 1; // This is not important JUST TIMEOUT for fail timeout.tv_usec = 0; ret = select(fd_frame+1, &readfds, NULL, NULL, &timeout); if (ret == -1) { LOGE("calling select failed!"); break; } else if (FD_ISSET(fd_frame, &readfds)) { pthread_mutex_lock(&mutex_camframe); // ready to get frame ret = ioctl(fd_frame, MSM_CAM_IOCTL_GETFRAME, frameA); if (ret >= 0) { // put buffers to config VFE if (ioctl(fd_frame, MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER, frameA) < 0) LOGE("MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER error %s", strerror(errno)); else receive_camframe_callback(frameA); //bFramePresent=true; } else LOGE("MSM_CAM_IOCTL_GETFRAME error %s", strerror(errno)); pthread_mutex_unlock(&mutex_camframe); } else { LOGV("frame is not ready! select returns %d", ret); usleep(100); } } return NULL; } // ************************************************************************************************************************************ //static cam_frame_start_parms frame_parms; static int recordingState = 0; static rat_t latitude[3]; static rat_t longitude[3]; static char lonref[2]; static char latref[2]; static char dateTime[20]; static rat_t altitude; static void addExifTag(exif_tag_id_t tagid, exif_tag_type_t type, uint32_t count, uint8_t copy, void *data) { if(exif_table_numEntries == MAX_EXIF_TABLE_ENTRIES) { LOGE("Number of entries exceeded limit"); return; } int index = exif_table_numEntries; exif_data[index].tag_id = tagid; exif_data[index].tag_entry.type = type; exif_data[index].tag_entry.count = count; exif_data[index].tag_entry.copy = copy; // LOGV("AddexifTAG data %s times: %d", data, count); if((type == EXIF_RATIONAL) && (count > 1)) exif_data[index].tag_entry.data._rats = (rat_t *)data; if((type == EXIF_RATIONAL) && (count == 1)) exif_data[index].tag_entry.data._rat = *(rat_t *)data; else if(type == EXIF_ASCII) exif_data[index].tag_entry.data._ascii = (char *)data; else if(type == EXIF_BYTE) exif_data[index].tag_entry.data._byte = *(uint8_t *)data; // Increase number of entries exif_table_numEntries++; return; } static void parseLatLong(const char *latlonString, int *pDegrees, int *pMinutes, int *pSeconds ) { double value = atof(latlonString); value = fabs(value); int degrees = (int) value; LOGV("PARSELATLON E"); double remainder = value - degrees; int minutes = (int) (remainder * 60); int seconds = (int) (((remainder * 60) - minutes) * 60 * 1000); *pDegrees = degrees; *pMinutes = minutes; *pSeconds = seconds; LOGV("PARSELATLON E"); } static void setLatLon(exif_tag_id_t tag, const char *latlonString) { int degrees, minutes, seconds; LOGV("SETLATLON E"); parseLatLong(latlonString, &degrees, &minutes, &seconds); rat_t value[3] = { {degrees, 1}, {minutes, 1}, {seconds, 1000} }; if(tag == EXIFTAGID_GPS_LATITUDE) { memcpy(latitude, value, sizeof(latitude)); addExifTag(EXIFTAGID_GPS_LATITUDE, EXIF_RATIONAL, 3, 1, (void *)latitude); } else { memcpy(longitude, value, sizeof(longitude)); addExifTag(EXIFTAGID_GPS_LONGITUDE, EXIF_RATIONAL, 3, 1, (void *)longitude); } LOGV("SETLATLON E"); } void QualcommCameraHardware::setGpsParameters() { const char *str = NULL; // Set latitude str = mParameters.get(CameraParameters::KEY_GPS_LATITUDE); LOGV("Latitude: %s", str); if(str != NULL) { setLatLon(EXIFTAGID_GPS_LATITUDE, str); // Set latitude ref str = NULL; str = mParameters.get(CameraParameters::KEY_GPS_LATITUDE_REF); if(str != NULL) { strncpy(latref, str, 1); latref[1] = '\0'; addExifTag(EXIFTAGID_GPS_LATITUDE_REF, EXIF_ASCII, 2, 1, (void *)latref); } } else return; // Set longitude str = NULL; str = mParameters.get(CameraParameters::KEY_GPS_LONGITUDE); if(str != NULL) { setLatLon(EXIFTAGID_GPS_LONGITUDE, str); // Set longitude ref str = NULL; str = mParameters.get(CameraParameters::KEY_GPS_LONGITUDE_REF); if(str != NULL) { strncpy(lonref, str, 1); lonref[1] = '\0'; addExifTag(EXIFTAGID_GPS_LONGITUDE_REF, EXIF_ASCII, 2, 1, (void *)lonref); } } // Set altitude str = NULL; str = mParameters.get(CameraParameters::KEY_GPS_ALTITUDE); if(str != NULL) { double value = atoi(str); uint32_t value_meter = value * 1000; rat_t alt_value = {value_meter, 1000}; memcpy(&altitude, &alt_value, sizeof(altitude)); addExifTag(EXIFTAGID_GPS_ALTITUDE, EXIF_RATIONAL, 1, 1, (void *)&altitude); // Set altitude ref int ref = mParameters.getInt(CameraParameters::KEY_GPS_ALTITUDE_REF); if( !(ref < 0 || ref > 1) ) addExifTag(EXIFTAGID_GPS_ALTITUDE_REF, EXIF_BYTE, 1, 1, (void *)&ref); } } // ************************************************************************************************************************************************** void QualcommCameraHardware::runJpegEncodeThread(void *data) { unsigned char *buffer ; // Reset the GPS information exif_table_numEntries = 0; LOGV("runJpegEncodeThread E"); int rotation = mParameters.getInt("rotation"); LOGD("native_jpeg_encode, rotation = %d", rotation); bool encode_location = true; camera_position_type pt; #define PARSE_LOCATION(what,type,fmt,desc) do { \ pt.what = 0; \ const char *what##_str = mParameters.get("gps-"#what); \ LOGV("GPS PARM %s --> [%s]", "gps-"#what, what##_str); \ if (what##_str) { \ type what = 0; \ if (sscanf(what##_str, fmt, &what) == 1) \ pt.what = what; \ else { \ LOGE("GPS " #what " %s could not" \ " be parsed as a " #desc, what##_str); \ encode_location = false; \ } \ } \ else { \ LOGD("GPS " #what " not specified: " \ "defaulting to zero in EXIF header."); \ encode_location = false; \ } \ } while(0) PARSE_LOCATION(timestamp, long, "%ld", "long"); if (!pt.timestamp) pt.timestamp = time(NULL); PARSE_LOCATION(altitude, short, "%hd", "short"); PARSE_LOCATION(latitude, double, "%lf", "double float"); PARSE_LOCATION(longitude, double, "%lf", "double float"); #undef PARSE_LOCATION if (encode_location) { LOGD("setting image location ALT %d LAT %lf LON %lf", pt.altitude, pt.latitude, pt.longitude); } else { LOGV("FAIL LOCATE PICTURE: not setting image location"); } camera_position_type *npt = &pt ; if(!encode_location) { npt = NULL; } int jpeg_quality = mParameters.getInt("jpeg-quality"); int wb = ((CAMERA_WB_AUTO == getParm("whitebalance", whitebalance)) ? 0 : 1); // 0 == Auto, 1 == Manual int ledm = ((LED_MODE_OFF == (led_mode_t) getParm("flash-mode", flashmode)) ? 0 : 1); //1 On, 0 Off // Receive and convert to jpeg internaly, without using privative app if (yuv420_save2jpeg((unsigned char*) mJpegHeap->mHeap->base(), mRawHeap->mHeap->base(), mRawWidth, mRawHeight, jpeg_quality, &mJpegSize)) LOGV("jpegConvert done! ExifWriter..."); else LOGE("jpegConvert failed!"); writeExif(mJpegHeap->mHeap->base(), mJpegHeap->mHeap->base(), mJpegSize, &mJpegSize, rotation, npt, wb, ledm); receiveJpegPicture(); mJpegThreadRunning = false; LOGV("runJpegEncodeThread X"); } bool QualcommCameraHardware::initPreview() { // See comments in deinitPreview() for why we have to wait for the frame // thread here, and why we can't use pthread_join(). LOGV("initPreview E: preview size=%dx%d", mPreviewWidth, mPreviewHeight); mFrameThreadWaitLock.lock(); while (mFrameThreadRunning) { LOGV("initPreview: waiting for old frame thread to complete."); mFrameThreadWait.wait(mFrameThreadWaitLock); LOGV("initPreview: old frame thread completed."); } mFrameThreadWaitLock.unlock(); mSnapshotThreadWaitLock.lock(); while (mSnapshotThreadRunning) { LOGV("initPreview: waiting for old snapshot thread to complete."); mSnapshotThreadWait.wait(mSnapshotThreadWaitLock); LOGV("initPreview: old snapshot thread completed."); } mSnapshotThreadWaitLock.unlock(); setZoom(); mPreviewFrameSize = mPreviewWidth * mPreviewHeight * 3/2; mPreviewHeap = new PreviewPmemPool(mCameraControlFd, mPreviewWidth * mPreviewHeight * 2, kPreviewBufferCount, mPreviewFrameSize, 0, "preview"); if (!mPreviewHeap->initialized()) { mPreviewHeap.clear(); LOGE("initPreview X: could not initialize preview heap."); return false; } mDimension.picture_width = DEFAULT_PICTURE_WIDTH; mDimension.picture_height = DEFAULT_PICTURE_HEIGHT; unsigned char activeBuffer; // (sizeof(mDimension) == 0x70) found in assembled codes // element type was unsigned long? if (native_set_dimension(&mDimension)) { for (int cnt = 0; cnt < kPreviewBufferCount; cnt++) { frames[cnt].fd = mPreviewHeap->mHeap->getHeapID(); frames[cnt].buffer = (uint32_t)mPreviewHeap->mHeap->base(); frames[cnt].y_off = 0; frames[cnt].cbcr_off = mPreviewWidth * mPreviewHeight; if (frames[cnt].buffer == 0) { LOGV("frames[%d].buffer: malloc failed!", cnt); return false; } frames[cnt].path = MSM_FRAME_ENC; activeBuffer = (cnt != kPreviewBufferCount - 1) ? 1 : 0; // returned type should be bool, verified from assembled codes native_register_preview_bufs(mCameraControlFd, &mDimension, &frames[cnt], activeBuffer); if (cnt == kPreviewBufferCount - 1) { LOGV("set preview callback"); mFrameThreadRunning = !pthread_create(&mFrameThread, NULL, cam_frame_click, // frame_thread, &frames[cnt]); if (mFrameThreadRunning) LOGV("Preview thread created"); else LOGE("Preview thread error"); } } } else LOGE("native_set_dimension failed"); return mFrameThreadRunning; } void QualcommCameraHardware::deinitPreview(void) { LOGV("deinitPreview E"); // When we call deinitPreview(), we signal to the frame thread that it // needs to exit, but we DO NOT WAIT for it to complete here. The problem // is that deinitPreview is sometimes called from the frame-thread's // callback, when the refcount on the Camera client reaches zero. If we // called pthread_join(), we would deadlock. So, we just call // LINK_camframe_terminate() in deinitPreview(), which makes sure that // after the preview callback returns, the camframe thread will exit. We // could call pthread_join() in initPreview() to join the last frame // thread. However, we would also have to call pthread_join() in release // as well, shortly before we destoy the object; this would cause the same // deadlock, since release(), like deinitPreview(), may also be called from // the frame-thread's callback. This we have to make the frame thread // detached, and use a separate mechanism to wait for it to complete. // camframe_terminate() never been used if (mFrameThreadRunning) { // Send a exit signal to stop the frame thread if (!pthread_kill(mFrameThread, SIGUSR1)) { LOGV("terminate frame_thread successfully"); mFrameThreadRunning = false; } else LOGE("frame_thread doesn't exist"); } LOGV("Unregister preview buffers"); for (int cnt = 0; cnt < kPreviewBufferCount; ++cnt) { native_unregister_preview_bufs(mCameraControlFd, &mDimension, &frames[cnt]); } mPreviewHeap.clear(); LOGV("deinitPreview X"); } bool QualcommCameraHardware::initRaw(bool initJpegHeap) { LOGV("initRaw E: picture size=%dx%d", mRawWidth, mRawHeight); mDimension.picture_width = mRawWidth; mDimension.picture_height = mRawHeight; mRawSize = mRawWidth * mRawHeight * 3 / 2; mJpegMaxSize = mRawWidth * mRawHeight * 3 / 2; if(!native_set_dimension(&mDimension)) { LOGE("initRaw X: failed to set dimension"); return false; } if (mJpegHeap != NULL) { LOGV("initRaw: clearing old mJpegHeap."); mJpegHeap.clear(); } // Thumbnails LOGV("initRaw: initializing mThumbHeap. with size %d", THUMBNAIL_BUFFER_SIZE); mThumbnailHeap = new PmemPool("/dev/pmem_adsp", mCameraControlFd, MSM_PMEM_THUMBNAIL, THUMBNAIL_BUFFER_SIZE, 1, THUMBNAIL_BUFFER_SIZE, 0, "thumbnail camera"); if (!mThumbnailHeap->initialized()) { mThumbnailHeap.clear(); mRawHeap.clear(); LOGE("initRaw X failed: error initializing mThumbnailHeap."); return false; } // Snapshot LOGV("initRaw: initializing mRawHeap. with size %d", mRawSize); mRawHeap = new PmemPool("/dev/pmem_adsp", mCameraControlFd, MSM_PMEM_MAINIMG, mJpegMaxSize, kRawBufferCount, mRawSize, 0, "snapshot camera"); if (!mRawHeap->initialized()) { LOGE("initRaw X failed with pmem_camera, trying with pmem_adsp"); mRawHeap = new PmemPool("/dev/pmem_adsp", mCameraControlFd, MSM_PMEM_MAINIMG, mJpegMaxSize, kRawBufferCount, mRawSize, 0, "snapshot camera"); if (!mRawHeap->initialized()) { mRawHeap.clear(); LOGE("initRaw X: error initializing mRawHeap"); return false; } } LOGV("do_mmap snapshot pbuf = %p, pmem_fd = %d", (uint8_t *)mRawHeap->mHeap->base(), mRawHeap->mHeap->getHeapID()); // JPEG if (initJpegHeap) { LOGV("initRaw: initializing mJpegHeap."); mJpegHeap = new AshmemPool(mJpegMaxSize, kJpegBufferCount, 0, // we do not know how big the picture wil be 0, "jpeg"); if (!mJpegHeap->initialized()) { mJpegHeap.clear(); mRawHeap.clear(); LOGE("initRaw X failed: error initializing mJpegHeap."); return false; } } mRawInitialized = true; LOGV("initRaw X success"); return true; } void QualcommCameraHardware::deinitRaw() { LOGV("deinitRaw E"); mThumbnailHeap.clear(); mJpegHeap.clear(); mRawHeap.clear(); mRawInitialized = false; LOGV("deinitRaw X"); } void QualcommCameraHardware::release() { LOGV("release E"); Mutex::Autolock l(&mLock); if (libmmcamera_target == NULL) { LOGE("ERROR: multiple release!"); return; } int rc; struct msm_ctrl_cmd_t ctrlCmd; led_mode_t value; if (mCameraRunning) { if (mMsgEnabled & CAMERA_MSG_VIDEO_FRAME) { mRecordFrameLock.lock(); mReleasedRecordingFrame = true; mRecordWait.signal(); mRecordFrameLock.unlock(); } stopPreviewInternal(); } if (mRawInitialized) deinitRaw(); // Turn off LED just in case it was left on value = LED_MODE_AUTO; native_set_parm(CAMERA_SET_PARM_LED_MODE, sizeof(value), (void *)&value); LOGV("CAMERA_EXIT"); ctrlCmd.timeout_ms = 5000; ctrlCmd.length = 0; ctrlCmd.type = (uint16_t)CAMERA_EXIT; if (ioctl(mCameraControlFd, MSM_CAM_IOCTL_CTRL_COMMAND, &ctrlCmd) < 0) LOGE("ioctl CAMERA_EXIT fd %d error %s", mCameraControlFd, strerror(errno)); LOGV("Stopping the conf thread"); rc = pthread_join(mCamConfigThread, NULL); if (rc) LOGE("config_thread exit failure: %s", strerror(errno)); if (mJpegThreadRunning) { LOGV("Stopping the jpeg thread"); rc = pthread_join(jpegThread, NULL); if (rc) LOGE("jpeg_thread exit failure: %s", strerror(errno)); } memset(&mDimension, 0, sizeof(mDimension)); close(mCameraControlFd); mCameraControlFd = -1; close(fd_frame); fd_frame = -1; if (libmmcamera_target) { ::dlclose(libmmcamera_target); LOGV("dlclose(libmmcamera_target)"); libmmcamera_target = NULL; } Mutex::Autolock lock(&singleton_lock); singleton.clear(); singleton_releasing = false; singleton_wait.signal(); LOGV("release X"); } QualcommCameraHardware::~QualcommCameraHardware() { LOGD("~QualcommCameraHardware"); } sp<IMemoryHeap> QualcommCameraHardware::getRawHeap() const { LOGV("getRawHeap"); return mRawHeap != NULL ? mRawHeap->mHeap : NULL; } sp<IMemoryHeap> QualcommCameraHardware::getPreviewHeap() const { LOGV("getPreviewHeap"); return mPreviewHeap != NULL ? mPreviewHeap->mHeap : NULL; } status_t QualcommCameraHardware::startPreviewInternal() { LOGV("startPreview E"); if (mCameraRunning) { LOGV("startPreview X: preview already running."); return NO_ERROR; } if (!mPreviewInitialized) { mPreviewInitialized = initPreview(); if (!mPreviewInitialized) { LOGE("startPreview X initPreview failed. Not starting preview."); return UNKNOWN_ERROR; } } mCameraRunning = native_start_preview(mCameraControlFd); if (!mCameraRunning) { deinitPreview(); mPreviewInitialized = false; LOGE("startPreview X: native_start_preview failed!"); return UNKNOWN_ERROR; } LOGV("startPreview X"); return NO_ERROR; } status_t QualcommCameraHardware::startPreview() { Mutex::Autolock l(&mLock); return startPreviewInternal(); } void QualcommCameraHardware::stopPreviewInternal() { LOGV("stopPreviewInternal E with mCameraRunning %d", mCameraRunning); if (mCameraRunning) { // Cancel auto focus. if (mMsgEnabled & CAMERA_MSG_FOCUS) { LOGV("canceling autofocus"); cancelAutoFocus(); } mAFenabled = false; LOGV("Stopping preview"); mCameraRunning = !native_stop_preview(mCameraControlFd); if (!mCameraRunning && mPreviewInitialized) { deinitPreview(); mPreviewInitialized = false; } else LOGE("stopPreviewInternal: failed to stop preview"); } LOGV("stopPreviewInternal X with mCameraRunning %d", mCameraRunning); } void QualcommCameraHardware::stopPreview() { LOGV("stopPreview: E"); Mutex::Autolock l(&mLock); if(mMsgEnabled & CAMERA_MSG_VIDEO_FRAME) return; if (mCameraRunning) stopPreviewInternal(); LOGV("stopPreview: X"); } void QualcommCameraHardware::runAutoFocus() { int status = false; led_mode_t value; mAutoFocusThreadLock.lock(); mAutoFocusFd = open(MSM_CAMERA_CONTROL, O_RDWR); if (mAutoFocusFd < 0) { LOGE("autofocus: cannot open %s: %s", MSM_CAMERA_CONTROL, strerror(errno)); mAutoFocusThreadRunning = false; mAutoFocusThreadLock.unlock(); return; } // Autofocusing when preview isn't showing breaks it if(mAFenabled) { /* This will block until either AF completes or is cancelled. */ native_set_afmode(camerafd, AF_MODE_MACRO); if (native_get_af_result(camerafd) == 0) { status = true; } } // native_set_afmode turns off LED light for some reason. // Need to toggle it to get it back on. value = (led_mode_t) getParm("flash-mode", flashmode); if (value == LED_MODE_ON) { value = LED_MODE_OFF; native_set_parm(CAMERA_SET_PARM_LED_MODE, sizeof(value), (void *)&value); value = LED_MODE_ON; native_set_parm(CAMERA_SET_PARM_LED_MODE, sizeof(value), (void *)&value); } mAutoFocusThreadRunning = false; close(mAutoFocusFd); mAutoFocusFd = -1; mAutoFocusThreadLock.unlock(); if (mMsgEnabled & CAMERA_MSG_FOCUS) { mNotifyCb(CAMERA_MSG_FOCUS, status, 0, mCallbackCookie); } } status_t QualcommCameraHardware::cancelAutoFocus() { return NO_ERROR; } void *auto_focus_thread(void *user) { sp<QualcommCameraHardware> obj = QualcommCameraHardware::getInstance(); if (obj != 0) { obj->runAutoFocus(); } else LOGW("not starting autofocus: the object went away!"); return NULL; } status_t QualcommCameraHardware::autoFocus() { Mutex::Autolock l(&mLock); if (mCameraControlFd < 0) { LOGE("not starting autofocus: main control fd %d", mCameraControlFd); return UNKNOWN_ERROR; } { mAutoFocusThreadLock.lock(); if (!mAutoFocusThreadRunning) { // Create a detatched thread here so that we don't have to wait // for it when we cancel AF. pthread_t thr; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); mAutoFocusThreadRunning = !pthread_create(&thr, &attr, auto_focus_thread, NULL); if (!mAutoFocusThreadRunning) { LOGE("failed to start autofocus thread"); mAutoFocusThreadLock.unlock(); return UNKNOWN_ERROR; } } mAutoFocusThreadLock.unlock(); } return NO_ERROR; } void QualcommCameraHardware::runSnapshotThread(void *data) { LOGV("runSnapshotThread E"); if (native_start_snapshot(mCameraControlFd)) receiveRawPicture(); else LOGE("main: native_start_snapshot failed!"); mSnapshotThreadWaitLock.lock(); mSnapshotThreadRunning = false; mSnapshotThreadWait.signal(); mSnapshotThreadWaitLock.unlock(); LOGV("runSnapshotThread X"); } void *snapshot_thread(void *user) { LOGV("snapshot_thread E"); sp<QualcommCameraHardware> obj = QualcommCameraHardware::getInstance(); if (obj != 0) { obj->runSnapshotThread(user); } else LOGW("not starting snapshot thread: the object went away!"); LOGV("snapshot_thread X"); return NULL; } status_t QualcommCameraHardware::takePicture() { LOGV("takePicture: E"); Mutex::Autolock l(&mLock); // Wait for old snapshot thread to complete. mSnapshotThreadWaitLock.lock(); while (mSnapshotThreadRunning) { LOGV("takePicture: waiting for old snapshot thread to complete."); mSnapshotThreadWait.wait(mSnapshotThreadWaitLock); LOGV("takePicture: old snapshot thread completed."); } if (mCameraRunning) stopPreviewInternal(); if (!initRaw(mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE)) { LOGE("initRaw failed. Not taking picture."); return UNKNOWN_ERROR; } mShutterLock.lock(); mShutterPending = true; mShutterLock.unlock(); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); mSnapshotThreadRunning = !pthread_create(&mSnapshotThread, &attr, snapshot_thread, NULL); mSnapshotThreadWaitLock.unlock(); LOGV("takePicture: X"); return mSnapshotThreadRunning ? NO_ERROR : UNKNOWN_ERROR; } status_t QualcommCameraHardware::cancelPicture() { LOGV("cancelPicture: EX"); return NO_ERROR; } void QualcommCameraHardware::initCameraParameters() { LOGV("initCameraParameters: E"); if (mCameraRunning) { setAntibanding(); setEffect(); setWhiteBalance(); setFlashMode(); setZoom(); } LOGV("initCameraParameters: X"); } status_t QualcommCameraHardware::setParameters( const CameraParameters& params) { LOGV("setParameters: E params = %p", &params); Mutex::Autolock l(&mLock); // Set preview size. preview_size_type *ps = preview_sizes; { int width, height; params.getPreviewSize(&width, &height); LOGV("requested size %d x %d", width, height); // Validate the preview sizes size_t i; for (i = 0; i < PREVIEW_SIZE_COUNT; ++i, ++ps) { if (width == ps->width && height == ps->height) break; } if (i == PREVIEW_SIZE_COUNT) { LOGE("Invalid preview size requested: %dx%d", width, height); return BAD_VALUE; } } mPreviewWidth = mDimension.display_width = ps->width; mPreviewHeight = mDimension.display_height = ps->height; params.getPictureSize(&mRawWidth, &mRawHeight); mDimension.picture_width = mRawWidth; mDimension.picture_height = mRawHeight; if(setGpsLocation(params) == NO_ERROR) LOGV("Seting GPS Parameters OK"); else LOGE("Error Seting GPS Parameters"); // Set up the jpeg-thumbnail-size parameters. { int val; val = params.getInt("jpeg-thumbnail-width"); if (val < 0) { mDimension.ui_thumbnail_width= THUMBNAIL_WIDTH; LOGW("jpeg-thumbnail-width is not specified: defaulting to %d", THUMBNAIL_WIDTH); } else mDimension.ui_thumbnail_width = val; val = params.getInt("jpeg-thumbnail-height"); if (val < 0) { mDimension.ui_thumbnail_height= THUMBNAIL_HEIGHT; LOGW("jpeg-thumbnail-height is not specified: defaulting to %d", THUMBNAIL_HEIGHT); } else mDimension.ui_thumbnail_height = val; } // User changed pic size, recheck zoom if (params.get("picture-size") != NULL && mParameters.get("picture-size") != NULL && strcmp(params.get("picture-size"), mParameters.get("picture-size")) != 0){ prevzoom = 99; LOGV("setParameters: user/system modified pic size! rechecking zoom"); } // setParameters mParameters = params; // Effect, WhiteBalance, AntiBanding... if (mCameraControlFd != -1) initCameraParameters(); LOGV("setParameters: X"); return NO_ERROR; } CameraParameters QualcommCameraHardware::getParameters() const { LOGV("getParameters: EX"); return mParameters; } extern "C" sp<CameraHardwareInterface> openCameraHardware() { return QualcommCameraHardware::createInstance(); } wp<QualcommCameraHardware> QualcommCameraHardware::singleton; // If the hardware already exists, return a strong pointer to the current // object. If not, create a new hardware object, put it in the singleton, // and return it. sp<CameraHardwareInterface> QualcommCameraHardware::createInstance() { LOGD("Revision: %s%s", REVISION_C, REVISION_H); LOGV("createInstance: E"); if (singleton != 0) { sp<CameraHardwareInterface> hardware = singleton.promote(); if (hardware != 0) { LOGD("createInstance: X return existing hardware=%p", &(*hardware)); return hardware; } } { struct stat st; int rc = stat("/dev/oncrpc", &st); if (rc < 0) { LOGD("createInstance: X failed to create hardware: %s", strerror(errno)); return NULL; } } QualcommCameraHardware *cam = new QualcommCameraHardware(); sp<QualcommCameraHardware> hardware(cam); singleton = hardware; cam->initDefaultParameters(); cam->startCamera(); LOGV("createInstance: X created hardware=%p", &(*hardware)); return hardware; } // For internal use only, hence the strong pointer to the derived type. sp<QualcommCameraHardware> QualcommCameraHardware::getInstance() { sp<CameraHardwareInterface> hardware = singleton.promote(); if (hardware != 0) { return sp<QualcommCameraHardware>(static_cast<QualcommCameraHardware*>(hardware.get())); } else { LOGV("getInstance: X new instance of hardware"); return sp<QualcommCameraHardware>(); } } // passes the Addresses to CameraService to getPreviewHeap void QualcommCameraHardware::receivePreviewFrame(struct msm_frame_t *frame) { if ( LOG_PREVIEW ) LOGV("receivePreviewFrame E"); if (!mCameraRunning) { LOGE("ignoring preview callback--camera has been stopped"); return; } // Find the offset within the heap of the current buffer. ssize_t offset = (ssize_t)frame->buffer - (ssize_t)mPreviewHeap->mHeap->base(); offset /= mPreviewFrameSize; mInPreviewCallback = true; if (mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) mDataCb(CAMERA_MSG_PREVIEW_FRAME, mPreviewHeap->mBuffers[offset], mCallbackCookie); if (mMsgEnabled & CAMERA_MSG_VIDEO_FRAME) { Mutex::Autolock rLock(&mRecordFrameLock); mDataCbTimestamp(systemTime(), CAMERA_MSG_VIDEO_FRAME, mPreviewHeap->mBuffers[offset], mCallbackCookie); if (mReleasedRecordingFrame != true) { LOGV("block for release frame request/command"); mRecordWait.wait(mRecordFrameLock); } mReleasedRecordingFrame = false; } mInPreviewCallback = false; if ( LOG_PREVIEW ) LOGV("receivePreviewFrame X"); if (!mAFenabled) mAFenabled = true; } status_t QualcommCameraHardware::startRecording() { LOGV("startRecording E"); updateVideoLightMode(1); Mutex::Autolock l(&mLock); mReleasedRecordingFrame = false; mCameraRecording = true; return startPreviewInternal(); } void QualcommCameraHardware::stopRecording() { LOGV("stopRecording: E"); updateVideoLightMode(0); Mutex::Autolock l(&mLock); { mRecordFrameLock.lock(); mReleasedRecordingFrame = true; mRecordWait.signal(); mRecordFrameLock.unlock(); mCameraRecording = false; if(mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) { LOGV("stopRecording: X, preview still in progress"); return; } } if (mCameraRunning) stopPreviewInternal(); LOGV("stopRecording: X"); } void QualcommCameraHardware::releaseRecordingFrame( const sp<IMemory>& mem __attribute__((unused))) { LOGV("releaseRecordingFrame E"); Mutex::Autolock l(&mLock); Mutex::Autolock rLock(&mRecordFrameLock); mReleasedRecordingFrame = true; mRecordWait.signal(); LOGV("releaseRecordingFrame X"); } bool QualcommCameraHardware::recordingEnabled() { LOGV("recordingEnabled"); return (mCameraRunning && mCameraRecording); } void QualcommCameraHardware::notifyShutter() { mShutterLock.lock(); if (mShutterPending && (mMsgEnabled & CAMERA_MSG_SHUTTER)) { mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie); mShutterPending = false; } mShutterLock.unlock(); } void QualcommCameraHardware::receiveRawPicture() { LOGV("receiveRawPicture: E"); notifyShutter(); if (mMsgEnabled & CAMERA_MSG_RAW_IMAGE) { LOGV("before native_get_picture"); if(native_get_picture(mCameraControlFd, &mCrop) == false) { LOGE("getPicture failed!"); return; } mDataCb(CAMERA_MSG_RAW_IMAGE, mRawHeap->mBuffers[0], mCallbackCookie); } else LOGV("Raw-picture callback was canceled--skipping."); if (mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE) { mJpegSize = mRawWidth * mRawHeight * 3/2; LOGV("Before JPEG Encoder Init"); if(native_jpeg_encode()) { LOGV("receiveRawPicture: X (success)"); return; } LOGE("jpeg encoding failed"); } else LOGV("JPEG callback is NULL, not encoding image."); if (mRawInitialized) deinitRaw(); LOGV("receiveRawPicture: X"); } void QualcommCameraHardware::receiveJpegPictureFragment( uint8_t *buff_ptr, uint32_t buff_size) { uint32_t remaining = mJpegHeap->mHeap->virtualSize(); remaining -= mJpegSize; uint8_t *base = (uint8_t *)mJpegHeap->mHeap->base(); LOGV("receiveJpegPictureFragment size %d", buff_size); if (buff_size > remaining) { LOGE("receiveJpegPictureFragment: size %d exceeds what " "remains in JPEG heap (%d), truncating", buff_size, remaining); buff_size = remaining; } memcpy(base + mJpegSize, buff_ptr, buff_size); mJpegSize += buff_size; } void QualcommCameraHardware::receiveJpegPicture(void) { LOGV("receiveJpegPicture: E image (%d uint8_ts out of %d)", mJpegSize, mJpegHeap->mBufferSize); LOGD("mJpegHeap->mFrameOffset %d", mJpegHeap->mFrameOffset ) ; int index = 0, rc; if (mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE) { // The reason we do not allocate into mJpegHeap->mBuffers[offset] is // that the JPEG image's size will probably change from one snapshot // to the next, so we cannot reuse the MemoryBase object. sp<MemoryBase> buffer = new MemoryBase(mJpegHeap->mHeap, index * mJpegHeap->mBufferSize + mJpegHeap->mFrameOffset, mJpegSize); mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, buffer, mCallbackCookie); buffer = NULL; } else LOGV("JPEG callback was cancelled--not delivering image."); if (mRawInitialized) deinitRaw(); LOGV("receiveJpegPicture: X callback done."); } bool QualcommCameraHardware::previewEnabled() { Mutex::Autolock l(&mLock); return (mCameraRunning && (mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME)); } int QualcommCameraHardware::getParm( const char *parm_str, const struct str_map *const parm_map) { // Check if the parameter exists. const char *str = mParameters.get(parm_str); if (str == NULL) return NOT_FOUND; // Look up the parameter value. return attr_lookup(parm_map, str); } const char* QualcommCameraHardware::getParm( const char *parm_str, const struct dstr_map *const parm_map) { // Check if the parameter exists. const char *str = mParameters.get(parm_str); if (str == NULL) return '\0'; // Look up the parameter value. return attr_lookup(parm_map, str); } void QualcommCameraHardware::setEffect() { int32_t value = getParm(CameraParameters::KEY_EFFECT, effect); if (value != NOT_FOUND) { native_set_parm(CAMERA_SET_PARM_EFFECT, sizeof(value), (void *)&value); } } void QualcommCameraHardware::setWhiteBalance() { int32_t value = getParm(CameraParameters::KEY_WHITE_BALANCE, whitebalance); if (value != NOT_FOUND) { native_set_parm(CAMERA_SET_PARM_WB, sizeof(value), (void *)&value); } } void QualcommCameraHardware::setAntibanding() { camera_antibanding_type value = (camera_antibanding_type) getParm(CameraParameters::KEY_ANTIBANDING, antibanding); native_set_parm(CAMERA_SET_PARM_ANTIBANDING, sizeof(value), (void *)&value); } void QualcommCameraHardware::setZoom() { int32_t level; int32_t multiplier; int32_t zoomsel; bool iscamcorder = false; if(native_get_maxzoom(mCameraControlFd, (void *)&mMaxZoom) == true){ LOGD("Maximum zoom value is %d", mMaxZoom); // maxZoom/5 in the ideal world, but it's stuck on 90 multiplier = getParm("picture-size", picturesize); // Camcorder mode uses preview size if (strcmp(mParameters.get("preview-frame-rate"),"15") != 0){ multiplier = getParm("preview-size", picturesize); iscamcorder = true; } zoomSupported = true; if(mMaxZoom > 0){ // To get more 'natural' zoom we reduce picture resolution // if the sensor can't cope with it zoomsel = mParameters.getInt(CameraParameters::KEY_ZOOM); if(!iscamcorder && prevzoom > zoomsel){ // Reducing zoom => increasing quality mParameters.set("picture-size", "2560x1920"); LOGV("User panning, increasing picture quality to max"); } prevzoom = zoomsel; while(!iscamcorder && zoomsel * 5 > 5 * multiplier && getParm("picture-size", reducesize) != NULL) { mParameters.set("picture-size", getParm("picture-size", reducesize)); multiplier = getParm("picture-size", picturesize); LOGV("Reducing picture quality; new multiplier: %d", multiplier); } level = zoomsel * (iscamcorder ? (multiplier*5)/11 : 5); // Update the parameters so initRaw doesn't use the wrong size later mParameters.getPictureSize(&mRawWidth, &mRawHeight); } } else { zoomSupported = false; LOGE("Failed to get maximum zoom value...setting max " "zoom to zero"); mMaxZoom = 0; } if (level >= mMaxZoom) { level = mMaxZoom; } LOGV("Set Zoom level: %d current: %d maximum: %d", level, mCurZoom, mMaxZoom); if (level == mCurZoom) { return; } if (level != -1) { LOGV("Final Zoom Level: %d", level); if (level >= 0 && level <= mMaxZoom) { native_set_parm(CAMERA_SET_PARM_ZOOM, sizeof(level), (void *)&level); mCurZoom = level; } } } void QualcommCameraHardware::setFlashMode() { led_mode_t value = (led_mode_t) getParm("flash-mode", flashmode); native_set_parm(CAMERA_SET_PARM_LED_MODE, sizeof(value), (void *)&value); } void QualcommCameraHardware::updateVideoLightMode(int starting) { led_mode_t value = (starting == 1 ? (led_mode_t) getParm("flash-mode", flashmode) : LED_MODE_OFF); //moto-specific flash #ifdef USE_BUGGY_QUALCOMM_ISP_FOR_VIDEOLIGHT native_set_parm(CAMERA_SET_PARM_LED_MODE, sizeof(value), (void *)&value); #else { FILE *fd = fopen("/sys/class/leds/cam-torch/brightness", "w"); if (fd) { if (fputs(value == LED_MODE_TORCH ? "255" : "0", fd) < 0) { LOGE("updateVideoLightMode: virtual file write failed !\n"); } else { LOGV("updateVideoLightMode '%s' successful", value == LED_MODE_TORCH ? "On" : "Off"); } fclose(fd); } else { LOGE("updateVideoLightMode: virtual file fopen() failed !\n"); } } #endif } QualcommCameraHardware::MemPool::MemPool(int buffer_size, int num_buffers, int frame_size, int frame_offset, const char *name) : mBufferSize(buffer_size), mNumBuffers(num_buffers), mFrameSize(frame_size), mFrameOffset(frame_offset), mBuffers(NULL), mName(name) { // empty } void QualcommCameraHardware::MemPool::completeInitialization() { // If we do not know how big the frame will be, we wait to allocate // the buffers describing the individual frames until we do know their // size. if (mFrameSize > 0) { mBuffers = new sp<MemoryBase>[mNumBuffers]; for (int i = 0; i < mNumBuffers; i++) { mBuffers[i] = new MemoryBase(mHeap, i * mBufferSize + mFrameOffset, mFrameSize); } } } QualcommCameraHardware::AshmemPool::AshmemPool(int buffer_size, int num_buffers, int frame_size, int frame_offset, const char *name) : QualcommCameraHardware::MemPool(buffer_size, num_buffers, frame_size, frame_offset, name) { LOGV("constructing MemPool %s backed by ashmem: " "%d frames @ %d uint8_ts, offset %d, " "buffer size %d", mName, num_buffers, frame_size, frame_offset, buffer_size); int page_mask = getpagesize() - 1; int ashmem_size = buffer_size * num_buffers; ashmem_size += page_mask; ashmem_size &= ~page_mask; mHeap = new MemoryHeapBase(ashmem_size); completeInitialization(); } static bool register_buf(int camfd, int size, int pmempreviewfd, uint32_t offset, uint8_t *buf, msm_pmem_t pmem_type, bool active, bool register_buffer = true); QualcommCameraHardware::PmemPool::PmemPool(const char *pmem_pool, int camera_control_fd, msm_pmem_t pmem_type, int buffer_size, int num_buffers, int frame_size, int frame_offset, const char *name) : QualcommCameraHardware::MemPool(buffer_size, num_buffers, frame_size, frame_offset, name), mPmemType(pmem_type), mCameraControlFd(camera_control_fd) { LOGV("constructing MemPool %s backed by pmem pool %s: " "%d frames @ %d bytes, offset %d, buffer size %d", mName, pmem_pool, num_buffers, frame_size, frame_offset, buffer_size); // Make a new mmap'ed heap that can be shared across processes. mAlignedSize = clp2(buffer_size * num_buffers); sp<MemoryHeapBase> masterHeap = new MemoryHeapBase(pmem_pool, mAlignedSize, 0); sp<MemoryHeapPmem> pmemHeap = new MemoryHeapPmem(masterHeap, 0); if (pmemHeap->getHeapID() >= 0) { pmemHeap->slap(); masterHeap.clear(); mHeap = pmemHeap; pmemHeap.clear(); mFd = mHeap->getHeapID(); if (::ioctl(mFd, PMEM_GET_SIZE, &mSize)) { LOGE("pmem pool %s ioctl(PMEM_GET_SIZE) error %s (%d)", pmem_pool, ::strerror(errno), errno); mHeap.clear(); return; } LOGV("pmem pool %s ioctl(PMEM_GET_SIZE) is %ld", pmem_pool, mSize.len); // Register buffers with the camera drivers. if (mPmemType != MSM_PMEM_OUTPUT2) { for (int cnt = 0; cnt < num_buffers; ++cnt) { register_buf(mCameraControlFd, buffer_size, mHeap->getHeapID(), 0, (uint8_t *)mHeap->base() + buffer_size * cnt, pmem_type, true); } } } else LOGE("pmem pool %s error: could not create master heap!", pmem_pool); completeInitialization(); } QualcommCameraHardware::PmemPool::~PmemPool() { LOGV("%s: %s E", __FUNCTION__, mName); // Unregister buffers with the camera drivers. if (mPmemType != MSM_PMEM_OUTPUT2) { for (int cnt = 0; cnt < mNumBuffers; ++cnt) { register_buf(mCameraControlFd, mBufferSize, mHeap->getHeapID(), 0, (uint8_t *)mHeap->base() + mBufferSize * cnt, mPmemType, true, false /* Unregister */); } } LOGV("destroying PmemPool %s: ", mName); LOGV("%s: %s X", __FUNCTION__, mName); } QualcommCameraHardware::MemPool::~MemPool() { LOGV("destroying MemPool %s", mName); if (mFrameSize > 0) delete [] mBuffers; mHeap.clear(); LOGV("destroying MemPool %s completed", mName); } QualcommCameraHardware::PreviewPmemPool::PreviewPmemPool( int control_fd, int buffer_size, int num_buffers, int frame_size, int frame_offset, const char *name) : QualcommCameraHardware::PmemPool("/dev/pmem_adsp", control_fd, MSM_PMEM_OUTPUT2, buffer_size, num_buffers, frame_size, frame_offset, name) { LOGV("QualcommCameraHardware::PreviewPmemPool::PreviewPmemPool"); if (initialized()) { //NOTE : SOME PREVIEWPMEMPOOL SPECIFIC CODE MAY BE ADDED } } QualcommCameraHardware::PreviewPmemPool::~PreviewPmemPool() { LOGV("destroying PreviewPmemPool"); if (initialized()) { LOGV("releasing PreviewPmemPool memory."); } } static bool register_buf(int camfd, int size, int pmempreviewfd, uint32_t offset, uint8_t *buf, msm_pmem_t pmem_type, bool active, bool register_buffer) { struct msm_pmem_info_t pmemBuf; pmemBuf.type = pmem_type; pmemBuf.fd = pmempreviewfd; pmemBuf.vaddr = buf; pmemBuf.y_off = 0; pmemBuf.active = active; if (pmem_type == MSM_PMEM_RAW_MAINIMG) pmemBuf.cbcr_off = 0; else pmemBuf.cbcr_off = ((size * 2 / 3) + 1) & ~1; LOGV("register_buf: camfd = %d, reg = %d buffer = %p", camfd, register_buffer, buf); if (ioctl(camfd, register_buffer ? MSM_CAM_IOCTL_REGISTER_PMEM : MSM_CAM_IOCTL_UNREGISTER_PMEM, &pmemBuf) < 0) { LOGE("register_buf: MSM_CAM_IOCTL_(UN)REGISTER_PMEM fd %d error %s", camfd, strerror(errno)); return false; } return true; } status_t QualcommCameraHardware::setGpsLocation(const CameraParameters& params) { LOGV("SetGpsLocation E:"); const char *StatusIn = params.get(CameraParameters::KEY_GPS_STATUS); LOGV("GPS STATUS ..................................................... %s", StatusIn); const char *latitude = params.get(CameraParameters::KEY_GPS_LATITUDE); if (latitude) { mParameters.set(CameraParameters::KEY_GPS_LATITUDE, latitude); } const char *latitudeRef = params.get(CameraParameters::KEY_GPS_LATITUDE_REF); if (latitudeRef) { mParameters.set(CameraParameters::KEY_GPS_LATITUDE_REF, latitudeRef); } const char *longitude = params.get(CameraParameters::KEY_GPS_LONGITUDE); if (longitude) { mParameters.set(CameraParameters::KEY_GPS_LONGITUDE, longitude); } const char *longitudeRef = params.get(CameraParameters::KEY_GPS_LONGITUDE_REF); if (longitudeRef) { mParameters.set(CameraParameters::KEY_GPS_LONGITUDE_REF, longitudeRef); } const char *altitudeRef = params.get(CameraParameters::KEY_GPS_ALTITUDE_REF); if (altitudeRef) { mParameters.set(CameraParameters::KEY_GPS_ALTITUDE_REF, altitudeRef); } const char *altitude = params.get(CameraParameters::KEY_GPS_ALTITUDE); if (altitude) { mParameters.set(CameraParameters::KEY_GPS_ALTITUDE, altitude); } const char *status = params.get(CameraParameters::KEY_GPS_STATUS); if (status) { mParameters.set(CameraParameters::KEY_GPS_STATUS, status); } const char *dateTime = params.get(CameraParameters::KEY_EXIF_DATETIME); if (dateTime) { mParameters.set(CameraParameters::KEY_EXIF_DATETIME, dateTime); } const char *timestamp = params.get(CameraParameters::KEY_GPS_TIMESTAMP); if (timestamp) { mParameters.set(CameraParameters::KEY_GPS_TIMESTAMP, timestamp); } const char *StatusOut = params.get(CameraParameters::KEY_GPS_STATUS); LOGV("GPS STATUS EXIT ................................................ %s", StatusOut); LOGV("SetGpsLocation X:"); return NO_ERROR; } status_t QualcommCameraHardware::MemPool::dump(int fd, const Vector<String16>& args) const { const size_t SIZE = 256; char buffer[SIZE]; String8 result; snprintf(buffer, 255, "QualcommCameraHardware::AshmemPool::dump\n"); result.append(buffer); if (mName) { snprintf(buffer, 255, "mem pool name (%s)\n", mName); result.append(buffer); } if (mHeap != 0) { snprintf(buffer, 255, "heap base(%p), size(%d), flags(%d), device(%s)\n", mHeap->getBase(), mHeap->getSize(), mHeap->getFlags(), mHeap->getDevice()); result.append(buffer); } snprintf(buffer, 255, "buffer size (%d), number of buffers (%d)," " frame size(%d), and frame offset(%d)\n", mBufferSize, mNumBuffers, mFrameSize, mFrameOffset); result.append(buffer); write(fd, result.string(), result.size()); return NO_ERROR; } static void receive_camframe_callback(struct msm_frame_t *frame) { if ( LOG_PREVIEW ) LOGV("receive_camframe_callback E"); sp<QualcommCameraHardware> obj = QualcommCameraHardware::getInstance(); if (obj != 0) { obj->receivePreviewFrame(frame); } if ( LOG_PREVIEW ) LOGV("receive_camframe_callback X"); } status_t QualcommCameraHardware::sendCommand(int32_t command, int32_t arg1, int32_t arg2) { LOGV("sendCommand: EX"); return BAD_VALUE; } }; // namespace android
30.696293
163
0.598102
[ "object", "vector" ]
93d895bf3a4494a6978a5d30e5f6d6615fd4c9b0
13,788
cpp
C++
ArcDelay/Write_Image.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
ArcDelay/Write_Image.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
ArcDelay/Write_Image.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Write_Image.cpp - write the arcview traffic image //********************************************************* #include "ArcDelay.hpp" #include "Vehicle_Shape.hpp" #define MAX_LANE 20 #define MAX_CELL 2000 #define MAX_TYPE 20 //--------------------------------------------------------- // Write_Image //--------------------------------------------------------- void ArcDelay::Write_Image (void) { int lane, nlanes, center, dir, end, period, nperiods, volume, type, ntype, start, right, left; int cell_size, half_cell, cell, cells, ncells, tod, rec, seconds, count, num_veh, spacing, space; int lane_cells; double ttime, density, speed, length, side, veh_width, offset, start_offset, share, vehicles, total, veh_len; char start_time [FIELD_BUFFER], end_time [FIELD_BUFFER], buffer [STRING_BUFFER]; bool version3_flag, offset_flag, distrib_flag, first; int cell_grid [MAX_LANE] [MAX_CELL]; int lane_use [MAX_LANE], veh_length [MAX_TYPE], veh_cells [MAX_TYPE]; double lane_veh [MAX_TYPE], lane_share [MAX_LANE] [MAX_TYPE]; XYZ_Point pt1, pt2; Use_Type use_type [MAX_TYPE]; Image_Data *image_ptr; Link_Data *link_ptr; Performance_Data *perf_ptr; Pocket_Data *pocket_ptr; Pocket_Index index_rec, *index_ptr; Link_Use_Data *use_ptr; Range_Data *range_ptr; Veh_Type_Data *veh_type_ptr; version3_flag = (delay_file->Dbase_Format () == VERSION3); offset_flag = (link_offset != 0.0); //---- process the vehicle type data ---- type = ntype = 1; veh_width = lane_width * 0.80; cell_size = 1000; for (veh_type_ptr = veh_type_data.First (); veh_type_ptr; veh_type_ptr = veh_type_data.Next ()) { type = veh_type_ptr->Type (); veh_length [type] = veh_type_ptr->Length (); use_type [type] = veh_type_ptr->Use (); if (type > ntype) ntype = type; if (veh_length [type] < cell_size) { cell_size = veh_length [type]; half_cell = (cell_size + 1) / 2; } } for (type = 1; type <= ntype; type++) { veh_cells [type] = (veh_length [type] + half_cell) / cell_size; } //---- process each time period ---- nperiods = time_period.Num_Ranges (); for (period = 1; period <= nperiods; period++) { range_ptr = time_period [period]; end = range_ptr->High () + 1; seconds = end - range_ptr->Low (); tod = Round ((range_ptr->Low () + end) / 2); str_cpy (start_time, sizeof (start_time), time_period.Format_Step (range_ptr->Low ())); str_cpy (end_time, sizeof (end_time), time_period.Format_Step (end)); //---- create a each shape file ---- first = true; for (image_ptr = (Image_Data *) image_data.First (); image_ptr; image_ptr = (Image_Data *) image_data.Next ()) { str_fmt (buffer, sizeof (buffer), "%s_%s.shp", image_ptr->name, time_period.Range_Label (period)); Print (1); if (!image_ptr->file->Open (buffer)) { File_Error ("Opening ArcView Traffic Image", image_ptr->file->Shape_Filename ()); } image_ptr->file->Write_Header (); if (first) { Show_Message ("Writing %s %s -- Link", image_ptr->file->File_Type (), end_time); first = false; } } Set_Progress (1000); //---- process each link ---- for (link_ptr = link_data.First_Key (); link_ptr; link_ptr = link_data.Next_Key ()) { Show_Progress (); length = UnRound (link_ptr->Length ()); //---- process each direction ---- for (dir = 0; dir < 2; dir++) { if (dir == 1) { perf_ptr = performance_data [link_ptr->BA_Dir ()]; } else { perf_ptr = performance_data [link_ptr->AB_Dir ()]; } if (perf_ptr == NULL || perf_ptr->Periods () == 0) continue; //---- save the link direction data ---- if (delay_file->LinkDir_Type () == LINK_SIGN) { if (dir == 1) { delay_file->Link (-link_ptr->Link ()); } else { delay_file->Link (link_ptr->Link ()); } } else { delay_file->Link (link_ptr->Link ()); if (delay_file->LinkDir_Type () == LINK_NODE) { delay_file->Dir ((dir == 1) ? link_ptr->Bnode () : link_ptr->Anode ()); } else { delay_file->Dir (dir); } } //---- calculate the performance ---- volume = perf_ptr->Volume (period); ttime = perf_ptr->TTime (period); speed = perf_ptr->Avg_Speed (period); density = perf_ptr->Density (period); //---- save the Version 3 fields ---- if (version3_flag) { delay_file->Time (end); delay_file->Lane (perf_ptr->Left () + 1); delay_file->Turn (0); delay_file->Volume (volume); delay_file->TTime (volume * ttime); delay_file->TTime2 (volume * ttime * ttime); delay_file->Vehicles ((int) (density + 0.5)); delay_file->Speed (density * speed); delay_file->Speed2 (density * speed * speed); } else { delay_file->Start_Time (start_time); delay_file->End_Time (end_time); delay_file->Volume (volume); delay_file->Enter (perf_ptr->Enter (period)); delay_file->Exit (perf_ptr->Exit (period)); delay_file->Speed (speed); delay_file->TTime (ttime); delay_file->Delay (perf_ptr->Delay (period)); delay_file->Density (density); delay_file->Max_Density (perf_ptr->Max_Density (period)); delay_file->Time_Ratio (perf_ptr->Time_Ratio (period)); delay_file->Avg_Queue (perf_ptr->Queue (period)); delay_file->Max_Queue (perf_ptr->Max_Queue (period)); delay_file->Cycle_Failure (perf_ptr->Failure (period)); delay_file->VMT (perf_ptr->Distance (period)); delay_file->VHT (perf_ptr->Time (period)); } delay_file->Num_Connect (0); //---- set the grid cells ---- memset (cell_grid, '\0', sizeof (cell_grid)); if (dir == 0) { start_offset = UnRound (link_ptr->Boffset ()); start = (link_ptr->Boffset () + half_cell) / cell_size + 1; ncells = (link_ptr->Length () - link_ptr->Aoffset () + half_cell) / cell_size - 1; } else { start_offset = UnRound (link_ptr->Aoffset ()); start = (link_ptr->Aoffset () + half_cell) / cell_size + 1; ncells = (link_ptr->Length () - link_ptr->Boffset () + half_cell) / cell_size - 1; } if (ncells <= start) ncells = start + 1; if (ncells >= MAX_CELL) ncells = MAX_CELL - 1; //---- initialize the pocket lanes and access restrictions ---- left = perf_ptr->Left (); right = perf_ptr->Right (); nlanes = left + perf_ptr->Thru () + right; right = nlanes - right; if (nlanes >= MAX_LANE) nlanes = MAX_LANE; for (lane=1; lane <= nlanes; lane++) { if (lane <= left || lane > right) { for (cell=start; cell <= ncells; cell++) { cell_grid [lane] [cell] = -1; } } lane_use [lane] = link_ptr->Use (); } //---- retrieve pocket lane information ---- index_rec.link_dir = perf_ptr->Link_Dir (); index_rec.pocket_id = 0; for (index_ptr = (Pocket_Index *) pocket_index.Get_GE (&index_rec); index_ptr != NULL && index_ptr->link_dir == index_rec.link_dir; index_ptr = (Pocket_Index *) pocket_index.Next_Key ()) { pocket_ptr = pocket_data.Get (index_ptr->pocket_id); if (pocket_ptr == NULL) continue; lane = pocket_ptr->Lane (); if ((lane > left && lane <= right) || lane > nlanes) continue; cells = pocket_ptr->Length () / cell_size; if (pocket_ptr->Type () == TURN_LANE) { cell = start; cells = MIN (start + cells - 1, ncells); } else if (pocket_ptr->Type () == MERGE_LANE) { cell = MAX (ncells - cells, start); cells = ncells; } else { cell = (pocket_ptr->Offset () + half_cell) / cell_size; cell = MAX (ncells - cell, start); cells = MIN (cell + cells, ncells); } for (; cell <= cells; cell++) { cell_grid [lane] [cell] = 0; } } //---- set lane use restrictions ---- for (rec = perf_ptr->TOD_List (); rec; rec = use_ptr->TOD_List ()) { use_ptr = link_use_data [rec]; if (use_ptr->Offset () > 0 || use_ptr->Length () > 0) continue; if (use_ptr->Start () <= tod && tod < use_ptr->End ()) { for (lane=use_ptr->Low_Lane (); lane <= use_ptr->High_Lane (); lane++) { if (lane > 0 && lane <= nlanes) { lane_use [lane] = use_ptr->Use (); } } } } //---- count cells per lane ---- for (lane = 1; lane <= nlanes; lane++) { count = 0; for (cell = 1; cell <= ncells; cell++) { if (cell_grid [lane] [cell] == 0) count++; } cell_grid [lane] [0] = count; } //---- find the center point ---- if (center_flag) { if (link_ptr->BA_Dir () == 0 || link_ptr->AB_Dir () == 0) { center = nlanes + 1; } else { center = 1; } } else { center = 1; } //---- allocate the vehicles types to lanes ---- memset (lane_share, '\0', sizeof (lane_share)); total = 0.0; for (type = 1; type <= ntype; type++) { count = type_share [type]; if (count == 0) continue; share = count; cells = 0; for (lane = 1; lane <= nlanes; lane++) { if (Use_Permission (lane_use [lane], use_type [type])) { cells += cell_grid [lane] [0]; } } if (cells == 0) continue; for (lane = 1; lane <= nlanes; lane++) { if (Use_Permission (lane_use [lane], use_type [type])) { density = share * cell_grid [lane] [0] / cells; lane_share [lane] [type] = density; total += density; } } } //---- normalize the vehicle shares ---- if (total > 0.0) { share = 1.0 / total; for (lane = 1; lane <= nlanes; lane++) { for (type = 1; type <= ntype; type++) { lane_share [lane] [type] *= share; } } } //---- process each attribute ---- for (image_ptr = (Image_Data *) image_data.First (); image_ptr; image_ptr = (Image_Data *) image_data.Next ()) { //---- check the attribute ---- switch (image_ptr->type) { case VOLUME_DATA: distrib_flag = true; vehicles = perf_ptr->Volume (period) * perf_ptr->TTime (period) / seconds; break; case DENSITY_DATA: distrib_flag = true; vehicles = perf_ptr->Density (period) * perf_ptr->Thru () * length / 1000.0; break; case MAX_DENSITY_DATA: distrib_flag = true; vehicles = perf_ptr->Max_Density (period) * perf_ptr->Thru () * length / 1000.0; break; case QUEUE_DATA: distrib_flag = false; vehicles = perf_ptr->Queue (period); break; case MAX_QUEUE_DATA: distrib_flag = false; vehicles = perf_ptr->Max_Queue (period); break; case FAILURE_DATA: distrib_flag = false; vehicles = perf_ptr->Failure (period) * 100.0 / seconds; //---- assume 100 second cycle ---- // vehicles = perf_ptr->Failure (period); break; } num_veh = (int) (vehicles + 0.9); if (num_veh <= 0) continue; //---- copy the data fields ---- image_ptr->file->Copy_Fields (delay_file); //---- assign the vehicles to lanes --- for (lane = 1; lane <= nlanes; lane++) { if (cell_grid [lane] [0] == 0) continue; //---- calculate the lane volume ---- total = 0.0; lane_cells = 0; memset (lane_veh, '\0', sizeof (lane_veh)); for (type = 1; type <= ntype; type++) { total += share = lane_share [lane] [type] * vehicles; lane_veh [type] = share; lane_cells += (int) (share * veh_cells [type] + 0.5); } volume = (int) (total + 0.5); if (volume == 0) continue; lane_veh [0] = total; side = (2 * lane - center) * lane_width / 2.0; //---- calculate vehicle spacing ---- if (distrib_flag) { if (lane_cells > 0) { spacing = cell_grid [lane] [0] / lane_cells; if (spacing > 2) spacing = 2; cells = lane_cells + (volume - 1) * spacing; density = (double) cells / cell_grid [lane] [0]; } else { spacing = 0; density = 1.0; } space = spacing; } //---- assign vehicle types to available cells ---- for (cell = start; cell <= ncells && volume > 0; cell++) { if (cell_grid [lane] [cell] != 0) continue; if (distrib_flag) { if (spacing > 0) { if (space < spacing) { space++; continue; } } if (random.Probability () > density) continue; space = 0; } total = 0.0; share = lane_veh [0] * random.Probability (); for (type = 1; type <= ntype; type++) { total += lane_veh [type]; if (share < total) break; } //---- draw the vehicle ---- if (shape_flag) { veh_len = UnRound (veh_length [type]); offset = (cell - 1) * UnRound (cell_size) + veh_len; if (dir == 0) { offset = length - offset; } Link_Shape (link_ptr, dir, &points, offset, veh_len, side); pt1 = *(points [points.Num_Points ()]); pt2 = *(points [1]); Vehicle_Shape (pt1, pt2, veh_width, &image_ptr->file->points); } else { offset = (cell - 1) * UnRound (cell_size) + 1.5; if (dir == 0) { offset = length - offset; } Link_Shape (link_ptr, dir, &points, offset, 0.0, side); image_ptr->file->points.Set (1, points [1]); } //---- save the vehicle image ---- if (!image_ptr->file->Write_Record ()) { Error ("Writing ArcView Traffic Image"); } volume--; cell += veh_cells [type] - 1; } } } } } End_Progress (); //---- close the files ---- for (image_ptr = (Image_Data *) image_data.First (); image_ptr; image_ptr = (Image_Data *) image_data.Next ()) { image_ptr->file->Close (); } } }
28.37037
114
0.562808
[ "shape" ]
93da2a85bdeab2b6fa0d50419a79d8609abe024a
5,861
cpp
C++
diamond-sycl/src/search/search.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
58
2020-08-06T18:53:44.000Z
2021-10-01T07:59:46.000Z
diamond-sycl/src/search/search.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
2
2020-12-04T12:35:02.000Z
2021-03-04T22:49:25.000Z
diamond-sycl/src/search/search.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
13
2020-08-19T13:44:18.000Z
2021-09-08T04:25:34.000Z
/**** DIAMOND protein aligner Copyright (C) 2013-2017 Benjamin Buchfink <buchfink@gmail.com> 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/>. ****/ #include "align_range.h" #include "hit_filter.h" #include "sse_dist.h" Trace_pt_buffer* Trace_pt_buffer::instance; TLS_PTR vector<Finger_print> *Seed_filter::vq_ptr, *Seed_filter::vs_ptr; TLS_PTR vector<Stage1_hit> *Seed_filter::hits_ptr; const unsigned tile_size[] = { 1024, 128 }; #define FAST_COMPARE2(q, s, stats, q_ref, s_ref, q_offset, s_offset, hits) if (q.match(s) >= config.min_identities) stats.inc(Statistics::TENTATIVE_MATCHES1) #define FAST_COMPARE(q, s, stats, q_ref, s_ref, q_offset, s_offset, hits) if (q.match(s) >= config.min_identities) hits.push_back(Stage1_hit(q_ref, q_offset, s_ref, s_offset)) void query_register_search(vector<Finger_print>::const_iterator q, vector<Finger_print>::const_iterator s, vector<Finger_print>::const_iterator s_end, const Range_ref &ref, vector<Stage1_hit> &hits, Statistics &stats) { const unsigned q_ref = unsigned(q - ref.q_begin); unsigned s_ref = unsigned(s - ref.s_begin); Finger_print q1 = *(q++), q2 = *(q++), q3 = *(q++), q4 = *(q++), q5 = *(q++), q6 = *q; const vector<Finger_print>::const_iterator end2 = s_end - (s_end - s) % 4; for (; s < end2; ) { Finger_print s1 = *(s++), s2 = *(s++), s3 = *(s++), s4 = *(s++); stats.inc(Statistics::SEED_HITS, 6 * 4); FAST_COMPARE(q1, s1, stats, q_ref, s_ref, 0, 0, hits); FAST_COMPARE(q2, s1, stats, q_ref, s_ref, 1, 0, hits); FAST_COMPARE(q3, s1, stats, q_ref, s_ref, 2, 0, hits); FAST_COMPARE(q4, s1, stats, q_ref, s_ref, 3, 0, hits); FAST_COMPARE(q5, s1, stats, q_ref, s_ref, 4, 0, hits); FAST_COMPARE(q6, s1, stats, q_ref, s_ref, 5, 0, hits); FAST_COMPARE(q1, s2, stats, q_ref, s_ref, 0, 1, hits); FAST_COMPARE(q2, s2, stats, q_ref, s_ref, 1, 1, hits); FAST_COMPARE(q3, s2, stats, q_ref, s_ref, 2, 1, hits); FAST_COMPARE(q4, s2, stats, q_ref, s_ref, 3, 1, hits); FAST_COMPARE(q5, s2, stats, q_ref, s_ref, 4, 1, hits); FAST_COMPARE(q6, s2, stats, q_ref, s_ref, 5, 1, hits); FAST_COMPARE(q1, s3, stats, q_ref, s_ref, 0, 2, hits); FAST_COMPARE(q2, s3, stats, q_ref, s_ref, 1, 2, hits); FAST_COMPARE(q3, s3, stats, q_ref, s_ref, 2, 2, hits); FAST_COMPARE(q4, s3, stats, q_ref, s_ref, 3, 2, hits); FAST_COMPARE(q5, s3, stats, q_ref, s_ref, 4, 2, hits); FAST_COMPARE(q6, s3, stats, q_ref, s_ref, 5, 2, hits); FAST_COMPARE(q1, s4, stats, q_ref, s_ref, 0, 3, hits); FAST_COMPARE(q2, s4, stats, q_ref, s_ref, 1, 3, hits); FAST_COMPARE(q3, s4, stats, q_ref, s_ref, 2, 3, hits); FAST_COMPARE(q4, s4, stats, q_ref, s_ref, 3, 3, hits); FAST_COMPARE(q5, s4, stats, q_ref, s_ref, 4, 3, hits); FAST_COMPARE(q6, s4, stats, q_ref, s_ref, 5, 3, hits); s_ref += 4; } for (; s < s_end; ++s) { stats.inc(Statistics::SEED_HITS, 6); FAST_COMPARE(q1, *s, stats, q_ref, s_ref, 0, 0, hits); FAST_COMPARE(q2, *s, stats, q_ref, s_ref, 1, 0, hits); FAST_COMPARE(q3, *s, stats, q_ref, s_ref, 2, 0, hits); FAST_COMPARE(q4, *s, stats, q_ref, s_ref, 3, 0, hits); FAST_COMPARE(q5, *s, stats, q_ref, s_ref, 4, 0, hits); FAST_COMPARE(q6, *s, stats, q_ref, s_ref, 5, 0, hits); ++s_ref; } } void inner_search(vector<Finger_print>::const_iterator q, vector<Finger_print>::const_iterator q_end, vector<Finger_print>::const_iterator s, vector<Finger_print>::const_iterator s_end, const Range_ref &ref, vector<Stage1_hit> &hits, Statistics &stats) { unsigned q_ref = unsigned(q - ref.q_begin); for (; q < q_end; ++q) { unsigned s_ref = unsigned(s - ref.s_begin); for (vector<Finger_print>::const_iterator s2 = s; s2 < s_end; ++s2) { stats.inc(Statistics::SEED_HITS); FAST_COMPARE((*q), *s2, stats, q_ref, s_ref, 0, 0, hits); ++s_ref; } ++q_ref; } } void Seed_filter::tiled_search(vector<Finger_print>::const_iterator q, vector<Finger_print>::const_iterator q_end, vector<Finger_print>::const_iterator s, vector<Finger_print>::const_iterator s_end, const Range_ref &ref, unsigned level) { switch (level) { case 0: case 1: for (; q < q_end; q += std::min(q_end - q, (ptrdiff_t)tile_size[level])) for (vector<Finger_print>::const_iterator s2 = s; s2 < s_end; s2 += std::min(s_end - s2, (ptrdiff_t)tile_size[level])) tiled_search(q, q + std::min(q_end - q, (ptrdiff_t)tile_size[level]), s2, s2 + std::min(s_end - s2, (ptrdiff_t)tile_size[level]), ref, level+1); break; case 2: for (; q < q_end; q += std::min(q_end-q,(ptrdiff_t)6)) if (q_end - q < 6) inner_search(q, q_end, s, s_end, ref, hits, stats); else query_register_search(q, s, s_end, ref, hits, stats); } } void load_fps(const sorted_list::const_iterator &i, vector<Finger_print> &v, const Sequence_set &seqs) { v.clear(); v.reserve(i.n); for (unsigned j = 0; j < i.n; ++j) v.push_back(Finger_print(seqs.data(i[j]))); } void Seed_filter::run(const sorted_list::const_iterator &q, const sorted_list::const_iterator &s) { hits.clear(); load_fps(q, vq, *query_seqs::data_); load_fps(s, vs, *ref_seqs::data_); tiled_search(vq.begin(), vq.end(), vs.begin(), vs.end(), Range_ref(vq.begin(), vs.begin()), 0); std::sort(hits.begin(), hits.end()); stats.inc(Statistics::TENTATIVE_MATCHES1, hits.size()); stage2_search(q, s, hits, stats, out, sid); }
40.42069
175
0.685378
[ "vector" ]
93dd0a98de52a081f9bd29ccd922f60fcffd9847
3,344
cpp
C++
main/Berimbau.cpp
gepid-upf/berimbau-esp32
843b4b6e340ecdac10a25ba5c03c3a4b9c41d87a
[ "MIT" ]
null
null
null
main/Berimbau.cpp
gepid-upf/berimbau-esp32
843b4b6e340ecdac10a25ba5c03c3a4b9c41d87a
[ "MIT" ]
null
null
null
main/Berimbau.cpp
gepid-upf/berimbau-esp32
843b4b6e340ecdac10a25ba5c03c3a4b9c41d87a
[ "MIT" ]
2
2019-07-03T15:59:03.000Z
2019-07-03T22:48:55.000Z
/** * @file Berimbau.cpp * * @author * Angelo Elias Dalzotto (150633@upf.br) * GEPID - Grupo de Pesquisa em Cultura Digital (gepid.upf.br) * Universidade de Passo Fundo (upf.br) * * @copyright * Copyright 2018 Angelo Elias Dalzotto * * @brief Berimbau is a digital toy to help kids with music learning. */ #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <Game.h> #include <Interface.h> #include <Audio.h> #include <Button.h> #include <Led.h> #include "moeda.h" // Just for testing #include "presa.h" #include "caxixi.h" #include "solta.h" // Members that are added to a static vector inside the class must be initialized here. static Button b_moeda(GPIO_NUM_39); static Button b_caxixi(GPIO_NUM_36); static Button b_presa(GPIO_NUM_35); static Button b_solta(GPIO_NUM_34); static Button b_blue(GPIO_NUM_32); static Button b_red(GPIO_NUM_23); static Button b_green(GPIO_NUM_22); static Button b_pink(GPIO_NUM_33); static Button b_left(GPIO_NUM_18); static Button b_right(GPIO_NUM_16); static Button b_up(GPIO_NUM_17); static Button b_down(GPIO_NUM_19); static Audio DRAM_ATTR a_moeda(moeda_data, moeda_length); static Audio DRAM_ATTR a_caxixi(caxixi_data, caxixi_length, false); static Audio DRAM_ATTR a_solta(solta_data, solta_length); static Audio DRAM_ATTR a_presa(presa_data, presa_length); static Led l_moeda(GPIO_NUM_4); static Led l_caxixi(GPIO_NUM_5); static Led l_presa(GPIO_NUM_0); static Led l_solta(GPIO_NUM_2); static const char* TAG = "MAIN"; extern "C" void app_main() { Interface::pre_init(); // Init the LCD and the Semaphore first for loading screen Interface::set_button(&b_blue, Interface::Direction::D_X); Interface::set_button(&b_red, Interface::Direction::D_O); Interface::set_button(&b_green, Interface::Direction::D_T); Interface::set_button(&b_pink, Interface::Direction::D_S); Interface::set_button(&b_right, Interface::Direction::D_RIGHT); Interface::set_button(&b_left, Interface::Direction::D_LEFT); Interface::set_button(&b_up, Interface::Direction::D_UP); Interface::set_button(&b_down, Interface::Direction::D_DOWN); Game::set_button(&b_moeda, Game::Instrument::MOEDA); Game::set_button(&b_caxixi, Game::Instrument::CAXIXI); Game::set_button(&b_presa, Game::Instrument::PRESA); Game::set_button(&b_solta, Game::Instrument::SOLTA); Game::set_audio(&a_moeda, Game::Instrument::MOEDA); Game::set_audio(&a_caxixi, Game::Instrument::CAXIXI); Game::set_audio(&a_presa, Game::Instrument::PRESA); Game::set_audio(&a_solta, Game::Instrument::SOLTA); Game::set_led(&l_moeda, Game::Instrument::MOEDA); Game::set_led(&l_caxixi, Game::Instrument::CAXIXI); Game::set_led(&l_presa, Game::Instrument::PRESA); Game::set_led(&l_solta, Game::Instrument::SOLTA); xTaskCreate(Interface::task, "Interface Task", 16384, nullptr, 6, nullptr); Audio::init(); // TimerG0 Timer0 interrupt 44.1KHz for Audio. xTaskCreate(Button::task, "Button_task", 2048, nullptr, 11, nullptr); // Updates the Button status. xTaskCreate(Game::task, "Game task", 8192, nullptr, 10, nullptr); xTaskCreate(Led::task, "LED Task", 2048, nullptr, 8, nullptr); // Sets and updates led status xTaskCreate(Game::urm_task, "URM Task", 2048, nullptr, 7, nullptr); // Sets the muffle cutoff based on URM }
35.574468
110
0.732057
[ "vector" ]
93dea6428f458ca013a5578cbe290351007070de
924
cpp
C++
Codechef/CodeChefEasy/Horses/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
Codechef/CodeChefEasy/Horses/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
Codechef/CodeChefEasy/Horses/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; vector <vector<int>> adjlist; #define sfor(n) for(int i=0;i<n;i++) #define mod 1000000007 #define pb push_back #define in insert #define mp make_pair #define inf mod #define bg begin() #define ed end() #define vi vector<int> #define imap map<int,int> #define smap map<string,int> #define set set<int> typedef long double ld; typedef long long int ll; ll max(ll x, ll y) { return x > y ? x : y; } ll min(ll x, ll y) { return x > y ? y : x; } int main() { ll t; cin>>t; while(t--) { ll n; cin>>n; ll a[n]; sfor(n) cin>>a[i]; ll dif=mod; for (int j = 0; j < n; ++j) { for (int i = j+1; i <n ; ++i) { ll d=a[j]-a[i]; if(d<0) d*=-1; dif=min(d,dif); } } cout<<dif<<endl; } return 0; }
18.117647
43
0.483766
[ "vector" ]
93e531d1cd30325a774ebd2c3102e036cf9ab57f
1,934
cc
C++
y2020/vision/viewer_replay.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
y2020/vision/viewer_replay.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
y2020/vision/viewer_replay.cc
AustinSchuh/971-Robot-Code
99abc66fd2d899c0bdab338dc6f57dc5def9be8d
[ "Apache-2.0" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
#include <opencv2/calib3d.hpp> #include <opencv2/features2d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc.hpp> #include "aos/events/logging/log_reader.h" #include "aos/events/simulated_event_loop.h" #include "aos/init.h" #include "y2020/vision/vision_generated.h" DEFINE_string(node, "pi1", "Node name to replay."); DEFINE_string(image_save_prefix, "/tmp/img", "Prefix to use for saving images from the logfile."); namespace frc971 { namespace vision { namespace { void ViewerMain(int argc, char *argv[]) { std::vector<std::string> unsorted_logfiles = aos::logger::FindLogs(argc, argv); // open logfiles aos::logger::LogReader reader(aos::logger::SortParts(unsorted_logfiles)); reader.Register(); const aos::Node *node = nullptr; if (aos::configuration::MultiNode(reader.configuration())) { node = aos::configuration::GetNode(reader.configuration(), FLAGS_node); } std::unique_ptr<aos::EventLoop> event_loop = reader.event_loop_factory()->MakeEventLoop("player", node); int image_count = 0; event_loop->MakeWatcher("/camera", [&image_count](const CameraImage &image) { cv::Mat image_mat(image.rows(), image.cols(), CV_8U); CHECK(image_mat.isContinuous()); const int number_pixels = image.rows() * image.cols(); for (int i = 0; i < number_pixels; ++i) { reinterpret_cast<uint8_t *>(image_mat.data)[i] = image.data()->data()[i * 2]; } cv::imshow("Display", image_mat); if (!FLAGS_image_save_prefix.empty()) { cv::imwrite("/tmp/img" + std::to_string(image_count++) + ".png", image_mat); } cv::waitKey(1); }); reader.event_loop_factory()->Run(); } } // namespace } // namespace vision } // namespace frc971 // Quick and lightweight grayscale viewer for images int main(int argc, char **argv) { aos::InitGoogle(&argc, &argv); frc971::vision::ViewerMain(argc, argv); }
30.698413
79
0.675284
[ "vector" ]
93e685914d7a2cef4115ddb78d6f39861939c400
267
cpp
C++
examples/appearance/multiplot/yyaxis/yyaxis_7.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-02T14:02:26.000Z
2020-10-28T07:00:44.000Z
examples/appearance/multiplot/yyaxis/yyaxis_7.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
null
null
null
examples/appearance/multiplot/yyaxis/yyaxis_7.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-01T16:22:07.000Z
2020-09-02T14:02:27.000Z
#include <matplot/matplot.h> int main() { using namespace matplot; std::vector<int> y1 = {1,10,7,6,7,7,4,6,1,6}; std::vector<int> y2 = {70,20,90,10,90,70,20,10,100,50}; plot(y1); hold(on); plot(y2)->use_y2(true); wait(); return 0; }
19.071429
59
0.558052
[ "vector" ]
93eec78df4ab0b90d2ddbaf2c9ef66f878e6d43d
626
cpp
C++
src/Main.cpp
Sanatramesh/CG-Texture-mapping
1206ca6cb20d6919f78558e54c0b467890d29df5
[ "MIT" ]
null
null
null
src/Main.cpp
Sanatramesh/CG-Texture-mapping
1206ca6cb20d6919f78558e54c0b467890d29df5
[ "MIT" ]
null
null
null
src/Main.cpp
Sanatramesh/CG-Texture-mapping
1206ca6cb20d6919f78558e54c0b467890d29df5
[ "MIT" ]
null
null
null
#include <iostream> #include "model.h" #include "view.h" #include "controller.h" using namespace std; View view; Model model, model1; /* * main: initialize glut window */ int main(int argc,char* argv[]) { if (argc != 3){ std::cout<<"Usage: ./assignment3 <ply1 filename> <ply2 filename>"<<std::endl; exit(-1); } Controller controller; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); glutInitWindowSize(400, 400); //Set the window size glutInitWindowPosition(50,50); //Create the window glutCreateWindow("Assignment 3: Texture Mapping"); controller.run(argv); return 0; }
20.193548
79
0.70607
[ "model" ]
93f08e47ac1889977d0736c90adab1de2c7ab180
8,490
cpp
C++
simulations/Elastic Wave Propagation in Plate/WaveDispersionAndPropagation.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
2
2021-08-06T19:40:34.000Z
2021-09-06T23:07:47.000Z
simulations/Elastic Wave Propagation in Plate/WaveDispersionAndPropagation.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
simulations/Elastic Wave Propagation in Plate/WaveDispersionAndPropagation.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
// // WaveDispersionAndPropagation.cpp // Relation-Based Simulator (RBS) // // Created by Ali Jenabidehkordi on 10.10.2020. // Copyright © 2020 Ali Jenabidehkordi. All rights reserved. // #include "coordinate_system/grid.h" #include "configuration/Part.h" #include "relations/peridynamic.h" #include <iostream> #include <time.h> using namespace rbs; using namespace rbs::configuration; using namespace std; /** * @brief Presents the construction process of work done by Nishawal et.al. on their paper: * "Simulation of Elastic Wave Propagation using Cellular Automata and Peridynamics, and Comparison with Experiments." * @details: Find more information and step by step description on https://github.com/alijenabi/RelationBasedSimulator/examples/Elastic%20Wave%20Propagation%20in%20Plate/Elastic%20Wave%20Propagation%20in%20Plate.md * @note Examples are suitable for clang compiler. Running them suing other compilers may require modification. * @note Examples are suitable for mac file-system. Running them on other operating systems may require modification. * @return EXIT_SUCCESS if all examples are build successfuly, EXIT_FAILURE otherwise. */ int main() { const std::string path = "/<An existing folder path>/"; auto& logger = report::Logger::centre(); /* - Uncomment the code below if you like to log the simulation.- */ // logger.setFileLevel(logger.Debug, path + "logs/", "Debug"); // logger.setFileLevel(logger.Timing, path + "logs/", "Timing"); // logger.setFileLevel(logger.Process, path + "logs/", "Process"); // logger.setFileLevel(logger.Warning, path + "logs/", "Warning"); using BC = report::Logger::Broadcast; logger.log(BC::Block, "Problem definition"); const double dencity = 1300; // kg / m^3 const double youngsModulus = 3.85e9; // GPa const double poissonRasio = 1. / 3.; const auto plateHeight = 0.5; // 0.5 m const auto plateWidth = 1.0; // 1.0 m const auto plateThickness = 0.006655; // 6.655 mm const auto horizonRasio = 3.; // m = 3 const auto gridSpacing = std::min({plateWidth / 1024, plateHeight / 512}); const auto horizonRadius = horizonRasio * gridSpacing; logger.log(BC::Process, "Initiating the plate's Part.\n"); using CS = coordinate_system::CoordinateSystem; auto platePart = Part("Plate", CS::Global().appendLocal(CS::Cartesian)); logger.log(BC::Process, "Creating the part geometry."); { const auto plateShape = geometry::Combined::Cuboid({-plateWidth / 2, -plateHeight, -plateThickness / 2}, space::vec3{plateWidth, 0, 0}, space::vec3{0, plateHeight, 0}, space::vec3{0, 0, plateThickness}); platePart.setGeometry(plateShape); } logger.log(BC::Block, "Meshing the part's coordinate system."); { const auto distanceVector = gridSpacing * space::consts::one3D; const auto startPoint = space::Point<3>{-plateWidth / 2, -plateHeight, -plateThickness / 2} + distanceVector / 2; const auto endPoint = space::Point<3>{plateWidth / 2, 0, plateThickness / 2} - distanceVector / 2; coordinate_system::grid::cartesian::uniformDirectional(startPoint, endPoint,distanceVector, platePart.local().axes()); platePart.local().axes()[2] = std::set<double>{0}; } logger.log(BC::Block, "Including the points to the coordiante system."); logger.log(BC::Process, "Including the grid points that are inside the part shape.\n"); { const auto& plateShape = platePart.geometry(); platePart.local().include([&plateShape](const auto& localPoint) { return plateShape.pointStatus(localPoint) == geometry::Inside; }); } logger.log(BC::Block, "Neighborhood search"); platePart.initiateNeighborhoods(); logger.log(BC::Process, "Adding the volume and the density."); const double gridVolume = pow(gridSpacing, 2) * plateThickness; const auto& neighborhoods = platePart.neighborhoods(); std::for_each(neighborhoods.begin(), neighborhoods.end(), [gridVolume, dencity](const Part::NeighborhoodPtr& neighborhood) { using Property = relations::peridynamic::Property; auto& centre = *neighborhood->centre(); centre.at(Property::Volume).setValue(gridVolume); centre.at(Property::Density).setValue(dencity); }); platePart.searchInnerNeighbors(horizonRadius); /* - Uncomment the code below to check the configuration and neighborhood search checkpoints. - */ // logger.log(BC::Block, "Exporting to VTK"); // logger.log(BC::ProcessStart, ""); // platePart.exportConfiguration(path + "vtks/"); // platePart.exportCheckpointNeighborhoods(path + "vtks/"); // logger.log(BC::ProcessEnd, ""); logger.log(BC::Block, "Defining the relations."); const auto maxForcePerNode = 20.7e3 / ( plateThickness * gridSpacing ); const auto boundaryConditioner = [gridSpacing, maxForcePerNode](const double time, configuration::Node& node) { using Property = relations::peridynamic::Property; auto& postion = node.initialPosition().value<space::Point<3> >().positionVector(); if (-gridSpacing <= postion[0] && postion[0] <= gridSpacing && -gridSpacing * 2.1 < postion[1]) { if (time <= 10e-6) { node.at(Property::Force) = -space::vec3{0, time * maxForcePerNode / 10e-6, 0}; } else if(time <= 20e-6) { node.at(Property::Force) = -space::vec3{0, maxForcePerNode - (time - 10e-6) * maxForcePerNode / 10e-6, 0}; } else { node.at(Property::Force) = space::consts::o3D; } } else { if (node.has(Property::Force)) node.at(Property::Force) = space::consts::o3D; } }; auto load = relations::peridynamic::BoundaryDomain(boundaryConditioner, platePart); auto timeIntegration = relations::peridynamic::time_integration::VelocityVerletAlgorithm(platePart); const double bulkModulus = youngsModulus / (3 * (1 - 2 * poissonRasio)); const double materialConstant = 12 * bulkModulus / (M_PI * pow(horizonRadius, 3) * plateThickness); logger.log(BC::Process, "Bulk Modulus = " + to_string(bulkModulus)); logger.log(BC::Process, "Material Constant = " + to_string(materialConstant)); auto platePDRelation = relations::peridynamic::BondBased::Elastic(materialConstant, gridSpacing, horizonRadius, platePart, false); using P = relations::peridynamic::Property; using On = relations::peridynamic::Exporter::Target; const std::set properties = {P::Displacement, P::Velocity, P::Acceleration, P::Force}; auto plateExporterCC = relations::peridynamic::Exporter(properties, On::CurrentConfiguration, platePart, path + "vtks/", "PlatePartOnCurrentConfig"); plateExporterCC.setCondition([](const double, const size_t timeStep) { return timeStep % 10 == 0; }); const auto exportationCondition = [](const double, const size_t timeStep) { return timeStep == 857; }; auto plateExporterAt107ms = relations::peridynamic::Exporter(properties, On::InitialConfiguration, platePart, path + "vtks/", "plateExporterAt107ms"); auto plateExporterAt107msCurrent = relations::peridynamic::Exporter(properties, On::InitialConfiguration, platePart, path + "vtks/", "plateExporterAt107msCurrent"); plateExporterAt107ms.setCondition(exportationCondition); plateExporterAt107msCurrent.setCondition(exportationCondition); const auto maxSondSpeed = sqrt(youngsModulus / dencity); const auto maxTimeSpan = std::min({0.125e-6, gridSpacing / maxSondSpeed * 0.8}); // .5 Safty Factor. logger.log(BC::Process, "Maximum Sound Speed = " + to_string(maxSondSpeed)); logger.log(BC::Process, "Maximum Time Span = " + report::date_time::duration::formated(maxTimeSpan, 3)); auto& analysis = Analyse::current(); analysis.setTimeSpan(maxTimeSpan); analysis.setMaxTime(308e-6); analysis.appendRelation(load); analysis.appendRelation(platePDRelation); analysis.appendRelation(timeIntegration); analysis.appendRelation(plateExporterCC); analysis.appendRelation(plateExporterAt107ms); analysis.appendRelation(plateExporterAt107msCurrent); return analysis.run(); return EXIT_SUCCESS; }
49.075145
214
0.674794
[ "geometry", "shape" ]
93f6234dc8a681cc9f6c092d20b6894f22208e7c
1,881
hh
C++
inc/Vector.hh
bartosz-bogulas/zad3
5e3dbf263b4f781d1820a02b937ebfeb62ce4e6f
[ "MIT" ]
null
null
null
inc/Vector.hh
bartosz-bogulas/zad3
5e3dbf263b4f781d1820a02b937ebfeb62ce4e6f
[ "MIT" ]
1
2020-04-19T21:40:09.000Z
2020-04-21T16:31:24.000Z
inc/Vector.hh
bartosz-bogulas/zad3
5e3dbf263b4f781d1820a02b937ebfeb62ce4e6f
[ "MIT" ]
null
null
null
#ifndef ZAD3_VECTOR_HH #define ZAD3_VECTOR_HH #include <iostream> #include "size.hh" /** * Klasa przedstawiajaca wektor */ class Vector { public: /** * Tworzy wektor z podanych skalarow * @param x * @param y * @param z */ Vector(double x, double y, double z); /** * Tworzy wektor zerowy */ Vector(); /** * Wylicza iloczyn skalarny * @param vector * @return wartosc */ double dot(const Vector& vector) const; /** * Wylicza dlugosc wektora * @return wartosc */ double length() const; /** * Operator dodawania wektorow * @param vector * @return wektor */ Vector operator+(const Vector& vector) const; /** * Operator odejmowania wektorow * @param vector * @return wektor */ Vector operator-(const Vector& vector) const; /** * Operator mnozenia wektora przez skalar * @param v * @return wektor */ Vector operator*(double v) const; /** * Operator dzielenia wektora przez skalar * @param v * @return wektor */ Vector operator/(double v) const; /** * Operator indeksowania wektora * @param i * @return skalar na i-tej pozycji w wektorze */ double operator()(int i) const; /** * Operator indeksowania wektora * @param i * @return referencje na skalar na i-tej pozycji w wektorze */ double& operator()(int i); /** * Przeladowany operator wejscia * @param in * @param vector */ friend std::istream& operator>>(std::istream& in, Vector& vector); /** * Przeladowany operator wyjscia * @param out * @param vector */ friend std::ostream& operator<<(std::ostream& out, const Vector& vector); private: double values[SIZE]; }; #endif //ZAD3_VECTOR_HH
18.81
77
0.577352
[ "vector" ]
93fb6c4e55df30cb0a3ace9639d85f0c46d5d6e2
601
cpp
C++
leet/ac/0692.top-k-frequent-words.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
leet/ac/0692.top-k-frequent-words.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
leet/ac/0692.top-k-frequent-words.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
class Solution { public: vector<string> topKFrequent(vector<string> &words, int k) { vector<string> ans; unordered_multiset<string> ms(words.begin(), words.end()); vector<set<string>> vs(words.size(), set<string>()); for (auto i = ms.begin(); i != ms.end(); i++) { vs[ms.count(*i)].insert(*i); } for (int i = words.size() - 1; i >= 0 && k > 0; i--) { for (auto j = vs[i].begin(); j != vs[i].end() && k > 0; j++) { ans.push_back(*j); k--; } } return ans; } };
31.631579
74
0.445923
[ "vector" ]
9e09d8a8d9103c1eff73bbfd24fae586cc2b894c
1,868
cpp
C++
particle.cpp
Penaz91/firework_demo
4ec185583d1b3db2b147fb25557effdf3e49f66e
[ "Unlicense" ]
null
null
null
particle.cpp
Penaz91/firework_demo
4ec185583d1b3db2b147fb25557effdf3e49f66e
[ "Unlicense" ]
null
null
null
particle.cpp
Penaz91/firework_demo
4ec185583d1b3db2b147fb25557effdf3e49f66e
[ "Unlicense" ]
null
null
null
#include "includes/particle.hpp" #include <iostream> #include <cmath> particle::particle(const sf::Vector2f& position, const sf::Vector2f& destination, const sf::Color& color, const float& radius, const float& fuseTimer): bExtinguished(false), vPosition(position), fLifetime(0.0f), fFuse(fuseTimer), cColor(color), vDestination(destination), vStartPosition(position){ shape = sf::CircleShape(radius); shape.setFillColor(cColor); shape.setPosition(vPosition); fDescentSpeed = (rand() / (float)RAND_MAX) * 50 + 10; //std::cout << "Particle created at ("<< vStartPosition.x << ", " << vStartPosition.y << ") directed towards ("<< vDestination.x << ", " << vDestination.y << ")" << std::endl; } void particle::draw(sf::RenderTarget &target, sf::RenderStates states) const{ if (!bExtinguished){ target.draw(shape, states); } } void particle::update(sf::Time timeElapsed){ fLifetime += timeElapsed.asSeconds(); if (fLifetime >= fFuse + 2.0f){ // Extinguished bExtinguished = true; }else if (fLifetime >= fFuse){ // Extinguishing float factor = 1 - std::pow((1 - ((fLifetime - fFuse) / 2.0f)), 2.0f); sf::Uint8 red = cColor.r + ((- cColor.r) * factor); sf::Uint8 green = cColor.g + ((-cColor.g) * factor); sf::Uint8 blue = cColor.b + ((-cColor.b) * factor); shape.setFillColor(sf::Color(red, green, blue)); float xDisplacement = (rand() / (float)RAND_MAX) * 27 - 13; vPosition += sf::Vector2f(xDisplacement, fDescentSpeed) * timeElapsed.asSeconds(); }else{ float factor = 1 - std::pow((1 - (fLifetime / fFuse)), 2.0f); vPosition = vStartPosition + (vDestination - vStartPosition) * factor; } shape.setPosition(vPosition); //std::cout << "Moving to (" << vPosition.x << ", " << vPosition.y << ")" << std::endl; }
46.7
297
0.626874
[ "shape" ]
9e176871e6f9b07871e29d19b2cff2b3952a0889
13,665
cpp
C++
SRC/Potential/ThreeBody/ThreeBody.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Potential/ThreeBody/ThreeBody.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Potential/ThreeBody/ThreeBody.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// ThreeBody.cpp: implementation for the ThreeBody class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details ////////////////////////////////////////////////////////////////////// #include "./ThreeBody.h" namespace Potential { namespace ThreeBody { ////////////////////////////////////////////////////////////////////// // Class LocalState ////////////////////////////////////////////////////////////////////// LocalState::LocalState() {} LocalState::~LocalState() {} Element::LocalState * LocalState::Clone() const { return new LocalState(*this); } LocalState::LocalState(Set::Manifold::Point *rhs_e0, Set::Manifold::Point *rhs_e1, Set::Manifold::Point *rhs_e2) : e0(rhs_e0), e1(rhs_e1), e2(rhs_e2) {} LocalState::LocalState(const set<Set::Manifold::Point *> &N) { set<Set::Manifold::Point *>::const_iterator pN = N.begin(); e0 = *pN; pN++; e1 = *pN; pN++; e2 = *pN; } LocalState::LocalState(const LocalState &rhs) : e0(rhs.e0), e1(rhs.e1), e2(rhs.e2) {} LocalState & LocalState::operator = (const LocalState &rhs) { if (this == &rhs) return *this; e0 = rhs.e0; e1 = rhs.e1; e2 = rhs.e2; return *this; } void LocalState::operator ++ () {} set<Set::Manifold::Point *> LocalState::GetNodes() const { set<Set::Manifold::Point *> Nodes; Nodes.insert(e0); Nodes.insert(e1); Nodes.insert(e2); return Nodes; } set<pair<Set::Manifold::Point *, Set::Manifold::Point *> > LocalState::GetNodePairs() const { set<pair<Set::Manifold::Point *, Set::Manifold::Point *> > NodePairs; NodePairs.insert(make_pair(e0,e0)); NodePairs.insert(make_pair(e0,e1)); NodePairs.insert(make_pair(e0,e2)); NodePairs.insert(make_pair(e1,e1)); NodePairs.insert(make_pair(e1,e0)); NodePairs.insert(make_pair(e1,e2)); NodePairs.insert(make_pair(e2,e2)); NodePairs.insert(make_pair(e2,e0)); NodePairs.insert(make_pair(e2,e1)); return NodePairs; } ////////////////////////////////////////////////////////////////////// // Class Energy<0> ////////////////////////////////////////////////////////////////////// Energy<0>::Energy() {} Energy<0>::~Energy() {} Element::Energy<0> * Energy<0>::Clone() const { return new Energy<0>(*this); } Element::LocalState * Energy<0>::GetLocalState() const { return LS; } Energy<0>::Energy( LocalState *rhs_LS, Potential::Angular::Energy<0> *rhs_V) : LS(rhs_LS), V(rhs_V) {} Energy<0>::Energy(const Energy<0> &rhs) : V(rhs.V){} const Energy<0> & Energy<0>::operator = (const Energy<0> &rhs) { if (this == &rhs) return *this; LS = rhs.LS; V = rhs.V; return *this; } double Energy<0>::operator () (const map<Set::Manifold::Point *, Set::VectorSpace::Vector> &x0) const { typedef Set::VectorSpace::Vector vector_type; typedef map<Set::Manifold::Point *, vector_type> map_type; map_type x = x0; Set::Manifold::Point *e0 = LS->e0; Set::Manifold::Point *e1 = LS->e1; Set::Manifold::Point *e2 = LS->e2; vector_type dx1 = x[e1] - x[e0]; vector_type dx2 = x[e2] - x[e0]; double r1 = Norm(dx1); double r2 = Norm(dx2); vector_type n1 = dx1/r1; vector_type n2 = dx2/r2; double c = n1(n2); return (*V)(c); } ////////////////////////////////////////////////////////////////////// // Class Energy<1> ////////////////////////////////////////////////////////////////////// Energy<1>::Energy() {} Energy<1>::~Energy() {} Element::Energy<1> * Energy<1>::Clone() const { return new Energy<1>(*this); } Element::LocalState * Energy<1>::GetLocalState() const { return LS; } Energy<1>::Energy( LocalState *rhs_LS, Potential::Angular::Energy<1> *rhs_DV) : LS(rhs_LS), DV(rhs_DV) {} Energy<1>::Energy(const Energy<1> &rhs) : DV(rhs.DV){} const Energy<1> & Energy<1>::operator = (const Energy<1> &rhs) { if (this == &rhs) return *this; LS = rhs.LS; DV = rhs.DV; return *this; } map<Set::Manifold::Point *, Set::VectorSpace::Vector> Energy<1>::operator () (const map<Set::Manifold::Point *, Set::VectorSpace::Vector> &x0) const { typedef Set::VectorSpace::Vector vector_type; typedef map<Set::Manifold::Point *, vector_type> map_type; map_type x = x0; Set::Manifold::Point *e0 = LS->e0; Set::Manifold::Point *e1 = LS->e1; Set::Manifold::Point *e2 = LS->e2; vector_type dx1 = x[e1] - x[e0]; vector_type dx2 = x[e2] - x[e0]; double r1 = Norm(dx1); double r2 = Norm(dx2); vector_type n1 = dx1/r1; vector_type n2 = dx2/r2; double c = n1(n2); vector_type dc1 = (n2 - c*n1)/r1; vector_type dc2 = (n1 - c*n2)/r2; vector_type dc0 = -(dc1 + dc2); double dv = (*DV)(c); map_type DE; DE.insert(map_type::value_type(e0,dv*dc0)); DE.insert(map_type::value_type(e1,dv*dc1)); DE.insert(map_type::value_type(e2,dv*dc2)); return DE; } ////////////////////////////////////////////////////////////////////// // Class Energy<2> ////////////////////////////////////////////////////////////////////// Energy<2>::Energy() {} Energy<2>::~Energy() {} Element::Energy<2> * Energy<2>::Clone() const { return new Energy<2>(*this); } Element::LocalState * Energy<2>::GetLocalState() const { return LS; } Energy<2>::Energy( LocalState *rhs_LS, Potential::Angular::Energy<1> *rhs_DV, Potential::Angular::Energy<2> *rhs_DDV) : LS(rhs_LS), DV(rhs_DV), DDV(rhs_DDV){} Energy<2>::Energy(const Energy<2> &rhs) : DV(rhs.DV), DDV(rhs.DDV){} const Energy<2> & Energy<2>::operator = (const Energy<2> &rhs) { if (this == &rhs) return *this; LS = rhs.LS; DV = rhs.DV; DDV = rhs.DDV; return *this; } map<pair<Set::Manifold::Point *, Set::Manifold::Point *>, Set::VectorSpace::Hom> Energy<2>::operator () (const map<Set::Manifold::Point *, Set::VectorSpace::Vector> &x0) const { typedef Set::VectorSpace::Vector vector_type; typedef Set::VectorSpace::Hom hom_type; typedef map<Set::Manifold::Point *, vector_type> map_type; typedef map<pair<Set::Manifold::Point *, Set::Manifold::Point *>, hom_type> dmap_type; map_type x = x0; Set::Manifold::Point *e0 = LS->e0; Set::Manifold::Point *e1 = LS->e1; Set::Manifold::Point *e2 = LS->e2; vector_type dx1 = x[e1] - x[e0]; vector_type dx2 = x[e2] - x[e0]; double r1 = Norm(dx1); double r2 = Norm(dx2); vector_type n1 = dx1/r1; vector_type n2 = dx2/r2; double c = n1(n2), c3 = 3.0*c; vector_type dc1 = (n2 - c*n1)/r1; vector_type dc2 = (n1 - c*n2)/r2; vector_type dc0 = -(dc1 + dc2); Set::VectorSpace::Hom n11 = Dyadic(n1,n1); Set::VectorSpace::Hom n12 = Dyadic(n1,n2); Set::VectorSpace::Hom n21 = Dyadic(n2,n1); Set::VectorSpace::Hom n22 = Dyadic(n2,n2); double r11 = r1*r1, r12 = r1*r2, r21 = r12, r22 = r2*r2; Set::VectorSpace::Hom ddc11 = c3*n11 - n12 - n21; ddc11[0][0] -= c; ddc11[1][1] -= c; ddc11[2][2] -= c; ddc11 /= r11; Set::VectorSpace::Hom ddc22 = c3*n22 - n21 - n12; ddc22[0][0] -= c; ddc22[1][1] -= c; ddc22[2][2] -= c; ddc22 /= r22; Set::VectorSpace::Hom ddc12 = c*n12 - n11 - n22; ddc12[0][0] += 1.0; ddc12[1][1] += 1.0; ddc12[2][2] += 1.0; ddc12 /= r12; Set::VectorSpace::Hom ddc21 = c*n21 - n22 - n11; ddc21[0][0] += 1.0; ddc21[1][1] += 1.0; ddc21[2][2] += 1.0; ddc21 /= r21; Set::VectorSpace::Hom ddc01 = -(ddc11 + ddc21); Set::VectorSpace::Hom ddc10 = -(ddc11 + ddc12); Set::VectorSpace::Hom ddc02 = -(ddc12 + ddc22); Set::VectorSpace::Hom ddc20 = -(ddc21 + ddc22); Set::VectorSpace::Hom ddc00 = ddc11 + ddc21 + ddc12 + ddc22; double dv = (*DV)(c), ddv = (*DDV)(c); dmap_type DDE; DDE.insert(dmap_type::value_type(make_pair(e0,e0),ddv*Dyadic(dc0,dc0)+dv*ddc00)); DDE.insert(dmap_type::value_type(make_pair(e1,e0),ddv*Dyadic(dc0,dc1)+dv*ddc01)); DDE.insert(dmap_type::value_type(make_pair(e2,e0),ddv*Dyadic(dc0,dc2)+dv*ddc02)); DDE.insert(dmap_type::value_type(make_pair(e1,e1),ddv*Dyadic(dc1,dc1)+dv*ddc11)); DDE.insert(dmap_type::value_type(make_pair(e0,e1),ddv*Dyadic(dc1,dc0)+dv*ddc10)); DDE.insert(dmap_type::value_type(make_pair(e2,e1),ddv*Dyadic(dc1,dc2)+dv*ddc12)); DDE.insert(dmap_type::value_type(make_pair(e2,e2),ddv*Dyadic(dc2,dc2)+dv*ddc22)); DDE.insert(dmap_type::value_type(make_pair(e0,e2),ddv*Dyadic(dc2,dc0)+dv*ddc20)); DDE.insert(dmap_type::value_type(make_pair(e1,e2),ddv*Dyadic(dc2,dc1)+dv*ddc21)); return DDE; } ////////////////////////////////////////////////////////////////////// // Class Jet<0> ////////////////////////////////////////////////////////////////////// Jet<0>::Jet() {} Jet<0>::~Jet() {} Element::Jet<0> * Jet<0>::Clone() const { return new Jet<0>(*this); } Element::LocalState * Jet<0>::GetLocalState() const { return LS; } Jet<0>::Jet( LocalState *rhs_LS, Potential::Angular::Jet<0> *rhs_J) : LS(rhs_LS), J(rhs_J) {} Jet<0>::Jet(const Jet<0> &rhs) : LS(rhs.LS), J(rhs.J) {} Jet<0> & Jet<0>::operator = (const Jet<0> &rhs) { if (this == &rhs) return *this; LS = rhs.LS; J = rhs.J; return *this; } pair<double, map<Set::Manifold::Point *, Set::VectorSpace::Vector> > Jet<0>::operator () (const map<Set::Manifold::Point *, Set::VectorSpace::Vector> &x0) const { typedef Set::VectorSpace::Vector vector_type; typedef map<Set::Manifold::Point *, vector_type> map_type; map_type x = x0; Set::Manifold::Point *e0 = LS->e0; Set::Manifold::Point *e1 = LS->e1; Set::Manifold::Point *e2 = LS->e2; vector_type dx1 = x[e1] - x[e0]; vector_type dx2 = x[e2] - x[e0]; double r1 = Norm(dx1); double r2 = Norm(dx2); vector_type n1 = dx1/r1; vector_type n2 = dx2/r2; double c = n1(n2); vector_type dc1 = (n2 - c*n1)/r1; vector_type dc2 = (n1 - c*n2)/r2; vector_type dc0 = -(dc1 + dc2); pair<double,double> j = (*J)(c); double dv = j.second; map_type DE; DE.insert(map_type::value_type(e0,dv*dc0)); DE.insert(map_type::value_type(e1,dv*dc1)); DE.insert(map_type::value_type(e2,dv*dc2)); return make_pair(j.first,DE); } ////////////////////////////////////////////////////////////////////// // Class Jet<1> ////////////////////////////////////////////////////////////////////// Jet<1>::Jet() {} Jet<1>::~Jet() {} Element::Jet<1> * Jet<1>::Clone() const { return new Jet<1>(*this); } Element::LocalState * Jet<1>::GetLocalState() const { return LS; } Jet<1>::Jet( LocalState *rhs_LS, Potential::Angular::Jet<1> *rhs_DJ) : LS(rhs_LS), DJ(rhs_DJ) {} Jet<1>::Jet(const Jet<1> &rhs) : LS(rhs.LS), DJ(rhs.DJ) {} Jet<1> & Jet<1>::operator = (const Jet<1> &rhs) { if (this == &rhs) return *this; LS = rhs.LS; DJ = rhs.DJ; return *this; } pair< map<Set::Manifold::Point *, Set::VectorSpace::Vector>, map<pair<Set::Manifold::Point *, Set::Manifold::Point *>, Set::VectorSpace::Hom> > Jet<1>::operator () (const map<Set::Manifold::Point *, Set::VectorSpace::Vector> &x0) const { typedef Set::VectorSpace::Vector vector_type; typedef Set::VectorSpace::Hom hom_type; typedef map<Set::Manifold::Point *, vector_type> map_type; typedef map<pair<Set::Manifold::Point *, Set::Manifold::Point *>, hom_type> dmap_type; map_type x = x0; Set::Manifold::Point *e0 = LS->e0; Set::Manifold::Point *e1 = LS->e1; Set::Manifold::Point *e2 = LS->e2; vector_type dx1 = x[e1] - x[e0]; vector_type dx2 = x[e2] - x[e0]; double r1 = Norm(dx1); double r2 = Norm(dx2); vector_type n1 = dx1/r1; vector_type n2 = dx2/r2; double c = n1(n2), c3 = 3.0*c; vector_type dc1 = (n2 - c*n1)/r1; vector_type dc2 = (n1 - c*n2)/r2; vector_type dc0 = -(dc1 + dc2); Set::VectorSpace::Hom n11 = Dyadic(n1,n1); Set::VectorSpace::Hom n12 = Dyadic(n1,n2); Set::VectorSpace::Hom n21 = Dyadic(n2,n1); Set::VectorSpace::Hom n22 = Dyadic(n2,n2); double r11 = r1*r1, r12 = r1*r2, r21 = r12, r22 = r2*r2; Set::VectorSpace::Hom ddc11 = c3*n11 - n12 - n21; ddc11[0][0] -= c; ddc11[1][1] -= c; ddc11[2][2] -= c; ddc11 /= r11; Set::VectorSpace::Hom ddc22 = c3*n22 - n21 - n12; ddc22[0][0] -= c; ddc22[1][1] -= c; ddc22[2][2] -= c; ddc22 /= r22; Set::VectorSpace::Hom ddc12 = c*n12 - n11 - n22; ddc12[0][0] += 1.0; ddc12[1][1] += 1.0; ddc12[2][2] += 1.0; ddc12 /= r12; Set::VectorSpace::Hom ddc21 = c*n21 - n22 - n11; ddc21[0][0] += 1.0; ddc21[1][1] += 1.0; ddc21[2][2] += 1.0; ddc21 /= r21; Set::VectorSpace::Hom ddc01 = -(ddc11 + ddc21); Set::VectorSpace::Hom ddc10 = -(ddc11 + ddc12); Set::VectorSpace::Hom ddc02 = -(ddc12 + ddc22); Set::VectorSpace::Hom ddc20 = -(ddc21 + ddc22); Set::VectorSpace::Hom ddc00 = -(ddc11 + ddc21 + ddc12 + ddc22); pair<double,double> dj = (*DJ)(c); double dv = dj.first; map_type DE; double ddv = dj.second; dmap_type DDE; DE.insert(map_type::value_type(e0,dv*dc0)); DE.insert(map_type::value_type(e1,dv*dc1)); DE.insert(map_type::value_type(e2,dv*dc2)); DDE.insert(dmap_type::value_type(make_pair(e0,e0),ddv*Dyadic(dc0,dc0)+dv*ddc00)); DDE.insert(dmap_type::value_type(make_pair(e1,e0),ddv*Dyadic(dc0,dc1)+dv*ddc01)); DDE.insert(dmap_type::value_type(make_pair(e2,e0),ddv*Dyadic(dc0,dc2)+dv*ddc02)); DDE.insert(dmap_type::value_type(make_pair(e1,e1),ddv*Dyadic(dc1,dc1)+dv*ddc11)); DDE.insert(dmap_type::value_type(make_pair(e0,e1),ddv*Dyadic(dc1,dc0)+dv*ddc10)); DDE.insert(dmap_type::value_type(make_pair(e2,e1),ddv*Dyadic(dc1,dc2)+dv*ddc12)); DDE.insert(dmap_type::value_type(make_pair(e2,e2),ddv*Dyadic(dc2,dc2)+dv*ddc22)); DDE.insert(dmap_type::value_type(make_pair(e0,e2),ddv*Dyadic(dc2,dc0)+dv*ddc20)); DDE.insert(dmap_type::value_type(make_pair(e1,e2),ddv*Dyadic(dc2,dc1)+dv*ddc21)); return make_pair(DE,DDE); } } }
30.91629
95
0.590267
[ "vector" ]
9e1ae11273b82d10fa2a0b5f51afbba437f2e83f
56,104
cpp
C++
Paper/Path.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
20
2016-12-13T22:34:35.000Z
2021-09-20T12:44:56.000Z
Paper/Path.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
Paper/Path.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
#include <Paper/Document.hpp> #include <Paper/CurveLocation.hpp> #include <Paper/Private/BooleanOperations.hpp> #include <Paper/Private/JoinAndCap.hpp> #include <Paper/Private/PathFlattener.hpp> #include <Paper/Private/PathFitter.hpp> #include <Crunch/Line.hpp> #include <Crunch/StringConversion.hpp> #include <Crunch/MatrixFunc.hpp> namespace paper { using namespace stick; Path::Path() { } void Path::addPoint(const Vec2f & _to) { createSegment(_to, Vec2f(0.0), Vec2f(0.0)); } void Path::cubicCurveTo(const Vec2f & _handleOne, const Vec2f & _handleTwo, const Vec2f & _to) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); //make relative current.setHandleOut(_handleOne - current.position()); createSegment(_to, _handleTwo - _to, Vec2f(0.0)); } void Path::quadraticCurveTo(const Vec2f & _handle, const Vec2f & _to) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); // Comment from paper.js Path.js: // This is exact: // If we have the three quad points: A E D, // and the cubic is A B C D, // B = E + 1/3 (A - E) // C = E + 1/3 (D - E) cubicCurveTo(_handle + (current.position() - _handle) / 3.0, _handle + (_to - _handle) / 3.0 , _to); } void Path::curveTo(const Vec2f & _through, const Vec2f & _to, Float32 _parameter) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); Float t1 = 1 - _parameter; Float tt = _parameter * _parameter; Vec2f handle = (_through - current.position() * tt - _to * tt) / (2 * _parameter * t1); quadraticCurveTo(handle, _to); } Error Path::arcTo(const Vec2f & _through, const Vec2f & _to) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); const Vec2f & from = current.position(); Vec2f lineOneStart = (from + _through) * 0.5; crunch::Line<Vec2f> lineOne(lineOneStart, crunch::rotate(_through - from, crunch::Constants<Float>::halfPi())); Vec2f lineTwoStart = (_through + _to) * 0.5; crunch::Line<Vec2f> lineTwo(lineTwoStart, crunch::rotate(_to - _through, crunch::Constants<Float>::halfPi())); auto result = crunch::intersect(lineOne, lineTwo); crunch::Line<Vec2f> line(from, _to - from); Int32 throughSide = line.side(_through); if (!result) { if (throughSide == 0) { // From paper.js // If the two lines are colinear, there cannot be an arc as the // circle is infinitely big and has no center point. If side is // 0, the connecting arc line of this huge circle is a line // between the two points, so we can use #lineTo instead. // Otherwise we bail out: addPoint(_to); return Error(); } return Error(ec::InvalidArgument, String::concat("Cannot put an arc through the given points: " , crunch::toString(_through), " and ", crunch::toString(_to)), STICK_FILE, STICK_LINE); } Vec2f vec = from - *result; Float extent = crunch::toDegrees(crunch::directedAngle(vec, _to - *result)); Int32 centerSide = line.side(*result); if (centerSide == 0) { // If the center is lying on the line, we might have gotten the // wrong sign for extent above. Use the sign of the side of the // through point. extent = throughSide * crunch::abs(extent); } else if (throughSide == centerSide) { // If the center is on the same side of the line (from, to) as // the through point, we're extending bellow 180 degrees and // need to adapt extent. extent -= 360.0 * (extent < 0 ? -1 : 1); } // Float ext = crunch::abs(extent); // Int32 count = ext >= 360.0 ? 4 : crunch::ceil(ext / 90.0); // Float inc = extent / (Float)count; // Float half = inc * crunch::Constants<Float>::pi() / 360.0; // Float z = 4.0 / 3.0 * std::sin(half) / (1.0 + std::cos(half)); // for (Int32 i = 0; i <= count; ++i) // { // // Explicitely use to point for last segment, since depending // // on values the calculation adds imprecision: // Vec2f pt = i < count ? result.intersections()[0] + vec : _to; // Vec2f out(-vec.y * z, vec.x * z); // if (i == 0) // { // // Modify startSegment // current.setHandleOut(out); // } // else // { // // Add new Segment // if (i < count) // createSegment(pt, Vec2f(vec.y * z, -vec.x * z), out); // else // createSegment(pt, Vec2f(vec.y * z, -vec.x * z), Vec2f(0.0)); // } // vec = crunch::rotate(vec, crunch::toRadians(inc)); // } //return Error(); return arcHelper(extent, current, vec, _to, *result, nullptr); } Error Path::arcTo(const Vec2f & _to, bool _bClockwise) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); const Vec2f & from = current.position(); Vec2f mid = (from + _to) * 0.5; Vec2f dir = (mid - from); dir = !_bClockwise ? Vec2f(-dir.y, dir.x) : Vec2f(dir.y, -dir.x); return arcTo(mid + dir, _to); } Error Path::arcTo(const Vec2f & _to, const Vec2f & _radii, Float _rotation, bool _bClockwise, bool _bLarge) { STICK_ASSERT(segmentArray().count()); if (crunch::isClose(_radii.x, (Float)0.0) || crunch::isClose(_radii.y, (Float)0.0)) { addPoint(_to); return Error(); } Vec2f from = segmentArray().last()->position(); Vec2f middle = (from + _to) * 0.5; Vec2f pt = crunch::rotate(from - middle, -_rotation); Float rx = crunch::abs(_radii.x); Float ry = crunch::abs(_radii.y); //printf("RX, RY %f %f\n", rx, ry); Float rxSq = rx * rx; Float rySq = ry * ry; Float xSq = pt.x * pt.x; Float ySq = pt.y * pt.y; Float factor = std::sqrt(xSq / rxSq + ySq / rySq); if (factor > 1) { //printf("APPLY FACTOR\n"); rx *= factor; ry *= factor; rxSq = rx * rx; rySq = ry * ry; } //printf("RX2, RY2 %f %f\n", rx, ry); factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) / (rxSq * ySq + rySq * xSq); if (crunch::abs(factor) < detail::PaperConstants::trigonometricEpsilon()) { //printf("SET FACTOR TO 0\n"); factor = 0; } if (factor < 0) { return Error(ec::InvalidArgument, "Cannot create an arc with the given arguments", STICK_FILE, STICK_LINE); } Vec2f center(rx * pt.y / ry, -ry * pt.x / rx); center = crunch::rotate(center * ((_bLarge == _bClockwise ? -1 : 1) * std::sqrt(factor)), _rotation) + middle; // Now create a matrix that maps the unit circle to the ellipse, // for easier construction below. Mat3f matrix = Mat3f::translation2D(center); matrix.rotate2D(_rotation); matrix.scale(_radii); Mat3f inv = crunch::inverse(matrix); Vec2f vect = inv * from; Float extent = crunch::directedAngle(vect, inv * _to); if (!_bClockwise && extent > 0) extent -= crunch::Constants<Float>::twoPi(); else if (_bClockwise && extent < 0) extent += crunch::Constants<Float>::twoPi(); return arcHelper(crunch::toDegrees(extent), *segmentArray().last(), vect, _to, center, &matrix); } Error Path::arcHelper(Float _extentDeg, Segment & _segment, const Vec2f & _direction, const Vec2f & _to, const Vec2f & _center, const Mat3f * _transform) { Float ext = crunch::abs(_extentDeg); Int32 count = ext >= 360.0 ? 4 : crunch::ceil(ext / 90.0); Float inc = _extentDeg / (Float)count; Float half = inc * crunch::Constants<Float>::pi() / 360.0; Float z = 4.0 / 3.0 * std::sin(half) / (1.0 + std::cos(half)); Vec2f dir = _direction; for (Int32 i = 0; i <= count; ++i) { // Explicitely use to point for last segment, since depending // on values the calculation adds imprecision: Vec2f pt = _to; Vec2f out(-dir.y * z, dir.x * z); if (i < count) { if (_transform) { pt = *_transform * dir; out = (*_transform * (dir + out)) - pt; } else { pt = _center + dir; } } if (i == 0) { // Modify startSegment _segment.setHandleOut(out); } else { // Add new Segment Vec2f in(dir.y * z, -dir.x * z); if (!_transform) { createSegment(pt, in, i < count ? out : Vec2f(0.0)); } else { createSegment(pt, (*_transform * (dir + in)) - pt, i < count ? out : Vec2f(0.0)); } } dir = crunch::rotate(dir, crunch::toRadians(inc)); } return Error(); } void Path::cubicCurveBy(const Vec2f & _handleOne, const Vec2f & _handleTwo, const Vec2f & _by) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); cubicCurveTo(current.position() + _handleOne, current.position() + _handleTwo, current.position() + _by); } void Path::quadraticCurveBy(const Vec2f & _handle, const Vec2f & _by) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); quadraticCurveTo(current.position() + _handle, current.position() + _by); } void Path::curveBy(const Vec2f & _through, const Vec2f & _by, Float32 _parameter) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); curveTo(current.position() + _through, current.position() + _by, _parameter); } Error Path::arcBy(const Vec2f & _through, const Vec2f & _by) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); return arcTo(current.position() + _through, current.position() + _by); } Error Path::arcBy(const Vec2f & _to, bool _bClockwise) { STICK_ASSERT(segmentArray().count()); Segment & current = *segmentArray().last(); return arcTo(current.position() + _to, _bClockwise); } void Path::closePath() { if (isClosed()) return; if (segmentArray().count() > 1) { Segment & first = *segmentArray()[0]; Segment & last = *segmentArray().last(); if (crunch::isClose(first.position(), last.position(), detail::PaperConstants::tolerance())) { first.setHandleIn(last.handleIn()); curveArray().last()->m_segmentB = first.m_index; segmentArray().removeLast(); } else { curveArray().append(stick::makeUnique<Curve>(document().allocator(), *this, last.m_index, first.m_index)); } set<comps::ClosedFlag>(true); markGeometryDirty(true); markBoundsDirty(true); } } void Path::smooth(Smoothing _type) { smooth(0, segmentArray().count() - 1, _type); } static Size smoothIndex(Int64 _idx, Int64 _length, bool _bClosed) { // Handle negative values based on whether a path is open or not: // Ranges on closed paths are allowed to wrapped around the // beginning/end (e.g. start near the end, end near the beginning), // while ranges on open paths stay within the path's open range. return min(_idx < 0 && _bClosed ? _idx % _length : _idx < 0 ? _idx + _length : _idx, _length - 1); } void Path::smooth(Int64 _from, Int64 _to, Smoothing _type) { // Continuous smoothing approach based on work by Lubos Brieda, // Particle In Cell Consulting LLC, but further simplified by // addressing handle symmetry across segments, and the possibility // to process x and y coordinates simultaneously. Also added // handling of closed paths. // https://www.particleincell.com/2012/bezier-splines/ // // We use different parameters for the two supported smooth methods // that use this algorithm: continuous and asymmetric. asymmetric // was the only approach available in v0.9.25 & below. _from = smoothIndex(_from, segmentArray().count(), isClosed()); _to = smoothIndex(_to, segmentArray().count(), isClosed()); if (_from > _to) { if (isClosed()) { _from -= segmentArray().count(); } else { Size tmp = _from; _from = _to; _to = tmp; } } if (_type == Smoothing::Asymmetric || _type == Smoothing::Continuous) { auto & segs = get<comps::Segments>(); bool bAsymmetric = _type == Smoothing::Asymmetric; Int64 amount = _to - _from + 1; Int64 n = amount - 1; bool bLoop = isClosed() && _from == 0 && _to == segs.count() - 1; // Overlap by up to 4 points on closed paths since a current // segment is affected by its 4 neighbors on both sides (?). Int64 padding = bLoop ? min(amount, (Int64)4) : 1; Int64 paddingLeft = padding; Int64 paddingRight = padding; if (!isClosed()) { // If the path is open and a range is defined, try using a // padding of 1 on either side. paddingLeft = min((Int64)1, _from); paddingRight = min((Int64)1, (Int64)segs.count() - _to - 1); } n += paddingLeft + paddingRight; if (n <= 1) return; DynamicArray<Vec2f> knots(n + 1); for (Int64 i = 0, j = _from - paddingLeft; i <= n; i++, j++) { knots[i] = segs[(j < 0 ? j + segs.count() : j) % segs.count()]->position(); } // In the algorithm we treat these 3 cases: // - left most segment (L) // - internal segments (I) // - right most segment (R) // // In both the continuous and asymmetric method, c takes these // values and can hence be removed from the loop starting in n - 2: // c = 1 (L), 1 (I), 0 (R) // // continuous: // a = 0 (L), 1 (I), 2 (R) // b = 2 (L), 4 (I), 7 (R) // u = 1 (L), 4 (I), 8 (R) // v = 2 (L), 2 (I), 1 (R) // // asymmetric: // a = 0 (L), 1 (I), 1 (R) // b = 2 (L), 4 (I), 2 (R) // u = 1 (L), 4 (I), 3 (R) // v = 2 (L), 2 (I), 0 (R) // (L): u = 1, v = 2 Float x = knots[0].x + 2 * knots[1].x; Float y = knots[0].y + 2 * knots[1].y; Float f = 2; Float n1 = n - 1; DynamicArray<Float> rx(n + 1); rx[0] = x; DynamicArray<Float> ry(n + 1); ry[0] = y; DynamicArray<Float> rf(n + 1); rf[0] = f; DynamicArray<Float> px(n + 1); DynamicArray<Float> py(n + 1); // Solve with the Thomas algorithm for (Size i = 1; i < n; i++) { bool bInternal = i < n1; // internal--(I) asymmetric--(R) (R)--continuous Float a = bInternal ? 1 : bAsymmetric ? 1 : 2; Float b = bInternal ? 4 : bAsymmetric ? 2 : 7; Float u = bInternal ? 4 : bAsymmetric ? 3 : 8; Float v = bInternal ? 2 : bAsymmetric ? 0 : 1; Float m = a / f; f = rf[i] = b - m; x = rx[i] = u * knots[i].x + v * knots[i + 1].x - m * x; y = ry[i] = u * knots[i].y + v * knots[i + 1].y - m * y; } px[n1] = rx[n1] / rf[n1]; py[n1] = ry[n1] / rf[n1]; for (Int64 i = n - 2; i >= 0; i--) { px[i] = (rx[i] - px[i + 1]) / rf[i]; py[i] = (ry[i] - py[i + 1]) / rf[i]; } px[n] = (3 * knots[n].x - px[n1]) / 2; py[n] = (3 * knots[n].y - py[n1]) / 2; // Now update the segments for (Int64 i = paddingLeft, max = n - paddingRight, j = _from; i <= max; i++, j++) { Int64 index = j < 0 ? j + segs.count() : j; Segment & segment = *segs[index]; Float hx = px[i] - segment.position().x; Float hy = py[i] - segment.position().y; if (bLoop || i < max) { segment.setHandleOut(Vec2f(hx, hy)); } if (bLoop || i > paddingLeft) { segment.setHandleIn(Vec2f(-hx, -hy)); } } rebuildCurves(); markGeometryDirty(true); markBoundsDirty(true); } } void Path::simplify(Float _tolerance) { detail::PathFitter fitter(*this, _tolerance, true); fitter.fit(); } void Path::addSegment(const Vec2f & _point, const Vec2f & _handleIn, const Vec2f & _handleOut) { createSegment(_point, _handleIn, _handleOut); } Segment & Path::insertSegment(Size _index, const Vec2f & _pos, const Vec2f & _handleIn, const Vec2f & _handleOut) { auto & segs = segmentArray(); auto seg = document().allocator().create<Segment>(*this, _pos, _handleIn, _handleOut, _index); //append case if (_index >= segs.count()) { segs.append(stick::UniquePtr<Segment>(seg, document().allocator())); if (segs.count() > 1) { auto & curves = curveArray(); // possibly remove the last closing curve if (isClosed() && curves.count() && curves.last()->m_segmentB == 0) curves.removeLast(); // add the new curve curves.append(stick::makeUnique<Curve>(document().allocator(), *this, segs.count() - 2, segs.count() - 1)); // possibly add the new closing curve if (isClosed()) curves.append(stick::makeUnique<Curve>(document().allocator(), *this, segs.count() - 1, 0)); } } //insert case else { auto sit = segs.insert(segs.begin() + _index, stick::UniquePtr<Segment>(seg, document().allocator())); //insert the new curve created by due to the segment insertion auto & curves = curveArray(); auto cit = curves.begin() + _index; cit = curves.insert(cit, stick::makeUnique<Curve>(document().allocator(), *this, seg->m_index , seg->m_index + 1)); //iterate over all the segments after the new one and update their indices ++sit; for (; sit != segs.end(); ++sit) { (*sit)->m_index++; } ++cit; for (; cit != curves.end(); ++cit) { (*cit)->markDirty(); (*cit)->m_segmentA++; if ((*cit)->m_segmentB != 0) (*cit)->m_segmentB++; } } //rebuildCurves(); markBoundsDirty(true); markGeometryDirty(true); return *seg; } void Path::removeSegment(Size _index) { auto & segs = segmentArray(); STICK_ASSERT(_index < segs.count()); segs.remove(segs.begin() + _index); updateSegmentIndices(_index, segmentArray().count()); rebuildCurves(); markGeometryDirty(true); } void Path::removeSegments(Size _from) { auto & segs = segmentArray(); STICK_ASSERT(_from < segs.count()); segs.remove(segs.begin() + _from, segs.end()); rebuildCurves(); markGeometryDirty(true); } void Path::removeSegments(Size _from, Size _to) { auto & segs = segmentArray(); STICK_ASSERT(_from < segs.count()); STICK_ASSERT(_to < segs.count()); segs.remove(segs.begin() + _from, segs.begin() + _to); updateSegmentIndices(_from, _to); rebuildCurves(); markGeometryDirty(true); } void Path::removeSegments() { segmentArray().clear(); curveArray().clear(); markGeometryDirty(true); } Segment & Path::createSegment(const Vec2f & _pos, const Vec2f & _handleIn, const Vec2f & _handleOut) { return insertSegment(segmentArray().count(), _pos, _handleIn, _handleOut); } void Path::reverse() { //TODO: Can be optimized auto & segs = get<comps::Segments>(); std::reverse(segs.begin(), segs.end()); Size i = 0; Vec2f tmp; for (; i < segs.count(); ++i) { segs[i]->m_index = i; tmp = segs[i]->m_handleOut; segs[i]->m_handleOut = segs[i]->m_handleIn; segs[i]->m_handleIn = tmp; } for (auto & c : get<comps::Children>()) { Path p = brick::reinterpretEntity<Path>(c); p.reverse(); } rebuildCurves(); markGeometryDirty(true); } void Path::setClockwise(bool _b) { if (isClockwise() != _b) reverse(); } void Path::flatten(Float _angleTolerance, Float _minDistance, Size _maxRecursion) { detail::PathFlattener::PositionArray newSegmentPositions; newSegmentPositions.reserve(1024); detail::PathFlattener::flatten(*this, newSegmentPositions, nullptr, _angleTolerance, _minDistance, _maxRecursion); auto & segs = segmentArray(); segs.clear(); for (const auto & pos : newSegmentPositions) { segs.append(stick::makeUnique<Segment>(document().allocator(), *this, pos, Vec2f(0.0f), Vec2f(0.0f), segs.count())); } //make sure to possibly remove duplicate closing segments again bool bClosed = isClosed(); if (bClosed) { set<comps::ClosedFlag>(false); closePath(); } rebuildCurves(); markBoundsDirty(true); markGeometryDirty(true); } void Path::flattenRegular(Float _maxDistance) { DynamicArray<Vec2f> tmp; Float currentOffset = 0; Float len = length(); auto stepAndSampleCount = regularOffsetAndSampleCount(_maxDistance); Float step = stepAndSampleCount.offset; for (Int32 i = 0; i < stepAndSampleCount.sampleCount; ++i) { tmp.append(positionAt(std::min(currentOffset, len))); Float delta = len - currentOffset; if (delta < step) { step = delta * 0.5; } currentOffset += step; } // Float maxLen = len; // if(!isClosed()) maxLen -= step; // while(currentOffset < len) // { // tmp.append(positionAt(std::min(currentOffset, len))); // currentOffset += step; // } // //due to floating point in accuracies, the last sample might overshoot the length of the path, // //if that is the case, we just sample the end of the path // if (tmp.count() < stepAndSampleCount.sampleCount) // { // printf("ADD LAST %f, %lu\n", len, curveArray().count()); // tmp.append(positionAt(len)); // } auto & segs = get<comps::Segments>(); segs.clear(); for (const Vec2f & p : tmp) { segs.append(stick::makeUnique<Segment>(document().allocator(), *this, p, Vec2f(0), Vec2f(0), segs.count())); } //printf("NUM NEW SEGS %lu\n", segs.count()); //make sure to possibly remove duplicate closing segments again bool bClosed = isClosed(); if (bClosed) { set<comps::ClosedFlag>(false); closePath(); } rebuildCurves(); markBoundsDirty(true); markGeometryDirty(true); } Path::OffsetAndSampleCount Path::regularOffsetAndSampleCount(Float _maxDistance) { Float len = length(); Size sampleCount = std::ceil(len / _maxDistance); return {std::min(len, len / (Float)sampleCount), isClosed() ? sampleCount - 1 : sampleCount}; } Float Path::regularOffset(Float _maxDistance) { return regularOffsetAndSampleCount(_maxDistance).offset; } Path::SegmentViewConst Path::segments() const { STICK_ASSERT(hasComponent<comps::Segments>()); return SegmentViewConst(segmentArray().begin(), segmentArray().end()); } Path::SegmentView Path::segments() { STICK_ASSERT(hasComponent<comps::Segments>()); //return get<comps::Segments>(); return SegmentView(segmentArray().begin(), segmentArray().end()); } Path::CurveViewConst Path::curves() const { STICK_ASSERT(hasComponent<comps::Curves>()); return CurveViewConst(curveArray().begin(), curveArray().end()); } Path::CurveView Path::curves() { STICK_ASSERT(hasComponent<comps::Curves>()); return CurveView(curveArray().begin(), curveArray().end()); } SegmentArray & Path::segmentArray() { STICK_ASSERT(hasComponent<comps::Segments>()); return get<comps::Segments>(); } const SegmentArray & Path::segmentArray() const { STICK_ASSERT(hasComponent<comps::Segments>()); return get<comps::Segments>(); } CurveArray & Path::curveArray() { STICK_ASSERT(hasComponent<comps::Curves>()); return get<comps::Curves>(); } const CurveArray & Path::curveArray() const { STICK_ASSERT(hasComponent<comps::Curves>()); return get<comps::Curves>(); } Vec2f Path::positionAt(Float _offset) const { auto loc = curveLocationAt(_offset); return loc.position(); } Vec2f Path::normalAt(Float _offset) const { auto loc = curveLocationAt(_offset); return loc.normal(); } Vec2f Path::tangentAt(Float _offset) const { auto loc = curveLocationAt(_offset); return loc.tangent(); } Float Path::curvatureAt(Float _offset) const { auto loc = curveLocationAt(_offset); return loc.curvature(); } Float Path::angleAt(Float _offset) const { auto loc = curveLocationAt(_offset); return loc.angle(); } //@TODO: BIG FAT TODO Path Path::splitAt(Float _offset) { } //@TODO: BIG FAT TODO Path Path::splitAt(const CurveLocation & _loc) { } Path Path::slice(Float _from, Float _to) const { return slice(curveLocationAt(_from), curveLocationAt(_to)); } Path Path::slice(const CurveLocation & _from, const CurveLocation & _to) const { STICK_ASSERT(_from.isValid()); STICK_ASSERT(_to.isValid()); STICK_ASSERT(_from.curve().path() == _to.curve().path()); //@TODO: is this cloning good enough? Path ret = clone(); ret.set<comps::ClosedFlag>(false); ret.removeSegments(); //add the first segment based on the start curve location const SegmentArray & segs = this->segmentArray(); auto bez = _from.curve().bezier().slice(_from.parameter(), 1); auto bez2 = _to.curve().bezier().slice(0, _to.parameter()); ret.addSegment(bez.positionOne(), Vec2f(0.0), bez.handleOne() - bez.positionOne()); //add all the segments inbetween for (stick::Size i = _from.curve().segmentTwo().m_index; i <= _to.curve().segmentOne().m_index; ++i) { auto & seg = segs[i]; Vec2f handleIn = seg->handleIn(); Vec2f handleOut = seg->handleOut(); if (i == _from.curve().segmentTwo().m_index && i == _to.curve().segmentOne().m_index) { handleIn = bez.handleTwo() - bez.positionTwo(); handleOut = bez2.handleOne() - bez2.positionOne(); } else if (i == _from.curve().segmentTwo().m_index) { handleIn = bez.handleTwo() - bez.positionTwo(); } else if (i == _to.curve().segmentOne().m_index) { handleOut = bez2.handleOne() - bez2.positionOne(); } ret.addSegment(seg->position(), handleIn, handleOut); } //add the last segment based on the end curve location ret.addSegment(bez2.positionTwo(), bez2.handleTwo() - bez2.positionTwo(), Vec2f(0.0f)); ret.insertAbove(*this); return ret; } CurveLocation Path::closestCurveLocation(const Vec2f & _point, Float & _outDistance) const { Float minDist = std::numeric_limits<Float>::infinity(); Float currentDist; Float closestParameter; Float currentParameter; auto closestCurve = curveArray().end(); auto it = curveArray().begin(); for (; it != curveArray().end(); ++it) { currentParameter = (*it)->closestParameter(_point, currentDist); if (currentDist < minDist) { minDist = currentDist; closestParameter = currentParameter; closestCurve = it; } } if (closestCurve != curveArray().end()) { _outDistance = minDist; return (*closestCurve)->curveLocationAtParameter(closestParameter); } return CurveLocation(); } CurveLocation Path::closestCurveLocation(const Vec2f & _point) const { Float tmp; return closestCurveLocation(_point, tmp); } CurveLocation Path::curveLocationAt(Float _offset) const { Float len = 0; Float start; auto it = curveArray().begin(); for (; it != curveArray().end(); ++it) { start = len; len += (*it)->length(); //we found the curve if (len >= _offset) { return (*it)->curveLocationAt(_offset - start); } } // comment from paper.js source in Path.js: // It may be that through impreciseness of getLength (length) , that the end // of the curves was missed: if (_offset <= length()) { return curveArray().last()->curveLocationAtParameter(1); } return CurveLocation(); } Float Path::length() const { auto & lenData = const_cast<Path *>(this)->get<comps::PathLength>(); if (lenData.bDirty) { lenData.length = 0; for (const auto & c : curveArray()) { lenData.length += c->length(); } lenData.bDirty = false; } return lenData.length; } void Path::peaks(stick::DynamicArray<CurveLocation> & _peaks) const { auto & curves = curveArray(); stick::DynamicArray<Float> tmp(document().allocator()); for (auto & curve : curves) { curve->peaks(tmp); for (auto p : tmp) { _peaks.append(curve->curveLocationAtParameter(p)); } } } void Path::extrema(stick::DynamicArray<CurveLocation> & _extrema) const { auto & curves = curveArray(); stick::DynamicArray<Float> tmp(document().allocator()); for (auto & curve : curves) { curve->extrema(tmp); for (auto p : tmp) { _extrema.append(curve->curveLocationAtParameter(p)); } } } stick::DynamicArray<CurveLocation> Path::extrema() const { stick::DynamicArray<CurveLocation> ret; extrema(ret); return ret; } Float Path::area() const { Float ret = 0; for (const auto & c : curveArray()) { ret += c->area(); } // take children into account for (auto & c : get<comps::Children>()) { Path p = brick::reinterpretEntity<Path>(c); ret += p.area(); } return ret; } bool Path::isClosed() const { return get<comps::ClosedFlag>(); } bool Path::isPolygon() const { for (const auto & seg : segmentArray()) { if (!seg->isLinear()) return false; } return true; } bool Path::isClockwise() const { // Comment from paper.js source: // Method derived from: // http://stackoverflow.com/questions/1165647 // We treat the curve points and handles as the outline of a polygon of // which we determine the orientation using the method of calculating // the sum over the edges. This will work even with non-convex polygons, // telling you whether it's mostly clockwise // TODO: Check if this works correctly for all open paths. // Float sum = 0; // Size i = 0; // Size i2; // auto & segs = segmentArray(); // Size s = segs.count(); // for (; i < s; ++i) // { // Vec2f posA = segs[i]->position(); // Vec2f handleA = posA + segs[i]->handleOut(); // i2 = (i + 1) % s; // Vec2f posB = segs[i2]->position(); // Vec2f handleB = posB + segs[i2]->handleIn(); // sum += (posA.x - handleA.x) * (handleA.y + posA.y); // sum += (handleA.x - handleB.x) * (handleB.y + handleA.y); // sum += (handleB.x - posB.x) * (posB.y + handleB.y); // } // return sum > 0; return area() >= 0; } void Path::rebuildCurves() { auto & curves = curveArray(); curves.clear(); auto & segs = segmentArray(); for (Size i = 0; i < segs.count() - 1; ++i) { curves.append(stick::makeUnique<Curve>(document().allocator(), *this, i, i + 1)); } if (isClosed() && segs.count() > 1) curves.append(stick::makeUnique<Curve>(document().allocator(), *this, segs.count() - 1, 0)); } void Path::updateSegmentIndices(Size _from, Size _to) { for (Size i = _from; i < _to && i < segmentArray().count(); ++i) { segmentArray()[i]->m_index = i; } } void Path::segmentChanged(const Segment & _seg) { //printf("SEGMENT CHANGED A %lu\n", curveArray().count()); if (curveArray().count() == 0) return; if (_seg.m_index == 0) { // printf("SEGMENT CHANGED B\n"); curveArray().first()->markDirty(); if (isClosed()) curveArray().last()->markDirty(); } else if (_seg.m_index == segmentArray().count() - 1) { // printf("SEGMENT CHANGED C\n"); curveArray().last()->markDirty(); if (isClosed()) curveArray().first()->markDirty(); } else { // printf("SEGMENT CHANGED D\n"); curveArray()[_seg.m_index - 1]->markDirty(); curveArray()[_seg.m_index]->markDirty(); } markBoundsDirty(true); markGeometryDirty(true); //printf("SEGMENT CHANGED E\n"); } namespace detail { //a helper to store segment data in stroke space struct SegmentData { Vec2f position; Vec2f handleIn; Vec2f handleOut; }; //helpers for updateStrokeBounds static void mergeStrokeCap(Rect & _rect, StrokeCap _cap, const SegmentData & _a, const SegmentData & _b, bool _bStart, const Vec2f & _strokePadding, const Mat3f & _strokeMat, const Mat3f * _transform) { Bezier curve(_a.position, _a.handleOut, _b.handleIn, _b.position); Vec2f dir = _bStart ? -curve.tangentAt(0) : curve.tangentAt(1); Vec2f pos = _bStart ? _a.position : _b.position; switch (_cap) { case StrokeCap::Square: { Vec2f a, b, c, d; detail::capSquare(pos, dir, a, b, c, d); c = _strokeMat * c; d = _strokeMat * d; _rect = crunch::merge(_rect, _transform ? *_transform * c : c); _rect = crunch::merge(_rect, _transform ? *_transform * d : d); break; } case StrokeCap::Round: { Vec2f p = _strokeMat * pos; if (_transform) { p = *_transform * p; } Rect r(p - _strokePadding, p + _strokePadding); _rect = crunch::merge(_rect, r); break; } case StrokeCap::Butt: { Vec2f min, max; detail::capOrJoinBevelMinMax(pos, dir, min, max); min = _strokeMat * min; max = _strokeMat * max; _rect = crunch::merge(_rect, _transform ? *_transform * min : min); _rect = crunch::merge(_rect, _transform ? *_transform * max : max); break; } default: break; } } static void mergeStrokeJoin(Rect & _rect, StrokeJoin _join, Float _miterLimit, const SegmentData & _prev, const SegmentData & _current, const SegmentData & _next, const Vec2f & _strokePadding, const Mat3f & _strokeMat, const Mat3f * _transform) { switch (_join) { case StrokeJoin::Round: { Vec2f p = _strokeMat * _current.position; if (_transform) { p = *_transform * p; } Rect r(p - _strokePadding, p + _strokePadding); _rect = crunch::merge(_rect, r); break; } case StrokeJoin::Miter: { /*const Curve & curveIn = *_segment.curveIn(); const Curve & curveOut = *_segment.curveOut();*/ Bezier curveIn(_prev.position, _prev.handleOut, _current.handleIn, _current.position); Bezier curveOut(_current.position, _current.handleOut, _next.handleIn, _next.position); //to know which side of the stroke is outside Vec2f lastDir = curveIn.tangentAt(1); Vec2f nextDir = curveOut.tangentAt(0); Vec2f lastPerp(lastDir.y, -lastDir.x); Vec2f perp(nextDir.y, -nextDir.x); Float cross = lastDir.x * nextDir.y - nextDir.x * lastDir.y; Vec2f miter; Float miterLen; Vec2f pos = _current.position; if (cross >= 0.0) { miter = detail::joinMiter(pos, pos + lastPerp, lastDir, pos + perp, nextDir, miterLen); } else { miter = detail::joinMiter(pos, pos - lastPerp, lastDir, pos - perp, nextDir, miterLen); } if (miterLen <= _miterLimit) { miter = _strokeMat * miter; _rect = crunch::merge(_rect, _transform ? *_transform * miter : miter); break; } //else fall back to Bevel } case StrokeJoin::Bevel: { Bezier curveIn(_prev.position, _prev.handleOut, _current.handleIn, _current.position); Bezier curveOut(_current.position, _current.handleOut, _next.handleIn, _next.position); Vec2f min, max; Vec2f dirA = curveIn.tangentAt(1); Vec2f dirB = curveOut.tangentAt(0); detail::capOrJoinBevelMinMax(_current.position, dirA, min, max); min = _strokeMat * min; max = _strokeMat * max; _rect = crunch::merge(_rect, _transform ? *_transform * min : min); _rect = crunch::merge(_rect, _transform ? *_transform * max : max); detail::capOrJoinBevelMinMax(_current.position, dirB, min, max); min = _strokeMat * min; max = _strokeMat * max; _rect = crunch::merge(_rect, _transform ? *_transform * min : min); _rect = crunch::merge(_rect, _transform ? *_transform * max : max); break; } default: break; } } } Path::BoundsResult Path::computeBoundsImpl(Float _padding, const Mat3f * _transform) { if (!segmentArray().count()) return {true, Rect(0, 0, 0, 0)}; if (segmentArray().count() == 1) { Vec2f p = _transform ? *_transform * segmentArray()[0]->position() : segmentArray()[0]->position(); return {false, Rect(p, p)}; } Rect ret; if (!_transform) { //if not transformation is applied in the document hierarchy, we can simply use the //existing beziers as local = global space. auto & curves = curveArray(); for (auto it = curves.begin(); it != curves.end(); ++it) { if (it == curves.begin()) ret = _padding > 0.0 ? (*it)->bounds(_padding) : (*it)->bounds(); else ret = crunch::merge(ret, _padding > 0.0 ? (*it)->bounds(_padding) : (*it)->bounds()); } } else { /*auto & curves = curveArray(); for (auto it = curves.begin(); it != curves.end(); ++it) { if (it == curves.begin()) ret = _padding > 0.0 ? (*it).bounds(_padding) : (*it).bounds(); else ret = crunch::merge(ret, _padding > 0.0 ? (*it).bounds(_padding) : (*it).bounds()); } Vec2f xa = absTrans[0] * ret.min().x; Vec2f xb = absTrans[0] * ret.max().x; Vec2f ya = absTrans[1] * ret.min().y; Vec2f yb = absTrans[1] * ret.max().y; Vec2f nmin = crunch::min(xa, xb) + crunch::min(ya, yb) + absTrans[2]; Vec2f nmax = crunch::max(xa, xb) + crunch::max(ya, yb) + absTrans[2]; return {Rect(nmin, nmax), false};*/ //if not, we have to bring the beziers to document space in order //to calculate the bounds. //we iterate over segments instead so we only do the matrix multiplication //once for each segment. auto & segs = segmentArray(); auto it = segs.begin(); Vec2f lastPosition = *_transform * (*it)->position(); Vec2f firstPosition = lastPosition; Vec2f lastHandle = *_transform * (*it)->handleOutAbsolute(); ++it; Vec2f currentPosition, handleIn; for (; it != segs.end(); ++it) { handleIn = *_transform * (*it)->handleInAbsolute(); currentPosition = *_transform * (*it)->position(); Bezier bez(lastPosition, lastHandle, handleIn, currentPosition); if (it == segs.begin() + 1) ret = bez.bounds(_padding); else ret = crunch::merge(ret, bez.bounds(_padding)); lastHandle = *_transform * (*it)->handleOutAbsolute(); lastPosition = currentPosition; } if (isClosed()) { Bezier bez(lastPosition, lastHandle, *_transform * segs.first()->handleInAbsolute(), firstPosition); ret = crunch::merge(ret, bez.bounds(_padding)); } } return {false, ret}; } Path::BoundsResult Path::computeBounds(const Mat3f * _transform) { return computeBoundsImpl(0.0, _transform); } Path::BoundsResult Path::computeStrokeBounds(const Mat3f * _transform) { if (!hasStroke()) return computeBounds(_transform); StrokeJoin join = strokeJoin(); StrokeCap cap = strokeCap(); Float sw = strokeWidth(); Float strokeRad = sw * 0.5; Float ml = miterLimit(); bool bIsScalingStroke = isScalingStroke(); Mat3f transform = _transform ? *_transform : Mat3f::identity(); Mat3f smat = strokeTransform(_transform, sw, bIsScalingStroke); Vec2f sp = strokePadding(strokeRad, bIsScalingStroke ? transform : Mat3f::identity()); //use proper 2D padding for non uniformly transformed strokes? auto result = computeBoundsImpl(max(sp.x, sp.y), _transform); bool bIsTransformed = _transform != nullptr; //if there is no bounds if (result.bEmpty) return result; auto & segments = segmentArray(); Size segmentCount = isClosed() ? segments.count() : segments.count() - 1; Mat3f ismat = crunch::inverse(smat); DynamicArray<detail::SegmentData> strokeSegs(segments.count()); for (Size i = 0; i < strokeSegs.count(); ++i) { strokeSegs[i] = {ismat * segments[i]->position(), ismat * (segments[i]->position() + segments[i]->handleIn()), ismat * (segments[i]->position() + segments[i]->handleOut())}; } for (Size i = 1; i < segments.count(); ++i) { detail::mergeStrokeJoin(result.rect, join, ml, strokeSegs[i - 1], strokeSegs[i], strokeSegs[i + 1], sp, smat, _transform); } if (isClosed()) { //closing join detail::mergeStrokeJoin(result.rect, join, ml, strokeSegs[strokeSegs.count() - 1], strokeSegs[0], strokeSegs[1], sp, smat, _transform); } else { //caps detail::mergeStrokeCap(result.rect, cap, strokeSegs[0], strokeSegs[1], true, sp, smat, _transform); detail::mergeStrokeCap(result.rect, cap, strokeSegs[strokeSegs.count() - 2], strokeSegs[strokeSegs.count() - 1], false, sp, smat, _transform); } //return the merged box; return result; } Path::BoundsResult Path::computeHandleBounds(const Mat3f * _transform) { auto ret = computeStrokeBounds(_transform); if (ret.bEmpty) return ret; if (_transform) { auto & segs = segmentArray(); for (auto & seg : segs) { ret.rect = crunch::merge(ret.rect, *_transform * seg->handleInAbsolute()); ret.rect = crunch::merge(ret.rect, *_transform * seg->handleOutAbsolute()); } } else { auto & segs = segmentArray(); for (auto & seg : segs) { ret.rect = crunch::merge(ret.rect, seg->handleInAbsolute()); ret.rect = crunch::merge(ret.rect, seg->handleOutAbsolute()); } } return ret; } bool Path::contains(const Vec2f & _point) const { if (!handleBounds().contains(_point)) return false; if (windingRule() == WindingRule::EvenOdd) return detail::winding(_point, detail::monoCurves(*const_cast<Path *>(this)), false) & 1; else return detail::winding(_point, detail::monoCurves(*const_cast<Path *>(this)), false) > 0; } void Path::applyTransform(const Mat3f & _transform) { for (auto & s : segmentArray()) { s->transform(_transform); } } Path Path::clone() const { return brick::reinterpretEntity<Path>(Item::clone()); } Curve & Path::curve(Size _index) { return *curveArray()[_index]; } const Curve & Path::curve(Size _index) const { return *curveArray()[_index]; } Segment & Path::segment(Size _index) { return *segmentArray()[_index]; } const Segment & Path::segment(Size _index) const { return *segmentArray()[_index]; } Size Path::curveCount() const { return curveArray().count(); } Size Path::segmentCount() const { return segmentArray().count(); } namespace detail { inline bool isAdjacentCurve(Size _a, Size _b, Size _curveCount, bool _bIsClosed) { if (_b == _a + 1 || (_bIsClosed && _a == 0 && _b == _curveCount - 1)) return true; return false; } // helper to recursively intersect paths and its children (compound path) inline void recursivelyIntersect(const Path & _self, const Path & _other, IntersectionArray & _intersections) { bool bSelf = _self == _other; const auto & curves = _self.curveArray(); auto * otherCurves = !bSelf ? &_other.curveArray() : &curves; for (Size i = 0; i < curves.count(); ++i) { const auto & a = curves[i]; for (Size j = bSelf ? i + 1 : 0; j < otherCurves->count(); ++j) { const auto & b = (*otherCurves)[j]; auto intersections = a->bezier().intersections(b->bezier()); for (stick::Int32 z = 0; z < intersections.count; ++z) { bool bAdd = true; //for self intersection we only add the intersection if its not where //adjacent curves connect. if (bSelf) { printf("DAA I %lu J %lu\n", i, j); if (isAdjacentCurve(i, j, curves.count(), _self.isClosed())) { printf("ITS ADJACENT\n"); if ((crunch::isClose(intersections.values[z].parameterOne, 1.0f, detail::PaperConstants::curveTimeEpsilon()) && crunch::isClose(intersections.values[z].parameterTwo, 0.0f, detail::PaperConstants::curveTimeEpsilon())) || //this case can only happen for closed paths where the first curve meets the last one (_self.isClosed() && crunch::isClose(intersections.values[z].parameterOne, 0.0f, detail::PaperConstants::curveTimeEpsilon()) && crunch::isClose(intersections.values[z].parameterTwo, 1.0f, detail::PaperConstants::curveTimeEpsilon()))) { printf("DONT FUCKING ADD\n"); bAdd = false; } } } if (bAdd) { // make sure we don't add an intersection twice. This can happen if the intersection // is located between two adjacent curves of the path. // @TODO: do some sorted insertion similar to what paper.js does to avoid having // to iterate over the whole array of found intersections. I am pretty sure that // just keeping it simple and iterating over a block of memory will perform better in // native code in most scenarios. auto cl = a->curveLocationAtParameter(intersections.values[z].parameterOne); for (auto & isec : _intersections) { printf("COMPARING WITH OLD ONE %f %f\n", cl.offset(), isec.location.offset()); if (cl.isSynonymous(isec.location)) { printf("ITS SYNNONYMOUS BIITCH\n"); bAdd = false; break; } } if (bAdd) _intersections.append({cl, intersections.values[z].position }); } } } } const auto & children = _other.children(); for (auto & c : children) { recursivelyIntersect(_self, brick::reinterpretEntity<Path>(c), _intersections); } } } IntersectionArray Path::intersections() const { return intersectionsImpl(*this); } IntersectionArray Path::intersections(const Path & _other) const { if (!bounds().overlaps(_other.bounds())) return IntersectionArray(); return intersectionsImpl(_other); } IntersectionArray Path::intersectionsImpl(const Path & _other) const { //@TODO: Take transformation matrix into account!! //@TODO: In terms of memory allocation and stuff this code is fucking gross :( IntersectionArray isecs; detail::recursivelyIntersect(*this, _other, isecs); for (auto & c : children()) { auto tmp = brick::reinterpretEntity<Path>(c).intersectionsImpl(_other); isecs.insert(isecs.end(), tmp.begin(), tmp.end()); } return isecs; } }
35.352237
195
0.501836
[ "transform" ]
9e1b3a9f3e6d56a4fd92c15f511b08e1eadcf249
716
hpp
C++
Kuplung/kuplung/ui/dialogs/DialogSVS.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
14
2017-02-17T17:12:40.000Z
2021-12-22T01:55:06.000Z
Kuplung/kuplung/ui/dialogs/DialogSVS.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
null
null
null
Kuplung/kuplung/ui/dialogs/DialogSVS.hpp
supudo/Kuplung
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
[ "Unlicense" ]
1
2019-10-15T08:10:10.000Z
2019-10-15T08:10:10.000Z
// // DialogSVS.hpp // Kuplung // // Created by Sergey Petrov on 2/1/16. // Copyright © 2016 supudo.net. All rights reserved. // #ifndef DialogSVS_hpp #define DialogSVS_hpp #include "kuplung/utilities/gl/GLIncludes.h" #include "kuplung/utilities/imgui/imgui.h" #include "kuplung/meshes/artefacts/StructuredVolumetricSampling.hpp" class DialogSVS { public: void init(); void render(bool* p_opened); GLuint vboTexture; float windowWidth, windowHeight; float viewPaddingHorizontal, viewPaddingVertical; private: int textureWidth, textureHeight; ImVec2 scrolling = ImVec2(0.0f, 0.0f); std::unique_ptr<StructuredVolumetricSampling> structured_Volumetric_Sampling; }; #endif /* DialogSVS_hpp */
21.69697
79
0.75838
[ "render" ]
9e2687eb5afca8e696ea619bda576d4a88ff6ee5
31,828
cpp
C++
src/glcanvas.cpp
matusnovak/finegraphics
815eb9bc30ac27e8032785ed8963978c2aca758b
[ "MIT" ]
2
2018-11-02T12:34:59.000Z
2021-02-12T06:42:34.000Z
src/glcanvas.cpp
matusnovak/finegraphics
815eb9bc30ac27e8032785ed8963978c2aca758b
[ "MIT" ]
null
null
null
src/glcanvas.cpp
matusnovak/finegraphics
815eb9bc30ac27e8032785ed8963978c2aca758b
[ "MIT" ]
1
2021-06-25T12:14:41.000Z
2021-06-25T12:14:41.000Z
#include <utility> #include <nanovg.h> #include <ffw/graphics/glcanvas.h> #include <ffw/graphics/exceptions.h> #include "ffw/graphics/mvp.h" #include <iostream> extern NVGcontext* nanovgCreateGL3(bool antialias, bool strokes); extern NVGcontext* nanovgCreateGL2(bool antialias, bool strokes); extern NVGcontext* nanovgCreateGLES2(bool antialias, bool strokes); extern NVGcontext* nanovgCreateGLES3(bool antialias, bool strokes); extern void nanovgDestroyGL2(NVGcontext* vg); extern void nanovgDestroyGL3(NVGcontext* vg); extern void nanovgDestroyGLES2(NVGcontext* vg); extern void nanovgDestroyGLES3(NVGcontext* vg); extern int nanovgCreateImageGL2(NVGcontext* vg, GLuint textureId, int w, int h, int flags); extern int nanovgCreateImageGL3(NVGcontext* vg, GLuint textureId, int w, int h, int flags); extern int nanovgCreateImageGLES2(NVGcontext* vg, GLuint textureId, int w, int h, int flags); extern int nanovgCreateImageGLES3(NVGcontext* vg, GLuint textureId, int w, int h, int flags); ///============================================================================= ffw::GLCanvas::Image::Image(const GLCanvas* canvas, const int ref):canvas(canvas),ref(ref) { } ///============================================================================= ffw::GLCanvas::Image::~Image() { if (ref >= 0 && canvas != nullptr) { //canvas->removeImage(*this); } } ///============================================================================= ffw::GLCanvas::Image::Image(Image&& other) NOEXCEPT { swap(other); } ///============================================================================= ffw::GLCanvas::Image& ffw::GLCanvas::Image::operator = (Image&& other) NOEXCEPT { if (this != &other) { swap(other); } return *this; } ///============================================================================= void ffw::GLCanvas::Image::swap(Image& other) NOEXCEPT { using std::swap; swap(canvas, other.canvas); swap(ref, other.ref); } ///============================================================================= ffw::GLCanvas::Font::Font(const GLCanvas* canvas, const int ref) : canvas(canvas), ref(ref) { } ///============================================================================= ffw::GLCanvas::Font::~Font() { if (ref >= 0 && canvas != nullptr) { canvas->removeFont(*this); } } ///============================================================================= ffw::GLCanvas::Font::Font(Font&& other) NOEXCEPT { swap(other); } ///============================================================================= ffw::GLCanvas::Font& ffw::GLCanvas::Font::operator = (Font&& other) NOEXCEPT { if (this != &other) { swap(other); } return *this; } ///============================================================================= void ffw::GLCanvas::Font::swap(Font& other) NOEXCEPT { using std::swap; swap(canvas, other.canvas); swap(ref, other.ref); } ///============================================================================= class ffw::GLCanvas::Impl { public: NVGcontext* nvg = nullptr; Settings settings; }; ///============================================================================= ffw::GLCanvas::GLCanvas():pimpl(nullptr) { } ///============================================================================= ffw::GLCanvas::GLCanvas(const Settings& settings):pimpl(new Impl) { pimpl->settings = settings; switch(settings.api) { case API::GL2: { pimpl->nvg = nanovgCreateGL2(settings.antialias, settings.strokes); break; } case API::GL3: { pimpl->nvg = nanovgCreateGL3(settings.antialias, settings.strokes); break; } case API::GLES2: { pimpl->nvg = nanovgCreateGLES2(settings.antialias, settings.strokes); break; } case API::GLES3: { pimpl->nvg = nanovgCreateGLES3(settings.antialias, settings.strokes); break; } case API::AUTO: { pimpl->nvg = nanovgCreateGL3(settings.antialias, settings.strokes); pimpl->settings.api = API::GL3; if (pimpl->nvg) break; pimpl->nvg = nanovgCreateGL2(settings.antialias, settings.strokes); pimpl->settings.api = API::GL2; if (pimpl->nvg) break; pimpl->nvg = nanovgCreateGLES2(settings.antialias, settings.strokes); pimpl->settings.api = API::GLES2; if (pimpl->nvg) break; pimpl->nvg = nanovgCreateGLES3(settings.antialias, settings.strokes); pimpl->settings.api = API::GLES3; break; } default: { throw GLException("Unsupported API"); } } if (!pimpl->nvg) throw GLException("Failed to initialize canvas"); } ///============================================================================= ffw::GLCanvas::GLCanvas(GLCanvas&& other) NOEXCEPT : GLCanvas() { swap(other); } ///============================================================================= ffw::GLCanvas& ffw::GLCanvas::operator = (GLCanvas&& other) NOEXCEPT { if (this != &other) { swap(other); } return *this; } ///============================================================================= ffw::GLCanvas::~GLCanvas() { destroy(); } ///============================================================================= void ffw::GLCanvas::destroy() { if (pimpl && pimpl->nvg) { switch(pimpl->settings.api) { case API::GL2: { nanovgDestroyGL2(pimpl->nvg); break; } case API::GL3: { nanovgDestroyGL3(pimpl->nvg); break; } case API::GLES2: { nanovgDestroyGLES2(pimpl->nvg); break; } case API::GLES3: { nanovgDestroyGLES3(pimpl->nvg); break; } default: { break; } } } } ///============================================================================= void ffw::GLCanvas::swap(GLCanvas& other) NOEXCEPT { using std::swap; swap(pimpl, other.pimpl); } ///============================================================================= void ffw::GLCanvas::beginFrame(const Vec2f& size) const { nvgBeginFrame(pimpl->nvg, size.x, size.y, pimpl->settings.devicePixelRatio); } ///============================================================================= void ffw::GLCanvas::endFrame() const { nvgEndFrame(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::cancelFrame() const { nvgCancelFrame(pimpl->nvg); } ///============================================================================= static NVGblendFactor toBlendFactor(const ffw::GLCanvas::BlendFactor factor) { switch (factor) { case ffw::GLCanvas::BlendFactor::ZERO: return NVGblendFactor::NVG_ZERO; case ffw::GLCanvas::BlendFactor::ONE: return NVGblendFactor::NVG_ONE; case ffw::GLCanvas::BlendFactor::SRC_COLOR: return NVGblendFactor::NVG_SRC_COLOR; case ffw::GLCanvas::BlendFactor::ONE_MINUS_SRC_COLOR: return NVGblendFactor::NVG_ONE_MINUS_SRC_COLOR; case ffw::GLCanvas::BlendFactor::DST_COLOR: return NVGblendFactor::NVG_DST_COLOR; case ffw::GLCanvas::BlendFactor::ONE_MINUS_DST_COLOR: return NVGblendFactor::NVG_ONE_MINUS_DST_COLOR; case ffw::GLCanvas::BlendFactor::SRC_ALPHA: return NVGblendFactor::NVG_SRC_ALPHA; case ffw::GLCanvas::BlendFactor::ONE_MINUS_SRC_ALPHA: return NVGblendFactor::NVG_ONE_MINUS_SRC_ALPHA; case ffw::GLCanvas::BlendFactor::DST_ALPHA: return NVGblendFactor::NVG_DST_ALPHA; case ffw::GLCanvas::BlendFactor::ONE_MINUS_DST_ALPHA: return NVGblendFactor::NVG_ONE_MINUS_DST_ALPHA; case ffw::GLCanvas::BlendFactor::SRC_ALPHA_SATURATE: return NVGblendFactor::NVG_SRC_ALPHA_SATURATE; default: return NVGblendFactor::NVG_ZERO; } } ///============================================================================= static NVGcompositeOperation toCompositeOperation(const ffw::GLCanvas::CompositeOperation op) { switch(op) { case ffw::GLCanvas::CompositeOperation::SOURCE_OVER: return NVGcompositeOperation::NVG_SOURCE_OVER; case ffw::GLCanvas::CompositeOperation::SOURCE_IN: return NVGcompositeOperation::NVG_SOURCE_IN; case ffw::GLCanvas::CompositeOperation::SOURCE_OUT: return NVGcompositeOperation::NVG_SOURCE_OUT; case ffw::GLCanvas::CompositeOperation::ATOP: return NVGcompositeOperation::NVG_ATOP; case ffw::GLCanvas::CompositeOperation::DESTINATION_OVER: return NVGcompositeOperation::NVG_DESTINATION_OVER; case ffw::GLCanvas::CompositeOperation::DESTINATION_IN: return NVGcompositeOperation::NVG_DESTINATION_IN; case ffw::GLCanvas::CompositeOperation::DESTINATION_OUT: return NVGcompositeOperation::NVG_DESTINATION_OUT; case ffw::GLCanvas::CompositeOperation::DESTINATION_ATOP: return NVGcompositeOperation::NVG_DESTINATION_ATOP; case ffw::GLCanvas::CompositeOperation::LIGHTER: return NVGcompositeOperation::NVG_LIGHTER; case ffw::GLCanvas::CompositeOperation::COPY: return NVGcompositeOperation::NVG_COPY; case ffw::GLCanvas::CompositeOperation::XOR: return NVGcompositeOperation::NVG_XOR; default: return NVGcompositeOperation::NVG_COPY; } } ///============================================================================= void ffw::GLCanvas::globalCompositeOperation(const CompositeOperation op) const { nvgGlobalCompositeOperation(pimpl->nvg, toCompositeOperation(op)); } ///============================================================================= void ffw::GLCanvas::globalCompositeBlendFunc( const BlendFactor sfactor, const BlendFactor dfactor) const { nvgGlobalCompositeBlendFunc(pimpl->nvg, toBlendFactor(sfactor), toBlendFactor(dfactor)); } ///============================================================================= void ffw::GLCanvas::globalCompositeBlendFuncSeparate( const BlendFactor srcRGB, const BlendFactor dstRGB, const BlendFactor srcAlpha, const BlendFactor dstAlpha) const { nvgGlobalCompositeBlendFuncSeparate(pimpl->nvg, toBlendFactor(srcRGB), toBlendFactor(dstRGB), toBlendFactor(srcAlpha), toBlendFactor(dstAlpha)); } ///============================================================================= void ffw::GLCanvas::save() const { nvgSave(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::restore() const { nvgRestore(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::reset() const { nvgReset(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::shapeAntiAlias(const bool enabled) const { nvgShapeAntiAlias(pimpl->nvg, enabled ? 1 : 0); } ///============================================================================= void ffw::GLCanvas::strokeColor(const Color& color) const { nvgStrokeColor(pimpl->nvg, *reinterpret_cast<const NVGcolor*>(&color)); } ///============================================================================= void ffw::GLCanvas::strokePaint(const Paint& paint) const { nvgStrokePaint(pimpl->nvg, *reinterpret_cast<const NVGpaint*>(&paint)); } ///============================================================================= void ffw::GLCanvas::fillColor(const Color& color) const { nvgFillColor(pimpl->nvg, *reinterpret_cast<const NVGcolor*>(&color)); } ///============================================================================= void ffw::GLCanvas::fillPaint(const Paint& paint) const { nvgFillPaint(pimpl->nvg, *reinterpret_cast<const NVGpaint*>(&paint)); } ///============================================================================= void ffw::GLCanvas::miterLimit(const float limit) const { nvgMiterLimit(pimpl->nvg, limit); } ///============================================================================= void ffw::GLCanvas::strokeWidth(const float size) const { nvgStrokeWidth(pimpl->nvg, size); } ///============================================================================= static NVGlineCap toLineCap(const ffw::GLCanvas::LineCap cap) { switch (cap) { case ffw::GLCanvas::LineCap::ROUND: return NVGlineCap::NVG_ROUND; case ffw::GLCanvas::LineCap::BUTT: return NVGlineCap::NVG_BUTT; case ffw::GLCanvas::LineCap::SQUARE: return NVGlineCap::NVG_SQUARE; default: return NVGlineCap::NVG_BUTT; } } ///============================================================================= void ffw::GLCanvas::lineCap(const LineCap cap) const { nvgLineCap(pimpl->nvg, toLineCap(cap)); } ///============================================================================= static NVGlineCap toLineCap(const ffw::GLCanvas::LineJoin join) { switch(join) { case ffw::GLCanvas::LineJoin::ROUND: return NVGlineCap::NVG_ROUND; case ffw::GLCanvas::LineJoin::BEVEL: return NVGlineCap::NVG_BEVEL; case ffw::GLCanvas::LineJoin::MITER: return NVGlineCap::NVG_MITER; default: return NVGlineCap::NVG_MITER; } } ///============================================================================= void ffw::GLCanvas::lineJoin(const LineJoin join) const { nvgLineJoin(pimpl->nvg, toLineCap(join)); } ///============================================================================= void ffw::GLCanvas::globalAlpha(const float alpha) const { nvgGlobalAlpha(pimpl->nvg, alpha); } ///============================================================================= void ffw::GLCanvas::resetTransform() const { nvgResetTransform(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::transform(const Mat3x3f& mat) const { nvgTransform(pimpl->nvg, mat[0], mat[1], mat[3], mat[4], mat[6], mat[7]); } ///============================================================================= void ffw::GLCanvas::translate(const Vec2f& pos) const { nvgTranslate(pimpl->nvg, pos.x, pos.y); } ///============================================================================= void ffw::GLCanvas::rotate(const float angle) const { nvgRotate(pimpl->nvg, float(angle * DEG_TO_RAD)); } ///============================================================================= void ffw::GLCanvas::rotateRad(const float angle) const { nvgRotate(pimpl->nvg, angle); } ///============================================================================= void ffw::GLCanvas::skewX(const float angle) const { nvgSkewX(pimpl->nvg, float(angle * DEG_TO_RAD)); } ///============================================================================= void ffw::GLCanvas::skewXRad(const float angle) const { nvgSkewX(pimpl->nvg, angle); } ///============================================================================= void ffw::GLCanvas::skewY(const float angle) const { nvgSkewY(pimpl->nvg, float(angle * DEG_TO_RAD)); } ///============================================================================= void ffw::GLCanvas::skewYRad(const float angle) const { nvgSkewY(pimpl->nvg, angle); } ///============================================================================= void ffw::GLCanvas::scale(float x, float y) const { nvgScale(pimpl->nvg, x, y); } ///============================================================================= ffw::Mat3x3f ffw::GLCanvas::getCurrentTransform() const { float xform[6] = { 0 }; nvgCurrentTransform(pimpl->nvg, xform); Mat3x3f mat; mat[0] = xform[0]; mat[1] = xform[1]; mat[3] = xform[2]; mat[4] = xform[3]; mat[6] = xform[4]; mat[7] = xform[5]; return mat; } ///============================================================================= void ffw::GLCanvas::setTransform(const Mat3x3f& mat) const { nvgResetTransform(pimpl->nvg); nvgTransform(pimpl->nvg, mat[0], mat[1], mat[3], mat[4], mat[6], mat[7]); } ///============================================================================= ffw::GLCanvas::Image ffw::GLCanvas::createImage(const GLTexture2D& texture, ImageFlags::Flag imageFlags) const { int ref; switch(pimpl->settings.api) { case API::GL2: { ref = nanovgCreateImageGL2(pimpl->nvg, texture.getHandle(), texture.getWidth(), texture.getHeight(), imageFlags); break; } case API::GL3: { ref = nanovgCreateImageGL3(pimpl->nvg, texture.getHandle(), texture.getWidth(), texture.getHeight(), imageFlags); break; } case API::GLES2: { ref = nanovgCreateImageGLES2(pimpl->nvg, texture.getHandle(), texture.getWidth(), texture.getHeight(), imageFlags); break; } case API::GLES3: { ref = nanovgCreateImageGLES3(pimpl->nvg, texture.getHandle(), texture.getWidth(), texture.getHeight(), imageFlags); break; } default: { throw GLException("Unsupported API"); } } auto ret = Image(this, ref); return ret; } ///============================================================================= void ffw::GLCanvas::removeImage(Image& image) const { nvgDeleteImage(pimpl->nvg, image.ref); } ///============================================================================= ffw::GLCanvas::Paint ffw::GLCanvas::linearGradient(const ffw::Vec2f& start, const ffw::Vec2f& end, const Color& icol, const Color& ocol) const { const auto paint = nvgLinearGradient(pimpl->nvg, start.x, start.y, end.x, end.y, *reinterpret_cast<const NVGcolor*>(&icol), *reinterpret_cast<const NVGcolor*>(&ocol)); Paint ret; ret.extent[0] = paint.extent[0]; ret.extent[1] = paint.extent[1]; for(auto i = 0; i < 6; i++)ret.xform[i] = paint.xform[i]; ret.feather = paint.feather; ret.innerColor = icol; ret.outerColor = ocol; return ret; } ///============================================================================= ffw::GLCanvas::Paint ffw::GLCanvas::boxGradient(const ffw::Vec2f& pos, const ffw::Vec2f& size, const float r, const float f, const Color& icol, const Color& ocol) const { const auto paint = nvgBoxGradient(pimpl->nvg, pos.x, pos.y, size.x, size.y, r, f, *reinterpret_cast<const NVGcolor*>(&icol), *reinterpret_cast<const NVGcolor*>(&ocol)); Paint ret; ret.extent[0] = paint.extent[0]; ret.extent[1] = paint.extent[1]; for (auto i = 0; i < 6; i++)ret.xform[i] = paint.xform[i]; ret.feather = paint.feather; ret.innerColor = icol; ret.outerColor = ocol; return ret; } ///============================================================================= ffw::GLCanvas::Paint ffw::GLCanvas::radialGradient(const Vec2f& center, const float inr, const float outr, const Color& icol, const Color& ocol) const { const auto paint = nvgRadialGradient(pimpl->nvg, center.x, center.y, inr, outr, *reinterpret_cast<const NVGcolor*>(&icol), *reinterpret_cast<const NVGcolor*>(&ocol)); Paint ret; ret.extent[0] = paint.extent[0]; ret.extent[1] = paint.extent[1]; for (auto i = 0; i < 6; i++)ret.xform[i] = paint.xform[i]; ret.feather = paint.feather; ret.innerColor = icol; ret.outerColor = ocol; return ret; } ///============================================================================= ffw::GLCanvas::Paint ffw::GLCanvas::imagePattern(const Vec2f& start, const Vec2f& end, const float angle, const Image& image, const float alpha) const { const auto paint = nvgImagePattern(pimpl->nvg, start.x, start.y, end.x, end.y, float(angle * DEG_TO_RAD), image.ref, alpha); Paint ret; for (auto i = 0; i < 2; i++)ret.extent[i] = paint.extent[i]; for (auto i = 0; i < 6; i++)ret.xform[i] = paint.xform[i]; ret.feather = paint.feather; ret.image = paint.image; ret.innerColor = *reinterpret_cast<const ffw::Color*>(&paint.innerColor); ret.outerColor = *reinterpret_cast<const ffw::Color*>(&paint.outerColor); return ret; } ///============================================================================= void ffw::GLCanvas::scissor(const Vec2f& pos, const Vec2f& size) const { nvgScissor(pimpl->nvg, pos.x, pos.y, size.x, size.y); } ///============================================================================= void ffw::GLCanvas::intersectScissor(const Vec2f& pos, const Vec2f& size) const { nvgIntersectScissor(pimpl->nvg, pos.x, pos.y, size.x, size.y); } ///============================================================================= void ffw::GLCanvas::resetScissor() const { nvgResetScissor(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::beginPath() const { nvgBeginPath(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::moveTo(const Vec2f& pos) const { nvgMoveTo(pimpl->nvg, pos.x, pos.y); } ///============================================================================= void ffw::GLCanvas::lineTo(const Vec2f& pos) const { nvgLineTo(pimpl->nvg, pos.x, pos.y); } ///============================================================================= void ffw::GLCanvas::bezierTo(const Vec2f& c1, const Vec2f& c2, const Vec2f& pos) const { nvgBezierTo(pimpl->nvg, c1.x, c1.y, c2.x, c2.y, pos.x, pos.y); } ///============================================================================= void ffw::GLCanvas::quadTo(const Vec2f& c, const Vec2f& pos) const { nvgQuadTo(pimpl->nvg, c.x, c.y, pos.x, pos.y); } ///============================================================================= void ffw::GLCanvas::arcTo(const Vec2f& x1, const Vec2f& x2, const float angle) const { nvgArcTo(pimpl->nvg, x1.x, x1.y, x2.x, x2.y, float(angle * DEG_TO_RAD)); } ///============================================================================= void ffw::GLCanvas::arcToRad(const Vec2f& x1, const Vec2f& x2, const float angle) const { nvgArcTo(pimpl->nvg, x1.x, x1.y, x2.x, x2.y, angle); } ///============================================================================= void ffw::GLCanvas::closePath() const { nvgClosePath(pimpl->nvg); } ///============================================================================= static NVGwinding toWinding(const ffw::GLCanvas::Winding dir) { switch(dir) { case ffw::GLCanvas::Winding::CCW: return NVGwinding::NVG_CCW; case ffw::GLCanvas::Winding::CW: return NVGwinding::NVG_CW; default: return NVGwinding::NVG_CCW; } } ///============================================================================= void ffw::GLCanvas::pathWinding(const Winding dir) const { nvgPathWinding(pimpl->nvg, toWinding(dir)); } ///============================================================================= static NVGsolidity toSolidity(const ffw::GLCanvas::Solidity dir) { switch (dir) { case ffw::GLCanvas::Solidity::HOLE: return NVGsolidity::NVG_HOLE; case ffw::GLCanvas::Solidity::SOLID: return NVGsolidity::NVG_SOLID; default: return NVGsolidity::NVG_SOLID; } } ///============================================================================= void ffw::GLCanvas::pathWinding(const Solidity dir) const { nvgPathWinding(pimpl->nvg, toSolidity(dir)); } ///============================================================================= void ffw::GLCanvas::arc(const Vec2f& center, const float r, const float a0, const float a1, const Winding dir) const { nvgArc(pimpl->nvg, center.x, center.y, r, float(a0 * DEG_TO_RAD), float(a1 * DEG_TO_RAD), toWinding(dir)); } ///============================================================================= void ffw::GLCanvas::arcRad(const Vec2f& center, const float r, const float a0, const float a1, const Winding dir) const { nvgArc(pimpl->nvg, center.x, center.y, r, a0, a1, toWinding(dir)); } ///============================================================================= void ffw::GLCanvas::rect(const Vec2f& pos, const Vec2f& size) const { nvgRect(pimpl->nvg, pos.x, pos.y, size.x, size.y); } ///============================================================================= void ffw::GLCanvas::roundedRect(const Vec2f& pos, const Vec2f& size, const float r) const { nvgRoundedRect(pimpl->nvg, pos.x, pos.y, size.x, size.y, r); } ///============================================================================= void ffw::GLCanvas::roundedRect(const Vec2f& pos, const Vec2f& size, const float radTopLeft, const float radTopRight, const float radBottomRight, const float radBottomLeft) const { nvgRoundedRectVarying(pimpl->nvg, pos.x, pos.y, size.x, size.y, radTopLeft, radTopRight, radBottomRight, radBottomLeft); } ///============================================================================= void ffw::GLCanvas::ellipse(const Vec2f& pos, const float rx, const float ry) const { nvgEllipse(pimpl->nvg, pos.x, pos.y, rx, ry); } ///============================================================================= void ffw::GLCanvas::circle(const Vec2f& pos, const float r) const { nvgCircle(pimpl->nvg, pos.x, pos.y, r); } ///============================================================================= void ffw::GLCanvas::fill() const { nvgFill(pimpl->nvg); } ///============================================================================= void ffw::GLCanvas::stroke() const { nvgStroke(pimpl->nvg); } ///============================================================================= ffw::GLCanvas::Font ffw::GLCanvas::createFont(const std::string& filename) const { const auto ref = nvgCreateFont(pimpl->nvg, "", filename.c_str()); auto ret = Font(this, ref); return ret; } ///============================================================================= ffw::GLCanvas::Font ffw::GLCanvas::createFontMem(unsigned char* data, const size_t length) const { const auto ref = nvgCreateFontMem(pimpl->nvg, "", data, length, 0); auto ret = Font(this, ref); return ret; } ///============================================================================= void ffw::GLCanvas::addFallbackFontId(Font& baseFont, Font& fallbackFont) const { nvgAddFallbackFontId(pimpl->nvg, baseFont.ref, fallbackFont.ref); } ///============================================================================= void ffw::GLCanvas::removeFont(Font& font) const { (void)font; // ??? } ///============================================================================= void ffw::GLCanvas::fontSize(const float size) const { nvgFontSize(pimpl->nvg, size); } ///============================================================================= void ffw::GLCanvas::fontBlur(const float blur) const { nvgFontBlur(pimpl->nvg, blur); } ///============================================================================= void ffw::GLCanvas::textLetterSpacing(const float spacing) const { nvgTextLetterSpacing(pimpl->nvg, spacing); } ///============================================================================= void ffw::GLCanvas::textLineHeight(const float lineHeight) const { nvgTextLineHeight(pimpl->nvg, lineHeight); } ///============================================================================= void ffw::GLCanvas::textAlign(const TextAlign::Flag align) const { nvgTextAlign(pimpl->nvg, align); } ///============================================================================= void ffw::GLCanvas::fontFace(const Font& font) const { nvgFontFaceId(pimpl->nvg, font.ref); } ///============================================================================= void ffw::GLCanvas::text(const Vec2f& pos, const char* string, const char* end) const { nvgTextBox(pimpl->nvg, pos.x, pos.y, std::numeric_limits<float>::max(), string, end); } ///============================================================================= void ffw::GLCanvas::textBox(const Vec2f& pos, const float breakRowWidth, const char* string, const char* end) const { nvgTextBox(pimpl->nvg, pos.x, pos.y, breakRowWidth, string, end); } ///============================================================================= float ffw::GLCanvas::textBounds(const Vec2f& pos, const char* string, const char* end, Vec4f& bounds) const { return nvgTextBounds(pimpl->nvg, pos.x, pos.y, string, end, &bounds[0]); } ///============================================================================= ffw::Vec4f ffw::GLCanvas::textBoxBounds(const Vec2f& pos, const float breakRowWidth, const char* string, const char* end) const { ffw::Vec4f ret; nvgTextBoxBounds(pimpl->nvg, pos.x, pos.y, breakRowWidth, string, end, &ret[0]); return ret; } ///============================================================================= void ffw::GLCanvas::textMetrics(float& ascender, float& descender, float& lineh) const { nvgTextMetrics(pimpl->nvg, &ascender, &descender, &lineh); } ///============================================================================= void ffw::GLCanvas::text(const Vec2f& pos, const std::string& str) const { text(pos, str.c_str(), str.c_str() + str.size()); } ///============================================================================= void ffw::GLCanvas::textBox(const Vec2f& pos, float breakRowWidth, const std::string& str) const { textBox(pos, breakRowWidth, str.c_str(), str.c_str() + str.size()); } ///============================================================================= float ffw::GLCanvas::textBounds(const Vec2f& pos, const std::string& str, Vec4f& bounds) const { return textBounds(pos, str.c_str(), str.c_str() + str.size(), bounds); } ///============================================================================= ffw::Vec4f ffw::GLCanvas::textBoxBounds(const Vec2f& pos, float breakRowWidth, const std::string& str) const { return textBoxBounds(pos, breakRowWidth, str.c_str(), str.c_str() + str.size()); } ///============================================================================= int ffw::GLCanvas::textBreakLines(const char* string, const char* end, float width, TextRow* rows, size_t numrows) const { return nvgTextBreakLines(pimpl->nvg, string, end, width, reinterpret_cast<NVGtextRow*>(rows), numrows); } ///============================================================================= int ffw::GLCanvas::textBreakLines(const std::string& string, float width, TextRow* rows, size_t numrows) const { return textBreakLines(string.c_str(), string.c_str() + string.size(), width, rows, numrows); } ///============================================================================= int ffw::GLCanvas::textGlyphPositions(const Vec2f& pos, const char* string, const char* end, GlyphPosition* positions, size_t numpositions) const { return nvgTextGlyphPositions(pimpl->nvg, pos.x, pos.y, string, end, reinterpret_cast<NVGglyphPosition*>(positions), numpositions); } ///============================================================================= int ffw::GLCanvas::textGlyphPositions(const Vec2f& pos, const std::string& str, GlyphPosition* positions, size_t numpositions) const { return textGlyphPositions(pos, str.c_str(), str.c_str() + str.size(), positions, numpositions); }
39.984925
147
0.489946
[ "transform", "solid" ]
9e2964f260e17da65f54d7f862a535e7a68588ca
4,265
hpp
C++
ql/forwardexchangerate.hpp
NicolaiLassesen/QuantLib
dc00374caf92d23b8f7f561ba3cc457dbe4709f5
[ "BSD-3-Clause" ]
null
null
null
ql/forwardexchangerate.hpp
NicolaiLassesen/QuantLib
dc00374caf92d23b8f7f561ba3cc457dbe4709f5
[ "BSD-3-Clause" ]
null
null
null
ql/forwardexchangerate.hpp
NicolaiLassesen/QuantLib
dc00374caf92d23b8f7f561ba3cc457dbe4709f5
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2020 Nicolai Lassesen This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file forwardexchangerate.hpp \brief forward exchange rate between two currencies */ #ifndef quantlib_forward_exchange_rate_hpp #define quantlib_forward_exchange_rate_hpp #include <ql/exchangerate.hpp> #include <ql/money.hpp> #include <ql/utilities/null.hpp> #include <ql/time/period.hpp> #include <utility> namespace QuantLib { //! forward exchange rate between two currencies /*! \test TODO */ class ForwardExchangeRate { public: //! \name Constructors //@{ ForwardExchangeRate(const Period& tenor = Period()); ForwardExchangeRate(const ExchangeRate& spotRate, const Decimal forwardPoints, const Period& tenor = Period()); //@} //! \name Inspectors //@{ //! the source currency. const Currency& source() const; //! the target currency. const Currency& target() const; //! the type ExchangeRate::Type type() const; //! the spot exchange rate object const ExchangeRate& spotExchangeRate() const; //! the spot exchange rate Decimal spotRate() const; //! the forward points Decimal forwardPoints() const; //! the all-in forward exchange rate Decimal forwardRate() const; //! the tenor const Period& tenor() const; //@} //! \name Utility methods //@{ //! apply the exchange rate to a cash amount Money exchange(const Money& amount) const; //! chain two exchange rates static ForwardExchangeRate chain(const ForwardExchangeRate& r1, const ForwardExchangeRate& r2); //! get inverse exchange rate static ForwardExchangeRate inverse(const ForwardExchangeRate& r); //@} private: ExchangeRate spotRate_; Decimal forwardPoints_; Period tenor_; ExchangeRate::Type type_; std::pair<ext::shared_ptr<ForwardExchangeRate>, ext::shared_ptr<ForwardExchangeRate> > rateChain_; }; // inline definitions inline ForwardExchangeRate::ForwardExchangeRate(const Period& tenor) : spotRate_(ExchangeRate()), forwardPoints_(Null<Decimal>()), tenor_(tenor), type_(ExchangeRate::Direct) {} inline ForwardExchangeRate::ForwardExchangeRate(const ExchangeRate& spotRate, Decimal forwardPoints, const Period& tenor) : spotRate_(spotRate), forwardPoints_(forwardPoints), tenor_(tenor), type_(ExchangeRate::Direct) {} inline const Currency& ForwardExchangeRate::source() const { return spotRate_.source(); } inline const Currency& ForwardExchangeRate::target() const { return spotRate_.target(); } inline ExchangeRate::Type ForwardExchangeRate::type() const { return type_; } inline const ExchangeRate& ForwardExchangeRate::spotExchangeRate() const { return spotRate_; } inline Decimal ForwardExchangeRate::spotRate() const { return spotRate_.rate(); } inline Decimal ForwardExchangeRate::forwardPoints() const { return forwardPoints_; } inline Decimal QuantLib::ForwardExchangeRate::forwardRate() const { return spotRate_.rate() + forwardPoints_ / 10000.0; } inline const Period& ForwardExchangeRate::tenor() const { return tenor_; } } #endif
35.541667
98
0.654162
[ "object" ]
9e310cb4c894ca23d08caef01cf618327db65944
485
cc
C++
cpp/MajorityElement.cc
speedfirst/leetcode
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
[ "BSD-3-Clause" ]
null
null
null
cpp/MajorityElement.cc
speedfirst/leetcode
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
[ "BSD-3-Clause" ]
null
null
null
cpp/MajorityElement.cc
speedfirst/leetcode
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
[ "BSD-3-Clause" ]
null
null
null
// https://oj.leetcode.com/problems/majority-element/ class Solution { public: int majorityElement(vector<int> &num) { int majEle = num[0]; int count = 1; for (int i = 1; i < num.size(); i++) { if (num[i] == majEle) count++; else { count--; if (count == 0) { majEle = num[i]; count = 1; } } } return majEle; } };
24.25
53
0.393814
[ "vector" ]
9e3188d915e43afc1247f2e048b493a41bba321b
5,159
hxx
C++
src/parse_common.hxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
16
2018-04-25T08:14:14.000Z
2022-01-29T06:19:16.000Z
src/parse_common.hxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
null
null
null
src/parse_common.hxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
null
null
null
#pragma once #include "scene.hxx" #include "camera.hxx" //#include "infiniteplane.hxx" #include "shader.hxx" #include "util.hxx" #include "light.hxx" #include <vector> #include <cstdio> #include <iostream> #include <fstream> #include <unordered_map> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #ifdef _MSC_VER // Warnings generated by yaml-cpp. Hopefully they are harmless. They don't look like it ... :-/ #pragma warning (disable: 4251) #pragma warning (disable: 4373) #pragma warning (disable: 4275) #endif #include <yaml-cpp/yaml.h> namespace scenereader { using RadianceOrImportance::AreaEmitter; namespace fs = boost::filesystem; using Transform = Eigen::Transform<double, 3, Eigen::Affine>; // TODO: Rename this template<class Thing> class SymbolTable { Thing currentThing; std::unordered_map<std::string, Thing> things; std::string name_of_this_table; public: SymbolTable(const std::string &_name) : currentThing{}, name_of_this_table(_name) {} int size() const { return isize(things); } const auto& name() const { return name_of_this_table; } void activate(const std::string &name) { auto it = things.find(name); if (it != things.end()) { currentThing = it->second; } else { char buffer[1024]; std::snprintf(buffer, 1024, "Error: %s %s not defined. Define it in the NFF file prior to referencing it.", this->name_of_this_table.c_str(), name.c_str()); throw std::runtime_error(buffer); } } void set_and_activate(const char* name, Thing thing) { currentThing = thing; things[name] = thing; } Thing operator()() const { return currentThing; } std::optional<Thing> operator[](const char *name) const { auto it = things.find(name); if (it == things.end()) return {}; else return it->second; } std::optional<Thing> operator[](const std::string &name) const { return this->operator[](name.c_str()); } }; class GlobalContext { std::unordered_map<Material, MaterialIndex, Material::Hash> to_material_index; std::vector<fs::path> search_paths; Scene* scene; RenderingParameters* params; fs::path filename; public: GlobalContext(Scene &scene_, RenderingParameters *params_, const fs::path &path_hint); auto& GetScene() const { return *scene; } auto* GetParams() const { return params; } auto GetFilename() const { return filename; } fs::path MakeFullPath(const fs::path &filename) const; }; struct Scope { SymbolTable<Shader*> shaders; SymbolTable<Medium*> mediums; SymbolTable<AreaEmitter*> areaemitters; std::unordered_map<std::string, Material> materials; Transform currentTransform; Scope() : shaders("Shader"), mediums("Medium"), areaemitters("AreaEmitter"), currentTransform{ Transform::Identity() } { } void InsertAndActivate(const std::string& name, Shader* item) { shaders.set_and_activate(name.c_str(), item); } void InsertAndActivate(const std::string& name, Medium* item) { mediums.set_and_activate(name.c_str(), item); } void InsertAndActivate(const std::string& name, AreaEmitter* item) { areaemitters.set_and_activate(name.c_str(), item); } template<class U> inline auto Lookup(const std::string &key) const; }; template<> inline auto Scope::Lookup<Shader>(const std::string &key) const { return shaders[key.c_str()]; } template<> inline auto Scope::Lookup<Medium>(const std::string &key) const { return mediums[key.c_str()]; } template<> inline auto Scope::Lookup<AreaEmitter>(const std::string &key) const { return areaemitters[key.c_str()]; } void AddDefaultMaterials(Scope &scope, const Scene &scene); inline auto NormalTrafo(const Transform &trafo) { return trafo.linear().inverse().transpose().eval(); } namespace assimp { using MaterialGetter = std::function<Material(const std::optional<std::string> &)>; void Read(Scene &scene, Transform model_transform, MaterialGetter material_getter, bool material_assignment_by_object_names, const fs::path &filename_path); } // namespace assimp } // namespace scenereader namespace YAML { // Adapted from https://github.com/jbeder/yaml-cpp/wiki/Tutorial template<> struct convert<Double3> { static bool decode(const Node& node, Double3& rhs) { if (!node.IsSequence() || node.size() != 3) { return false; } rhs[0] = node[0].as<double>(); rhs[1] = node[1].as<double>(); rhs[2] = node[2].as<double>(); return true; } }; template<> struct convert<RGB> { static bool decode(const Node& node, RGB& rhs) { if (!node.IsSequence() || (node.size() != 3 && node.size() != 1)) { return false; } rhs[0] = RGBScalar{ node[0].as<double>() }; if (node.size() == 3) { rhs[1] = RGBScalar{ node[1].as<double>() }; rhs[2] = RGBScalar{ node[2].as<double>() }; } else { rhs[1] = rhs[2] = rhs[0]; } return true; } }; }
24.684211
163
0.648381
[ "vector", "transform" ]
9e3d2d09deb31b8b043c08d113fbb1161cd63f18
1,089
cpp
C++
SGIPC practice contests/stl sgipc cntst/prime factorization.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
SGIPC practice contests/stl sgipc cntst/prime factorization.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
SGIPC practice contests/stl sgipc cntst/prime factorization.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #include <vector> #include <math.h> using namespace std; int main() { vector<long long unsigned int>prime; long long unsigned int n,i,j,val,count=0,ans=1,x=0,f=0,sqrtN; cin>>n; sqrtN=sqrt(n); //cout<<sqrtN<<endl; bool flag[n+50]; flag[0]=1; flag[1]=1; prime.push_back(2); for(i=4; i<=sqrtN; i+=2) { flag[i]=1; } for (i=3; i*i<=(long long unsigned int)sqrtN; i=i+2) { if (flag[i]==0) { for (j=i*i; j<=sqrtN; j=2*i+j) { flag[j]=1; } } } for (i=3; i<=sqrtN; i+=2) { if (flag[i]==0) { cout<<i<<endl; prime.push_back(i); } } val=prime.size(); //cout<<val<<endl; for(i=0; i<val; i++) { if (n%prime[i]==0) { while (n%prime[i]==0) { x++; n=n/prime[i]; } cout<<prime[i]<<"^"<<x<<endl; } x=0; //sqrtN=sqrt(n); } return 0; }
18.775862
65
0.395776
[ "vector" ]
9e472ee2c322edeab21b7b3b9ce863040f404804
4,057
cpp
C++
modules/task_2/barysheva_m_tape_hor_chart/tape_hor_chart.cpp
NickitaKraev/pp_2021_autumn
dac9c0aa556ef15823af16bfae0044e282c5f7cb
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_2/barysheva_m_tape_hor_chart/tape_hor_chart.cpp
NickitaKraev/pp_2021_autumn
dac9c0aa556ef15823af16bfae0044e282c5f7cb
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/barysheva_m_tape_hor_chart/tape_hor_chart.cpp
NickitaKraev/pp_2021_autumn
dac9c0aa556ef15823af16bfae0044e282c5f7cb
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Barysheva Maria #include "../../../modules/task_2/barysheva_m_tape_hor_chart/tape_hor_chart.h" #include <mpi.h> #include <algorithm> #include <random> #include <string> #include <vector> #define A_TAG 1 #define B_TAG 2 vector<int> getRandomMatrix(int n, int m) { std::random_device dev; std::mt19937 gen(dev()); vector<int> matrix(n * m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i * m + j] = gen() % 100; } } return matrix; } vector<int> SequentialMatrixMultiplication(vector<int> A, vector<int> B, int A_n, int A_m, int B_m) { int B_n = A_m; int matrix_size = A_n * B_m; vector<int> matrix(matrix_size, 0); for (int i = 0; i < A_n; i++) { for (int j = 0; j < B_m; j++) { for (int k = 0; k < A_m; k++) { matrix[i * B_m + j] += A[i * B_n + k] * B[k * B_m + j]; } } } return matrix; } vector<int> ParallelMatrixMultiplication(vector<int> A, vector<int> B, int A_n, int A_m) { int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (A_n < size || size == 1) { if (rank == 0) { return SequentialMatrixMultiplication(A, B, A_n, A_m, A_n); } else { return vector<int>{}; } } int B_n = A_m; int B_m = A_n; int delta = A_n / size; int rem = A_n % size; if (rank == 0) { for (int proc = 1; proc < size; proc++) { int index_A = proc * delta * A_m; int index_B = proc * delta; if (rem != 0) { index_A += rem * A_m; index_B += rem; } vector<int> b_columns(delta * B_n, 0); for (int i = 0; i < static_cast<int>(b_columns.size()); i++) { int index_n = i % delta; int index_m = (i / delta) * B_m; b_columns[i] = B[index_B + index_n + index_m]; } MPI_Send(A.data() + index_A, delta * A_m, MPI_INT, proc, A_TAG, MPI_COMM_WORLD); MPI_Send(b_columns.data(), b_columns.size(), MPI_INT, proc, B_TAG, MPI_COMM_WORLD); } } int local_x = (delta + rem) * A_m; vector<int> local_a(local_x, 0); vector<int> local_b(local_x + 1, 0); if (rank == 0) { for (int i = 0; i < local_x; i++) { int index_n = i % (delta + rem); int index_m = (i / (delta + rem)) * B_m; local_b[i] = B[index_n + index_m]; local_a[i] = A[i]; } } else { MPI_Recv(local_a.data(), local_x - rem * A_m, MPI_INT, 0, A_TAG, MPI_COMM_WORLD, MPI_STATUSES_IGNORE); MPI_Recv(local_b.data(), local_x - rem * A_m, MPI_INT, 0, B_TAG, MPI_COMM_WORLD, MPI_STATUSES_IGNORE); } if (rank == 0) { local_b[local_x] = 0; } else { local_b[local_x] = rank * delta + rem; } vector<int> local_product(A_n * B_m, 0); int from = (rank + 1) % size; int to = (rank - 1) < 0 ? size - 1 : rank - 1; for (int i = 0; i < size; i++) { int local_A_n; if (rank == 0) { local_A_n = delta + rem; } else { local_A_n = delta; } int local_B_m; if ((rank + i) % size == 0) { local_B_m = delta + rem; } else { local_B_m = delta; } vector<int> temp = SequentialMatrixMultiplication( local_a, local_b, local_A_n, A_m, local_B_m); int index_matrix; if (rank == 0) { index_matrix = 0; } else { index_matrix = (rank * delta + rem) * A_n; } for (int j = 0; j < static_cast<int>(temp.size()); j++) { int index_n = local_b[local_x] + j % local_B_m; int index_m = (j / local_B_m) * A_n; local_product[index_matrix + index_n + index_m] += temp[j]; } MPI_Sendrecv_replace(local_b.data(), local_b.size(), MPI_INT, to, i, from, i, MPI_COMM_WORLD, MPI_STATUSES_IGNORE); } vector<int> global_product(A_n * B_m, 0); MPI_Reduce(local_product.data(), global_product.data(), local_product.size(), MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); return global_product; }
25.515723
79
0.548928
[ "vector" ]
9e476db7b67de7a1fc5d205cc44c61ad9e051df3
649
hh
C++
include/WCSimPiZeroSeeder.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimPiZeroSeeder.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
include/WCSimPiZeroSeeder.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
/* * WCSimPiZeroSeeder.hh * * Created on: 9 Sep 2015 * Author: ajperch */ #pragma once #include "WCSimLikelihoodFitter.hh" #include <vector> class WCSimPiZeroSeed; class WCSimFitterConfig; class WCSimPiZeroSeeder : public WCSimLikelihoodFitter { public: WCSimPiZeroSeeder(WCSimFitterConfig *config); virtual ~WCSimPiZeroSeeder(); std::vector<WCSimPiZeroSeed *> GetSeeds(); WCSimPiZeroSeed *GetSeed(unsigned int i); unsigned int GetNumSeeds(); virtual void SetEvent(const int &event); protected: virtual void MakeSeeds() = 0; std::vector<WCSimPiZeroSeed *> fPiZeroSeeds; bool fMadeSeeds; ClassDef(WCSimPiZeroSeeder, 0); };
19.666667
54
0.753467
[ "vector" ]
eafb1aab1e95fe0bdfa539d797b1622321f93a4d
9,947
cpp
C++
matlab/panoContext_code/DDSampling/roomAlignment/roomAlignmentMexLiving_delete.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
380
2018-02-23T02:58:35.000Z
2022-03-21T06:34:33.000Z
matlab/panoContext_code/DDSampling/roomAlignment/roomAlignmentMexLiving_delete.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
36
2018-04-11T03:49:42.000Z
2021-01-21T01:25:47.000Z
matlab/panoContext_code/DDSampling/roomAlignment/roomAlignmentMexLiving_delete.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
94
2018-02-25T05:23:51.000Z
2022-02-11T02:00:47.000Z
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #include <omp.h> //#include <future> #include "mex.h" #include <fstream> #include <vector> #include <algorithm> using namespace std; #define INF 1000000 //#define MAXCOST 3.0f #define NUMBTHREAD 4 float MAXCOST = 3.0f; int verbose = 0; struct OBJHYP { float fObjSize[3]; float fObjCenter[3]; int iObjType; float fAspectRatioXY; float fAreaXY; }; struct ROOMHYP { int iRoomIdx; vector<OBJHYP> vObjects; }; template <class T> void ReadData(const mxArray *M, vector<ROOMHYP> &V) { const mwSize *dims = mxGetDimensions(M); int hypRoomNum = (int) dims[0]; V.assign( hypRoomNum, ROOMHYP()); for (int i = 0; i < hypRoomNum; i++) { T *objcenter = (T *) mxGetData( mxGetField( M, i, "objcenter") ); T *objsize = (T *) mxGetData( mxGetField( M, i, "objsize") ); T *objtype = (T *) mxGetData( mxGetField( M, i, "objtype") ); T *objaspectXY = (T *) mxGetData( mxGetField( M, i, "objaspectXY") ); T *objregionXY = (T *) mxGetData( mxGetField( M, i, "objregionXY") ); const mwSize *d = mxGetDimensions(mxGetField( M, i, "objtype")); int numObject = int(d[1]); V[i].vObjects.assign( numObject, OBJHYP()); V[i].iRoomIdx = 0; for (int j = 0; j<numObject; j++) { OBJHYP &obj = V[i].vObjects[j]; int iStartID = j*3; obj.iObjType = objtype[j]; obj.fAspectRatioXY = (float) objaspectXY[j]; obj.fAreaXY = (float) objregionXY[j]; obj.fObjSize[0] = (float) objsize[iStartID]; obj.fObjSize[1] = (float) objsize[iStartID+1]; obj.fObjSize[2] = (float) objsize[iStartID+2]; obj.fObjCenter[0] = (float) objcenter[iStartID]; obj.fObjCenter[1] = (float) objcenter[iStartID+1]; obj.fObjCenter[2] = (float) objcenter[iStartID+2]; } } } template <typename T> vector<int> sort_indexes(const vector<T> &v) { // initialize original index locations vector<int> idx(v.size()); for (int i = 0; i != idx.size(); ++i) idx[i] = i; // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](int i1, int i2) {return v[i1] < v[i2];}); return idx; } void bipartiteMatching(vector<float> IN_costMat, int IN_hypnum, int IN_gndnum, float &OUT_cost, vector<int> &OUT_hypid, vector<int> &OUT_gndid) { OUT_hypid.reserve(IN_hypnum); OUT_gndid.reserve(IN_gndnum); OUT_cost = 0; vector<int> idx = sort_indexes(IN_costMat); for ( int i=0; i<idx.size(); i++) { if (IN_costMat[idx[i]]<MAXCOST) { int hypid = idx[i]%IN_hypnum; int gndid = idx[i]/IN_hypnum; OUT_hypid.push_back(hypid); OUT_gndid.push_back(gndid); OUT_cost += IN_costMat[idx[i]]; //min( MAXCOST, IN_costMat[idx[i]]); for (int j=0; j<IN_hypnum; j++) { IN_costMat[gndid*IN_hypnum+j] = INF; } for (int j=0; j<IN_gndnum; j++) { IN_costMat[j*IN_hypnum+hypid] = INF; } } } } float objCtrDist( OBJHYP &ob1, OBJHYP &ob2, float *invnorm) { float fDist[3]; //float fSize[3]; float buf = 0; for ( int i=0; i<3; i++) { buf = (ob1.fObjCenter[i] - ob2.fObjCenter[i])*invnorm[i]; fDist[i] = buf*buf; //buf = (ob1.fObjSize[i]+ob2.fObjSize[i])/2; //fSize[i] = buf*buf; } return sqrt(fDist[0]+fDist[1]+fDist[2]); //return sqrt((fDist[0]+fDist[1]+fDist[2])/(fSize[0]+fSize[1]+fSize[2])); } float objVolInte( OBJHYP &ob1, OBJHYP &ob2) { float fMinSize[3]; for (int i=0; i<3; i++) { fMinSize[i] = min(ob1.fObjSize[i], ob2.fObjSize[i]); } return fMinSize[0]*fMinSize[1]*fMinSize[2]; } float objVolume( OBJHYP &ob) { return ob.fObjSize[0]*ob.fObjSize[1]*ob.fObjSize[2]; } float objTypeCost( OBJHYP &ob1, OBJHYP &ob2) { if ( ob1.iObjType == ob2.iObjType) { return 0; } else { return 1; } } void roomMatching( ROOMHYP &hyp, ROOMHYP &gnd, float &match_cost) { float hypRoomAR = hyp.vObjects[hyp.iRoomIdx].fAspectRatioXY; float gndRoomAR = gnd.vObjects[gnd.iRoomIdx].fAspectRatioXY; float hypRoomRe = hyp.vObjects[hyp.iRoomIdx].fAreaXY; float gndRoomRe = gnd.vObjects[gnd.iRoomIdx].fAreaXY; float RegionProp = hypRoomRe/gndRoomRe; if ( RegionProp<0.5 || RegionProp>2) { match_cost = INF; return; } float AspectProp = hypRoomAR/gndRoomAR; if ( AspectProp<0.5 || AspectProp>2) { match_cost = INF; return; } int HypObjNum = hyp.vObjects.size(); int GndObjNum = gnd.vObjects.size(); float ctrDistNorm[3]; ctrDistNorm[0] = 4.0/min(hyp.vObjects[hyp.iRoomIdx].fObjSize[0], gnd.vObjects[gnd.iRoomIdx].fObjSize[0]); ctrDistNorm[1] = 4.0/min(hyp.vObjects[hyp.iRoomIdx].fObjSize[1], gnd.vObjects[gnd.iRoomIdx].fObjSize[1]); ctrDistNorm[2] = 4.0/min(hyp.vObjects[hyp.iRoomIdx].fObjSize[2], gnd.vObjects[gnd.iRoomIdx].fObjSize[2]); float ctrDistThres = sqrt(2.0*(MAXCOST+0.125))-0.5; float volCostThres = 1.0/(1+MAXCOST); vector<float> costMat(HypObjNum*GndObjNum); float gndstart; float locCtrDist, locVolInte, locVolume1, locVolume2, locVolCost, locTypeCost; for ( int gid=0; gid<GndObjNum; gid++) { gndstart = gid*HypObjNum; for (int hid = 0; hid<HypObjNum; hid++) { locCtrDist = objCtrDist(hyp.vObjects[hid], gnd.vObjects[gid], ctrDistNorm); if ( locCtrDist>ctrDistThres) { costMat[gndstart+hid] = INF; continue; } locVolInte = objVolInte(hyp.vObjects[hid], gnd.vObjects[gid]); locVolume1 = objVolume(hyp.vObjects[hid]); locVolume2 = objVolume(gnd.vObjects[gid]); locVolCost = locVolInte/(locVolume1+locVolume2-locVolInte); if ( locVolCost<volCostThres) { costMat[gndstart+hid] = INF; continue; } locTypeCost = objTypeCost(hyp.vObjects[hid], gnd.vObjects[gid]); costMat[gndstart+hid] = 0.5*(locCtrDist+0.5)*(locCtrDist+0.5)-0.125 + 1.0/(locVolCost+0.000001)-1; /*if (verbose>2) { printf("hypid: %d, gndid: %d, CtrDist: %f, VolInte: %f, Vol1: %f, Vol2: %f, Volc: %f, Type: %f\n", hid+1, gid+1, locCtrDist, locVolInte, locVolume1, locVolume2, locVolInte/(locVolume1+locVolume2-locVolInte), locTypeCost); }*/ if (locTypeCost>0.5) { costMat[gndstart+hid] += 1; } if (hyp.vObjects[hid].iObjType==29 || gnd.vObjects[gid].iObjType==29) { costMat[gndstart+hid] *= 2; } } } vector<int> match_hypid; vector<int> match_gndid; bipartiteMatching(costMat, HypObjNum, GndObjNum, match_cost, match_hypid, match_gndid); if (verbose>1) { printf("hypID: "); for (int i=0; i<match_hypid.size(); i++) { printf("%d ", match_hypid[i]+1); } printf("\n"); printf("gndID: "); for (int i=0; i<match_gndid.size(); i++) { printf("%d ", match_gndid[i]+1); } printf("\n"); printf("Cost: "); for (int i=0; i<match_gndid.size(); i++) { printf("%f ", costMat[match_gndid[i]*HypObjNum+match_hypid[i]]); } printf("\n"); } vector<bool> unmatchedGnd; unmatchedGnd.assign(GndObjNum, true); vector<bool> unmatchedHyp; unmatchedHyp.assign(HypObjNum, true); for ( int i=0; i<match_gndid.size(); i++) { unmatchedGnd[match_gndid[i]] = false; } for ( int i=0; i<match_hypid.size(); i++) { unmatchedHyp[match_hypid[i]] = false; } float normVolume = 1.0/ctrDistNorm[0]/ctrDistNorm[1]/ctrDistNorm[2]; float missVolume, missCost; float hypUnmatchCost = MAXCOST/2/2; float gndUnmatchCost = MAXCOST/2; for (int i=0; i<GndObjNum; i++) { if ( unmatchedGnd[i] ) { missVolume = gnd.vObjects[i].fObjSize[0]*gnd.vObjects[i].fObjSize[1]*gnd.vObjects[i].fObjSize[2]; missCost = gndUnmatchCost * missVolume/normVolume * 2; match_cost += min(max(missCost, gndUnmatchCost), gndUnmatchCost*4); if (verbose>1) { printf("%d unmatched gnd adds %f cost\n", i+1, min(max(missCost, gndUnmatchCost), gndUnmatchCost*4)); } } } for (int i=0; i<HypObjNum; i++) { if ( unmatchedHyp[i] ) { missVolume = hyp.vObjects[i].fObjSize[0]*hyp.vObjects[i].fObjSize[1]*hyp.vObjects[i].fObjSize[2]; missCost = hypUnmatchCost * missVolume/normVolume * 2; match_cost += min(max(missCost, hypUnmatchCost), hypUnmatchCost*4); if (verbose>1) { printf("%d unmatched hyp adds %f cost\n", i+1, min(max(missCost, hypUnmatchCost), hypUnmatchCost*4)); } } } //match_cost += MAXCOST*(GndObjNum-match_gndid.size()) + 0.5*MAXCOST*(HypObjNum-match_hypid.size()); match_cost /= GndObjNum; if (verbose>0) { printf("Total: %f\n", match_cost); } } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { vector<ROOMHYP> vHypRooms; ReadData<float>( prhs[0], vHypRooms); vector<ROOMHYP> vGndRooms; ReadData<float>( prhs[1], vGndRooms); double *c = (double *) mxGetData(prhs[2]); MAXCOST = *c; if ( nrhs==3) { verbose = 0; } else if (nrhs==4) { double *c = (double *) mxGetData(prhs[3]); verbose = (int)(*c); } else { printf("Wrong number of input.\n"); return; } mwSize dims[2]; dims[0] = vHypRooms.size(); dims[1] = vGndRooms.size(); mxArray *out1 = mxCreateNumericArray( 2, dims, mxSINGLE_CLASS, mxREAL); float* p = (float *)mxGetData(out1); //omp_set_dynamic(0); //omp_set_num_threads(NUMBTHREAD); //#pragma omp parallel for //vector<future<void>> f(16); //int count = 0; //omp_set_dynamic(0); //omp_set_num_threads(NUMBTHREAD); #pragma omp parallel for for (int i=0; i<vGndRooms.size(); i++) { for (int j=0; j<vHypRooms.size(); j++) { roomMatching( vHypRooms[j], vGndRooms[i], p[i*vHypRooms.size()+j]); //f[count++] = async([&](){ // roomMatching( vHypRooms[j], vGndRooms[i], p[i*vHypRooms.size()+j]); //}, std::launch::async); // //if (count == 16) { // for(int k = 0; k != 16; ++k) { // f[k].get(); // } // count = 0; //} } } nlhs = 1; plhs[0] = out1; }
25.570694
226
0.6226
[ "vector" ]
d80b3255140815c537df548f84ffc8a41bddb8e0
2,566
cpp
C++
cpp/A0167/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:13.000Z
2021-11-26T14:34:34.000Z
cpp/A0167/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:49.000Z
2021-11-28T11:28:49.000Z
cpp/A0167/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
null
null
null
// URL : https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/ // Author : Modnar // Date : 2020/02/20 #include <map> #include <vector> #include <cstdlib> #include <iostream> /* ************************* */ // 使用同A0001相同的算法 // Time: 8ms Memory: 9.9MB class Solution { public: std::vector<int> twoSum(std::vector<int> &nums, int target) { std::map<int, int> mpos; for (int i = 0; i != nums.size(); ++i) { if (mpos.find(nums[i]) == mpos.end()) mpos[target-nums[i]] = i + 1; else return std::vector<int>({mpos[nums[i]], i+1}); } return std::vector<int>(); } }; /* ************************* */ // Time: 8ms Memory: 9.7MB namespace AnsOne { /** * 使用双下标来访问vector两端,当两下标所指值之和小于target时,低下标增加;大于 * 时,高下标减小,直至高低下标交换位置(按题意,此情况不会发生)。 */ class Solution { public: std::vector<int> twoSum(std::vector<int> &nums, int target) { for (int i = 0, j = nums.size()-1; i < j; ) { int sum = nums[i] + nums[j]; if (sum < target) ++i; else if (sum > target) --j; else return std::vector<int>({i+1, j+1}); } return std::vector<int>(); } }; } // Time: 8ms Memory: 9.8MB namespace AnsTwo { /** * 对vector从头遍历,针对当前下标,对其右侧所有元素(按从左到右即从小到大顺序)进行 * 二分查找,直到某个下标满足题意。 */ class Solution { public: std::vector<int> twoSum(std::vector<int> &nums, int target) { int length = nums.size(); for (int i = 0; i != length; ++i) { int pos; if ((pos = binSearch(nums, i+1, length, target-nums[i])) != -1) return std::vector<int>({i+1, pos+1}); } return std::vector<int>(); } private: int binSearch(const std::vector<int> &nums, int low, int high, int target) { while (low <= high) { int mid = low + (high - low) / 2; if (target > nums[mid]) low = mid + 1; else if (target < nums[mid]) high = mid - 1; else return mid; } return -1; } }; } int main(int argc, char *argv[]) { std::vector<int> nums = {5, 25, 75}; for (int &val : (new AnsTwo::Solution())->twoSum(nums, 100)) std::cout << val << " "; std::cout << std::endl; return 0; }
27.297872
84
0.450117
[ "vector" ]
d80cff54d059e4082745a57ee47e92c45d5a94f9
10,197
cpp
C++
src/dTree/DTree.cpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
3
2019-02-28T11:29:45.000Z
2021-03-24T23:22:05.000Z
src/dTree/DTree.cpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
null
null
null
src/dTree/DTree.cpp
fdbresearch/FBENCH
9f6c4ea79448649a74d2136ead93e4e5008a33a5
[ "Apache-2.0" ]
1
2021-03-19T02:56:16.000Z
2021-03-19T02:56:16.000Z
//===----------------------------------------------------------------------===// // // FBench // // https://fdbresearch.github.io/ // // Copyright (c) 2019, FDB Research Group, University of Oxford // //===----------------------------------------------------------------------===// #include <fstream> #include <sstream> #include <algorithm> #include <DTree.h> #include <Logging.hpp> #include <set> #define BUF_SIZE 1024 static const char ATTRIBUTE_SEPARATOR_CHAR = ','; static const char COMMENT_CHAR = '#'; static const char PARAMETER_SEPARATOR_CHAR = ' '; using namespace std; DTree::DTree(string fileName) { buildFromFile(fileName); extendDTree(_root); } DTree::~DTree(void) { for (int i = 0; i < _numOfAttributes + _numOfRelations; ++i) if (_nodes[i] != NULL) delete _nodes[i]; } int DTree::numberOfAttributes() { return _numOfAttributes; } int DTree::numberOfRelations() { return _numOfRelations; } DTreeNode* DTree::getNode(int index) { if (index < 0 || index >= _numOfAttributes + _numOfRelations) return NULL; if (_nodes[index] == NULL) { return _nodes[index]; } return _nodes[index]; } DTreeNode* DTree::getNode(string relationName) { unordered_map<string, int>::iterator result = _nodesMap.find(relationName); if (result == _nodesMap.end()) { return NULL; } return getNode((*result).second); } int DTree::getIndexByName(string relationName) { unordered_map<string, int>::iterator result = _nodesMap.find(relationName); if (result == _nodesMap.end()) return -1; return (*result).second; } void DTree::extendDTree(DTreeNode* node) { node->_schema.push_back(node->_id); node->_childrenIDs = new int[node->_numOfChildren + 1]; /* Copy the schema from all children up. */ DTreeNode* child = node->_firstChild; for (int i = 0; i < node->_numOfChildren; ++i) { extendDTree(child); node->_schema.insert(node->_schema.end(), child->_schema.begin(), child->_schema.end()); node->_childrenIDs[i] = child->_id; child = child->_next; } } void DTree::buildFromFile(string fileName) { /* Load the DTree config file into an input stream. */ ifstream input(fileName); if (!input) { ERROR(fileName+" does not exist. \n"); exit(1); } /* Number of attributes and tables. */ int n, m; string nString, mString; /* String and associated stream to receive lines from the file. */ string line; stringstream ssLine; /* String to receive the attributes from the relation. */ string attr; /* Extract number of attributes and tables. */ while (getline(input, line)) { if (line[0] == COMMENT_CHAR || line == "") continue; break; } ssLine << line; getline(ssLine, nString, PARAMETER_SEPARATOR_CHAR); getline(ssLine, mString, PARAMETER_SEPARATOR_CHAR); ssLine.clear(); /* Convert the strings to integers. */ n = stoi(nString); m = stoi(mString); vector<vector<int> > attributes; this->_numOfAttributes = n; this->_numOfRelations = m; this->_nodes.clear(); this->_nodes.resize(n + m, NULL); this->_nodesMap.clear(); this->_attr = attributes; /* Read all the attributes - name and value - and parent and key. */ string name; string type; string key; string index; string parent; string caching; for (int i = 0; i < n; ++i) { /* Extract node information for each attribute. */ while (getline(input, line)) { if (line[0] == COMMENT_CHAR || line == "") continue; break; } ssLine << line; /* Get the six parameters specified for each attribute. */ getline(ssLine, index, PARAMETER_SEPARATOR_CHAR); getline(ssLine, name, PARAMETER_SEPARATOR_CHAR); getline(ssLine, type, PARAMETER_SEPARATOR_CHAR); getline(ssLine, parent, PARAMETER_SEPARATOR_CHAR); getline(ssLine, key, PARAMETER_SEPARATOR_CHAR); getline(ssLine, caching, PARAMETER_SEPARATOR_CHAR); /* Clear string stream. */ ssLine.clear(); if (i != stoi(index)) ERROR("Inconsistent index specified in your DTree config file.\n"); this->_nodes[i] = new DTreeNode(name, i); this->_nodesMap[name] = i; this->_nodes[i]->_caching = (caching != "0"); key.erase(key.begin()); key.erase(key.end() - 1); ssLine << key; while (getline(ssLine, attr, ATTRIBUTE_SEPARATOR_CHAR)) { this->_nodes[i]->_key.push_back(atoi(attr.c_str())); } if (stoi(parent) == -1) { this->_root = this->_nodes[i]; this->_nodes[i]->_parent = NULL; } else { this->_nodes[stoi(parent)]->addChild(this->_nodes[i]); } /* Clear string stream. */ ssLine.clear(); } /* Read all the relation names, their parents and attributes. */ for (int i = 0; i < m; ++i) { /* Extract node information for each relation. */ while (getline(input, line)) { if (line[0] == COMMENT_CHAR || line == "") continue; break; } ssLine << line; /* Get the three parameters specified for each relation. */ getline(ssLine, name, PARAMETER_SEPARATOR_CHAR); getline(ssLine, parent, PARAMETER_SEPARATOR_CHAR); getline(ssLine, key, PARAMETER_SEPARATOR_CHAR); /* Clear string stream. */ ssLine.clear(); this->_nodes[n + i] = new DTreeNode(name, n + i); this->_nodesMap[name] = n + i; this->_nodes[n + i]->_parent = this->_nodes[stoi(parent)]; ssLine << key; vector<int> temp; while (getline(ssLine, attr, ATTRIBUTE_SEPARATOR_CHAR)) { temp.push_back(_nodesMap[attr]); } this->_attr.push_back(temp); /* Clear string stream. */ ssLine.clear(); } } /** * Build the ancestor map by preorder traversal */ static void buildAnc(DTreeNode* node, int parentID, std::unordered_map<int, std::set<int>>& ancMap) { // ancMap // anc = anc(parent) + parent std::set<int> ancs; if (parentID != -1) { ancs.insert(ancMap[parentID].begin(), ancMap[parentID].end()); ancs.insert(parentID); } ancMap.insert({node->_id, ancs}); DTreeNode* child = node->_firstChild; for (int i = 0; i < node->_numOfChildren; ++i) { buildAnc(child, node->_id, ancMap); child = child->_next; } return; } /** * Get all root-to-leaf paths */ static void getPaths(DTreeNode* node, std::unordered_map<int, std::set<int>>& ancMap, std::set<std::set<int>>& paths) { // leaf node if (node->_numOfChildren == 0) { std::set<int> path(ancMap[node->_id]); path.insert(node->_id); paths.insert(path); } DTreeNode* child = node->_firstChild; for (int i = 0; i < node->_numOfChildren; ++i) { getPaths(child, ancMap, paths); child = child->_next; } return; } /** * Attributes from a relation should be on a single root-to-leaf path */ static void checkPaths(DTreeNode* node, DTree* dtree, std::unordered_map<int, std::set<int>>& ancMap) { // get all root-to-leaf paths std::set<std::set<int>> paths; getPaths(node, ancMap, paths); // attrs from each relation for (auto attrs : dtree->_attr) { bool found = false; for (auto path : paths) { std::set<int> attrsSet(attrs.begin(), attrs.end()); // attrs should be a subset of the path if (std::includes(path.begin(), path.end(), attrsSet.begin(), attrsSet.end())) { found = true; break; } } if (!found) { // report the relation std::string s; for (auto attrId : attrs) { s += dtree->_nodes[attrId]->_name; s += ", "; } std::cout << "The attributes " << s << "come from the same relation but they are not in a single root-to-leaf path." << std::endl; } } } /** * Return all attributes that are in the same relation with A */ static std::set<int> schemaOf(int id, DTree* dtree) { // union of all _attr that contain the id std::set<int> schema; for (auto attrs : dtree->_attr) { // if the attr vector contains the target id if (std::find(attrs.begin(), attrs.end(), id) != attrs.end()) { schema.insert(attrs.begin(), attrs.end()); } } return schema; } /** * Check the key sets of attributes: * 1. key(A) is a subset anc(A) * 2. schema(A) intersects anc(A) is a subset of key(A) * 3. for any child B of A, key(B) is a subset of key(A) \union A * schema(A) means the attributes that are in the same relation with A */ static void checkKey(DTreeNode* node, DTree* dtree, std::unordered_map<int, std::set<int>>& ancMap) { // process the node // 1. key(A) is a subset anc(A) std::set<int> keys(node->_key.begin(), node->_key.end()); std::set<int> ancs = ancMap[node->_id]; if (!std::includes(ancs.begin(), ancs.end(), keys.begin(), keys.end())) { // assertion 1 is violated std::cout << "The key(" << node->_name << ") should be the subset of anc(" << node->_name << ")." << std::endl; } // 2. schema(A) intersects anc(A) is a subset of key(A) std::set<int> schema = schemaOf(node->_id, dtree); std::set<int> intersection; std::set_intersection(schema.begin(), schema.end(), ancs.begin(), ancs.end(), std::inserter(intersection, intersection.begin())); if (!std::includes(keys.begin(), keys.end(), intersection.begin(), intersection.end())) { // assertion 2 is violated std::cout << "The schema attributes of " << node->_name << " should be a subset of key(" << node->_name << ") set." << std::endl; } // key(A) union A std::set<int> unionKeys(keys.begin(), keys.end()); unionKeys.insert(node->_id); // recursion DTreeNode* child = node->_firstChild; for (int i = 0; i < node->_numOfChildren; ++i) { // 3. for any child B of A, key(B) is a subset of key(A) \union A if (!std::includes(unionKeys.begin(), unionKeys.end(), child->_key.begin(), child->_key.end())) { // assertion 3 is violated std::cout << "The key(" << child->_name << ") should be a subset of key(" << node->_name << ")." << std::endl; } checkKey(child, dtree, ancMap); child = child->_next; } return; } /** * Check the validation of the dtree */ void DTree::isValid() { // add the anc set to each variable // use a hashmap to mapping from attr->ancs std::unordered_map<int, std::set<int>> ancMap = {}; // attr -> anc set // TODO: sanity check of spelling and indexing // build the anc sets for attrs buildAnc(this->_root, -1, ancMap); // Attributes from a relation should be on a single root-to-leaf path checkPaths(this->_root, this, ancMap); // three conditions of dtree nodes checkKey(this->_root, this, ancMap); std::cout << "Completed the dtree checking." << std::endl; }
24.220903
133
0.64519
[ "vector" ]
d81193791de38c3b8758c894eaa3564fe622d969
24,668
hpp
C++
Source/RegionGrowing/Algorithm/ssBVH/ssBVH_Node.hpp
timdecode/InteractiveElementPalettes
ea5b7fcd78f8413aa9c770788259fbb944d4778d
[ "MIT" ]
33
2019-04-23T23:00:09.000Z
2021-11-09T11:44:09.000Z
Source/RegionGrowing/Algorithm/ssBVH/ssBVH_Node.hpp
timdecode/InteractiveDiscreteElementPalettes
ea5b7fcd78f8413aa9c770788259fbb944d4778d
[ "MIT" ]
1
2019-10-09T15:57:56.000Z
2020-03-05T20:01:01.000Z
Source/RegionGrowing/Algorithm/ssBVH/ssBVH_Node.hpp
timdecode/InteractiveDiscreteElementPalettes
ea5b7fcd78f8413aa9c770788259fbb944d4778d
[ "MIT" ]
6
2019-04-25T00:10:55.000Z
2021-04-12T05:16:28.000Z
// Copyright(C) David W. Jeske, 2014, and released to the public domain. // // Dynamic BVH (Bounding Volume Hierarchy) using incremental refit and tree-rotations // // initial BVH build based on: Bounding Volume Hierarchies (BVH) – A brief tutorial on what they are and how to implement them // http://www.3dmuve.com/3dmblog/?p=182 // // Dynamic Updates based on: "Fast, Effective BVH Updates for Animated Scenes" (Kopta, Ize, Spjut, Brunvand, David, Kensler) // http://www.cs.utah.edu/~thiago/papers/rotations.pdf // // see also: Space Partitioning: Octree vs. BVH // http://thomasdiewald.com/blog/?p=1488 // // // TODO: implement node merge/split, to handle updates when LEAF_OBJ_MAX > 1 // #include <vector> #include "ssBVH.hpp" namespace dynamicBVH { template <typename ObjectT> class BVHNode { public: AABB box; BVHNode<ObjectT> * parent = nullptr; BVHNode<ObjectT> * left = nullptr; BVHNode<ObjectT> * right = nullptr; int depth; std::vector<ObjectT> gobjects; // only populated in leaf nodes BVHNode(const std::vector<ObjectT>& gobjects_in) : gobjects(gobjects_in) {} BVHNode(BVHNode<ObjectT> * parent_in, std::vector<ObjectT> gobjects_in, Axis lastSplitAxis, int depth_in) { parent = parent_in; depth = depth_in; // Check if we’re at our LEAF node, and if so, save the objects and stop recursing. Also store the min/max for the leaf node and update the parent appropriately if( gobjectlist.size() <= bvh.LEAF_OBJ_MAX ) { // once we reach the leaf node, we must set prev/next to null to signify the end left = nullptr; right = nullptr; // at the leaf node we store the remaining objects, so initialize a list gobjects = gobjects_in; computeVolume(nAda); splitIfNecessary(nAda); } else { // -------------------------------------------------------------------------------------------- // if we have more than (bvh.LEAF_OBJECT_COUNT) objects, then compute the volume and split gobjects = gobjectlist; computeVolume(nAda); splitNode(nAda); childRefit(nAda,recurse:false); } } Axis pickSplitAxis() { float axis_x = box.Max.X - box.Min.X; float axis_y = box.Max.Y - box.Min.Y; float axis_z = box.Max.Z - box.Min.Z; // return the biggest axis if (axis_x > axis_y) { if (axis_x > axis_z) return Axis.X; else return Axis.Z; } else { if (axis_y > axis_z) return Axis.Y; else return Axis.Z; } } bool isLeaf() { return gobjects.size() > 0; } Axis nextAxis(Axis cur) { return cur % Axis.End; } void expandVolume(SSBVHNodeAdaptor<ObjectT> nAda, Vector3 objectpos, float radius) { bool expanded = false; // test min X and max X against the current bounding volume if ((objectpos.X - radius) < box.Min.X) { box.Min.X = (objectpos.X - radius); expanded = true; } if ((objectpos.X + radius) > box.Max.X) { box.Max.X = (objectpos.X + radius); expanded = true; } // test min Y and max Y against the current bounding volume if ((objectpos.Y - radius) < box.Min.Y) { box.Min.Y = (objectpos.Y - radius); expanded = true; } if ((objectpos.Y + radius) > box.Max.Y) { box.Max.Y = (objectpos.Y + radius); expanded = true; } // test min Z and max Z against the current bounding volume if ( (objectpos.Z - radius) < box.Min.Z ) { box.Min.Z = (objectpos.Z - radius); expanded = true; } if ( (objectpos.Z + radius) > box.Max.Z ) { box.Max.Z = (objectpos.Z + radius); expanded = true; } if (expanded && parent != null) { parent.childExpanded(nAda, this); } } private void assignVolume(Vector3 objectpos, float radius) { box.Min.X = objectpos.X - radius; box.Max.X = objectpos.X + radius; box.Min.Y = objectpos.Y - radius; box.Max.Y = objectpos.Y + radius; box.Min.Z = objectpos.Z - radius; box.Max.Z = objectpos.Z + radius; } void computeVolume(SSBVHNodeAdaptor<ObjectT> nAda) { assignVolume( nAda.objectpos(gobjects[0]), nAda.radius(gobjects[0])); for(int i=1; i<gobjects.Count;i++) { expandVolume( nAda, nAda.objectpos(gobjects[i]) , nAda.radius(gobjects[i]) ); } } bool refitVolume(SSBVHNodeAdaptor<ObjectT> nAda) { if (gobjects.Count == 0) { throw new NotImplementedException(); } // TODO: fix this... we should never get called in this case... SSAABB oldbox = box; computeVolume(nAda); if (!box.Equals(oldbox)) { if (parent != null) parent.childRefit(nAda); return true; } else { return false; } } float SAH(SSAABB box) { float x_size = box.Max.X - box.Min.X; float y_size = box.Max.Y - box.Min.Y; float z_size = box.Max.Z - box.Min.Z; return 2.0f * ( (x_size * y_size) + (x_size * z_size) + (y_size * z_size) ); } float SAH(ref SSAABB box) { float x_size = box.Max.X - box.Min.X; float y_size = box.Max.Y - box.Min.Y; float z_size = box.Max.Z - box.Min.Z; return 2.0f * ( (x_size * y_size) + (x_size * z_size) + (y_size * z_size) ); } float SAH(BVHNode<ObjectT> * node) { float x_size = node.box.Max.X - node.box.Min.X; float y_size = node.box.Max.Y - node.box.Min.Y; float z_size = node.box.Max.Z - node.box.Min.Z; return 2.0f * ( (x_size * y_size) + (x_size * z_size) + (y_size * z_size) ); } float SAH(SSBVHNodeAdaptor<ObjectT> nAda, GO obj) { float radius = nAda.radius(obj); return (float)(4.0 * Math.PI * radius * radius); // bounding sphere surface area } SSAABB AABBofPair(ssBVHNode<ObjectT> nodea, ssBVHNode<ObjectT> nodeb) { SSAABB box = nodea.box; box.ExpandToFit(nodeb.box); return box; } float SAHofPair(ssBVHNode<ObjectT> nodea, ssBVHNode<ObjectT> nodeb) { SSAABB box = nodea.box; box.ExpandToFit(nodeb.box); return SAH(ref box); } float SAHofPair(SSAABB boxa, SSAABB boxb) { SSAABB pairbox = boxa; pairbox.ExpandToFit(boxb); return SAH(ref pairbox); } // The list of all candidate rotations, from "Fast, Effective BVH Updates for Animated Scenes", Figure 1. enum Rot { NONE, L_RL, L_RR, R_LL, R_LR, LL_RR, LL_RL, } class rotOpt : IComparable<rotOpt> { // rotation option public float SAH; public Rot rot; internal rotOpt(float SAH, Rot rot) { this.SAH = SAH; this.rot = rot; } public int CompareTo(rotOpt other) { return SAH.CompareTo(other.SAH); } } List<Rot>_rots = new List<Rot> ((Rot[])Enum.GetValues(typeof(Rot))); private List<Rot> eachRot { get { return _rots; } } /// <summary> /// tryRotate looks at all candidate rotations, and executes the rotation with the best resulting SAH (if any) /// </summary> /// <param name="bvh"></param> void tryRotate(ssBVH<ObjectT>& bvh) { // if we are not a grandparent, then we can't rotate, so queue our parent and bail out if (left.isLeaf() && right.isLeaf() ) { if (parent != null) { bvh.refitNodes.insert(parent); return; } } // for each rotation, check that there are grandchildren as necessary (aka not a leaf) // then compute total SAH cost of our branches after the rotation. float mySAH = SAH(left) + SAH(right); rotOpt bestRot = eachRot.Min( (rot) => { switch (rot) { case Rot.NONE: return new rotOpt(mySAH,Rot.NONE); // child to grandchild rotations case Rot.L_RL: if (right.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(right.left) + SAH(AABBofPair(left,right.right)), rot); case Rot.L_RR: if (right.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(right.right) + SAH(AABBofPair(left,right.left)), rot); case Rot.R_LL: if (left.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(AABBofPair(right,left.right)) + SAH(left.left), rot); case Rot.R_LR: if (left.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(AABBofPair(right,left.left)) + SAH(left.right), rot); // grandchild to grandchild rotations case Rot.LL_RR: if (left.IsLeaf || right.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(AABBofPair(right.right,left.right)) + SAH(AABBofPair(right.left,left.left)), rot); case Rot.LL_RL: if (left.IsLeaf || right.IsLeaf) return new rotOpt(float.MaxValue,Rot.NONE); else return new rotOpt(SAH(AABBofPair(right.left,left.right)) + SAH(AABBofPair(left.left,right.right)), rot); // unknown... default: throw new NotImplementedException("missing implementation for BVH Rotation SAH Computation .. " + rot.ToString()); } }); // perform the best rotation... if (bestRot.rot != Rot.NONE) { // if the best rotation is no-rotation... we check our parents anyhow.. if (parent != null) { // but only do it some random percentage of the time. if ((DateTime.Now.Ticks % 100) < 2) { bvh.refitNodes.Add(parent); } } } else { if (parent != null) { bvh.refitNodes.Add(parent); } if ( ((mySAH - bestRot.SAH) / mySAH ) < 0.3f) { return; // the benefit is not worth the cost } Console.WriteLine("BVH swap {0} from {1} to {2}", bestRot.rot.ToString(), mySAH, bestRot.SAH); // in order to swap we need to: // 1. swap the node locations // 2. update the depth (if child-to-grandchild) // 3. update the parent pointers // 4. refit the boundary box ssBVHNode<ObjectT> swap = null; switch (bestRot.rot) { case Rot.NONE: break; // child to grandchild rotations case Rot.L_RL: swap = left; swap.depth++; left = right.left; left.parent = this; left.depth--; right.left = swap; swap.parent = right; right.childRefit(nAda); break; case Rot.L_RR: swap = left; swap.depth++; left = right.right; left.parent = this; left.depth--; right.right = swap; swap.parent = right; right.childRefit(nAda); break; case Rot.R_LL: swap = right; swap.depth++; right = left.left; right.parent = this; right.depth--; left.left = swap; swap.parent = left; left.childRefit(nAda); break; case Rot.R_LR: swap = right; swap.depth++; right = left.right; right.parent = this; right.depth--; left.right = swap; swap.parent = left; left.childRefit(nAda); break; // grandchild to grandchild rotations case Rot.LL_RR: swap = left.left; left.left = right.right; right.right = swap; left.left.parent = left; swap.parent = right; left.childRefit(nAda,recurse:false); right.childRefit(nAda); break; case Rot.LL_RL: swap = left.left; left.left = right.left; right.left = swap; left.left.parent = left; swap.parent = right; left.childRefit(nAda,recurse:false); right.childRefit(nAda); break; // unknown... default: throw new NotImplementedException("missing implementation for BVH Rotation .. " + bestRot.rot.ToString()); } } } void splitNode(SSBVHNodeAdaptor<ObjectT> nAda) { // second, decide which axis to split on, and sort.. List<ObjectT> splitlist = gobjects; splitlist.ForEach( o => nAda.unmapObject(o) ); Axis splitAxis = pickSplitAxis(); switch (splitAxis) // sort along the appropriate axis { case Axis.X: splitlist.Sort(delegate(GO go1, GO go2) { return nAda.objectpos(go1).X.CompareTo(nAda.objectpos(go2).X); }); break; case Axis.Y: splitlist.Sort(delegate(GO go1, GO go2) { return nAda.objectpos(go1).Y.CompareTo(nAda.objectpos(go2).Y); }); break; case Axis.Z: splitlist.Sort(delegate(GO go1, GO go2) { return nAda.objectpos(go1).Z.CompareTo(nAda.objectpos(go2).Z); }); break; default: throw new NotImplementedException(); } int center = (int) (splitlist.Count / 2); // Find the center object in our current sub-list gobjects = null; // create the new left and right nodes... left = new ssBVHNode<ObjectT>(nAda.BVH, this, splitlist.GetRange(0,center), splitAxis, this.depth+1); // Split the Hierarchy to the left right = new ssBVHNode<ObjectT>(nAda.BVH, this, splitlist.GetRange(center,splitlist.Count - center), splitAxis, this.depth+1); // Split the Hierarchy to the right } void splitIfNecessary(SSBVHNodeAdaptor<ObjectT> nAda) { if (gobjects.Count > nAda.BVH.LEAF_OBJ_MAX) splitNode(nAda); } void addObject(SSBVHNodeAdaptor<ObjectT> nAda, GO newOb, ref SSAABB newObBox, float newObSAH) { if (gobjects != null) { // add the object and map it to our leaf gobjects.Add(newOb); nAda.mapObjectToBVHLeaf(newOb,this); refitVolume(nAda); // split if necessary... splitIfNecessary(nAda); } else { // find the best way to add this object.. 3 options.. // 1. send to left node (L+N,R) // 2. send to right node (L,R+N) // 3. merge and pushdown left-and-right node (L+R,N) float leftSAH = SAH(left); float rightSAH = SAH(right); float sendLeftSAH = rightSAH + SAH(left.box.ExpandedBy(newObBox)); // (L+N,R) float sendRightSAH = leftSAH + SAH(right.box.ExpandedBy(newObBox)); // (L,R+N) float mergedLeftAndRightSAH = SAH(AABBofPair(left,right)) + newObSAH; // (L+R,N) // Doing a merge-and-pushdown can be expensive, so we only do it if it's notably better const float MERGE_DISCOUNT = 0.3f; if (mergedLeftAndRightSAH < ( Math.Min(sendLeftSAH,sendRightSAH)) * MERGE_DISCOUNT ) { // merge and pushdown left and right as a new node.. var mSubnode = new ssBVHNode<ObjectT>(nAda.BVH); mSubnode.left = left; mSubnode.right = right; mSubnode.parent = this; mSubnode.gobjects = null; // we need to be an interior node... so null out our object list.. left.parent = mSubnode; right.parent = mSubnode; mSubnode.childRefit(nAda, recurse:false); // make new subnode for obj var nSubnode = new ssBVHNode<ObjectT>(nAda.BVH); nSubnode.parent = this; nSubnode.gobjects = new List<ObjectT>{ newOb }; nAda.mapObjectToBVHLeaf(newOb,nSubnode); nSubnode.computeVolume(nAda); // make assignments.. this.left = mSubnode; this.right = nSubnode; this.setDepth(this.depth); // propagate new depths to our children. this.childRefit(nAda); } else { if ( sendLeftSAH < sendRightSAH ) // send left left.addObject(nAda,newOb,ref newObBox, newObSAH); else // send right right.addObject(nAda,newOb,ref newObBox, newObSAH); } } } int countBVHNodes() { if (gobjects != null) { return 1; } else { return left.countBVHNodes() + right.countBVHNodes(); } } void removeObject(SSBVHNodeAdaptor<ObjectT> nAda, GO newOb) { if (gobjects == null) { throw new Exception("removeObject() called on nonLeaf!"); } nAda.unmapObject(newOb); gobjects.Remove(newOb); if (gobjects.Count > 0) { refitVolume(nAda); } else { // our leaf is empty, so collapse it if we are not the root... if (parent != null) { gobjects = null; parent.removeLeaf(nAda, this); parent = null; } } } setDepth(int newdepth) { this.depth = newdepth; if (gobjects == null) { left.setDepth(newdepth+1); right.setDepth(newdepth+1); } } void removeLeaf(BVHNode * leafToRemove) { if (left == null || right == null) { throw new Exception("bad intermediate node"); } ssBVHNode<ObjectT> keepLeaf; if( leafToRemove == left ) keepLeaf = right; else keepLeaf = left; // "become" the leaf we are keeping. box = keepLeaf.box; left = keepLeaf.left; right = keepLeaf.right; objects = keepLeaf.gobjects; // clear the leaf.. // keepLeaf.left = null; keepLeaf.right = null; keepLeaf.gobjects = null; keepLeaf.parent = null; if (gobjects == null) { left.parent = this; right.parent = this; // reassign child parents.. setDepth(depth); // recompute children depth } else // map the objects we adopted to us... gobjects.ForEach( o => { nAda.mapObjectToBVHLeaf(o,this); } ); // propagate our new volume.. if (parent != null) { parent.childRefit(nAda); } } ssBVHNode<ObjectT> rootNode() { ssBVHNode<ObjectT> cur = this; while (cur.parent != null) { cur = cur.parent; } return cur; } void findOverlappingLeaves(SSBVHNodeAdaptor<ObjectT> nAda, Vector3 origin, float radius, List<ssBVHNode<ObjectT>> overlapList) { if (toAABB().IntersectsSphere(origin,radius)) { if (gobjects != null) { overlapList.Add(this); } else { left.findOverlappingLeaves(nAda,origin,radius,overlapList); right.findOverlappingLeaves(nAda,origin,radius,overlapList); } } } void findOverlappingLeaves(SSBVHNodeAdaptor<ObjectT> nAda, SSAABB aabb, List<ssBVHNode<ObjectT>> overlapList) { if (toAABB().IntersectsAABB(aabb)) { if (gobjects != null) { overlapList.Add(this); } else { left.findOverlappingLeaves(nAda,aabb,overlapList); right.findOverlappingLeaves(nAda,aabb,overlapList); } } } void childExpanded(SSBVHNodeAdaptor<ObjectT> nAda, ssBVHNode<ObjectT> child) { bool expanded = false; if (child.box.Min.X < box.Min.X) { box.Min.X = child.box.Min.X; expanded = true; } if (child.box.Max.X > box.Max.X) { box.Max.X = child.box.Max.X; expanded = true; } if (child.box.Min.Y < box.Min.Y) { box.Min.Y = child.box.Min.Y; expanded = true; } if (child.box.Max.Y > box.Max.Y) { box.Max.Y = child.box.Max.Y; expanded = true; } if (child.box.Min.Z < box.Min.Z) { box.Min.Z = child.box.Min.Z; expanded = true; } if (child.box.Max.Z > box.Max.Z) { box.Max.Z = child.box.Max.Z; expanded = true; } if (expanded && parent != null) { parent.childExpanded(nAda, this); } } void childRefit(SSBVHNodeAdaptor<ObjectT> nAda, bool recurse=true) { SSAABB oldbox = box; box.Min.X = left.box.Min.X; box.Max.X = left.box.Max.X; box.Min.Y = left.box.Min.Y; box.Max.Y = left.box.Max.Y; box.Min.Z = left.box.Min.Z; box.Max.Z = left.box.Max.Z; if (right.box.Min.X < box.Min.X) { box.Min.X = right.box.Min.X; } if (right.box.Min.Y < box.Min.Y) { box.Min.Y = right.box.Min.Y; } if (right.box.Min.Z < box.Min.Z) { box.Min.Z = right.box.Min.Z; } if (right.box.Max.X > box.Max.X) { box.Max.X = right.box.Max.X; } if (right.box.Max.Y > box.Max.Y) { box.Max.Y = right.box.Max.Y; } if (right.box.Max.Z > box.Max.Z) { box.Max.Z = right.box.Max.Z; } if (recurse && parent != null) { parent.childRefit(nAda); } } } }
40.373159
212
0.48265
[ "object", "vector" ]
d812c0b34736babd7354efc458c2a29df5f36343
9,743
cc
C++
src/distortion/dmestm.cc
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
src/distortion/dmestm.cc
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
src/distortion/dmestm.cc
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
[ "MIT" ]
null
null
null
/** * @author George Foster * @file dmestm.cc * @brief Estimate distortion model probabilities from counts * * Technologies langagieres interactives / Interactive Language Technologies * Inst. de technologie de l'information / Institute for Information Technology * Conseil national de recherches Canada / National Research Council Canada * Copyright 2009, Sa Majeste la Reine du Chef du Canada / * Copyright 2009, Her Majesty in Right of Canada */ #include <iostream> #include <fstream> #include <file_utils.h> #include <arg_reader.h> #include <phrase_table.h> #include "dmstruct.h" #include "printCopyright.h" using namespace Portage; using namespace std; static char help_message[] = "\n\ dmestm [options] [dmc]\n\ \n\ Estimate a distortion model from a distortion count file <dmc> produced by\n\ dmcount (read from stdin if <dmc> is omitted). <dmc> may be one or more count\n\ files cat'd together. Output is written to stdout, in same format as the input,\n\ but with probabilities instead of counts.\n\ \n\ Options:\n\ \n\ -v Write progress reports to cerr.\n\ -s Sort output by source phrase [don't]\n\ -prune1 n Prune so that each language1 phrase has at most n translations.\n\ Based on summed joint freqs; done right after reading in counts.\n\ -prune1w n Same as prune1, but multiply n by the number of words in the\n\ current source phrase. Only one of prune1 or prune1w may be used.\n\ -wtu w Scale uniform prior by w to get prior counts [30]\n\ -wtg w Scale global prior (sum over all phrase pair freqs) by w [30]\n\ -wt1 w Scale l1 prior (rel freq for each l1 phrase) by w [15]\n\ -wt2 w Scale l2 prior (rel freq for each l2 phrase) by w [15]\n\ -eval cf Evaluate the model on counts file <cf>. Write perplexity to stderr.\n\ -g gf Write the smoothed global distribution to file <gf>.\n\ "; // globals static Uint verbose = 0; static bool sorting = false; static Uint prune1 = 0; static Uint prune1w = 0; static string dmc; static string gf; static double uniform_wt = 30; // wt on uniform prior static double global_wt = 30; // wt on global (sum over all counts) prior static double l1_wt = 15; // wt on l1 (sum over all linked l2 phrases) prior static double l2_wt = 15; // wt on l2 (sum over all linked l1 phrases) prior static string eval; // counts file for evaluation static void getArgs(int argc, char* argv[]); // Primitives for MAP smoothing: scale prior distn, add prior counts to // empirical counts, and normalize. These operate on arrays rather than // vectors in case we eventually want to precompute and store priors for // l1 and l2 phrases. float* scale(float* counts, double w) { for (Uint i = 0; i < DistortionCount::size(); ++i) counts[i] *= w; return counts; } float* add(float* prior, const DistortionCount& empc) { float* p = prior; for (Uint i = 0; i < empc.size(); ++i) *p++ += empc.val(i); return prior; } float* norm(float* counts) { Uint n = DistortionCount::size() / 2; float sum1 = 0.0, sum2 = 0.0; for (Uint i = 0; i < n; ++i) { sum1 += counts[i]; sum2 += counts[i+n]; } for (Uint i = 0; i < n; ++i) { counts[i] /= sum1; counts[i+n] /= sum2; } return counts; } // Calculate the log likelihood incr due to the counts in <dc> under <distn>. double logLikelihood(float* distn, const DistortionCount& dc, Uint what = 0) { double like = 0.0; Uint b = 0, e = dc.size(); if (what == 1) e = dc.size() / 2; // prev probs else if (what == 2) b = dc.size() / 2; // next probs for (Uint i = b; i < e; ++i) if (dc.val(i)) like += dc.val(i) * log(distn[i]); return like; } // main int main(int argc, char* argv[]) { printCopyright(2009, "dmestm"); getArgs(argc, argv); string line; vector<char*> toks; PhraseTableBase::ToksIter b1, e1, b2, e2, v, a, f; DistortionCount dc; // Open the STDOUT pipe now, so we fork while the memory footprint is still small. string outname("-"); if (sorting) outname = "| LC_ALL=C TMPDIR=. sort"; oSafeMagicStream os(outname); // read eval counts into pteval if required Uint nphrases_eval_tot = 0; PhraseTableGen<DistortionCount> pteval; if (eval.size()) { iSafeMagicStream in(eval); while (getline(in, line)) { char buffer[line.size()+1]; strcpy(buffer, line.c_str()); pteval.extractTokens(line, buffer, toks, b1, e1, b2, e2, v, a, f, true); dc.read(v, toks.end()); pteval.addPhrasePair(b1, e1, b2, e2, dc); ++nphrases_eval_tot; } } // read main counts into pt iSafeMagicStream in(dmc.size() ? dmc : "-"); PhraseTableGen<DistortionCount> pt; while (getline(in, line)) { char buffer[line.size()+1]; strcpy(buffer, line.c_str()); pt.extractTokens(line, buffer, toks, b1, e1, b2, e2, v, a, f, true); dc.read(v, toks.end()); pt.addPhrasePair(b1, e1, b2, e2, dc); } if (verbose) cerr << "read counts: " << pt.numLang1Phrases() << " l1 phrases, " << pt.numLang2Phrases() << " l2 phrases" << endl; // prune based on total freqs (sum across m,s,d conditions) if called for if (prune1 || prune1w) { if (verbose) cerr << "pruning to best " << (prune1 ? prune1 : prune1w) << " translations" << (prune1w ? " per word" : "") << ", using total freqs" << endl; pt.pruneLang2GivenLang1(prune1 ? prune1 : prune1w, prune1w != 0); } // Make global & marginal counts for each language, for smoothing. DistortionCount global_counts; vector<DistortionCount> l1_marginals(pt.numLang1Phrases()); vector<DistortionCount> l2_marginals(pt.numLang2Phrases()); for (PhraseTableGen<DistortionCount>::iterator p = pt.begin(); p != pt.end(); ++p) { global_counts += p.getJointFreqRef(); l1_marginals[p.getPhraseIndex(1)] += p.getJointFreqRef(); l2_marginals[p.getPhraseIndex(2)] += p.getJointFreqRef(); } // set up global prior smoothing counts vector<float> global_prior(DistortionCount::size(), 1.0); norm(add(scale(norm(&global_prior[0]), uniform_wt), global_counts)); scale(&global_prior[0], global_wt); // global prior counts (unnormalized) // Estimate and output. (This could be sped up by pre-computing and storing // the smoothed prior counts for each l1 and l2 phrase.) vector<float> l1_prior(DistortionCount::size()); vector<float> l2_prior(DistortionCount::size()); string p1, p2; vector<string> toks1, toks2; double ll = 0.0, ll_eval = 0.0, ll_eval_prev = 0.0, ll_eval_next = 0.0; Uint totfreq = 0, totfreq_eval = 0.0; Uint nphrases = 0, nphrases_eval = 0.0; for (PhraseTableGen<DistortionCount>::iterator p = pt.begin(); p != pt.end(); ++p) { l1_prior = global_prior; l2_prior = global_prior; scale(norm(add(&l1_prior[0], l1_marginals[p.getPhraseIndex(1)])), l1_wt); scale(norm(add(&l2_prior[0], l2_marginals[p.getPhraseIndex(2)])), l2_wt); for (Uint i = 0; i < DistortionCount::size(); ++i) l1_prior[i] += l2_prior[i]; norm(add(&l1_prior[0], p.getJointFreqRef())); ll += logLikelihood(&l1_prior[0], p.getJointFreqRef()); totfreq += p.getJointFreqRef().freq(); ++nphrases; if (eval.size()) { p.getPhrase(1, toks1); p.getPhrase(2, toks2); if (pteval.exists(toks1.begin(), toks1.end(), toks2.begin(), toks2.end(), dc)) { ll_eval += logLikelihood(&l1_prior[0], dc); ll_eval_prev += logLikelihood(&l1_prior[0], dc, 1); ll_eval_next += logLikelihood(&l1_prior[0], dc, 2); totfreq_eval += dc.freq(); ++nphrases_eval; } } p.getPhrase(1, p1); p.getPhrase(2, p2); pt.writePhrasePair(os, p1.c_str(), p2.c_str(), NULL, l1_prior, false, 0.0f); } if (gf.size()) { oSafeMagicStream os(gf); // recalculate global_prior from counts, in case global_wt is 0 global_prior.assign(DistortionCount::size(), 1.0); norm(add(scale(norm(&global_prior[0]), uniform_wt), global_counts)); for (Uint i = 0; i < global_prior.size(); ++i) os << global_prior[i] << ' '; os << endl; } if (verbose) { cerr << nphrases << " phrases written, total count = " << totfreq << ", ppx = " << exp(-ll / (2 * totfreq)) << endl; } if (eval.size()) { cerr << "eval file " << eval << ": " << nphrases_eval << "/" << nphrases_eval_tot << " phrases used, total count = " << totfreq_eval << ", ppx = " << exp(-ll_eval / (2 * totfreq_eval)) << ", ppx-prev = " << exp(-ll_eval_prev / (totfreq_eval)) << ", ppx-next = " << exp(-ll_eval_next / (totfreq_eval)) << endl; } } // Arg processing void getArgs(int argc, char* argv[]) { const char* switches[] = {"v", "s", "prune1:", "prune1w:", "wtu:", "wtg:", "wt1:", "wt2:", "eval:", "g:"}; ArgReader arg_reader(ARRAY_SIZE(switches), switches, 0, 1, help_message); arg_reader.read(argc-1, argv+1); vector<string> verboses; arg_reader.testAndSet("v", verboses); arg_reader.testAndSet("s", sorting); arg_reader.testAndSet("prune1", prune1); arg_reader.testAndSet("prune1w", prune1w); arg_reader.testAndSet("wtu", uniform_wt); arg_reader.testAndSet("wtg", global_wt); arg_reader.testAndSet("wt1", l1_wt); arg_reader.testAndSet("wt2", l2_wt); arg_reader.testAndSet("eval", eval); arg_reader.testAndSet("g", gf); arg_reader.testAndSet(0, "dmc", dmc); verbose = verboses.size(); }
34.549645
90
0.623011
[ "vector", "model" ]
d8147533a54a71455d765d1c4f80481e434252e5
2,036
cpp
C++
gluecodium/src/test/resources/smoke/nesting/output/android/jni/com_example_smoke_OuterStruct_InnerStruct__Conversion.cpp
limingchina/gluecodium
dbb13bb937956555e538b70d19659deef6f766ff
[ "Apache-2.0" ]
138
2019-12-11T13:16:52.000Z
2022-03-28T01:24:21.000Z
gluecodium/src/test/resources/smoke/nesting/output/android/jni/com_example_smoke_OuterStruct_InnerStruct__Conversion.cpp
limingchina/gluecodium
dbb13bb937956555e538b70d19659deef6f766ff
[ "Apache-2.0" ]
310
2020-01-14T11:46:26.000Z
2022-03-31T15:05:40.000Z
gluecodium/src/test/resources/smoke/nesting/output/android/jni/com_example_smoke_OuterStruct_InnerStruct__Conversion.cpp
limingchina/gluecodium
dbb13bb937956555e538b70d19659deef6f766ff
[ "Apache-2.0" ]
10
2019-12-11T11:46:16.000Z
2021-11-02T10:41:59.000Z
/* * */ #include "com_example_smoke_OuterStruct_InnerStruct__Conversion.h" #include "ArrayConversionUtils.h" #include "FieldAccessMethods.h" #include "JniCallJavaMethod.h" #include "JniClassCache.h" namespace gluecodium { namespace jni { ::smoke::OuterStruct::InnerStruct convert_from_jni(JNIEnv* _jenv, const JniReference<jobject>& _jinput, ::smoke::OuterStruct::InnerStruct*) { ::smoke::OuterStruct::InnerStruct _nout{}; ::std::vector< ::std::chrono::system_clock::time_point > n_other_field = convert_from_jni( _jenv, ::gluecodium::jni::get_object_field_value(_jenv, _jinput, "otherField", "Ljava/util/List;"), (::std::vector< ::std::chrono::system_clock::time_point >*)nullptr ); _nout.other_field = n_other_field; return _nout; } ::gluecodium::optional<::smoke::OuterStruct::InnerStruct> convert_from_jni(JNIEnv* _jenv, const JniReference<jobject>& _jinput, ::gluecodium::optional<::smoke::OuterStruct::InnerStruct>*) { return _jinput ? ::gluecodium::optional<::smoke::OuterStruct::InnerStruct>(convert_from_jni(_jenv, _jinput, (::smoke::OuterStruct::InnerStruct*)nullptr)) : ::gluecodium::optional<::smoke::OuterStruct::InnerStruct>{}; } REGISTER_JNI_CLASS_CACHE("com/example/smoke/OuterStruct$InnerStruct", com_example_smoke_OuterStruct_00024InnerStruct, ::smoke::OuterStruct::InnerStruct) JniReference<jobject> convert_to_jni(JNIEnv* _jenv, const ::smoke::OuterStruct::InnerStruct& _ninput) { auto& javaClass = CachedJavaClass<::smoke::OuterStruct::InnerStruct>::java_class; auto _jresult = ::gluecodium::jni::alloc_object(_jenv, javaClass); auto jother_field = convert_to_jni(_jenv, _ninput.other_field); ::gluecodium::jni::set_object_field_value(_jenv, _jresult, "otherField", "Ljava/util/List;", jother_field); return _jresult; } JniReference<jobject> convert_to_jni(JNIEnv* _jenv, const ::gluecodium::optional<::smoke::OuterStruct::InnerStruct> _ninput) { return _ninput ? convert_to_jni(_jenv, *_ninput) : JniReference<jobject>{}; } } }
42.416667
152
0.747544
[ "vector" ]
d8182e163ce001f6a3269840ee6f8d34b4a8d7d0
6,853
cpp
C++
lib/Remote/Builtin/TestRemote.cpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
180
2017-09-11T00:44:36.000Z
2022-03-25T09:23:47.000Z
lib/Remote/Builtin/TestRemote.cpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
109
2015-01-19T07:33:38.000Z
2017-08-12T00:29:13.000Z
lib/Remote/Builtin/TestRemote.cpp
lsbharadwaj/PothosCore
02b3491ed06f23924a4c749f35b7fade88b81a14
[ "BSL-1.0" ]
32
2017-09-20T10:47:29.000Z
2022-03-24T06:13:03.000Z
// Copyright (c) 2013-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Testing.hpp> #include <Pothos/Plugin.hpp> #include <Pothos/Proxy.hpp> #include <Pothos/Remote.hpp> #include <Pothos/Managed.hpp> #include <Pothos/Util/Network.hpp> #include <Poco/Pipe.h> #include <Poco/PipeStream.h> #include <Poco/URI.h> #include <iostream> #include <future> #include <thread> #include <cstdlib> #include <complex> #include <algorithm> #include <cstdlib> //atoi class SuperBar { public: SuperBar(void) { _bar = 0; } SuperBar(int bar) { _bar = bar; } void setBar(int bar) { _bar = bar; } int getBar(void) { return _bar; } static int what(void) { return 42; } int _bar; }; class SuperFoo { public: static SuperBar make(int bar) { return SuperBar(bar); } static SuperBar *makeNew(int bar) { return new SuperBar(bar); } static std::shared_ptr<SuperBar> makeShared(int bar) { return std::shared_ptr<SuperBar>(makeNew(bar)); } }; static void test_simple_runner(Pothos::ProxyEnvironment::Sptr env) { Pothos::ManagedClass() .registerConstructor<SuperBar>() .registerConstructor<SuperBar, int>() .registerMethod(POTHOS_FCN_TUPLE(SuperBar, setBar)) .registerMethod(POTHOS_FCN_TUPLE(SuperBar, getBar)) .registerStaticMethod(POTHOS_FCN_TUPLE(SuperBar, what)) .registerField(POTHOS_FCN_TUPLE(SuperBar, _bar)) .commit("SuperBar"); //grab the proxy class auto superBarProxy = env->findProxy("SuperBar"); //test a static method POTHOS_TEST_EQUAL(superBarProxy.call<int>("what"), 42); //make an instance and test auto superBarInstance0 = superBarProxy(); superBarInstance0.call("setBar", 123); POTHOS_TEST_EQUAL(superBarInstance0.call<int>("getBar"), 123); //test field access superBarInstance0.set("_bar", 321); POTHOS_TEST_EQUAL(superBarInstance0.get<int>("_bar"), 321); //make an instance and test auto superBarInstance1 = superBarProxy(21); POTHOS_TEST_EQUAL(superBarInstance1.call<int>("getBar"), 21); Pothos::ManagedClass() .registerClass<SuperFoo>() .registerStaticMethod(POTHOS_FCN_TUPLE(SuperFoo, make)) .registerStaticMethod(POTHOS_FCN_TUPLE(SuperFoo, makeNew)) .registerStaticMethod(POTHOS_FCN_TUPLE(SuperFoo, makeShared)) .commit("SuperFoo"); //grab the proxy class auto superFooProxy = env->findProxy("SuperFoo"); //test it making a super bar and test auto superBarInstance2 = superFooProxy.call("make", 4567); POTHOS_TEST_EQUAL(superBarInstance2.call<int>("getBar"), 4567); auto superBarInstance3 = superFooProxy.call("makeNew", -543); POTHOS_TEST_EQUAL(superBarInstance3.call<int>("getBar"), -543); superBarInstance3.call("delete"); auto superBarInstance4 = superFooProxy.call("makeShared", 987); POTHOS_TEST_EQUAL(superBarInstance4.call<int>("getBar"), 987); //runtime registration does not associate the module //therefore to be safe, we unregister these classes now Pothos::ManagedClass::unload("SuperBar"); Pothos::ManagedClass::unload("SuperFoo"); } POTHOS_TEST_BLOCK("/proxy/remote/tests", test_inception) { auto env = Pothos::ProxyEnvironment::make("managed"); //spawn server and connect auto serverHandle1 = env->findProxy("Pothos/RemoteServer")("tcp://"+Pothos::Util::getWildcardAddr()); auto actualPort1 = serverHandle1.call("getActualPort"); auto clientHandle1 = env->findProxy("Pothos/RemoteClient")("tcp://"+Pothos::Util::getLoopbackAddr(actualPort1)); //create a remote environment auto &ios = clientHandle1.call<std::iostream &>("getIoStream"); auto remoteEnv = Pothos::RemoteClient::makeEnvironment(ios, "managed"); //now the remove env can make a new server //which can now be connected to locally auto serverHandle2 = remoteEnv->findProxy("Pothos/RemoteServer")("tcp://"+Pothos::Util::getWildcardAddr()); auto actualPort2 = serverHandle2.call("getActualPort"); auto clientHandle2 = env->findProxy("Pothos/RemoteClient")("tcp://"+Pothos::Util::getLoopbackAddr(actualPort2)); } //! A thread to handle remote proxy requests static void runRemoteProxy(Poco::Pipe &p0, Poco::Pipe &p1) { //std::cout << "run start \n"; Poco::PipeInputStream is(p0); Poco::PipeOutputStream os(p1); Pothos::RemoteHandler handler; handler.runHandler(is, os); //std::cout << "run exit \n"; } POTHOS_TEST_BLOCK("/proxy/remote/tests", test_remote) { //check that the test runs locally first test_simple_runner(Pothos::ProxyEnvironment::make("managed")); //tests remote proxy as well as managed: Poco::Pipe p0, p1; Poco::PipeInputStream is(p1); Poco::PipeOutputStream os(p0); std::thread t0(&runRemoteProxy, std::ref(p0), std::ref(p1)); test_simple_runner(Pothos::RemoteClient::makeEnvironment(is, os, "managed")); t0.join(); } POTHOS_TEST_BLOCK("/proxy/remote/tests", test_server) { Pothos::RemoteServer server("tcp://"+Pothos::Util::getWildcardAddr()); Pothos::RemoteClient client("tcp://"+Pothos::Util::getLoopbackAddr(server.getActualPort())); auto env = Pothos::RemoteClient::makeEnvironment(client.getIoStream(), "managed"); std::cout << "Env peering address " << env->getPeeringAddress() << std::endl; } struct EchoTester { static int echo(int x) { return x; } }; static int callRemoteEcho(const Pothos::ProxyEnvironment::Sptr &env, int x) { return env->findProxy("EchoTester").call("echo", x); } POTHOS_TEST_BLOCK("/proxy/remote/tests", test_multithread_safe) { Pothos::ManagedClass() .registerClass<EchoTester>() .registerStaticMethod(POTHOS_FCN_TUPLE(EchoTester, echo)) .commit("EchoTester"); Poco::Pipe p0, p1; Poco::PipeInputStream is(p1); Poco::PipeOutputStream os(p0); std::thread t0(&runRemoteProxy, std::ref(p0), std::ref(p1)); { auto env = Pothos::RemoteClient::makeEnvironment(is, os, "managed"); //create futures and expected results std::vector<std::future<int>> futures; std::vector<int> expected; for (size_t i = 0; i < 100; i++) { expected.push_back(std::rand()); futures.push_back(std::async(std::launch::async, &callRemoteEcho, env, expected.back())); } //check results for (size_t i = 0; i < expected.size(); i++) { const auto val = futures[i].get(); POTHOS_TEST_EQUAL(expected[i], val); } } t0.join(); //runtime registration does not associate the module //therefore to be safe, we unregister these classes now Pothos::ManagedClass::unload("EchoTester"); }
29.412017
116
0.667883
[ "vector" ]
d81ef3d11c9b1893ddfdb67eb348e10fb94a9b65
4,390
cpp
C++
src/solo_part_guitar.cpp
sea-kg/guitar-solo-part-generator
a13676c305a78a0bc0172e5137bdb34617d34881
[ "MIT" ]
2
2020-07-15T07:13:30.000Z
2021-12-01T20:30:37.000Z
src/solo_part_guitar.cpp
sea-kg/guitar-solo-part-generator
a13676c305a78a0bc0172e5137bdb34617d34881
[ "MIT" ]
12
2020-02-25T20:13:12.000Z
2020-07-16T16:41:32.000Z
src/solo_part_guitar.cpp
sea-kg/guitar-solo-part-generator
a13676c305a78a0bc0172e5137bdb34617d34881
[ "MIT" ]
1
2021-12-22T15:04:16.000Z
2021-12-22T15:04:16.000Z
#include "solo_part_guitar.h" #include <wsjcpp_core.h> // --------------------------------------------------------------------- // SoloPartGuitar SoloPartGuitar::SoloPartGuitar() { TAG = "SoloPartGuitar"; // init m_vAllNameOfNotes std::string arrNotesInOctave[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; for (int o = 0; o < 9; o++) { for (int n = 0; n < 12; n++) { m_vAllNameOfNotes.push_back(arrNotesInOctave[n] + std::to_string(o)); } } m_vGuitarTuning.push_back("E4"); // 1 string m_vGuitarTuning.push_back("B3"); m_vGuitarTuning.push_back("G3"); m_vGuitarTuning.push_back("D3"); m_vGuitarTuning.push_back("A2"); m_vGuitarTuning.push_back("E2"); // 6 string // m_vGuitarTuning.push_back("B1"); // 7 string // m_vGuitarTuning.push_back("F#1"); // 8 string } // --------------------------------------------------------------------- void SoloPartGuitar::addNote(PositionNoteGuitar note) { m_vNotes.push_back(note); } // --------------------------------------------------------------------- std::vector<PositionNoteGuitar> SoloPartGuitar::getListOfNotes() { return m_vNotes; } // --------------------------------------------------------------------- std::string SoloPartGuitar::exportTabulatur() { std::string sRet = ""; std::string stringNames[] = {"", "E4", "B3", "G3", "D3", "A2", "E2"}; for (int iString = 1; iString <= 6; iString++) { sRet += std::to_string(iString) + "|" + stringNames[iString] + "|-"; for (int x = 0; x < m_vNotes.size(); x++) { PositionNoteGuitar note = m_vNotes[x]; if (note.getGuitarString() == iString) { int nFret = note.getFret(); std::string sPrefix = ((nFret < 10) ? "--" : "-"); sRet += sPrefix + std::to_string(nFret); } else { sRet += "---"; } } sRet += "\n"; } sRet += "HAND|-"; for (int x = 0; x < m_vNotes.size(); x++) { PositionNoteGuitar note = m_vNotes[x]; GuitarTouchFinger nFinger = note.getFinger(); if (nFinger == GuitarTouchFinger::GUITAR_NO_FINGER) { sRet += "--N"; } else if (nFinger == GuitarTouchFinger::GUITAR_INDEX_FINGER) { sRet += "--I"; } else if (nFinger == GuitarTouchFinger::GUITAR_MIDDLE_FINGER) { sRet += "--M"; } else if (nFinger == GuitarTouchFinger::GUITAR_RING_FINGER) { sRet += "--R"; } else if (nFinger == GuitarTouchFinger::GUITAR_LITTLE_FINGER) { sRet += "--L"; } } sRet += "\n"; sRet += "N - No finger / empty string\n"; sRet += "I - Index finger\n"; sRet += "M - Middle finger\n"; sRet += "R - Ring finger\n"; sRet += "L - Little finger\n"; return sRet; } // --------------------------------------------------------------------- nlohmann::json SoloPartGuitar::exportToJson() { nlohmann::json json = nlohmann::json::array(); for (int i = 0; i < m_vNotes.size(); i++) { PositionNoteGuitar note = m_vNotes[i]; nlohmann::json jsonNote; jsonNote["time"] = std::to_string(i * 8) + "/32"; // TODO hardcode jsonNote["string"] = note.getGuitarString(); jsonNote["fret"] = note.getFret(); jsonNote["finger"] = GuitarSoloPartGeneratorEnums::fingerToValue(note.getFinger()); jsonNote["duration"] = "1/4"; // TODO hardcode jsonNote["note"] = findNoteByPosition(note); json.push_back(jsonNote); } return json; } // --------------------------------------------------------------------- std::vector<std::string> SoloPartGuitar::getGuitarTuning() { return m_vGuitarTuning; } // --------------------------------------------------------------------- std::string SoloPartGuitar::findNoteByPosition(const PositionNoteGuitar &note) { int nString = note.getGuitarString(); if (nString == 0) { return ""; } std::string sPos0 = m_vGuitarTuning[nString-1]; int nPos0 = -1; for (int i = 0; i < m_vAllNameOfNotes.size(); i++) { if (m_vAllNameOfNotes[i] == sPos0) { nPos0 = i; break; } } return m_vAllNameOfNotes[nPos0 + note.getFret()]; } // ---------------------------------------------------------------------
34.296875
103
0.48656
[ "vector" ]
d8201af21633fb97d3c61263acc5bec31bcd2d5e
7,403
cpp
C++
src/cimple/Exception.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/cimple/Exception.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/cimple/Exception.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and associated documentation files (the "Software"), ** to deal in the Software without restriction, including without limitation ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** and/or sell copies of the Software, and to permit persons to whom the ** Software is furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** SOFTWARE. ** **============================================================================== */ #include <cstdarg> #include <cstdio> #include "Exception.h" CIMPLE_NAMESPACE_BEGIN struct Detail { const char* name; Exception::Code code; const char* message; }; static const Detail _details[] = { { "FAILED", Exception::FAILED, "A general error occurred that is not covered by a more specific error " "code" }, { "ACCESS_DENIED", Exception::ACCESS_DENIED, "Access to a CIM resource is not available to the client" }, { "INVALID_NAMESPACE", Exception::INVALID_NAMESPACE, "The target namespace does not exist" }, { "INVALID_PARAMETER", Exception::INVALID_PARAMETER, "One or more parameter values passed to the method are not valid" }, { "INVALID_CLASS", Exception::INVALID_CLASS, "The specified class does not exist" }, { "NOT_FOUND", Exception::NOT_FOUND, "The requested object cannot be found" }, { "NOT_SUPPORTED", Exception::NOT_SUPPORTED, "The requested operation is not supported" }, { "CLASS_HAS_CHILDREN", Exception::CLASS_HAS_CHILDREN, "The operation cannot be invoked on this class because it has " "subclasses" }, { "CLASS_HAS_INSTANCES", Exception::CLASS_HAS_INSTANCES, "The operation cannot be invoked on this class because one or more " "instances of this class exist" }, { "INVALID_SUPERCLASS", Exception::INVALID_SUPERCLASS, "The operation cannot be invoked because the specified superclass " "does not exist" }, { "ALREADY_EXISTS", Exception::ALREADY_EXISTS, "The operation cannot be invoked because an object already exists" }, { "NO_SUCH_PROPERTY", Exception::NO_SUCH_PROPERTY, "The specified property does not exist" }, { "TYPE_MISMATCH", Exception::TYPE_MISMATCH, "The value supplied is not compatible with the type" }, { "QUERY_LANGUAGE_NOT_SUPPORTED", Exception::QUERY_LANGUAGE_NOT_SUPPORTED, "The query language is not recognized or supported" }, { "INVALID_QUERY", Exception::INVALID_QUERY, "The query is not valid for the specified query language" }, { "METHOD_NOT_AVAILABLE", Exception::METHOD_NOT_AVAILABLE, "The extrinsic method cannot be invoked" }, { "METHOD_NOT_FOUND", Exception::METHOD_NOT_FOUND, "The specified extrinsic method does not exist" }, { "NAMESPACE_NOT_EMPTY", Exception::NAMESPACE_NOT_EMPTY, "The specified Namespace is not empty" }, { "BAD_CAST", Exception::BAD_CAST, "attempted to cast between incompatible types" }, { "NULL_ACCESS", Exception::NULL_ACCESS, "accessed null pointer" }, { "BAD_URL", Exception::BAD_URL, "malformed universal resource locator" }, { "ALREADY_CONNECTED", Exception::ALREADY_CONNECTED, "attempted to connect while already connected" }, { "NOT_CONNECTED", Exception::NOT_CONNECTED, "attempted an operation requiring a connection when no connection " "has been established" }, { "CONNECT_FAILED", Exception::CONNECT_FAILED, "failed to establish a connection" }, { "BAD_XML", Exception::BAD_XML, "error while parsing XML" }, { "BAD_ENUMERATOR", Exception::BAD_ENUMERATOR, "attempted to use an uninitialized or exhausted enumerator" }, { "BAD_CONVERSION", Exception::BAD_CONVERSION, "conversion failure" } }; static size_t _num_details = sizeof(_details) / sizeof(_details[0]); static const Detail& _find_detail(Exception::Code code) { for (size_t i = 0; i < _num_details; i++) { if (_details[i].code == code) return _details[i]; } return _details[0]; } Exception::Exception(Code code) : _code(code) { const Detail& detail = _find_detail(code); _message = detail.name; _message.append(": "); _message.append(detail.message); } Exception::Exception(Code code, const char* format, ...) : _code(code) { char buffer[4096]; va_list ap; va_start(ap, format); size_t n = vsprintf(buffer, format, ap); assert(n < sizeof(buffer)); va_end(ap); const Detail& detail = _find_detail(code); _message = detail.name; _message.append(": "); _message.append(detail.message); _message.append(": \""); _message.append(buffer); _message.append("\""); } Exception::Exception(const Exception& x) : _message(x._message) { } Exception& Exception::operator=(const Exception& x) { _code = x._code; _message = x._message; return *this; } Exception::~Exception() { } const String& Exception::message() const { return _message; } bool Exception::valid_cim_code(uint32 code) { switch (code) { case Exception::FAILED: case Exception::ACCESS_DENIED: case Exception::INVALID_NAMESPACE: case Exception::INVALID_PARAMETER: case Exception::INVALID_CLASS: case Exception::NOT_FOUND: case Exception::NOT_SUPPORTED: case Exception::CLASS_HAS_CHILDREN: case Exception::CLASS_HAS_INSTANCES: case Exception::INVALID_SUPERCLASS: case Exception::ALREADY_EXISTS: case Exception::NO_SUCH_PROPERTY: case Exception::TYPE_MISMATCH: case Exception::QUERY_LANGUAGE_NOT_SUPPORTED: case Exception::INVALID_QUERY: case Exception::METHOD_NOT_AVAILABLE: case Exception::METHOD_NOT_FOUND: case Exception::NAMESPACE_NOT_EMPTY: return true; default: return false; } // Unreachable! return false; } CIMPLE_NAMESPACE_END
26.822464
80
0.619479
[ "object" ]
d820490ce184288c4de52c12514b64e9ebbd8151
1,581
cpp
C++
src/bounce_softbody/dynamics/fixtures/world_fixture.cpp
tlemo/bounce_softbody
5243261586c6c066eb91ca191141246fef9ad683
[ "Zlib" ]
26
2021-05-16T20:41:30.000Z
2022-02-08T06:45:22.000Z
src/bounce_softbody/dynamics/fixtures/world_fixture.cpp
tlemo/bounce_softbody
5243261586c6c066eb91ca191141246fef9ad683
[ "Zlib" ]
1
2021-12-21T03:14:45.000Z
2021-12-21T17:06:44.000Z
src/bounce_softbody/dynamics/fixtures/world_fixture.cpp
tlemo/bounce_softbody
5243261586c6c066eb91ca191141246fef9ad683
[ "Zlib" ]
1
2021-12-21T03:11:02.000Z
2021-12-21T03:11:02.000Z
/* * Copyright (c) 2016-2019 Irlan Robson * * 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 <bounce_softbody/dynamics/fixtures/world_fixture.h> #include <bounce_softbody/dynamics/body.h> b3WorldFixture::b3WorldFixture() { } void b3WorldFixture::Create(b3BlockAllocator* allocator, b3Body* body, const b3WorldFixtureDef& def) { m_shape = def.shape->Clone(allocator); m_body = body; m_friction = def.friction; } void b3WorldFixture::Destroy(b3BlockAllocator* allocator) { b3Shape::Destroy(m_shape, allocator); } void b3WorldFixture::DestroyContacts() { b3SphereAndShapeContact* c = m_body->m_contactManager.m_shapeContactList.m_head; while (c) { b3SphereAndShapeContact* c0 = c; c = c->m_next; if (c0->m_f2 == this) { m_body->m_contactManager.Destroy(c0); } } }
31
100
0.762808
[ "shape" ]
d82e3e9892dbad3987661022d6b2120c40a92800
2,724
hh
C++
include/utils/std_util.hh
YPARK/mm-vae
371e60821b0d0bf866bf465a8bc7bfa048bbf32c
[ "MIT" ]
1
2021-03-18T02:01:31.000Z
2021-03-18T02:01:31.000Z
include/utils/std_util.hh
YPARK/mm-vae
371e60821b0d0bf866bf465a8bc7bfa048bbf32c
[ "MIT" ]
null
null
null
include/utils/std_util.hh
YPARK/mm-vae
371e60821b0d0bf866bf465a8bc7bfa048bbf32c
[ "MIT" ]
null
null
null
#include <algorithm> #include <functional> #include <unordered_map> #include <tuple> #include <string> #include <sstream> #include <vector> #ifndef STD_UTIL_HH_ #define STD_UTIL_HH_ char * str2char(const std::string &s) { char *ret = new char[s.size() + 1]; std::strcpy(ret, s.c_str()); return ret; } std::vector<std::string> split(const std::string &s, char delim) { std::stringstream ss(s); std::string item; std::vector<std::string> elems; while (std::getline(ss, item, delim)) { elems.push_back(std::move(item)); } return elems; } template <typename Vec> auto std_argsort(const Vec &data) { using Index = std::ptrdiff_t; std::vector<Index> index(data.size()); std::iota(std::begin(index), std::end(index), 0); std::sort(std::begin(index), std::end(index), [&](Index lhs, Index rhs) { return data.at(lhs) > data.at(rhs); }); return index; } /** * vector -> map: name -> position index */ template <typename S, typename I> std::unordered_map<S, I> make_position_dict(const std::vector<S> &name_vec) { std::unordered_map<S, I> name_to_id; for (I i = 0; i < name_vec.size(); ++i) { const S &j = name_vec.at(i); name_to_id[j] = i; } return name_to_id; } template <typename S, typename I> std::tuple<std::vector<I>, std::vector<S>, std::unordered_map<S, I>> make_indexed_vector(const std::vector<S> &name_vec) { std::unordered_map<S, I> name_to_id; std::vector<S> id_to_name; std::vector<I> id_vec; id_vec.reserve(name_vec.size()); for (I i = 0; i < name_vec.size(); ++i) { const S &ii = name_vec.at(i); if (name_to_id.count(ii) == 0) { const I j = name_to_id.size(); name_to_id[ii] = j; id_to_name.push_back(ii); } id_vec.emplace_back(name_to_id.at(ii)); } return std::make_tuple(id_vec, id_to_name, name_to_id); } template <typename I> std::vector<std::vector<I>> make_index_vec_vec(const std::vector<I> &_id) { using vec_ivec = std::vector<std::vector<I>>; const I nn = *std::max_element(_id.begin(), _id.end()) + 1; vec_ivec ret(nn, std::vector<I> {}); for (I i = 0; i < _id.size(); ++i) { const I k = _id.at(i); ret[k].push_back(i); } return ret; } // template <typename Vec> // auto // std_argsort_par(const Vec& data) { // using Index = std::ptrdiff_t; // std::vector<Index> index(data.size()); // std::iota(std::begin(index), std::end(index), 0); // std::sort(std::execution::par, std::begin(index), std::end(index), // [&](Index lhs, Index rhs) { return data.at(lhs) > data.at(rhs); // }); // return index; // } #endif
23.482759
78
0.599853
[ "vector" ]
d83044963a5cf5efecda6160043f7c0b76587aac
2,859
cc
C++
log/async_logging.cc
xingdl2007/polly
c23906d7f58d2eb263cb102b0343dccd5a245881
[ "BSD-3-Clause" ]
2
2018-04-12T21:13:18.000Z
2018-06-10T14:18:04.000Z
log/async_logging.cc
xingdl2007/polly
c23906d7f58d2eb263cb102b0343dccd5a245881
[ "BSD-3-Clause" ]
null
null
null
log/async_logging.cc
xingdl2007/polly
c23906d7f58d2eb263cb102b0343dccd5a245881
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018 The Polly Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include <functional> #include "async_logging.h" namespace polly { AsyncLogging::AsyncLogging(std::string const &file) : cur_buffer_(new Buffer), next_buffer_(new Buffer), thread_(nullptr), done(false), log_file_(file) {} // thread safe void AsyncLogging::Append(Slice const &slice) { std::lock_guard<std::mutex> lock(mutex_); // find valid buffer if (cur_buffer_->space() >= slice.size()) { cur_buffer_->append(slice); } else { buffers_.push_back(std::move(cur_buffer_)); if (next_buffer_) { cur_buffer_ = std::move(next_buffer_); } else { cur_buffer_ = std::make_unique<Buffer>(); } cur_buffer_->append(slice); cond_.notify_one(); } } void AsyncLogging::ThreadFunction(std::promise<void> &promise) { // sync with `StartWorker()` promise.set_value(); // swap buffers auto tempBuffer1 = std::make_unique<Buffer>(); auto tempBuffer2 = std::make_unique<Buffer>(); std::vector<std::unique_ptr<Buffer>> tempBuffers; while (!done) { assert(tempBuffer1 != nullptr); assert(tempBuffer2 != nullptr); assert(tempBuffers.empty()); { std::unique_lock<std::mutex> lock(mutex_); if (buffers_.empty()) { cond_.wait_for(lock, std::chrono::seconds(3)); } tempBuffer1.swap(cur_buffer_); if (next_buffer_ == nullptr) { tempBuffer2.swap(next_buffer_); } tempBuffers.swap(buffers_); } tempBuffers.push_back(std::move(tempBuffer1)); if (tempBuffer2 != nullptr) { tempBuffers.push_back(std::move(tempBuffer2)); } for (auto &it: tempBuffers) { log_file_.Append(it->slice()); } // tempBuffers at least have two buffers tempBuffers.resize(2); tempBuffer1 = std::move(tempBuffers.back()); tempBuffers.pop_back(); tempBuffer2 = std::move(tempBuffers.back()); tempBuffers.pop_back(); tempBuffers.clear(); tempBuffer1->reset(); tempBuffer2->reset(); } } // start distinct thread, write logs to disk file. void AsyncLogging::StartWorker() { std::promise<void> promise; std::future<void> future = promise.get_future(); // method 1: use bind/function // thread_ = std::make_unique<std::thread>( // std::bind(&AsyncLogging::ThreadFunction, this, // std::placeholders::_1), // std::ref(promise)); // method 2 : use lambda thread_ = std::make_unique<std::thread>([&]() { this->ThreadFunction(promise); }); // make sure thread is running future.wait(); } // wait worker thread exit void AsyncLogging::StopWorker() { cond_.notify_one(); done = true; thread_->join(); } } // namespace polly
26.719626
77
0.654774
[ "vector" ]
d830b1399b4fa418f78c85f693c882994f47926e
892
cpp
C++
src/processor.cpp
AlmasShintemirov/CppND-System-Monitor-Project-Updated
4c39ba09ee4d88cc38007df34d29b54822c28772
[ "MIT" ]
null
null
null
src/processor.cpp
AlmasShintemirov/CppND-System-Monitor-Project-Updated
4c39ba09ee4d88cc38007df34d29b54822c28772
[ "MIT" ]
null
null
null
src/processor.cpp
AlmasShintemirov/CppND-System-Monitor-Project-Updated
4c39ba09ee4d88cc38007df34d29b54822c28772
[ "MIT" ]
null
null
null
#include "processor.h" #include "linux_parser.h" #include <string> #include <vector> using std::string; using std::vector; // DONE: Return the aggregate CPU utilization float Processor::Utilization() { vector<int> cpu_data = LinuxParser::CpuUtilization(); //Processor::ReadData(Idle, NonIdle); // user nice system idle iowait irq softirq steal guest guest_nice //cpu 74608 2520 24433 1117073 6176 4054 0 0 0 0 int Idle = cpu_data[3] + cpu_data[4]; int NonIdle = cpu_data[0] + cpu_data[1] + cpu_data[2] + cpu_data[5] + cpu_data[6] + cpu_data[7]; //differentiate: actual value minus the previous one int totald = (Idle + NonIdle) - (prevIdle_ + prevNonIdle_); int idled = Idle - prevIdle_; float CPU_Percentage = (float) (totald - idled)/totald; prevIdle_ = Idle; prevNonIdle_ = NonIdle; return CPU_Percentage; }
34.307692
98
0.671525
[ "vector" ]
d837317179ece6a561e2176d4da81b9e7578acc8
35,223
cxx
C++
src/mod/pub/lib/noise/perlinnoise.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/mod/pub/lib/noise/perlinnoise.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/mod/pub/lib/noise/perlinnoise.cxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#include "stdafx.hxx" #include "perlinnoise.hxx" #include "pfm.hxx" #include "rng/rng.hxx" Palette Perlin::pal; PerlinSettings Perlin::settings; float** Perlin::noisev; int Perlin::crtSeed; float Perlin::cur_freq; int Perlin::width; int Perlin::twidth; int Perlin::theight; int Perlin::format; bool Perlin::flat; bool Perlin::tileable; bool Perlin::sphere_mapped; Palette Perlin::palTab[100]; int Perlin::palCount = 0; PerlinSettings Perlin::settingsTab[100]; int Perlin::settingsCount = 0; void Perlin::initPalette() { Perlin::pal.name = "-"; } void Perlin::initSettings() { float freq = 0.75f; float amp = 1.5f; float lacunarity = 1.f; float persistence = 0.5f; int octaves = 2; int seed = mws::time::get_time_millis() & 0x7fffffff; setParams(freq, amp, lacunarity, persistence, octaves, seed); Perlin::settings.smoothFn = SMOOTHING_ON; Perlin::settings.interpFn = LINEAR_INTERPOLATION; Perlin::settings.filterFn = ABS_BOUND; Perlin::settings.noiseFn = 1; Perlin::format = FLAT; Perlin::pal.clearColors(); Perlin::pal.setColor(0.f, 51, 51, 51); Perlin::pal.setColor(0.05f, 51, 51, 51); Perlin::pal.setColor(.5f, 255, 255, 255); Perlin::pal.setColor(1.f, 255, 255, 255); } void Perlin::addPalette(std::string name) { palTab[palCount] = Palette(); pal = palTab[palCount++]; // Init palette so that we are in a valid state. initPalette(); pal.name = name; } Palette Perlin::getCurrentPalette() { return pal; } Palette Perlin::getPalette(std::string name) { Palette palette; // for (int k = 0; k < palCount; k++) // { // if (name.compare(palTab[k].name) == 0) // { // palette = palTab[k]; // break; // } // } return palette; } void Perlin::setCurrentPalette(int idx) { pal = palTab[idx]; } void Perlin::setCurrentPalette(std::string name) { for (int k = 0; k < palCount; k++) { if (name.compare(palTab[k].name) == 0) { pal = palTab[k]; break; } } } void Perlin::addSettings(std::string name) { settingsTab[settingsCount] = PerlinSettings(); settings = settingsTab[settingsCount++]; // Init settings so that we are in a valid state. initSettings(); //settings.name = name; } PerlinSettings Perlin::getCurrentSettings() { return settings; } PerlinSettings Perlin::getSettings(std::string name) { PerlinSettings ps; // for (int k = 0; k < settingsCount; k++) // { // if (name.compare(settingsTab[k].name) == 0) // { // ps = settingsTab[k]; // break; // } // } return ps; } void Perlin::setCurrentSettings(int idx) { settings = settingsTab[idx]; } void Perlin::setCurrentSettings(std::string name) { // for (int k = 0; k < settingsCount; k++) // { // if (name.compare(settingsTab[k].name) == 0) // { // settings = settingsTab[k]; // break; // } // } } float Perlin::smoothFn(int a, int b) { switch (Perlin::settings.smoothFn) { case SMOOTHING_OFF: return noise2D(a, b); case SMOOTHING_ON: return smoothedNoise2D(a, b); } return 0; } float Perlin::interpFn(float a1, float a2, float a3) { switch (Perlin::settings.interpFn) { case LINEAR_INTERPOLATION: return linearInterpolation(a1, a2, a3); case COSINE_INTERPOLATION: return cosineInterpolation(a1, a2, a3); case CUBIC_INTERPOLATION: return cubicInterpolation(a1, a2, a3); //return 0; } return 0; } float Perlin::filterFn(float a1) { switch (Perlin::settings.filterFn) { case NORMALIZED_TRUNCATED_BOUND: return normalizedTruncatedBound(a1); case ABS_BOUND: return absBound(a1); case TRUNCATED_BOUND: return truncatedBound(a1); } return 0; } float Perlin::smoothedNoise2D(int x,int y) { float corners = ( noise2D(x-1, y-1)+noise2D(x+1, y-1)+noise2D(x-1, y+1)+noise2D(x+1, y+1) ) / 16; float sides = ( noise2D(x-1, y) +noise2D(x+1, y) +noise2D(x, y-1) +noise2D(x, y+1) ) / 8; float center = noise2D(x, y) / 4; return corners + sides + center; } float Perlin::absBound(float n) { if(n < 0.0f) n = -n; if(n > 1.0f) n = 1.0f; return n; } float Perlin::truncatedBound(float n) { if(n < 0.0f) n = 0.0f; if(n > 1.0f) n = 1.0f; return n; } float Perlin::normalizedTruncatedBound(float n) { if(n < -1.0f) n = -1.0f; if(n > 1.0f) n = 1.0f; return (n*.5f) + .5f; } void Perlin::genTxt(int *argb, int width, int height, int scanLength) { int w = width / 2; int h = height / 4; //game.RNG rng = new game.RNG(); float p; int kf = 1; for(int y = 0, l = 0; y < h; y++) { int offset = l = kf * y * scanLength; for(int x = 0; x < w; x++, l++) { //argb[l] = rng.nextInt() & 0xffffff; } } for(int y = 0, l = 0; y < h; y++) { int offset = l = kf * y * scanLength; for(int x = 0; x < w; x++, l++) { //argb[l] = RGBBuff.average(x, y) + (rng.nextInt() % 0xffffff)/2; //argb[l] = RGBBuff.average(x, y); } } for(int y = 0, l = 0; y < h; y++) { int offset = l = kf * y * scanLength; for(int x = 0; x < w; x++, l++) { //argb[l] = rng.nextInt(); //p = noise2D(x + y * 8997587); //p = (1.0f - (rng.nextInt() & 0x7fffffff) / 1073741824.f); p = argb[l] / (float)0xffffff; argb[l] = Perlin::pal.getColor(p); } // System.arraycopy(argb, offset, argb, l, w); // //System.arraycopy(argb, offset, argb, l + w, 2 * w); // //System.arraycopy(argb, offset, argb, offset + 2 * h * scanLength, scanLength); // System.arraycopy(argb, offset, argb, -offset + 2 * (2 * h - 1) * scanLength, scanLength); } } void Perlin::genPerlinTile(int *tileBounds, int tileBoundsLength, int *argb, int tileWidth) { float p; int tileHeight = tileBoundsLength / 2; int xl, xr; int adr = 0; //System.out.println("th " + tileHeight); for(int y = 0; y < tileHeight; y++, adr += tileWidth) { xl = tileBounds[y] + 1; xr = tileBounds[y + tileHeight]; //System.out.println("xl " + xl + " xr " + xr); for(int x = xl, off = adr + xl; x <= xr; x++, off++) { p = getNoise2D(x, y, settings.noiseFn); p = Perlin::filterFn(p); argb[off] = Perlin::pal.getColor(p); } } } void Perlin::genPerlinTexture(int *argb, int twidth0, int theight0) { //setParams(.1f, iamp, persistence, octaves, random_seed); twidth = twidth0; theight = theight0; float *hm = new float[twidth0 * theight0]; genHeightMap(hm, twidth0, theight0); genColorMap(argb, hm, twidth0, theight0); //paintTexture(); delete hm; } void Perlin::genHeightMap(float *hm, int twidth0, int theight0) { float p; int w = twidth; int h = theight; Perlin::width = w; for(int y = 0, l = 0; y < h; y++) { for(int x = 0; x < w; x++, l++) { p = getNoise2D(x, y, settings.noiseFn); //p = Cellular(x,y,twidth,20, crtSeed); p = Perlin::filterFn(p); hm[l] = p; } } } void Perlin::genColorMap(int *argb, float *hm, int twidth0, int theight0) { for(int y = 0, l = 0; y < theight0; y++) { for(int x = 0; x < twidth0; x++, l++) { argb[l] = Perlin::pal.getColor(hm[l]); } } } void Perlin::setParams(float init_freq, float init_amp, float lacunarity0, float persistence0, int octaves, int random_seed) { Perlin::settings.ifreq = init_freq; Perlin::settings.iamp = init_amp; Perlin::settings.lacunarity = lacunarity0; Perlin::settings.persistence = persistence0; Perlin::settings.octaves = octaves; Perlin::settings.seed = crtSeed = random_seed; } float Perlin::noise1D(int x) { x += Perlin::settings.seed; x = (x<<13) ^ x; return ( 1.0f - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f); //return ( 1.0f - ((x * 15731 + 789221) & 0x7fffffff) / 1073741824.0f); } int Perlin::rndNoise(int x, int y) { //System.out.println("c " + crtSeed); //if((crtSeed = A * (crtSeed % Q) - R * (crtSeed / Q)) <= 0)crtSeed += M; //crtSeed += x-y; //crtSeed = A * (crtSeed % Q) - R * (crtSeed / Q); crtSeed = (crtSeed + x) * 15731; crtSeed = (crtSeed + y) * 789221; crtSeed &= 0x7fffffff; return crtSeed; } float Perlin::noise2D(int x, int y) { /* if(Perlin::format == TILEABLE) { // round f to nearest int s float f = Perlin::cur_freq*Perlin::width; int s = (int)f; if(f - s > .5f) s++; if (s > 0) { x %= s; y %= s; } if (x < 0) x += s; if (y < 0) y += s; } */ //float f = 1.f - rndNoise(x, y) / 1073741824.f; //float f = rndNoise(x, y); //System.out.println("f " + f); //return f; // all the mysterious large numbers in these functions are prime. float fl= noise1D(x + y * 8997587);//57); //return Noise((y ^ 0x562a56fa ) * ( x ^ y )); //return Noise((y ^ 0x386a6c5e ) * ( x ^ y )); /* x = x+y*8997587+Perlin::random_seed; //x += Perlin::random_seed; x = (x<<13) ^ x; return ( 1.0f - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f); */ //if(y==17&&x==17) { //trace("seed %d %f" , Perlin::settings.seed, fl); } return fl; } float Perlin::linearInterpolation(float a,float b,float x) { return a*(1-x) + b*x; } float Perlin::cosineInterpolation(float a, float b, float x) { // accelerate this with a cos lookup table? float ft = x * 3.1415927f; float f = (1 - (float)cos(ft)) * .5f; return a*(1-f)+b*f; } float Perlin::cubicInterpolation(float a, float b, float x) { float fac1 = 3 * (float)pow(1-x, 2) - 2 * (float)pow(1-x,3); float fac2 = 3 * (float)pow(x, 2) - 2 * (float)pow(x, 3); return a * fac1 + b * fac2; //add the weighted factors } float Perlin::perlinNoise2D(float x, float y) { float total = 0; float freq = Perlin::settings.ifreq; float amp = Perlin::settings.iamp; for(int i = 0; i < Perlin::settings.octaves; i++) { Perlin::cur_freq = freq; total += interpolatedNoise2D(x * freq, y * freq) * amp; freq *= Perlin::settings.lacunarity; amp *= Perlin::settings.persistence; } return total; } float Perlin::interpolatedNoise2D(float x, float y) { //if (true)return ImprovedNoise.noise3D(x, y, 0); //if (true)return OriginalNoise.noise2(x, y); int a = (int)x; int b = (int)y; float frac_a = x - a; float frac_b = y - b; float v1, v2, v3, v4; v1 = smoothFn(a, b); v2 = smoothFn(a + 1, b); v3 = smoothFn(a, b + 1); v4 = smoothFn(a + 1, b + 1); /* v1 = smoothedNoise2D(a,b); v2 = smoothedNoise2D(a + 1, b); v3 = smoothedNoise2D(a,b+1); v4 = smoothedNoise2D(a+1,b+1); */ /* v1 = noisev[b][a]; v2 = noisev[b][a + 1]; v3 = noisev[b + 1][a]; v4 = noisev[b + 1][a + 1]; */ float i1 = Perlin::interpFn(v1 , v2 , frac_a); float i2 = Perlin::interpFn(v3 , v4 , frac_a); return Perlin::interpFn(i1 , i2 , frac_b); } float Perlin::perlinNoise3D(float x, float y, float z) { float total = 0; float freq = Perlin::settings.ifreq; float amp = Perlin::settings.iamp; for(int i = 0; i < Perlin::settings.octaves; i++) { total += interpolatedNoise3D(x * freq, y * freq, z * freq) * amp; freq *= 2; amp *= Perlin::settings.persistence; } return total; } float Perlin::noise3D(int x, int y, int z) { return noise1D(x + (y * 89213) + (z * 8997587)); } float Perlin::interpolatedNoise3D(float x, float y, float z) { int a = (int)x; int b = (int)y; int c = (int)z; float frac_a = x - a; float frac_b = y - b; float frac_c = z - c; float v1 = noise3D(a,b,c); float v2 = noise3D(a+1,b,c); float v3 = noise3D(a,b+1,c); float v4 = noise3D(a+1,b+1,c); float i1 = Perlin::interpFn(v1 , v2 , frac_a); float i2 = Perlin::interpFn(v3 , v4 , frac_a); float i3 = Perlin::interpFn(i1 , i2 , frac_b); float v5 = noise3D(a,b,c+1); float v6 = noise3D(a+1,b,c+1); float v7 = noise3D(a,b+1,c+1); float v8 = noise3D(a+1,b+1,c+1); float j1 = Perlin::interpFn(v5 , v6 , frac_a); float j2 = Perlin::interpFn(v7 , v8 , frac_a); float j3 = Perlin::interpFn(j1 , j2 , frac_b); return Perlin::interpFn(i3 , j3 , frac_c); } void Perlin::genSphereTiledTexture(int *argb,int w, int h, int scanLength) { float p, u, v, r, s, a, b, c; for(int x = 0; x < w; x++) { for(int y = 0; y < h; y++) { u = (float)x/(float)w; v = (float)y/(float)h; r = u * 2.0f * 3.14156f; s = (v - .5f) * 3.14156f; a = (float)(cos(r)*cos(s)); b = (float)(sin(r)*cos(s)); c = (float)(sin(s)); a+=1.0f; b+=1.0f; c+=1.0f; a*=w; b*=w; c*=w; p = perlinNoise3D(a,b,c); p = Perlin::filterFn(p); argb[(y * scanLength) + x] = Perlin::pal.getColor(p); } } } float Perlin::Cellular(float x,float y,int width,int tam_cas, int seed) { double primero=2*tam_cas, segundo=2*tam_cas,tercero=2*tam_cas,dist_aux; int casilla_pto; double xpunto, ypunto; int n_casillas=(int)(width/tam_cas)+1; int casillax=(int)(x/tam_cas); int casillay=(int)(y/tam_cas); int casilla=n_casillas*casillay+casillax; for (int j=-1;j<2;j++) { for (int i=-1;i<2;i++) { casilla_pto=casilla+i+j*n_casillas; xpunto=(casillax+i)*tam_cas+noise1D(casilla_pto+seed)*tam_cas; ypunto=(casillay+j)*tam_cas+noise1D(casilla_pto+10+seed)*tam_cas; dist_aux=sqrt((x-xpunto)*(x-xpunto)+(y-ypunto)*(y-ypunto)); if (primero>dist_aux) { tercero=segundo; segundo=primero; primero=dist_aux; } else { if (segundo>dist_aux) { tercero= segundo; segundo=dist_aux;} else {if (tercero>dist_aux) {tercero=dist_aux;}} } }} return (float)(primero*primero/(segundo*tercero)); } float Perlin::getNoise2D(int x, int y, int id) { switch(id) { case 0: return Perlin::perlinNoise2D(x, y); case 1: return (Perlin::noise2D(x,y) + 2 * Perlin::perlinNoise2D(x,y)) / 6; } return 0; } float grad[12][3] = { {1.0,1.0,0.0},{-1.0,1.0,0.0},{1.0,-1.0,0.0},{-1.0,-1.0,0.0}, {1.0,0.0,1.0},{-1.0,0.0,1.0},{1.0,0.0,-1.0},{-1.0,0.0,-1.0}, {0.0,1.0,1.0},{0.0,-1.0,1.0},{0.0,1.0,-1.0},{0.0,-1.0,-1.0} }; int perm_init[512] = {151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; int perm[512]; void set_seed(int seed) { for (int i = 0; i < 256; i++) { int shift = (i + seed) % 256; perm[i] = perm_init[shift & 0xff]; perm[i + 256] = perm_init[shift & 0xff]; } } float dot(float x, float y, float z, float* g) { return x*g[0] + y*g[1] + z*g[2]; } float noise(float xin, float yin, float zin){ float F3, G3, t, X0, Y0, Z0, x0, y0, z0, s, x1, y1, z1, x2, y2, z2, x3, y3, z3, t0, t1, t2, t3, n0, n1, n2, n3; int i, j, k, ii, jj, kk, i1, j1, k1, i2, j2, k2, gi0, gi1, gi2, gi3; F3 = 1.0/3.0; s = (xin+yin+zin)*F3; i = xin+s; j = yin+s; k = zin+s; G3 = 1.0/6.0; t = (i+j+k)*G3; X0 = i-t; Y0 = j-t; Z0 = k-t; x0 = xin-X0; y0 = yin-Y0; z0 = zin-Z0; if(x0 >= y0){ if(y0 >= z0){ i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; } else if(x0 >= z0){ i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; } else{ i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; } } else{ if(y0 < z0){ i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; } else if(x0 < z0){ i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; } else{ i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; } } x1 = x0 - i1 + G3; y1 = y0 - j1 + G3; z1 = z0 - k1 + G3; x2 = x0 - i2 + 2.0*G3; y2 = y0 - j2 + 2.0*G3; z2 = z0 - k2 + 2.0*G3; x3 = x0 - 1.0 + 3.0*G3; y3 = y0 - 1.0 + 3.0*G3; z3 = z0 - 1.0 + 3.0*G3; ii = i & 255; jj = j & 255; kk = k & 255; gi0 = perm[ii+perm[jj+perm[kk]]] % 12; gi1 = perm[ii+i1+perm[jj+j1+perm[kk+k1]]] % 12; gi2 = perm[ii+i2+perm[jj+j2+perm[kk+k2]]] % 12; gi3 = perm[ii+1+perm[jj+1+perm[kk+1]]] % 12; t0 = 0.6 - x0*x0 - y0*y0 - z0*z0; if(t0<0){ n0 = 0.0; } else{ t0 *= t0; n0 = t0 * t0 * dot(x0, y0, z0, grad[gi0]); } t1 = 0.6 - x1*x1 - y1*y1 - z1*z1; if(t1<0){ n1 = 0.0; } else{ t1 *= t1; n1 = t1 * t1 * dot(x1, y1, z1, grad[gi1]); } t2 = 0.6 - x2*x2 - y2*y2 - z2*z2; if(t2<0){ n2 = 0.0; } else{ t2 *= t2; n2 = t2 * t2 * dot(x2, y2, z2, grad[gi2]); } t3 = 0.6 - x3*x3 - y3*y3 - z3*z3; if(t3<0){ n3 = 0.0; } else{ t3 *= t3; n3 = t3 * t3 * dot(x3, y3, z3, grad[gi3]); } return 16.0*(n0 + n1 + n2 + n3)+1.0; } float simplex_noise(int octaves, float x, float y, float z){ float value = 0.0; int i; for(i=0; i<octaves; i++){ value += noise( x*powf(2, i), y*powf(2, i), z*powf(2, i) ); } return value; } // SimplexNoise1234 // Copyright 2003-2011, Stefan Gustavson #define FASTFLOOR(x) ( ((x)>0) ? ((int)x) : (((int)x)-1) ) //--------------------------------------------------------------------- // Static data /* * Permutation table. This is just a random jumble of all numbers 0-255, * repeated twice to avoid wrapping the index at 255 for each lookup. * This needs to be exactly the same for all instances on all platforms, * so it's easiest to just keep it as static explicit data. * This also removes the need for any initialisation of this class. * * Note that making this an int[] instead of a char[] might make the * code run faster on platforms with a high penalty for unaligned single * byte addressing. Intel x86 is generally single-byte-friendly, but * some other CPUs are faster with 4-aligned reads. * However, a char[] is smaller, which avoids cache trashing, and that * is probably the most important aspect on most architectures. * This array is accessed a *lot* by the noise functions. * A vector-valued noise over 3D accesses it 96 times, and a * float-valued 4D noise 64 times. We want this to fit in the cache! */ unsigned char SimplexNoise1234::perm[512] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; //--------------------------------------------------------------------- /* * Helper functions to compute gradients-dot-residualvectors (1D to 4D) * Note that these generate gradients of more than unit length. To make * a close match with the value range of classic Perlin noise, the final * noise values need to be rescaled to fit nicely within [-1,1]. * (The simplex noise functions as such also have different scaling.) * Note also that these noise functions are the most practical and useful * signed version of Perlin noise. To return values according to the * RenderMan specification from the SL noise() and pnoise() functions, * the noise values need to be scaled and offset to [0,1], like this: * float SLnoise = (SimplexNoise1234::noise(x,y,z) + 1.0) * 0.5; */ float SimplexNoise1234::grad( int hash, float x ) { int h = hash & 15; float grad = 1.0f + (h & 7); // Gradient value 1.0, 2.0, ..., 8.0 if (h&8) grad = -grad; // Set a random sign for the gradient return ( grad * x ); // Multiply the gradient with the distance } float SimplexNoise1234::grad( int hash, float x, float y ) { int h = hash & 7; // Convert low 3 bits of hash code float u = h<4 ? x : y; // into 8 simple gradient directions, float v = h<4 ? y : x; // and compute the dot product with (x,y). return ((h&1)? -u : u) + ((h&2)? -2.0f*v : 2.0f*v); } float SimplexNoise1234::grad( int hash, float x, float y , float z ) { int h = hash & 15; // Convert low 4 bits of hash code into 12 simple float u = h<8 ? x : y; // gradient directions, and compute dot product. float v = h<4 ? y : h==12||h==14 ? x : z; // Fix repeats at h = 12 to 15 return ((h&1)? -u : u) + ((h&2)? -v : v); } float SimplexNoise1234::grad( int hash, float x, float y, float z, float t ) { int h = hash & 31; // Convert low 5 bits of hash code into 32 simple float u = h<24 ? x : y; // gradient directions, and compute dot product. float v = h<16 ? y : z; float w = h<8 ? z : t; return ((h&1)? -u : u) + ((h&2)? -v : v) + ((h&4)? -w : w); } // A lookup table to traverse the simplex around a given point in 4D. // Details can be found where this table is used, in the 4D noise method. /* TODO: This should not be required, backport it from Bill's GLSL code! */ static unsigned char simplex[64][4] = { {0,1,2,3},{0,1,3,2},{0,0,0,0},{0,2,3,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,2,3,0}, {0,2,1,3},{0,0,0,0},{0,3,1,2},{0,3,2,1},{0,0,0,0},{0,0,0,0},{0,0,0,0},{1,3,2,0}, {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, {1,2,0,3},{0,0,0,0},{1,3,0,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,3,0,1},{2,3,1,0}, {1,0,2,3},{1,0,3,2},{0,0,0,0},{0,0,0,0},{0,0,0,0},{2,0,3,1},{0,0,0,0},{2,1,3,0}, {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}, {2,0,1,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,0,1,2},{3,0,2,1},{0,0,0,0},{3,1,2,0}, {2,1,0,3},{0,0,0,0},{0,0,0,0},{0,0,0,0},{3,1,0,2},{0,0,0,0},{3,2,0,1},{3,2,1,0} }; // 1D simplex noise float SimplexNoise1234::noise(float x) { int i0 = FASTFLOOR(x); int i1 = i0 + 1; float x0 = x - i0; float x1 = x0 - 1.0f; float n0, n1; float t0 = 1.0f - x0*x0; // if(t0 < 0.0f) t0 = 0.0f; t0 *= t0; n0 = t0 * t0 * grad(perm[i0 & 0xff], x0); float t1 = 1.0f - x1*x1; // if(t1 < 0.0f) t1 = 0.0f; t1 *= t1; n1 = t1 * t1 * grad(perm[i1 & 0xff], x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 would scale to fit exactly within [-1,1], but // we want to match PRMan's 1D noise, so we scale it down some more. return 0.25f * (n0 + n1); } // 2D simplex noise float SimplexNoise1234::noise(float x, float y) { #define F2 0.366025403 // F2 = 0.5*(sqrt(3.0)-1.0) #define G2 0.211324865 // G2 = (3.0-Math.sqrt(3.0))/6.0 float n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in float s = (x+y)*F2; // Hairy factor for 2D float xs = x + s; float ys = y + s; int i = FASTFLOOR(xs); int j = FASTFLOOR(ys); float t = (float)(i+j)*G2; float X0 = i-t; // Unskew the cell origin back to (x,y) space float Y0 = j-t; float x0 = x-X0; // The x,y distances from the cell origin float y0 = y-Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if(x0>y0) {i1=1; j1=0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1) else {i1=0; j1=1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords float y1 = y0 - j1 + G2; float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords float y2 = y0 - 1.0f + 2.0f * G2; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds int ii = i & 0xff; int jj = j & 0xff; // Calculate the contribution from the three corners float t0 = 0.5f - x0*x0-y0*y0; if(t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii+perm[jj]], x0, y0); } float t1 = 0.5f - x1*x1-y1*y1; if(t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1]], x1, y1); } float t2 = 0.5f - x2*x2-y2*y2; if(t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii+1+perm[jj+1]], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 40.0f * (n0 + n1 + n2); // TODO: The scale factor is preliminary! } // 3D simplex noise float SimplexNoise1234::noise(float x, float y, float z) { // Simple skewing factors for the 3D case #define F3 0.333333333 #define G3 0.166666667 float n0, n1, n2, n3; // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in float s = (x+y+z)*F3; // Very nice and simple skew factor for 3D float xs = x+s; float ys = y+s; float zs = z+s; int i = FASTFLOOR(xs); int j = FASTFLOOR(ys); int k = FASTFLOOR(zs); float t = (float)(i+j+k)*G3; float X0 = i-t; // Unskew the cell origin back to (x,y,z) space float Y0 = j-t; float Z0 = k-t; float x0 = x-X0; // The x,y,z distances from the cell origin float y0 = y-Y0; float z0 = z-Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords /* This code would benefit from a backport from the GLSL version! */ if(x0>=y0) { if(y0>=z0) { i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; } // X Y Z order else if(x0>=z0) { i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; } // X Z Y order else { i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; } // Z X Y order } else { // x0<y0 if(y0<z0) { i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; } // Z Y X order else if(x0<z0) { i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; } // Y Z X order else { i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; } // Y X Z order } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. float x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords float y1 = y0 - j1 + G3; float z1 = z0 - k1 + G3; float x2 = x0 - i2 + 2.0f*G3; // Offsets for third corner in (x,y,z) coords float y2 = y0 - j2 + 2.0f*G3; float z2 = z0 - k2 + 2.0f*G3; float x3 = x0 - 1.0f + 3.0f*G3; // Offsets for last corner in (x,y,z) coords float y3 = y0 - 1.0f + 3.0f*G3; float z3 = z0 - 1.0f + 3.0f*G3; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds int ii = i & 0xff; int jj = j & 0xff; int kk = k & 0xff; // Calculate the contribution from the four corners float t0 = 0.6f - x0*x0 - y0*y0 - z0*z0; if(t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii+perm[jj+perm[kk]]], x0, y0, z0); } float t1 = 0.6f - x1*x1 - y1*y1 - z1*z1; if(t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1+perm[kk+k1]]], x1, y1, z1); } float t2 = 0.6f - x2*x2 - y2*y2 - z2*z2; if(t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii+i2+perm[jj+j2+perm[kk+k2]]], x2, y2, z2); } float t3 = 0.6f - x3*x3 - y3*y3 - z3*z3; if(t3<0.0f) n3 = 0.0f; else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii+1+perm[jj+1+perm[kk+1]]], x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return 32.0f * (n0 + n1 + n2 + n3); // TODO: The scale factor is preliminary! } // 4D simplex noise float SimplexNoise1234::noise(float x, float y, float z, float w) { // The skewing and unskewing factors are hairy again for the 4D case #define F4 0.309016994 // F4 = (Math.sqrt(5.0)-1.0)/4.0 #define G4 0.138196601 // G4 = (5.0-Math.sqrt(5.0))/20.0 float n0, n1, n2, n3, n4; // Noise contributions from the five corners // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in float s = (x + y + z + w) * F4; // Factor for 4D skewing float xs = x + s; float ys = y + s; float zs = z + s; float ws = w + s; int i = FASTFLOOR(xs); int j = FASTFLOOR(ys); int k = FASTFLOOR(zs); int l = FASTFLOOR(ws); float t = (i + j + k + l) * G4; // Factor for 4D unskewing float X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space float Y0 = j - t; float Z0 = k - t; float W0 = l - t; float x0 = x - X0; // The x,y,z,w distances from the cell origin float y0 = y - Y0; float z0 = z - Z0; float w0 = w - W0; // For the 4D case, the simplex is a 4D shape I won't even try_ to describe. // To find out which of the 24 possible simplices we're in, we need to // determine the magnitude ordering of x0, y0, z0 and w0. // The method below is a good way of finding the ordering of x,y,z,w and // then find the correct traversal order for the simplex we?re in. // First, six pair-wise comparisons are performed between each possible pair // of the four coordinates, and the results are used to add up binary bits // for an integer index. int c1 = (x0 > y0) ? 32 : 0; int c2 = (x0 > z0) ? 16 : 0; int c3 = (y0 > z0) ? 8 : 0; int c4 = (x0 > w0) ? 4 : 0; int c5 = (y0 > w0) ? 2 : 0; int c6 = (z0 > w0) ? 1 : 0; int c = c1 + c2 + c3 + c4 + c5 + c6; int i1, j1, k1, l1; // The integer offsets for the second simplex corner int i2, j2, k2, l2; // The integer offsets for the third simplex corner int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w // impossible. Only the 24 indices which have non-zero entries make any sense. // We use a thresholding to set the coordinates in turn from the largest magnitude. // The number 3 in the "simplex" array is at the position of the largest coordinate. i1 = simplex[c][0]>=3 ? 1 : 0; j1 = simplex[c][1]>=3 ? 1 : 0; k1 = simplex[c][2]>=3 ? 1 : 0; l1 = simplex[c][3]>=3 ? 1 : 0; // The number 2 in the "simplex" array is at the second largest coordinate. i2 = simplex[c][0]>=2 ? 1 : 0; j2 = simplex[c][1]>=2 ? 1 : 0; k2 = simplex[c][2]>=2 ? 1 : 0; l2 = simplex[c][3]>=2 ? 1 : 0; // The number 1 in the "simplex" array is at the second smallest coordinate. i3 = simplex[c][0]>=1 ? 1 : 0; j3 = simplex[c][1]>=1 ? 1 : 0; k3 = simplex[c][2]>=1 ? 1 : 0; l3 = simplex[c][3]>=1 ? 1 : 0; // The fifth corner has all coordinate offsets = 1, so no need to look that up. float x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords float y1 = y0 - j1 + G4; float z1 = z0 - k1 + G4; float w1 = w0 - l1 + G4; float x2 = x0 - i2 + 2.0f*G4; // Offsets for third corner in (x,y,z,w) coords float y2 = y0 - j2 + 2.0f*G4; float z2 = z0 - k2 + 2.0f*G4; float w2 = w0 - l2 + 2.0f*G4; float x3 = x0 - i3 + 3.0f*G4; // Offsets for fourth corner in (x,y,z,w) coords float y3 = y0 - j3 + 3.0f*G4; float z3 = z0 - k3 + 3.0f*G4; float w3 = w0 - l3 + 3.0f*G4; float x4 = x0 - 1.0f + 4.0f*G4; // Offsets for last corner in (x,y,z,w) coords float y4 = y0 - 1.0f + 4.0f*G4; float z4 = z0 - 1.0f + 4.0f*G4; float w4 = w0 - 1.0f + 4.0f*G4; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds int ii = i & 0xff; int jj = j & 0xff; int kk = k & 0xff; int ll = l & 0xff; // Calculate the contribution from the five corners float t0 = 0.6f - x0*x0 - y0*y0 - z0*z0 - w0*w0; if(t0 < 0.0f) n0 = 0.0f; else { t0 *= t0; n0 = t0 * t0 * grad(perm[ii+perm[jj+perm[kk+perm[ll]]]], x0, y0, z0, w0); } float t1 = 0.6f - x1*x1 - y1*y1 - z1*z1 - w1*w1; if(t1 < 0.0f) n1 = 0.0f; else { t1 *= t1; n1 = t1 * t1 * grad(perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]], x1, y1, z1, w1); } float t2 = 0.6f - x2*x2 - y2*y2 - z2*z2 - w2*w2; if(t2 < 0.0f) n2 = 0.0f; else { t2 *= t2; n2 = t2 * t2 * grad(perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]], x2, y2, z2, w2); } float t3 = 0.6f - x3*x3 - y3*y3 - z3*z3 - w3*w3; if(t3 < 0.0f) n3 = 0.0f; else { t3 *= t3; n3 = t3 * t3 * grad(perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]], x3, y3, z3, w3); } float t4 = 0.6f - x4*x4 - y4*y4 - z4*z4 - w4*w4; if(t4 < 0.0f) n4 = 0.0f; else { t4 *= t4; n4 = t4 * t4 * grad(perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]], x4, y4, z4, w4); } // Sum up and scale the result to cover the range [-1,1] return 27.0f * (n0 + n1 + n2 + n3 + n4); // TODO: The scale factor is preliminary! }
28.966283
2,362
0.59535
[ "shape", "vector", "3d" ]
d844144bf0ab481a7f6daa63da707dba61c75f92
1,761
cpp
C++
practice/63-unique-paths-ii/LeetCode_63_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/63-unique-paths-ii/LeetCode_63_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/63-unique-paths-ii/LeetCode_63_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
/** * 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? 网格中的障碍物和空位置分别用 1 和 0 来表示。 说明:m 和 n 的值均不超过 100。 示例 1: 输入: [   [0,0,0],   [0,1,0],   [0,0,0] ] 输出: 2 解释: 3x3 网格的正中间有一个障碍物。 从左上角到右下角一共有 2 条不同的路径: 1. 向右 -> 向右 -> 向下 -> 向下 2. 向下 -> 向下 -> 向右 -> 向右 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include <iostream> #include <vector> using namespace std; class Solution { public: int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) { int m = obstacleGrid.size(); if (m < 1) return 0; int n = obstacleGrid[0].size(); if (n < 1) return 1; long ans[m][n]; // 首列 for (int i = 0; i < m; ++i) { if (obstacleGrid[i][0] == 1) { ans[i][0] = 0; } else { ans[i][0] = i == 0 ? 1 : ans[i - 1][0]; } } // 首行 for (int i = 0; i < n; ++i) { if (obstacleGrid[0][i] == 1) { ans[0][i] = 0; } else { ans[0][i] = i == 0 ? 1 : ans[0][i - 1]; } } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (obstacleGrid[i][j] == 1) { ans[i][j] = 0; } else { // 如果不为空 ans[i][j] = ans[i - 1][j] + ans[i][j - 1]; } } } return ans[m - 1][n - 1]; } };
18.935484
67
0.385009
[ "vector" ]
d84c31b55963cd4e962293a9563bb0f42dcd3151
3,441
cc
C++
check/libs/pasta/core/slicing.cc
jonathanzjl/pasta
b825e188fb017ee7fb46d749fdc8b191a7c45384
[ "BSD-2-Clause" ]
1
2019-09-22T20:00:35.000Z
2019-09-22T20:00:35.000Z
check/libs/pasta/core/slicing.cc
jonathanzjl/pasta
b825e188fb017ee7fb46d749fdc8b191a7c45384
[ "BSD-2-Clause" ]
null
null
null
check/libs/pasta/core/slicing.cc
jonathanzjl/pasta
b825e188fb017ee7fb46d749fdc8b191a7c45384
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2018 Zhijin Li * * 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. */ // --------------------------------------------------------------------------- // // File: slicing.cc for pasta // // Created by Zhijin Li // E-mail: <jonathan.zj.lee@gmail.com> // // Started on Fri Nov 2 17:38:33 2018 Zhijin Li // Last update Fri Nov 9 23:16:07 2018 Zhijin Li // --------------------------------------------------------------------------- # include "pasta/core.hh" # include "pasta/utilities.hh" int main() { /// Create vectors for slicing: /// note -> in-place slicing works only for /// dynamic vectors (Eigen). /// Eigen::Matrix<int,1,-1> int_vec(10); std::vector<int> int_vec_stl(10); std::iota(int_vec.data(), int_vec.data()+int_vec.size(), 0); std::iota(int_vec_stl.begin(), int_vec_stl.end(), 0); Eigen::Matrix<int,1,-1> int_vec2(int_vec); std::vector<int> int_vec_stl2(int_vec_stl); /// Define slicing vectors. std::vector<short> logical_stl(10); Eigen::Matrix<bool,10,1> logical_eig; for(int n = 0; n < 10; ++n) if(n%2 == 0) { logical_stl[n] = 42; logical_eig(n) = false; } else { logical_stl[n] = 0; logical_eig(n) = true; } pasta::utils::logical_slice(int_vec, logical_stl, 42); pasta::utils::logical_slice(int_vec_stl, logical_stl, 42); pasta::utils::logical_slice(int_vec2, logical_eig); pasta::utils::logical_slice(int_vec_stl2, logical_eig); /// Check correctness. if( int_vec.size() != 5 || int_vec_stl.size() != 5 || int_vec2.size() != 5 || int_vec_stl2.size() != 5 ) { std::cerr << "logical slice went wrong: size mismatch.\n"; return 1; } for(int n = 0; n < 5; ++n) { if( int_vec(n)%2 != 0 || int_vec_stl[n]%2 != 0 ) { std::cerr << "logical slice (42) went wrong: value mismatch.\n"; return 1; } if( int_vec2(n)%2 == 0 || int_vec_stl2[n]%2 == 0 ) { std::cerr << "logical slice (true) went wrong: value mismatch.\n"; return 1; } } return 0; }
31.861111
79
0.619297
[ "vector" ]
d84c62fac89b504cde572315f3f68e5f38752f3e
1,677
cpp
C++
muan/control/nonlinear_feedback_controller.cpp
hansonl02/frc-robot-code
4b120c917a7709df9f010c9089a87c320bab3a16
[ "MIT" ]
61
2017-01-22T04:38:32.000Z
2022-03-07T00:04:37.000Z
muan/control/nonlinear_feedback_controller.cpp
hansonl02/frc-robot-code
4b120c917a7709df9f010c9089a87c320bab3a16
[ "MIT" ]
3
2018-06-28T05:34:57.000Z
2019-01-16T15:46:22.000Z
muan/control/nonlinear_feedback_controller.cpp
hansonl02/frc-robot-code
4b120c917a7709df9f010c9089a87c320bab3a16
[ "MIT" ]
17
2017-05-12T15:32:03.000Z
2021-12-09T12:49:38.000Z
#include "muan/control/nonlinear_feedback_controller.h" namespace muan { namespace control { NonLinearFeedbackController::NonLinearFeedbackController(DrivetrainModel model, double beta, double zeta) : model_(model), beta_(beta), zeta_(zeta) {} NonLinearFeedbackController::Output NonLinearFeedbackController::Update( Eigen::Vector2d velocity, Eigen::Vector2d acceleration, Pose current, Pose error, bool high_gear) { double k1 = 2. * zeta_ * std::sqrt(beta_ * velocity(0) * velocity(0) + velocity(1) * velocity(1)); double k2 = beta_; double err_sin = std::abs(error.heading()) < 1e-9 ? 1. : std::sin(error.heading()) / error.heading(); Eigen::Vector2d adjusted_velocity; adjusted_velocity(0) = velocity(0) * std::cos(error.heading()) + k1 * ((std::cos(current.heading()) * error.Get()(0)) + (std::sin(current.heading()) * error.Get()(1))); adjusted_velocity(1) = velocity(1) + k2 * velocity(0) * err_sin * (std::cos(current.heading()) * error.Get()(1) - std::sin(current.heading()) * error.Get()(0)) + k1 * error.heading(); Eigen::Vector2d left_right_velocity = model_.InverseKinematics(adjusted_velocity); Eigen::Vector2d left_right_ff = model_.InverseDynamics(velocity, acceleration, high_gear); return {left_right_velocity, left_right_ff}; } } // namespace control } // namespace muan
37.266667
103
0.56768
[ "model" ]
d84e7b851c8058b359c0c3d6cca7e87c84c9a515
2,853
cpp
C++
src/coroutine.cpp
moslevin/Mark3
780aeae99d47cb0ddae611b80597305ec852e588
[ "BSD-3-Clause" ]
11
2018-09-13T12:12:18.000Z
2021-05-12T23:11:09.000Z
src/coroutine.cpp
moslevin/Mark3
780aeae99d47cb0ddae611b80597305ec852e588
[ "BSD-3-Clause" ]
1
2019-02-18T20:37:22.000Z
2019-02-18T20:37:22.000Z
src/coroutine.cpp
moslevin/Mark3
780aeae99d47cb0ddae611b80597305ec852e588
[ "BSD-3-Clause" ]
8
2018-09-13T12:12:27.000Z
2021-07-04T10:59:44.000Z
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012 - 2019 m0slevin, all rights reserved. See license.txt for more information =========================================================================== */ /** @file coroutine.cpp @brief Coroutine object implementation */ #include "coroutine.h" #include "cosched.h" #include "criticalguard.h" #include "kernel.h" namespace Mark3 { //--------------------------------------------------------------------------- Coroutine::~Coroutine() { if (m_pclOwner != CoScheduler::GetStopList()) { Kernel::Panic(PANIC_ACTIVE_COROUTINE_DESCOPED); } const auto cs = CriticalGuard{}; m_pclOwner->Remove(this); } //--------------------------------------------------------------------------- void Coroutine::Init(PORT_PRIO_TYPE uPriority_, CoroutineHandler pfHandler_, void* pvContext_) { m_bQueued = false; m_pfHandler = pfHandler_; m_pvContext = pvContext_; m_uPriority = uPriority_; m_pclOwner = CoScheduler::GetStopList(); const auto cs = CriticalGuard{}; m_pclOwner->Add(this); } //--------------------------------------------------------------------------- void Coroutine::Run() { { // Begin critical section const auto cs = CriticalGuard{}; m_pclOwner->Remove(this); m_pclOwner = CoScheduler::GetStopList(); m_pclOwner->Add(this); m_bQueued = false; } // end critical section m_pfHandler(this, m_pvContext); } //--------------------------------------------------------------------------- void Coroutine::Activate() { const auto cs = CriticalGuard{}; if (m_bQueued) { return; } m_pclOwner->Remove(this); m_pclOwner = CoScheduler::GetCoList(m_uPriority); m_pclOwner->Add(this); m_bQueued = true; } //--------------------------------------------------------------------------- void Coroutine::SetPriority(PORT_PRIO_TYPE uPriority_) { const auto cs = CriticalGuard{}; m_pclOwner->Remove(this); m_uPriority = uPriority_; if (m_bQueued) { m_pclOwner = CoScheduler::GetCoList(m_uPriority); } else { m_pclOwner = CoScheduler::GetStopList(); } m_pclOwner->Add(this); } //--------------------------------------------------------------------------- PORT_PRIO_TYPE Coroutine::GetPriority() { return m_uPriority; } } // namespace Mark3
27.970588
94
0.464073
[ "object" ]
d8528b5486bc8417de42dbf4dc54030309673a5f
17,620
cpp
C++
Tracing/MDL/volumeProcess.cpp
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
Tracing/MDL/volumeProcess.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
Tracing/MDL/volumeProcess.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
/*========================================================================= Copyright 2009 Rensselaer Polytechnic Institute 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning(disable : 4996) #endif # define Curvature_Anistropic_Diffusion 1 #include <iostream> #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkOtsuThresholdImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "GCBinarization/cell_binarization.h" #include "distTransform.h" using std::cerr; using std::cout; using std::endl; using std::string; #define DATATYPEIN unsigned char #define DATATYPEOUT unsigned char const unsigned char m_NumberOfHistogramBins = 128; DATATYPEIN *volin; int sizeX, sizeY, sizeZ; float *tempimage; double OtsuThreshold (int sizeX,int sizeY,int sizeZ); int main(int argc, char *argv[]) { //check that the user specified the right number of command line arguments if(argc < 3) { cerr << argv[0] << " <input file> <output file>" << endl; cerr << argv[0] << " <raw input file> <sizeX> <sizeY> <sizeZ> <output file>" << endl; return EXIT_FAILURE; } //check if the input image is .raw bool rawInput = false; string inputFileName = argv[1]; const char *outputFileName; //double space[3]={1,1,1}; if(inputFileName.rfind(".raw") != string::npos) { //if so, the user is also required to pass in image dimensions if(argc < 6) { cerr << "Usage: <raw input file> <sizeX> <sizeY> <sizeZ> <output file>" << endl; return EXIT_FAILURE; } rawInput = true; sizeX = atoi(argv[2]); sizeY = atoi(argv[3]); sizeZ = atoi(argv[4]); outputFileName = argv[5]; } else { outputFileName = argv[2]; } FILE *infile = 0; FILE *outfile; int i,j,k; int ii, jj, kk; DATATYPEOUT *volout; long idx; int sizeExpand = 0; DATATYPEOUT blockMax; int timesDilate; int border; unsigned short *GraphcutResults; cout << "Volume Processing..." << endl; //make sure we can write to the output file if((outfile=fopen(outputFileName, "wb")) == NULL) { cerr << "Output file open error!" << endl; return EXIT_FAILURE; } typedef float PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; ImageType::Pointer inputImage; if(rawInput) { if((infile=fopen(inputFileName.c_str(), "rb"))==NULL) { cout << "Input file open error!" << endl; return EXIT_FAILURE; } volin = (DATATYPEIN*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEIN)); if (fread(volin, sizeof(DATATYPEIN), sizeX*sizeY*sizeZ, infile) < (unsigned int)(sizeX*sizeY*sizeZ)) { cerr << "File size is not the same as volume size" << endl; return EXIT_FAILURE; } inputImage = ImageType::New(); ImageType::PointType origin; origin[0] = 0.; origin[1] = 0.; origin[2] = 0.; inputImage->SetOrigin( origin ); ImageType::IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; ImageType::SizeType size; size[0] = sizeX; size[1] = sizeY; size[2] = sizeZ; ImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); inputImage->SetRegions( region ); inputImage->Allocate(); inputImage->FillBuffer(0); inputImage->Update(); typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; IteratorType iterator1(inputImage,inputImage->GetRequestedRegion()); int lng = sizeX*sizeY*sizeZ; for(int i=0; i<lng; i++) { iterator1.Set((float)volin[i]); ++iterator1; } } // end if(rawInput) else { typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); inputImage = reader->GetOutput(); reader->SetFileName( inputFileName.c_str() ); try { reader->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught!" << endl; cerr << err << endl; return EXIT_FAILURE; } } // end of itk image read // ---------------Linear Mapping --------------------// typedef itk::RescaleIntensityImageFilter< ImageType, ImageType> RescaleFilterType; RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); rescaleFilter->SetInput(inputImage); rescaleFilter->SetOutputMinimum( 0 ); rescaleFilter->SetOutputMaximum( 255 ); try { rescaleFilter->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught!" << endl; cerr << err << endl; return EXIT_FAILURE; } inputImage = rescaleFilter->GetOutput(); cout << "The Linear Mapping is done\n"; # if Curvature_Anistropic_Diffusion { cout << "The Curvature Diffusion is doing\n"; typedef itk::CurvatureAnisotropicDiffusionImageFilter< ImageType, ImageType > MCD_FilterType; MCD_FilterType::Pointer MCDFilter = MCD_FilterType::New(); //Initialnization, using the paper's optimal parameters const unsigned int numberOfIterations = 5; const double timeStep = 0.0425; const double conductance = 3; MCDFilter->SetNumberOfIterations(numberOfIterations); MCDFilter->SetTimeStep( timeStep ); MCDFilter->SetConductanceParameter( conductance ); MCDFilter->SetInput(inputImage); try { MCDFilter->Update(); } catch( itk::ExceptionObject & err ) { cerr << "ExceptionObject caught!" << endl; cerr << err << endl; return EXIT_FAILURE; } inputImage=MCDFilter->GetOutput(); cout << "The Curvature Diffusion is done\n"; } #endif ImageType::RegionType region = inputImage->GetBufferedRegion(); ImageType::SizeType size = region.GetSize(); cout << "input image size: " << size << endl; sizeX = size[0]; sizeY = size[1]; sizeZ = size[2]; itk::ImageRegionIterator< ImageType > itr( inputImage, inputImage->GetBufferedRegion() ); itr.GoToBegin(); idx = 0; volin = (DATATYPEIN*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEIN)); while( ! itr.IsAtEnd() ) { volin[idx] = itr.Get(); ++itr; ++idx; } //allocate memory for the output image volout = (DATATYPEOUT*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(DATATYPEOUT)); // one pre-processing scheme GraphcutResults = (unsigned short*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(unsigned short)); Neuron_Binarization_3D(volin,GraphcutResults,sizeX,sizeY,sizeZ,0,1); for (k=0; k<(sizeZ+sizeExpand*2); k++) for (j=0; j<sizeY; j++) for (i=0; i<sizeX; i++) { volout[k *sizeX*sizeY + j *sizeX + i] = 0; } //initial to zeros std::cout << "Do you think we need the distance transform to make the centerline of image become bright with higher intensity?"; char tmpAnswer = 'n'; //tmpAnswer = getchar(); if (tmpAnswer =='Y' || tmpAnswer =='y') { unsigned char *GraphcutResultsTmp; GraphcutResultsTmp = (unsigned char*)malloc(sizeX*sizeY*(sizeZ+sizeExpand*2)*sizeof(unsigned char)); for (k=0; k<(sizeZ+sizeExpand*2); k++) for (j=0; j<sizeY; j++) for (i=0; i<sizeX; i++) { GraphcutResultsTmp[k *sizeX*sizeY + j *sizeX + i] = (unsigned char) GraphcutResults[k *sizeX*sizeY + j *sizeX + i]; } //initial to zeros distTransform(GraphcutResultsTmp,sizeX,sizeY,sizeZ); for (k=0; k<sizeZ; k++) { // threshold first for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; volin[idx] = GraphcutResultsTmp [idx]; } // end for } // end for } // end for free(GraphcutResultsTmp); GraphcutResultsTmp=NULL; } // end if else { for (k=0; k<sizeZ; k++) { // threshold first for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; if (GraphcutResults [idx] == 0) { volin[idx] = 0; } } } } } // end else free(GraphcutResults); GraphcutResults=NULL; // the secpnd Pre-Processing method, corresponding to the old version MDL /* double threshold; // by xiao liang, using 3 sigma theory to estimate threshold; double meanValue =0.0, VarianceValue = 0.0; // threshold first for (k=0; k<sizeZ; k++) { for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; meanValue += volin[idx]; } } } meanValue = meanValue/(double)(sizeX*sizeY*sizeZ); // threshold first for (k=0; k<sizeZ; k++) { for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; VarianceValue += (volin[idx]-meanValue)*(volin[idx]-meanValue); } } } VarianceValue = VarianceValue/(double)(sizeX*sizeY*sizeZ); VarianceValue = sqrt(VarianceValue); double m_threshold=OtsuThreshold (sizeX,sizeY,sizeZ); if (m_threshold > 7 || m_threshold < 0) { threshold =(meanValue-VarianceValue/30); } else { threshold = m_threshold; } //threshold =7; cout << "OTSU optimal threshold " << threshold << endl; for (k=0; k<(sizeZ+sizeExpand*2); k++) for (j=0; j<sizeY; j++) for (i=0; i<sizeX; i++) { volout[k *sizeX*sizeY + j *sizeX + i] = 0; } //initial to zeros for (k=0; k<sizeZ; k++) { // threshold first for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; if (volin[idx] < threshold) { volin[idx] = 0; } } } } */ // Method 2: Dilation of the object timesDilate = 1; border = 3; while (timesDilate >0 ) { for (k=border; k<sizeZ-border; k++) { for (j=border; j<sizeY-border; j++) { for (i=border; i<sizeX-border; i++) { blockMax = volin[k *sizeX*sizeY + j *sizeX + i]; for (kk=-1; kk<=1; kk++) { for (jj=-1; jj<=1; jj++) { for (ii=-1; ii<=1; ii++) { if(volin[(k+kk)*sizeX*sizeY + (j+jj)*sizeX + (i+ii)] > blockMax) { blockMax = volin[(k+kk)*sizeX*sizeY + (j+jj)*sizeX + (i+ii)]; } } } } // Keep the peak of the original intensity if (blockMax == volin[k *sizeX*sizeY + j *sizeX + i] && blockMax != 0) { blockMax = blockMax + 1; //if (blockMax > 255) blockMax = 255; } volout[k *sizeX*sizeY + j *sizeX + i] = blockMax; } } } // copy volout back to volin for the next dilation for (k=0; k<sizeZ; k++) { for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { volin[k *sizeX*sizeY + j *sizeX + i] = volout[k *sizeX*sizeY + j *sizeX + i]; } } } timesDilate--; } //----- Image write /* typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType; IteratorType iterator1(inputImage,inputImage->GetRequestedRegion()); int lng = sizeX*sizeY*sizeZ; for(int i=0; i<lng; i++) { iterator1.Set((float)volin[i]); ++iterator1; } */ //write the output image and free memory fwrite(volout, sizeX*sizeY*sizeZ, sizeof(DATATYPEOUT), outfile); FILE *mhdfile; if((mhdfile=fopen("volume_Processed.mhd","w"))==NULL) { cerr << "output file open error!" << endl; return -1; } fprintf (mhdfile,"ObjectType = Image\n"); fprintf (mhdfile,"NDims = 3\n"); fprintf (mhdfile,"BinaryData = True\n"); fprintf (mhdfile,"BinaryDataByteOrderMSB = False\n"); fprintf (mhdfile,"CompressedData = False\n"); fprintf (mhdfile,"TransformMatrix = 1 0 0 0 1 0 0 0 1\n"); fprintf (mhdfile,"Offset = 0 0 0\n"); fprintf (mhdfile,"CenterOfRotation = 0 0 0\n"); fprintf (mhdfile,"AnatomicalOrientation = RAI\n"); fprintf (mhdfile,"ElementSpacing = 1 1 1\n"); fprintf (mhdfile,"DimSize = %d %d %d\n",sizeX,sizeY,sizeZ); fprintf (mhdfile,"ElementType = MET_UCHAR\n"); fprintf (mhdfile,"ElementDataFile = volume_Processed.raw\n"); fclose(mhdfile); if (rawInput) fclose(infile); fclose(outfile); free(volin); // by xiao free(volout); // by xiao volin=NULL; volout=NULL; //cout << "Done" << endl; return 0; } // This function is designed to compute the opyimal threshold using OTSU method; // this algoritm is implemented by xiao liang based on ITK's OTSU algorithm double OtsuThreshold (int sizeX,int sizeY,int sizeZ) { int i,j,k; double m_Threshold =0; double totalPixels = (double)(sizeX*sizeY*sizeZ); if ( totalPixels == 0 ) { return m_Threshold; } unsigned char MinValue = volin[0], MaxValue = volin[0]; double meanValue=0.0, varianceValue=0.0; int idx; // just for the location0 for (k=0; k < sizeZ; k++) { // for (j=0; j < sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; meanValue += volin[idx]; if (volin[idx]> MaxValue) MaxValue = volin[idx]; if (volin[idx]< MinValue) MinValue = volin[idx]; } } } cout << "Max = " << (int)MaxValue << ", Min = " << (int)MinValue << endl; meanValue = meanValue/totalPixels; for (k=0; k<sizeZ; k++) { // for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; varianceValue += (volin[idx]-meanValue)*(volin[idx]-meanValue); } } } if ( MinValue >= MaxValue) { m_Threshold=MinValue; return m_Threshold; } m_Threshold = (meanValue-varianceValue/30); // this step is only initialized a good experimental value for m_Threshold, because the 3D image // is sparse, there are lots of zero values; // create a histogram double relativeFrequency[m_NumberOfHistogramBins]; for ( j = 0; j < m_NumberOfHistogramBins; j++ ) { relativeFrequency[j] = 0.0; } double binMultiplier = (double) m_NumberOfHistogramBins /(double) ( MaxValue - MinValue); cout << "binMultiplier = " << binMultiplier << endl; double Voxelvalue; // temp variable unsigned int binNumber; for (k=0; k<sizeZ; k++) { // for (j=0; j<sizeY; j++) { for (i=0; i<sizeX; i++) { idx = k *sizeX*sizeY + j *sizeX + i; Voxelvalue = volin[idx]; if ( Voxelvalue == MinValue ) { binNumber = 0; } // end if else { binNumber = (unsigned int)(((Voxelvalue - MinValue) * binMultiplier ) - 1); if ( binNumber == m_NumberOfHistogramBins ) // in case of rounding errors { binNumber -= 1; }// end if }// end else // printf("binNumber???? = %f MaxValue=%f \n", binNumber+1,MaxValue); relativeFrequency[binNumber] += 1.0; }// } } // test // for (i=0;i<m_NumberOfHistogramBins;i++) // printf ( "%d bin = %f, ",i, relativeFrequency[i]); // normalize the frequencies double totalMean = 0.0; for ( j = 0; j < m_NumberOfHistogramBins; j++ ) { relativeFrequency[j] /= totalPixels; totalMean += (j+1) * relativeFrequency[j]; } // compute Otsu's threshold by maximizing the between-class // variance double freqLeft = relativeFrequency[0]; double meanLeft = 1.0; double meanRight = ( totalMean - freqLeft ) / ( 1.0 - freqLeft ); double maxVarBetween = freqLeft * ( 1.0 - freqLeft ) * sqrt( meanLeft - meanRight ); int maxBinNumber = 0; double freqLeftOld = freqLeft; double meanLeftOld = meanLeft; for ( j = 1; j < m_NumberOfHistogramBins; j++ ) { freqLeft += relativeFrequency[j]; meanLeft = ( meanLeftOld * freqLeftOld + (j+1) * relativeFrequency[j] ) / freqLeft; if (freqLeft == 1.0) { meanRight = 0.0; } else { meanRight = ( totalMean - meanLeft * freqLeft ) / ( 1.0 - freqLeft ); } double varBetween = freqLeft * ( 1.0 - freqLeft ) * sqrt( meanLeft - meanRight ); if ( varBetween > maxVarBetween ) { maxVarBetween = varBetween; maxBinNumber = j; } // cache old values freqLeftOld = freqLeft; meanLeftOld = meanLeft; } m_Threshold = double( MinValue + ( maxBinNumber + 1 ) / binMultiplier ); cout << "m_threshold = " << m_Threshold << endl; return m_Threshold; }
26.69697
130
0.579569
[ "object", "transform", "3d" ]
d863eb0e1e052f1a0f382435a30a77f045ea4ec8
15,211
hpp
C++
cppwamp/include/cppwamp/internal/variantvisitors.hpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
39
2015-04-04T00:29:47.000Z
2021-06-27T11:25:38.000Z
cppwamp/include/cppwamp/internal/variantvisitors.hpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
115
2015-04-04T01:59:32.000Z
2020-12-04T09:23:09.000Z
cppwamp/include/cppwamp/internal/variantvisitors.hpp
katreniak/cppwamp
b37d3a9e83bca9594d6acd29a3fb7db39bda6cc9
[ "BSL-1.0" ]
8
2015-05-04T06:24:55.000Z
2020-11-11T12:38:46.000Z
/*------------------------------------------------------------------------------ Copyright Butterfly Energy Systems 2014-2015. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ------------------------------------------------------------------------------*/ #ifndef CPPWAMP_INTERNAL_VARIANT_VISITORS_HPP #define CPPWAMP_INTERNAL_VARIANT_VISITORS_HPP #include <algorithm> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include <utility> #include "../traits.hpp" #include "../visitor.hpp" #include "varianttraits.hpp" namespace wamp { namespace internal { //------------------------------------------------------------------------------ // The !isSameType is required because std::vector<bool>::const_reference may // or may not just be bool. template <typename T> using EnableIfBoolRef = EnableIf<isBool<T>() && !isSameType<T, bool>()>; template <typename T, typename U> constexpr bool bothAreNumbers() {return isNumber<T>() && isNumber<U>();} template <typename T, typename U> using EnableIfBothAreNumbers = EnableIf<bothAreNumbers<T, U>()>; template <typename T, typename U> using DisableIfBothAreNumbers = DisableIf<bothAreNumbers<T, U>()>; template <typename T> using DisableIfVariant = DisableIf<isSameType<T, Variant>()>; template <typename TFrom, typename TTo> using EnableIfConvertible = EnableIf<std::is_convertible<TFrom,TTo>::value>; template <typename TFrom, typename TTo> using DisableIfConvertible = DisableIf<std::is_convertible<TFrom,TTo>::value>; //------------------------------------------------------------------------------ class TypeName : public Visitor<String> { public: template <typename TField> String operator()(const TField&) const {return FieldTraits<TField>::typeName();} }; //------------------------------------------------------------------------------ class EquivalentTo : public Visitor<bool> { public: template <typename TField> bool operator()(const TField& lhs, const TField& rhs) const {return lhs == rhs;} template <typename TArg, EnableIfBoolRef<TArg> = 0> bool operator()(const bool lhs, const TArg rhs) const {return lhs == bool(rhs);} template <typename TField, typename TArg, DisableIfBothAreNumbers<TField,TArg> = 0> bool operator()(const TField&, const TArg&) const {return false;} template <typename TField, typename TArg, EnableIfBothAreNumbers<TField,TArg> = 0> bool operator()(const TField lhs, const TArg rhs) const {return lhs == rhs;} template <typename TElem, DisableIfVariant<TElem> = 0> bool operator()(const Array& lhs, const std::vector<TElem>& rhs) const { using VecConstRef = typename std::vector<TElem>::const_reference; // clang libc++ parameterizes equality comparison for default binary // predicate on iterator value type instead of const reference type, // which leads to an ambiguous function resolution. return (lhs.size() != rhs.size()) ? false : std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin(), [](const Variant& lElem, VecConstRef rElem) {return lElem == rElem;}); } template <typename TValue, DisableIfVariant<TValue> = 0> bool operator()(const Object& lhs, const std::map<String, TValue>& rhs) const { using Map = std::map<String, TValue>; using MapPair = typename Map::value_type; using ObjectPair = typename Object::value_type; return (lhs.size() != rhs.size()) ? false : std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin(), [](const ObjectPair& lPair, const MapPair& rPair) { return lPair.first == rPair.first && lPair.second == rPair.second; }); } }; //------------------------------------------------------------------------------ class NotEquivalentTo : public Visitor<bool> { public: template <typename TField> bool operator()(const TField& lhs, const TField& rhs) const {return lhs != rhs;} template <typename TArg, EnableIfBoolRef<TArg> = 0> bool operator()(const bool lhs, const TArg rhs) const {return lhs != rhs;} template <typename TField, typename TArg, DisableIfBothAreNumbers<TField,TArg> = 0> bool operator()(const TField&, const TArg&) const {return true;} template <typename TField, typename TArg, EnableIfBothAreNumbers<TField,TArg> = 0> bool operator()(TField lhs, TArg rhs) const {return lhs != rhs;} template <typename TElem, DisableIfVariant<TElem> = 0> bool operator()(const Array& lhs, const std::vector<TElem>& rhs) const { using VecConstRef = typename std::vector<TElem>::const_reference; // clang libc++ parameterizes equality comparison for default binary // predicate on iterator value type instead of const reference type, // which leads to an ambiguous function resolution. return (lhs.size() != rhs.size()) ? true : std::mismatch(lhs.cbegin(), lhs.cend(), rhs.cbegin(), [](const Variant& lElem, VecConstRef rElem) {return lElem == rElem;}).first != lhs.cend(); } template <typename TValue, DisableIfVariant<TValue> = 0> bool operator()(const Object& lhs, const std::map<String, TValue>& rhs) const { using Map = std::map<String, TValue>; using MapPair = typename Map::value_type; using ObjectPair = typename Object::value_type; auto comp = [](const ObjectPair& lPair, const MapPair& rPair) { return lPair.first == rPair.first && lPair.second == rPair.second; }; return (lhs.size() != rhs.size()) ? true : ( std::mismatch(lhs.cbegin(), lhs.cend(), rhs.cbegin(), std::move(comp)).first != lhs.end() ); } }; //------------------------------------------------------------------------------ class Output : public Visitor<> { public: template <typename TField> void operator()(const TField& f, std::ostream& out) const {out << f;} void operator()(const Bool& b, std::ostream& out) const { out << (b ? "true" : "false"); } void operator()(const Array& a, std::ostream& out) const { out << '['; for (const auto& v: a) { if (&v != &a.front()) out << ","; if (v.template is<TypeId::string>()) out << '"' << v.template as<TypeId::string>() << '"'; else applyWithOperand(*this, v, out); } out << ']'; } void operator()(const Object& o, std::ostream& out) const { out << '{'; for (auto kv = o.cbegin(); kv != o.cend(); ++kv) { if (kv != o.cbegin()) out << ','; out << '"' << kv->first << "\":"; const auto& v = kv->second; if (v.template is<TypeId::string>()) out << '"' << v.template as<TypeId::string>() << '"'; else applyWithOperand(*this, v, out); } out << '}'; } }; } // namespace internal //------------------------------------------------------------------------------ class Variant::Construct : public Visitor<> { public: explicit Construct(Variant& dest) : dest_(dest) {} template <typename TField> void operator()(const TField& field) const {dest_.constructAs<TField>(field);} private: Variant& dest_; }; //------------------------------------------------------------------------------ class Variant::MoveConstruct : public Visitor<> { public: explicit MoveConstruct(Variant& dest) : dest_(dest) {} template <typename TField> void operator()(TField& field) const {dest_.constructAs<TField>(std::move(field));} private: Variant& dest_; }; //------------------------------------------------------------------------------ class Variant::MoveAssign : public Visitor<> { public: explicit MoveAssign(Variant& dest) : dest_(dest) {} template <typename TField> void operator()(TField& leftField, TField& rightField) const {leftField = std::move(rightField);} template <typename TOld, typename TNew> void operator()(TOld&, TNew& rhs) const { dest_.destructAs<TOld>(); dest_.constructAs<TNew>(std::move(rhs)); dest_.typeId_ = FieldTraits<TNew>::typeId; } private: Variant& dest_; }; //------------------------------------------------------------------------------ class Variant::Destruct : public Visitor<> { public: Destruct(void* field) : field_(field) {} template <typename TField> void operator()(TField&) const {Access<TField>::destruct(field_);} private: void* field_; }; //------------------------------------------------------------------------------ class Variant::Swap : public Visitor<> { public: explicit Swap(Variant& leftVariant, Variant& rightVariant) : leftVariant_(leftVariant), rightVariant_(rightVariant) {} template <typename TField> void operator()(TField& leftField, TField& rightField) const { using std::swap; swap(leftField, rightField); } template <typename TLeft, typename TRight> void operator()(TLeft& leftField, TRight& rightField) const { TLeft leftTemp = std::move(leftField); leftVariant_.destructAs<TLeft>(); leftVariant_.constructAs<TRight>(std::move(rightField)); rightVariant_.destructAs<TRight>(); rightVariant_.constructAs<TLeft>(std::move(leftTemp)); std::swap(leftVariant_.typeId_, rightVariant_.typeId_); } private: Variant& leftVariant_; Variant& rightVariant_; }; //------------------------------------------------------------------------------ class Variant::LessThan : public Visitor<bool> { public: template <typename TField> bool operator()(const TField& leftField, const TField& rightField) const {return leftField < rightField;} template <typename TLeft, typename TRight, internal::DisableIfBothAreNumbers<TLeft,TRight> = 0> bool operator()(const TLeft&, const TRight&) const {return FieldTraits<TLeft>::typeId < FieldTraits<TRight>::typeId;} template <typename TLeft, typename TRight, internal::EnableIfBothAreNumbers<TLeft,TRight> = 0> bool operator()(TLeft lhs, TRight rhs) const {return lhs < rhs;} }; //------------------------------------------------------------------------------ class Variant::ConvertibleTo : public Visitor<bool> { public: // Conversions to same type template <typename TField> bool operator()(const TField&, Tag<TField>) const {return true;} // Implicit conversions template <typename TField, typename TResult, internal::EnableIfConvertible<TField,TResult> = 0> bool operator()(const TField&, Tag<TResult>) const {return true;} // Invalid conversions template <typename TField, typename TResult, internal::DisableIfConvertible<TField,TResult> = 0> bool operator()(const TField&, Tag<TResult>) const {return false;} // Vector conversions template <typename TElem, internal::DisableIfVariant<TElem> = 0> bool operator()(const Array& from, Tag<std::vector<TElem>>) const { if (from.empty()) return true; Tag<TElem> toElem; for (const auto& fromElem: from) { if (!applyWithOperand(*this, fromElem, toElem)) return false; } return true; } // Map conversions template <typename TValue, internal::DisableIfVariant<TValue> = 0> bool operator()(const Object& from, Tag<std::map<String, TValue>>) const { if (from.empty()) return true; Tag<TValue> toValue; for (const auto& fromKv: from) { if (!applyWithOperand(*this, fromKv.second, toValue)) return false; } return true; } }; //------------------------------------------------------------------------------ class Variant::ConvertTo : public Visitor<> { public: // Conversions to same type template <typename TField> void operator()(const TField& from, TField& to) const {to = from;} // Implicit conversions template <typename TField, typename TResult, internal::EnableIfConvertible<TField,TResult> = 0> void operator()(const TField& from, TResult& to) const {to = static_cast<TResult>(from);} // Invalid conversions template <typename TField, typename TResult, internal::DisableIfConvertible<TField,TResult> = 0> void operator()(const TField&, TResult&) const { throw error::Conversion( "wamp::error::Conversion: Invalid conversion " "from " + FieldTraits<TField>::typeName() + " to " + ArgTraits<TResult>::typeName()); } // Vector conversions template <typename TElem, internal::DisableIfVariant<TElem> = 0> void operator()(const Array& from, std::vector<TElem>& to) const { TElem toElem; for (size_t i=0; i<from.size(); ++i) { try { applyWithOperand(*this, from.at(i), toElem); } catch (const error::Conversion& e) { std::ostringstream oss; oss << e.what() << " (for Array element #" << i << ')'; throw error::Conversion(oss.str()); } to.push_back(std::move(toElem)); } } // Map conversions template <typename TValue, internal::DisableIfVariant<TValue> = 0> void operator()(const Object& from, std::map<String, TValue>& to) const { TValue toValue; for (const auto& fromKv: from) { try { applyWithOperand(*this, fromKv.second, toValue); } catch (const error::Conversion& e) { std::ostringstream oss; oss << e.what() << " (for Object member \"" << fromKv.first << "\")"; throw error::Conversion(oss.str()); } to.emplace(fromKv.first, std::move(toValue)); } } }; //------------------------------------------------------------------------------ class Variant::ElementCount : public Visitor<Variant::SizeType> { public: using SizeType = Variant::SizeType; template <typename T> SizeType operator()(const T&) {return 1u;} SizeType operator()(const Null&) {return 0u;} SizeType operator()(const Array& a) {return a.size();} SizeType operator()(const Object& o) {return o.size();} }; } // namespace wamp #endif // CPPWAMP_INTERNAL_VARIANT_VISITORS_HPP
33.284464
80
0.550983
[ "object", "vector" ]
d8656d6c82d2e3eec4406541ebb42f4a18843ab5
5,226
cpp
C++
gwo-viz/src/gwo_viz/GWO.cpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
gwo-viz/src/gwo_viz/GWO.cpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
gwo-viz/src/gwo_viz/GWO.cpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <cmath> #include <cstdlib> #include <iostream> #include <vector> #include <corex/core/math_functions.hpp> #include <corex/core/ds/Point.hpp> #include <gwo_viz/GWO.hpp> #include <gwo_viz/GWOResult.hpp> namespace gwo_viz { GWO::GWO() : numItersPerformed(0) {} GWOResult GWO::optimize(int32_t numIterations, int32_t numWolves, cx::Point bestSolution, cx::Point minPt, cx::Point maxPt) { GWO::Solutions solutions; std::vector<cx::Point> wolfPreys; std::vector<cx::Point> pack; for (int32_t i = 0; i < numWolves; i++) { float x = cx::getRandomRealUniformly(minPt.x, maxPt.x); float y = cx::getRandomRealUniformly(minPt.y, maxPt.y); pack.emplace_back(x, y); } std::sort( pack.begin(), pack.end(), [&bestSolution](const cx::Point& a, const cx::Point& b) { float aFitness = std::fabs(cx::distance2D(bestSolution, a)); float bFitness = std::fabs(cx::distance2D(bestSolution, b)); return aFitness < bFitness; }); cx::Point alphaWolf = pack[0]; cx::Point betaWolf = pack[1]; cx::Point deltaWolf = pack[2]; solutions.push_back(pack); wolfPreys.push_back((alphaWolf + betaWolf + deltaWolf) / 3.f); this->numItersPerformed = 0; float a = 2.f; for (int32_t t = 0; t < numIterations; t++) { alphaWolf = pack[0]; betaWolf = pack[1]; deltaWolf = pack[2]; std::array<cx::Point, 3> Al; std::array<cx::Point, 3> Cl; std::array<cx::Point, 3> r1l; std::array<cx::Point, 3> r2l; for (int32_t n = 0; n < 3; n++) { r1l[n].x = cx::getRandomRealUniformly(0.f, 1.f); r1l[n].y = cx::getRandomRealUniformly(0.f, 1.f); r2l[n].x = cx::getRandomRealUniformly(0.f, 1.f); r2l[n].y = cx::getRandomRealUniformly(0.f, 1.f); Al[n].x = (2 * a * r1l[n].x) - a; Al[n].y = (2 * a * r1l[n].y) - a; Cl[n].x = 2 * r2l[n].x; Cl[n].y = 2 * r2l[n].y; } std::cout << "Al: " << "(" << Al[0].x << ", " << Al[0].y << ") " << "(" << Al[1].x << ", " << Al[1].y << ") " << "(" << Al[2].x << ", " << Al[2].y << ")\n"; std::cout << "Cl: " << "(" << Cl[0].x << ", " << Cl[0].y << ") " << "(" << Cl[1].x << ", " << Cl[1].y << ") " << "(" << Cl[2].x << ", " << Cl[2].y << ")\n"; for (int32_t j = 3; j < numWolves; j++) { std::cout << "------" << j << "-------\n"; std::cout << "Wolves: " << "A: (" << alphaWolf.x << ", " << alphaWolf.y << ") " << "B: (" << betaWolf.x << ", " << betaWolf.y << ") " << "D: (" << deltaWolf.x << ", " << deltaWolf.y << ")\n"; // Generate the coefficient values. cx::Point Aw; cx::Point Cw; cx::Point r1w; cx::Point r2w; r1w.x = cx::getRandomRealUniformly(0.f, 1.f); r1w.y = cx::getRandomRealUniformly(0.f, 1.f); r2w.x = cx::getRandomRealUniformly(0.f, 1.f); r2w.y = cx::getRandomRealUniformly(0.f, 1.f); Aw.x = (2 * a * r1w.x) - a; Aw.y = (2 * a * r1w.y) - a; Cw.x = 2 * r2w.x; Cw.y = 2 * r2w.y; auto wolf = pack[j]; auto Da = cx::vec2Abs(cx::pairwiseMult(Cl[0], alphaWolf) - wolf); auto Db = cx::vec2Abs(cx::pairwiseMult(Cl[1], betaWolf) - wolf); auto Dd = cx::vec2Abs(cx::pairwiseMult(Cl[2], deltaWolf) - wolf); auto X1 = alphaWolf - cx::pairwiseMult(Al[0], Da); auto X2 = betaWolf - cx::pairwiseMult(Al[1], Db); auto X3 = deltaWolf - cx::pairwiseMult(Al[2], Dd); pack[j] = (X1 + X2 + X3) / 3.f; std::cout << "Aw: " << "(" << Aw.x << ", " << Aw.y << ")\n"; std::cout << "Cw: " << "(" << Cw.x << ", " << Cw.y << ")\n"; std::cout << "Da: " << "(" << Da.x << ", " << Da.y << ")\n"; std::cout << "Db: " << "(" << Db.x << ", " << Db.y << ")\n"; std::cout << "Dd: " << "(" << Dd.x << ", " << Dd.y << ")\n"; std::cout << "X1: (" << X1.x << ", " << X1.y << ")\n"; std::cout << "X2: (" << X2.x << ", " << X2.y << ")\n"; std::cout << "X3: (" << X3.x << ", " << X3.y << ")\n"; std::cout << "Wolf: (" << pack[j].x << ", " << pack[j].y << ")\n"; } std::sort( pack.begin(), pack.end(), [&bestSolution](const cx::Point& a, const cx::Point& b) { float aFitness = std::fabs(cx::distance2D(bestSolution, a)); float bFitness = std::fabs(cx::distance2D(bestSolution, b)); return aFitness < bFitness; }); solutions.push_back(pack); wolfPreys.push_back((pack[0] + pack[1] + pack[2]) / 3.f); a = 2.f - (2.f * (static_cast<float>(t) / numIterations)); this->numItersPerformed++; } return GWOResult{ solutions, wolfPreys }; } int32_t GWO::getNumItersPerformed() { return this->numItersPerformed; } }
31.481928
75
0.454841
[ "vector" ]
d875ca8c45ccba979defef14eb5714d08c3d62b6
1,222
hpp
C++
test/proj.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
3
2019-11-05T10:27:35.000Z
2019-12-02T06:25:53.000Z
test/proj.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
null
null
null
test/proj.hpp
storm-ptr/bark
e4cd481183aba72ec6cf996eff3ac144c88b79b6
[ "MIT" ]
2
2019-12-01T18:01:02.000Z
2021-04-07T08:34:04.000Z
// Andrew Naplavkov #ifndef BARK_TEST_PROJ_HPP #define BARK_TEST_PROJ_HPP #include <bark/geometry/as_text.hpp> #include <bark/geometry/geom_from_wkb.hpp> #include <bark/proj/transformer.hpp> #include <bark/test/wkt.hpp> TEST_CASE("proj") { using namespace bark::geometry; using namespace bark::proj; /// @see http://spatialreference.org/ref/epsg/4326/proj4/ /// @see http://spatialreference.org/ref/epsg/3395/proj4/ transformer latlong_to_mercator{ "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ", "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 " "+units=m +no_defs "}; for (auto&& wkt1 : Wkt) { auto wkb(as_binary(geom_from_text(wkt1))); latlong_to_mercator.inplace_forward(wkb); auto wkt2 = as_text(geom_from_wkb(wkb)); CHECK(wkt1 != wkt2); latlong_to_mercator.inplace_backward(wkb); CHECK(wkt1 == as_text(geom_from_wkb(wkb))); } auto bbox = box{{0, 80}, {1, 81}}; auto wkt = as_text(bbox); bbox = latlong_to_mercator.forward(bbox); CHECK(wkt != as_text(bbox)); bbox = latlong_to_mercator.backward(bbox); CHECK(wkt == as_text(bbox)); } #endif // BARK_TEST_PROJ_HPP
29.804878
75
0.663666
[ "geometry" ]
d8780e03345233b7d5dc16822975b72b122fa276
25,231
hpp
C++
Bo/core/mesh.hpp
rukletsov/bo
bfece9e8f910b0c8f522733854405bf0a801b0e8
[ "BSD-2-Clause" ]
3
2016-09-14T03:30:30.000Z
2021-11-16T10:53:32.000Z
Bo/core/mesh.hpp
rukletsov/bo
bfece9e8f910b0c8f522733854405bf0a801b0e8
[ "BSD-2-Clause" ]
null
null
null
Bo/core/mesh.hpp
rukletsov/bo
bfece9e8f910b0c8f522733854405bf0a801b0e8
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************** Triangular mesh class. Copyright (c) 2010 - 2013 Alexander Rukletsov <rukletsov@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #ifndef MESH_HPP_5839D2AB_1DFF_4DCE_A5A2_051A5102190D_ #define MESH_HPP_5839D2AB_1DFF_4DCE_A5A2_051A5102190D_ #include <cstddef> #include <vector> #include <set> #include <string> #include <iostream> #include <limits> #include <stdexcept> #include <functional> #include <boost/assert.hpp> #include <boost/format.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/scoped_ptr.hpp> #include "bo/core/vector.hpp" #include "bo/core/triangle.hpp" #include "bo/core/kdtree.hpp" #include "bo/distances/distances_3d.hpp" namespace bo { // A basic class for a 3D triangular mesh. Consumes more memory than a possible // minimum (a standard graph storage) but provides faster access to frequently // used structures and operations. NOT thread-safe in the current implemetation. template <typename T> class Mesh { public: typedef Mesh<T> SelfType; // Mesh vertices. Their order shouldn't be changed, since other collections // use vertex indices as references. typedef Vector<T, 3> Vertex; typedef std::vector<Vertex> Vertices; // Face is a triangle with vertices representing indices of the mesh vertices. typedef Triangle<std::size_t> Face; typedef std::vector<Face> Faces; // Normal is a 3-vector can be attached to a vertex or to a face. A normal // corresponds to a component with the same index in relevant collection. typedef Vector<double, 3> Normal; typedef std::vector<Normal> Normals; // Neighbours for each vertex. Each neighbour contains indices of vertex in // vertices collection. typedef std::set<std::size_t> AdjacentVerticesPerVertex; typedef std::vector<AdjacentVerticesPerVertex> AdjacentVertices; // Neighbouring faces for each vertex. Each adjacent face is an index of a face // in faces collection. typedef std::set<std::size_t> AdjacentFacesPerVertex; typedef std::vector<AdjacentFacesPerVertex> AdjacentFaces; private: typedef std::pair<Vertex, std::size_t> TreeNode; typedef KDTree<3, TreeNode, boost::function<T (TreeNode, std::size_t)> > Tree; typedef boost::scoped_ptr<Tree> TreePtr; public: // Creates an empty mesh ready to store initial_count vertices. Mesh(std::size_t initial_count = 0); // Custom copy c-tor for correct copying of the k-d tree. Mesh(const Mesh& other); // Idiomatic swap. void swap(Mesh& other); // Idiomatic assignment operator for correct assignment. Mesh& operator=(Mesh other); // Adds a new vertex to the mesh and returns its index. std::size_t add_vertex(const Vertex& vertex); // Adds a new vertex to the mesh only if there are no vertices at the distance // of search_radius. Returns either the index of the new vertex or the index // of the closest vertex that already exists in the mesh. std::size_t add_vertex_checked(const Vertex& vertex, T search_radius); // Adds several vertices to the mesh and returns the index of the first vertex. // The indices of the other vertices can be easily calculated by adding 1 successively. std::size_t add_vertices(const Vertices& vertices); // Adds a new face and returns its index. Updates dependent collections. std::size_t add_face(const Face& face); // Returns face normal. Throws if face_index is out of range. Normal get_face_normal(std::size_t face_index) const; // Creates and returns vertex normal, computed according to // N.Max, "Weights for Computing Vertex Normals from Facet Normals", // Journal of Graphics Tools, Vol. 4, No. 2, 1999. // Throws if face index is out of range. Normal get_vertex_normal(std::size_t vertex_index) const; // Finds closest point on the mesh to a given one. Uses naive implementation, // which measures the distance to each face and then takes the minimum. Vertex get_closest_point(const Vertex& point) const; // Computes the distance between the given point and the mesh. Returns the // euclidean norm of the difference between the given point and the closest to it // point on the mesh. double distance(const Vertex& point) const; // Joins the given mesh into the current one. First adds points, then recalculates // faces and finally adds faces. SelfType& join(const SelfType& other); // Joins the given mesh into the current one. Instead of adding all points, tries // to use existed vertices that are close to candidates for insertion. SelfType& join_checked(const SelfType& other, T search_radius); static SelfType from_vertices(const Vertices& vertices); // Returns data from connectivity structures. Throws if face index is out of range. const AdjacentVerticesPerVertex& get_neighbouring_vertices( std::size_t vertex_index) const; const AdjacentFacesPerVertex& get_neighbouring_faces_by_vertex( std::size_t vertex_index) const; // Temporary accessor methods. const Vertices& get_all_vertices() const; const Faces& get_all_faces() const; const Normals& get_all_face_normals() const; // The k-d tree management functions. void build_tree(); void destroy_tree(); // Allow mesh stream operator<< access Mesh members. template <typename V> friend std::ostream& operator<<(std::ostream& os, const Mesh<V>& obj); private: // Adds connectivity relations. Return false in case of new relation leads to // a duplicate. bool add_edge_(std::size_t vertex1, std::size_t vertex2); bool add_adjacent_face_(std::size_t vertex, std::size_t face); // Computes and returns a normal for the given face. Normal compute_face_normal_(const Face& face) const; // Finds the closest point on the given mesh face to the given point. For // more information see // http://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf Vertex closest_point_on_face(std::size_t face_index, const Vertex& P) const; template <typename F> SelfType& join(const SelfType& other, F inserter); // Range checkers. Throw if an index is out of range. void vertex_rangecheck_(std::size_t vertex_index) const; void face_rangecheck_(std::size_t face_index) const; // Helper function for k-d tree. static T point3D_accessor_(TreeNode pt, std::size_t k); private: // Basic mesh data. Vertices vertices_; Faces faces_; Normals face_normals_; // Some other properties can be used, e.g. triangle strips (for speeding up // rendering), curvature information, BBox, grid, etc (See TriMesh implementation // by Szymon Rusinkiewicz as an example.) // The k-d tree for mesh vertices. Created on demand, can be used for finding // existed vertices when trying inserting a new one. TreePtr tree_; // Connectivity structures. AdjacentVertices neighbours_; AdjacentFaces adjacent_faces_; // We can also add, e.g. faces adjacent to faces over edges, i.e. each face will // have maximum 3 these neighbouring faces. }; // Prints formatted mesh data to a given stream. See boost.format library for more // details about formatting. template <typename T> std::ostream& operator<<(std::ostream& os, const Mesh<T>& obj) { // TODO: Add syncro primitives to stream operator and, perhaps, verbose levels. // Print full vertex info. os << boost::format("Mesh object %1$#x, %2% bytes: ") % &obj % sizeof(obj) << std::endl << "Vertices: " << obj.vertices_.size() << std::endl; typename Mesh<T>::Vertices::const_iterator vertices_end = obj.vertices_.end(); for (typename Mesh<T>::Vertices::const_iterator it = obj.vertices_.begin(); it != vertices_end; ++it) { // Print vertex coordinates. std::size_t index = it - obj.vertices_.begin(); os << boost::format("vertex %1%: ") % index << std::endl << "\t" << boost::format("x: %1%, %|18t|y: %2%, %|36t|z: %3%,") % it->x() % it->y() % it->z(); // Print neighbouring vertices. os << std::endl << "\t" << boost::format("neighbours (%1%): ") % obj.neighbours_[index].size(); typename Mesh<T>::AdjacentVerticesPerVertex::const_iterator neighbours_end = obj.neighbours_[index].end(); for (typename Mesh<T>::AdjacentVerticesPerVertex::const_iterator neighbour = obj.neighbours_[index].begin(); neighbour != neighbours_end; ++neighbour) { os << boost::format("%1%, %|4t|") % (*neighbour); } // Print adjacent faces. os << std::endl << "\t" << boost::format("adjacent faces (%1%): ") % obj.adjacent_faces_[index].size(); typename Mesh<T>::AdjacentFacesPerVertex::const_iterator faces_end = obj.adjacent_faces_[index].end(); for (typename Mesh<T>::AdjacentFacesPerVertex::const_iterator face = obj.adjacent_faces_[index].begin(); face != faces_end; ++face) { os << boost::format("%1%, %|4t|") % (*face); } os << std::endl; } // Print full faces info. os << "Faces: " << obj.faces_.size() << std::endl; typename Mesh<T>::Faces::const_iterator faces_end = obj.faces_.end(); for (typename Mesh<T>::Faces::const_iterator face = obj.faces_.begin(); face != faces_end; ++face) { // Print face's vertices. std::size_t index = face - obj.faces_.begin(); os << boost::format("face %1%: ") % index << std::endl << "\t" << boost::format("A: %1%, %|18t|B: %2%, %|36t|C: %3%,") % face->A() % face->B() % face->C(); // Print face's normal. typename Mesh<T>::Normal normal = obj.face_normals_[index]; os << std::endl << "\t" << boost::format("normal: (%1%, %2%, %3%)") % normal.x() % normal.y() % normal.z(); os << std::endl; } // Print footer and return. os << boost::format("end of object %1$#x.") % &obj << std::endl; return os; } template <typename T> Mesh<T>::Mesh(std::size_t initial_count) { vertices_.reserve(initial_count); faces_.reserve(initial_count); face_normals_.reserve(initial_count); neighbours_.reserve(initial_count); adjacent_faces_.reserve(initial_count); } template <typename T> Mesh<T>::Mesh(const Mesh& other): vertices_(other.vertices_), faces_(other.faces_), face_normals_(other.face_normals_), neighbours_(other.neighbours_), adjacent_faces_(other.adjacent_faces_) { // Copies k-d tree if it exists. Can be expensive. if (other.tree_) tree_.reset(new Tree(*other.tree_)); } template <typename T> void Mesh<T>::swap(Mesh& other) { vertices_.swap(other.vertices_); faces_.swap(other.faces_); face_normals_.swap(other.face_normals_); tree_.swap(other.tree_); neighbours_.swap(other.neighbours_); adjacent_faces_.swap(other.adjacent_faces_); } template <typename T> Mesh<T>& Mesh<T>::operator=(Mesh other) { other.swap(*this); return *this; } template <typename T> std::size_t Mesh<T>::add_vertex(const Vertex& vertex) { // Actually, a syncro primitive should be added here. vertices_.push_back(vertex); std::size_t new_vertex_index = vertices_.size() - 1; // Add empty connectivity containers. neighbours_.push_back(AdjacentVerticesPerVertex()); adjacent_faces_.push_back(AdjacentFacesPerVertex()); // Check for post-conditions. These include sizes of connectivity structures // and vertex container. If any of the condition is not satisfied consider // this as an internal bug. Therefore no need to throw. BOOST_ASSERT(((neighbours_.size() == vertices_.size()) || (adjacent_faces_.size() == vertices_.size())) && "Vertex connectivity structures are of different sizes."); return new_vertex_index; } template <typename T> std::size_t Mesh<T>::add_vertex_checked(const Vertex& vertex, T search_radius) { // If k-d tree is not built, build it. if (!tree_) build_tree(); // Search for an existed vertex in a given radius. A coversion is needed so that // candidate type and tree node type are identical. typename Tree::const_iterator candidate = tree_->find_nearest( std::make_pair(vertex, std::numeric_limits<std::size_t>::max()), search_radius).first; // If found std::size_t vertex_id = (candidate == tree_->end()) ? add_vertex(vertex) : candidate->second; return vertex_id; } template <typename T> std::size_t Mesh<T>::add_vertices(const Vertices& vertices) { // Calculate the index of the first inserted vertex. std::size_t first_inserted_index = vertices_.size(); // Insert all vertices at once. vertices_.insert(vertices_.end(), vertices.begin(), vertices.end()); // Add empty connectivity structures. neighbours_.insert(neighbours_.end(), vertices.size(), AdjacentVerticesPerVertex()); adjacent_faces_.insert(adjacent_faces_.end(), vertices.size(), AdjacentFacesPerVertex()); // Check for post-conditions. See add_vertex() for more details. BOOST_ASSERT(((neighbours_.size() == vertices_.size()) || (adjacent_faces_.size() == vertices_.size())) && "Vertex connectivity structures are of different sizes."); return first_inserted_index; } template <typename T> std::size_t Mesh<T>::add_face(const Face& face) { // Check if all vertices exist in the mesh. if ((vertices_.size() <= face.A()) || (vertices_.size() <= face.B()) || (vertices_.size() <= face.C())) { BOOST_ASSERT(false && "Bad vertex indices in the face."); throw std::out_of_range("Face cannot be added to the mesh because it " "references non-existent vertices."); } // Add the face and get its index. Syncro primitive needed. faces_.push_back(face); std::size_t new_face_index = faces_.size() - 1; // Update vertex neighbours (insert edges). add_edge_(face.A(), face.B()); add_edge_(face.B(), face.C()); add_edge_(face.C(), face.A()); // Update adjacent faces. add_adjacent_face_(face.A(), new_face_index); add_adjacent_face_(face.B(), new_face_index); add_adjacent_face_(face.C(), new_face_index); // Compute and save face normal. face_normals_.push_back(compute_face_normal_(face)); // Check for post-conditions. These include sizes of connectivity structures // and face container. If any of the condition is not satisfied consider this // as an internal bug. Therefore no need to throw. BOOST_ASSERT((face_normals_.size() == faces_.size()) && "Vertex connectivity structures are of different sizes."); return new_face_index; } template <typename T> typename Mesh<T>::Normal Mesh<T>::get_face_normal(std::size_t face_index) const { // Check if the given face exists in the mesh. face_rangecheck_(face_index); return face_normals_[face_index]; } template <typename T> typename Mesh<T>::Normal Mesh<T>::get_vertex_normal(std::size_t vertex_index) const { // TODO: add caching for computed normals. // Check if the given vertex exists in the mesh. vertex_rangecheck_(vertex_index); // A normal of a vertex is a sum of weighted normals of adjacent faces. Normal normal; AdjacentFacesPerVertex::const_iterator faces_end = adjacent_faces_[vertex_index].end(); for (AdjacentFacesPerVertex::const_iterator face_index = adjacent_faces_[vertex_index].begin(); face_index != faces_end; ++face_index) { // Determine to which face vertex considered vertex belong. Without loss of // generality, suppose, that face[2] == vertex_index. const Face& face = faces_[*face_index]; std::size_t pt1 = face[0]; std::size_t pt2 = face[1]; if (face[0] == vertex_index) pt1 = face[2]; else if (face[1] == vertex_index) pt2 = face[2]; // Compute face's normal weight (multiplied dot products of two edges). Vector<T, 3> edge1 = vertices_[pt1] - vertices_[vertex_index]; Vector<T, 3> edge2 = vertices_[pt2] - vertices_[vertex_index]; T weight = ((edge1 * edge1) * (edge2 * edge2)); // Append weighted face's normal. normal += face_normals_[*face_index] * (1.0 / weight); } // Face normals can be the null vectors. try { normal = normal.normalized(); } catch(const std::logic_error&) { } return normal; } template <typename T> typename Mesh<T>::Vertex Mesh<T>::get_closest_point(const Vertex& point) const { Vertex closest; double min_distance = std::numeric_limits<double>::max(); std::size_t faces_size = faces_.size(); for (std::size_t face_index = 0; face_index < faces_size; ++face_index) { Vertex face_closest = closest_point_on_face(face_index, point); double face_distance = (face_closest - point).eucl_norm(); if (face_distance < min_distance) { min_distance = face_distance; closest = face_closest; } } return closest; } template <typename T> double Mesh<T>::distance(const Vertex& point) const { return distances::euclidean_distance_d(get_closest_point(point), point); } template <typename T> Mesh<T>& Mesh<T>::join(const Mesh<T>& other) { return join(other, std::mem_fun(&SelfType::add_vertex)); } template <typename T> Mesh<T>& Mesh<T>::join_checked(const Mesh<T>& other, T search_radius) { return join(other, boost::bind(&SelfType::add_vertex_checked, _1, _2, search_radius)); } template <typename T> Mesh<T> Mesh<T>::from_vertices(const Vertices& vertices) { SelfType mesh(vertices.size()); for (typename Vertices::const_iterator it = vertices.begin(); it != vertices.end(); ++it) mesh.add_vertex(*it); return mesh; } template <typename T> const typename Mesh<T>::AdjacentVerticesPerVertex& Mesh<T>::get_neighbouring_vertices( std::size_t vertex_index) const { // Check if the given vertex exists in the mesh. vertex_rangecheck_(vertex_index); return neighbours_[vertex_index]; } template <typename T> const typename Mesh<T>::AdjacentFacesPerVertex& Mesh<T>::get_neighbouring_faces_by_vertex( std::size_t vertex_index) const { // Check if the given vertex exists in the mesh. vertex_rangecheck_(vertex_index); return adjacent_faces_[vertex_index]; } template <typename T> inline const typename Mesh<T>::Vertices& Mesh<T>::get_all_vertices() const { return vertices_; } template <typename T> inline const typename Mesh<T>::Faces& Mesh<T>::get_all_faces() const { return faces_; } template <typename T> inline const typename Mesh<T>::Normals& Mesh<T>::get_all_face_normals() const { return face_normals_; } template <typename T> void Mesh<T>::build_tree() { // Copy vertex data with corresponding indices to a separate container. This is // necessary as we are going to store in the tree vertices ids in addition to // vertices themselves. For this reason, std::transform cannot be used. std::vector<TreeNode> nodes_container; std::size_t vertices_count = vertices_.size(); nodes_container.reserve(vertices_count); for (std::size_t idx = 0; idx < vertices_count; ++idx) nodes_container.push_back(std::make_pair(vertices_[idx], idx)); // Create an empty k-d tree and then construct it from the prepared container. // The container is changed, but it is OK. tree_.reset(new Tree(std::ptr_fun(point3D_accessor_))); tree_->efficient_replace_and_optimise(nodes_container); } template <typename T> void Mesh<T>::destroy_tree() { tree_.reset(); } // Private utility functions. template <typename T> bool Mesh<T>::add_edge_(std::size_t vertex1, std::size_t vertex2) { // If the neighbouring relation between the given vertices already exists, // set::insert signal this and won't add a duplicate. A neighbouring relation // must be mutual. In case one vertex has another as a neighbour and another // has not, report an error through assertion. Consider this situation a severe // internal bug, therefore no exception throwing needed. bool exists1 = neighbours_[vertex1].insert(vertex2).second; bool exists2 = neighbours_[vertex2].insert(vertex1).second; BOOST_ASSERT(!(exists1 ^ exists2) && "Neighbouring relation is not mutual."); return (exists1 && exists2); } template <typename T> bool Mesh<T>::add_adjacent_face_(std::size_t vertex, std::size_t face) { // If the face is already attached to the vertex, set::insert won't add a // duplicate. See set::insert documentation. return adjacent_faces_[vertex].insert(face).second; } template <typename T> typename Mesh<T>::Normal Mesh<T>::compute_face_normal_(const Face& face) const { // Get two vectors representing the given face. Vector<T, 3> a = vertices_[face.A()] - vertices_[face.B()]; Vector<T, 3> b = vertices_[face.B()] - vertices_[face.C()]; // If these vectors are collinear (face points are lying on the same line) its // cross product will be the null vector and its normalization is meaningless. Normal normal(0); try { Vector<T, 3> cross_pr = a.cross_product(b); normal = cross_pr.normalized(); } catch(const std::logic_error&) { } return normal; } template <typename T> typename Mesh<T>::Vertex Mesh<T>::closest_point_on_face(std::size_t face_index, const Vertex& P) const { // No need to check if the given face exists in the mesh since the function is // private and a debug assertion would suffice. BOOST_ASSERT((faces_.size() > face_index) && "Specified face doesn't exist."); Vertex closest_point = distances::find_closest_point_on_triangle(P, vertices_[faces_[face_index].A()], vertices_[faces_[face_index].B()], vertices_[faces_[face_index].C()]); return closest_point; } template <typename T> template <typename F> Mesh<T>& Mesh<T>::join(const Mesh<T>& other, F inserter) { // Cache vertices count. std::size_t other_size = other.vertices_.size(); // Lookup table for faces transformation. std::vector<std::size_t> lookup_table(other_size); // Insert vertices and fill lookup table. for (std::size_t other_idx = 0; other_idx < other_size; ++other_idx) { std::size_t new_idx = inserter(this, other.vertices_[other_idx]); lookup_table[other_idx] = new_idx; } // Transform and insert faces. typename Faces::const_iterator other_end = other.faces_.end(); for (typename Faces::const_iterator old_face = other.faces_.begin(); old_face != other_end; ++old_face) { std::size_t new_a = lookup_table[old_face->A()]; std::size_t new_b = lookup_table[old_face->B()]; std::size_t new_c = lookup_table[old_face->C()]; this->add_face(Face(new_a, new_b, new_c)); } return *this; } template <typename T> void Mesh<T>::vertex_rangecheck_(std::size_t vertex_index) const { if (vertices_.size() <= vertex_index) throw std::out_of_range("Specified vertex doesn't exist."); } template <typename T> void Mesh<T>::face_rangecheck_(std::size_t face_index) const { if (faces_.size() <= face_index) throw std::out_of_range("Specified face doesn't exist."); } template <typename T> inline T Mesh<T>::point3D_accessor_(TreeNode pt, std::size_t k) { return pt.first[k]; } } // namespace bo #endif // MESH_HPP_5839D2AB_1DFF_4DCE_A5A2_051A5102190D_
35.387097
94
0.679165
[ "mesh", "object", "vector", "transform", "3d" ]
d87b4709dc67c4aadbb040efc754f5972ca79b72
1,557
cpp
C++
proj/fpga/zcu106/Vitis-AI-DPU_TRD-for-ZCU106/zcu106_dpu/Vitis-AI/alveo/apps/face_detect/evaluation/RegionsSingleImage.cpp
timebe00/Mercenary
7762bad28e4f49b2ad84fb8abbd8056bd01f61d4
[ "MIT" ]
3
2020-10-29T15:00:30.000Z
2021-10-21T08:09:34.000Z
evaluation/RegionsSingleImage.cpp
ZhouKai90/Evaluation
96ea16fabb573d2d856c9118737cc1ccc6eec447
[ "MIT" ]
20
2020-10-31T03:19:03.000Z
2020-11-02T18:59:49.000Z
evaluation/RegionsSingleImage.cpp
ZhouKai90/Evaluation
96ea16fabb573d2d856c9118737cc1ccc6eec447
[ "MIT" ]
9
2020-10-14T02:04:10.000Z
2020-12-01T08:23:02.000Z
#include "RegionsSingleImage.hpp" #include <iostream> #include <vector> using std::vector; using std::cerr; using std::cout; using std::endl; RegionsSingleImage::RegionsSingleImage(std::string fName){ #ifdef __CVLOADIMAGE_WORKING__ im = cvLoadImage(fName.c_str(), CV_LOAD_IMAGE_COLOR); #else im = readImage(fName.c_str(), CV_LOAD_IMAGE_COLOR); #endif if(im == NULL) { cerr << "Could not read image from " << fName << endl; assert(false); } list = new std::vector<Region *>; } RegionsSingleImage::RegionsSingleImage(IplImage *I) { assert(I != NULL); im = cvCreateImage(cvGetSize(I), I->depth, I->nChannels); cvCopy(I, im, 0); list = new std::vector<Region *>; } RegionsSingleImage::~RegionsSingleImage() { if(list) for(unsigned int i=0; i< list->size(); i++) if(list->at(i)) delete(list->at(i)); delete(list); cvReleaseImage(&im); } unsigned int RegionsSingleImage::length() { return (unsigned int)(list->size()); } Region * RegionsSingleImage::get(int i) { return list->at(i); } void RegionsSingleImage::set(int i, Region *r) { list->at(i) = r; } const IplImage *RegionsSingleImage::getImage(){ return (const IplImage *)im; } std::vector<double> * RegionsSingleImage::getUniqueScores(){ vector<double> *v = new vector<double>; v->reserve(list->size()); for(unsigned int i=0; i<list->size(); i++) v->push_back(list->at(i)->detScore); sort(v->begin(), v->end()); vector<double>::iterator uniElem = unique(v->begin(), v->end()); v->erase(uniElem, v->end()); return v; }
21.328767
66
0.659602
[ "vector" ]
f230daa56f74c0a3c3b9a04ffbe99a457185ca1d
14,254
cpp
C++
vlc_linux/vlc-3.0.16/modules/demux/adaptive/logic/BufferingLogic.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/logic/BufferingLogic.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/logic/BufferingLogic.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/* * BufferingLogic.cpp ***************************************************************************** * Copyright (C) 2014 - 2020 VideoLabs, VideoLAN and VLC authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "BufferingLogic.hpp" #include "../playlist/BaseRepresentation.h" #include "../playlist/BasePeriod.h" #include "../playlist/AbstractPlaylist.hpp" #include "../playlist/SegmentTemplate.h" #include "../playlist/SegmentTimeline.h" #include "../playlist/SegmentList.h" #include "../playlist/SegmentBase.h" #include <limits> #include <cassert> using namespace adaptive; using namespace adaptive::playlist; using namespace adaptive::logic; const mtime_t AbstractBufferingLogic::BUFFERING_LOWEST_LIMIT = CLOCK_FREQ * 2; const mtime_t AbstractBufferingLogic::DEFAULT_MIN_BUFFERING = CLOCK_FREQ * 6; const mtime_t AbstractBufferingLogic::DEFAULT_MAX_BUFFERING = CLOCK_FREQ * 30; const mtime_t AbstractBufferingLogic::DEFAULT_LIVE_BUFFERING = CLOCK_FREQ * 15; AbstractBufferingLogic::AbstractBufferingLogic() { userMinBuffering = 0; userMaxBuffering = 0; userLiveDelay = 0; } void AbstractBufferingLogic::setLowDelay(bool b) { userLowLatency = b; } void AbstractBufferingLogic::setUserMinBuffering(mtime_t v) { userMinBuffering = v; } void AbstractBufferingLogic::setUserMaxBuffering(mtime_t v) { userMaxBuffering = v; } void AbstractBufferingLogic::setUserLiveDelay(mtime_t v) { userLiveDelay = v; } DefaultBufferingLogic::DefaultBufferingLogic() : AbstractBufferingLogic() { } uint64_t DefaultBufferingLogic::getStartSegmentNumber(BaseRepresentation *rep) const { if(rep->getPlaylist()->isLive()) return getLiveStartSegmentNumber(rep); const MediaSegmentTemplate *segmentTemplate = rep->inheritSegmentTemplate(); if(segmentTemplate) { const SegmentTimeline *timeline = segmentTemplate->inheritSegmentTimeline(); if(timeline) return timeline->minElementNumber(); return segmentTemplate->inheritStartNumber(); } const SegmentList *list = rep->inheritSegmentList(); if(list) return list->getStartIndex(); const SegmentBase *base = rep->inheritSegmentBase(); if(base) return base->getSequenceNumber(); return 0; } mtime_t DefaultBufferingLogic::getMinBuffering(const AbstractPlaylist *p) const { if(isLowLatency(p)) return BUFFERING_LOWEST_LIMIT; mtime_t buffering = userMinBuffering ? userMinBuffering : DEFAULT_MIN_BUFFERING; if(p->getMinBuffering()) buffering = std::max(buffering, p->getMinBuffering()); return std::max(buffering, BUFFERING_LOWEST_LIMIT); } mtime_t DefaultBufferingLogic::getMaxBuffering(const AbstractPlaylist *p) const { if(isLowLatency(p)) return getMinBuffering(p); mtime_t buffering = userMaxBuffering ? userMaxBuffering : DEFAULT_MAX_BUFFERING; if(p->isLive()) buffering = std::min(buffering, getLiveDelay(p)); if(p->getMaxBuffering()) buffering = std::min(buffering, p->getMaxBuffering()); return std::max(buffering, getMinBuffering(p)); } mtime_t DefaultBufferingLogic::getLiveDelay(const AbstractPlaylist *p) const { if(isLowLatency(p)) return getMinBuffering(p); mtime_t delay = userLiveDelay ? userLiveDelay : DEFAULT_LIVE_BUFFERING; if(p->suggestedPresentationDelay.Get()) delay = p->suggestedPresentationDelay.Get(); if(p->timeShiftBufferDepth.Get()) delay = std::min(delay, p->timeShiftBufferDepth.Get()); return std::max(delay, getMinBuffering(p)); } uint64_t DefaultBufferingLogic::getLiveStartSegmentNumber(BaseRepresentation *rep) const { AbstractPlaylist *playlist = rep->getPlaylist(); /* Get buffering offset min <= max <= live delay */ mtime_t i_buffering = getBufferingOffset(playlist); /* Try to never buffer up to really end */ /* Enforce no overlap for demuxers segments 3.0.0 */ /* FIXME: check duration instead ? */ const unsigned SAFETY_BUFFERING_EDGE_OFFSET = 1; const unsigned SAFETY_EXPURGING_OFFSET = 2; SegmentList *segmentList = rep->inheritSegmentList(); SegmentBase *segmentBase = rep->inheritSegmentBase(); MediaSegmentTemplate *mediaSegmentTemplate = rep->inheritSegmentTemplate(); if(mediaSegmentTemplate) { uint64_t start = 0; const Timescale timescale = mediaSegmentTemplate->inheritTimescale(); const SegmentTimeline *timeline = mediaSegmentTemplate->inheritSegmentTimeline(); if(timeline) { uint64_t safeMinElementNumber = timeline->minElementNumber(); uint64_t safeMaxElementNumber = timeline->maxElementNumber(); stime_t safeedgetime, safestarttime, duration; for(unsigned i=0; i<SAFETY_BUFFERING_EDGE_OFFSET; i++) { if(safeMinElementNumber == safeMaxElementNumber) break; safeMaxElementNumber--; } bool b_ret = timeline->getScaledPlaybackTimeDurationBySegmentNumber(safeMaxElementNumber, &safeedgetime, &duration); if(unlikely(!b_ret)) return 0; safeedgetime += duration - 1; for(unsigned i=0; i<SAFETY_EXPURGING_OFFSET; i++) { if(safeMinElementNumber + 1 >= safeMaxElementNumber) break; safeMinElementNumber++; } b_ret = timeline->getScaledPlaybackTimeDurationBySegmentNumber(safeMinElementNumber, &safestarttime, &duration); if(unlikely(!b_ret)) return 0; if(playlist->timeShiftBufferDepth.Get()) { stime_t edgetime; bool b_ret = timeline->getScaledPlaybackTimeDurationBySegmentNumber(timeline->maxElementNumber(), &edgetime, &duration); if(unlikely(!b_ret)) return 0; edgetime += duration - 1; stime_t timeshiftdepth = timescale.ToScaled(playlist->timeShiftBufferDepth.Get()); if(safestarttime + timeshiftdepth < edgetime) { safestarttime = edgetime - timeshiftdepth; safeMinElementNumber = timeline->getElementNumberByScaledPlaybackTime(safestarttime); } } assert(safestarttime<=safeedgetime); stime_t starttime; if(safeedgetime - safestarttime > timescale.ToScaled(i_buffering)) starttime = safeedgetime - timescale.ToScaled(i_buffering); else starttime = safestarttime; start = timeline->getElementNumberByScaledPlaybackTime(starttime); assert(start >= timeline->minElementNumber()); assert(start >= safeMinElementNumber); assert(start <= timeline->maxElementNumber()); assert(start <= safeMaxElementNumber); return start; } /* Else compute, current time and timeshiftdepth based */ else if(mediaSegmentTemplate->duration.Get()) { /* Compute playback offset and effective finished segment from wall time */ mtime_t now = CLOCK_FREQ * time(NULL); mtime_t playbacktime = now - i_buffering; mtime_t minavailtime = playlist->availabilityStartTime.Get() + rep->getPeriodStart(); const uint64_t startnumber = mediaSegmentTemplate->inheritStartNumber(); const Timescale timescale = mediaSegmentTemplate->inheritTimescale(); if(!timescale) return startnumber; const mtime_t duration = timescale.ToTime(mediaSegmentTemplate->inheritDuration()); if(!duration) return startnumber; /* restrict to DVR window */ if(playlist->timeShiftBufferDepth.Get()) { mtime_t elapsed = now - minavailtime; elapsed = elapsed - (elapsed % duration); /* align to last segment */ mtime_t alignednow = minavailtime + elapsed; if(playlist->timeShiftBufferDepth.Get() < elapsed) minavailtime = alignednow - playlist->timeShiftBufferDepth.Get(); if(playbacktime < minavailtime) playbacktime = minavailtime; } /* Get completed segment containing the time ref */ start = mediaSegmentTemplate->getLiveTemplateNumber(playbacktime); if (unlikely(start < startnumber)) { assert(startnumber > start); /* blame getLiveTemplateNumber() */ start = startnumber; } const uint64_t max_safety_offset = playbacktime - minavailtime / duration; const uint64_t safety_offset = std::min((uint64_t)SAFETY_BUFFERING_EDGE_OFFSET, max_safety_offset); if(startnumber + safety_offset <= start) start -= safety_offset; else start = startnumber; return start; } } else if (segmentList && !segmentList->getSegments().empty()) { const Timescale timescale = segmentList->inheritTimescale(); const std::vector<ISegment *> list = segmentList->getSegments(); const ISegment *back = list.back(); /* working around HLS discontinuities by using durations */ stime_t totallistduration = 0; for(auto it = list.begin(); it != list.end(); ++it) totallistduration += (*it)->duration.Get(); /* Apply timeshift restrictions */ stime_t availableduration; if(playlist->timeShiftBufferDepth.Get()) { availableduration = std::min(totallistduration, timescale.ToScaled(playlist->timeShiftBufferDepth.Get())); } else availableduration = totallistduration; uint64_t availableliststartnumber = list.front()->getSequenceNumber(); if(totallistduration != availableduration) { stime_t offset = totallistduration - availableduration; for(auto it = list.begin(); it != list.end(); ++it) { availableliststartnumber = (*it)->getSequenceNumber(); if(offset < (*it)->duration.Get()) break; offset -= (*it)->duration.Get(); } } uint64_t safeedgenumber = back->getSequenceNumber() - std::min((uint64_t)list.size() - 1, (uint64_t)SAFETY_BUFFERING_EDGE_OFFSET); uint64_t safestartnumber = availableliststartnumber; for(unsigned i=0; i<SAFETY_EXPURGING_OFFSET; i++) { if(safestartnumber + 1 >= safeedgenumber) break; safestartnumber++; } stime_t maxbufferizable = 0; stime_t safeedgeduration = 0; for(auto it = list.begin(); it != list.end(); ++it) { if((*it)->getSequenceNumber() < safestartnumber) continue; if((*it)->getSequenceNumber() <= safeedgenumber) maxbufferizable += (*it)->duration.Get(); else safeedgeduration += (*it)->duration.Get(); } stime_t tobuffer = std::min(maxbufferizable, timescale.ToScaled(i_buffering)); stime_t skipduration = totallistduration - safeedgeduration - tobuffer ; uint64_t start = safestartnumber; for(auto it = list.begin(); it != list.end(); ++it) { start = (*it)->getSequenceNumber(); if((*it)->duration.Get() > skipduration) break; skipduration -= (*it)->duration.Get(); } return start; } else if(segmentBase) { const std::vector<ISegment *> list = segmentBase->subSegments(); if(!list.empty()) return segmentBase->getSequenceNumber(); const Timescale timescale = rep->inheritTimescale(); const ISegment *back = list.back(); const stime_t bufferingstart = back->startTime.Get() + back->duration.Get() - timescale.ToScaled(i_buffering); uint64_t start; if(!SegmentInfoCommon::getSegmentNumberByScaledTime(list, bufferingstart, &start)) return list.front()->getSequenceNumber(); if(segmentBase->getSequenceNumber() + SAFETY_BUFFERING_EDGE_OFFSET <= start) start -= SAFETY_BUFFERING_EDGE_OFFSET; else start = segmentBase->getSequenceNumber(); return start; } return std::numeric_limits<uint64_t>::max(); } mtime_t DefaultBufferingLogic::getBufferingOffset(const AbstractPlaylist *p) const { return p->isLive() ? getLiveDelay(p) : getMaxBuffering(p); } bool DefaultBufferingLogic::isLowLatency(const AbstractPlaylist *p) const { if(userLowLatency.isSet()) return userLowLatency.value(); return p->isLowLatency(); }
37.909574
113
0.614354
[ "vector" ]
f23717bcf653e01c7bb454c57ab3bb2499a2286a
44,462
cpp
C++
Official Windows Platform Sample/Windows 8.1 desktop samples/[C++]-Windows 8.1 desktop samples/UI Automation document content client sample/C++/UiaDocumentClient.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/UIAutomationDocumentClient/cpp/UiaDocumentClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Samples/UIAutomationDocumentClient/cpp/UiaDocumentClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.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 <windows.h> #include <ole2.h> #include <uiautomation.h> #include <strsafe.h> IUIAutomation *_automation; // Maximum Text length we will read const int maxLength = 10000; // Maximum number of comments we'll search for const int maxComments = 25; // a class used to wrap and access a Comment Element class Comment { public: // This takes ownership and responsibility for releasing the element reference // So it does not AddRef it, the caller should not Release the element after // it has created the Comment object, as it has passed ownership to it. Comment(_In_ IUIAutomationElement *element) : _commentElement(element) { _annotation = NULL; } ~Comment() { _commentElement->Release(); if (_annotation != NULL) { _annotation->Release(); } } bool Compare(_In_opt_ Comment *other) { bool retVal = false; if (other != NULL) { BOOL compResult; HRESULT hr = _automation->CompareElements(_commentElement, other->_commentElement, &compResult); if (FAILED(hr)) { wprintf(L"CompareElements failed, HR: 0x%08x\n", hr); } else { retVal = (compResult == TRUE); } } return retVal; } // Should be immediately after constructor, other calls rely on _annotation being set HRESULT GetAnnotationPattern() { HRESULT hr = _commentElement->GetCurrentPatternAs(UIA_AnnotationPatternId, IID_PPV_ARGS(&_annotation)); if (FAILED(hr)) { wprintf(L"Failed to Get Annotation Pattern, HR: 0x%08x\n", hr); } else if (_annotation == NULL) { wprintf(L"Element does not actually support Annotation Pattern\n"); hr = E_FAIL; } return hr; } HRESULT RangeFromAnnotation(_In_ IUIAutomationTextPattern2 *textPattern, _Outptr_result_maybenull_ IUIAutomationTextRange **range) { HRESULT hr = textPattern->RangeFromAnnotation(_commentElement, range); if (FAILED(hr)) { wprintf(L"RangeFromAnnotation failed, HR: 0x%08x\n", hr); } return hr; } void Print(_In_ bool summary) { BSTR name; HRESULT hr = _commentElement->get_CurrentName(&name); if (FAILED(hr)) { wprintf(L"Failed to Get Name Property, HR: 0x%08x\n", hr); } else { if (summary) { wprintf(L"\"%30s\"\n", name); } else { BSTR typeName; hr = _annotation->get_CurrentAnnotationTypeName(&typeName); if (FAILED(hr)) { wprintf(L"Failed to Get AnnotationTypeName Property, HR: 0x%08x\n", hr); } else { BSTR author; hr = _annotation->get_CurrentAuthor(&author); if (FAILED(hr)) { wprintf(L"Failed to Get Author Property, HR: 0x%08x\n", hr); } else { BSTR dateTime; hr = _annotation->get_CurrentDateTime(&dateTime); if (FAILED(hr)) { wprintf(L"Failed to Get DateTime Property, HR: 0x%08x\n", hr); } else { wprintf(L"Type: %s\nAuthor: %s\nDate/Time: %s\n%s\n", typeName, author, dateTime, name); SysFreeString(dateTime); } SysFreeString(author); } SysFreeString(typeName); } } SysFreeString(name); } } private: IUIAutomationElement* _commentElement; IUIAutomationAnnotationPattern* _annotation; }; // A class used to wrap and access a Text Range class Range { public: // This takes ownership and responsibility for releasing the range reference // So it does not AddRef it, the caller should not Release the range after // it has created the range object, as it has passed ownership to it. Range(_In_opt_ IUIAutomationTextRange *range) { _range = range; } ~Range() { if (_range != NULL) { _range->Release(); } } // Assumes that _range is NOT null void FindAndPrintStyle(_In_ int style) { IUIAutomationTextRange *remainingRange; HRESULT hr = _range->Clone(&remainingRange); if (FAILED(hr)) { wprintf(L"Clone failed on range, HR: 0x%08x\n", hr); } else { VARIANT styleVar; styleVar.vt = VT_I4; styleVar.lVal = style; while (SUCCEEDED(hr)) { IUIAutomationTextRange *foundRange; hr = remainingRange->FindAttribute(UIA_StyleIdAttributeId, styleVar, FALSE, &foundRange); if (FAILED(hr)) { wprintf(L"FindAttribute failed, HR: 0x%08x\n", hr); } else { if (foundRange != NULL) { BSTR text; hr = foundRange->GetText(maxLength, &text); if (FAILED(hr)) { wprintf(L"GetText failed, HR: 0x%08x\n", hr); } else { wprintf(L" - \"%s\"\n", text); SysFreeString(text); } // Next, to continue the loop, we move the beginning endpoint of our working range (remainingRange), forward // to the ending point of the last range we found. This gives us a range containing all the text we haven't // searched yet. hr = remainingRange->MoveEndpointByRange(TextPatternRangeEndpoint_Start, foundRange, TextPatternRangeEndpoint_End); foundRange->Release(); if (FAILED(hr)) { wprintf(L"MoveEndpointByRange failed, HR: 0x%08x\n", hr); } } else { break; } } } remainingRange->Release(); } } void FindAndPrintHeaders() { if (_range == NULL) { wprintf(L"Headers: <None>\n"); } else { wprintf(L"Title:\n"); FindAndPrintStyle(StyleId_Title); wprintf(L"Heading 1:\n"); FindAndPrintStyle(StyleId_Heading1); wprintf(L"Heading 2:\n"); FindAndPrintStyle(StyleId_Heading2); wprintf(L"Heading 3:\n"); FindAndPrintStyle(StyleId_Heading3); } } // This is a quick check of whether a specific range (the input), is past the endpoint // of this range object (the internal _range of this Range object). It does this by // checking whether the start point of the input range is greater than or equal to the // endpoint of the internal range. bool IsThisRangePastMyEndpoint(_In_ IUIAutomationTextRange *range) { bool retVal = true; int compare; HRESULT hr = _range->CompareEndpoints(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start, &compare); if (FAILED(hr)) { // If this call fails, assume we're past the end wprintf(L"CompareEndpoints failed on range, HR: 0x%08x\n", hr); } else { retVal = compare <= 0; } return retVal; } // This will extract the comments from an IUIAutomationElementArray, adding any new ones to the comments array HRESULT GetNewCommentsFromArray(_In_ IUIAutomationElementArray *commentElements, _Inout_updates_to_(commentCount, *foundCommentCount) Comment **comments, _In_ int commentCount, _Inout_ int *foundCommentCount) { HRESULT hr = S_OK; int count; hr = commentElements->get_Length(&count); if (FAILED(hr)) { wprintf(L"get_Length failed on element array, HR: 0x%08x\n", hr); } else { for (int i = 0; i < count && SUCCEEDED(hr); i++) { IUIAutomationElement *element; hr = commentElements->GetElement(i, &element); if (FAILED(hr) || element == NULL) { wprintf(L"GetElement failed on element array, HR: 0x%08x\n", hr); } else { bool addedComment = false; Comment *newComment = new Comment(element); if (newComment == NULL) { wprintf(L"Not enough memory to create a new Comment\n"); // Comment failed to be created, so did not take ownership of element element->Release(); hr = E_OUTOFMEMORY; } else { hr = newComment->GetAnnotationPattern(); if (SUCCEEDED(hr)) { bool found = false; // check if the comment is already in the array for (int j = 0; j < *foundCommentCount; j++) { if (newComment->Compare(comments[j])) { found = true; break; } } // If it's not there, add it to the list if (!found) { if ((*foundCommentCount) < commentCount) { // The array takes ownership of the comment at this point comments[*foundCommentCount] = newComment; addedComment = true; (*foundCommentCount)++; } } } if (!addedComment) { delete newComment; } } } _Analysis_assume_((*foundCommentCount) <= commentCount); } } return hr; } // This call will move the range argument, so don't pass in a range you don't want moved, clone it first HRESULT WalkForCommentsInRange(_In_ IUIAutomationTextRange *range, _Inout_updates_to_(commentCount, *foundCommentCount) Comment **comments, _In_ int commentCount, _Inout_ int *foundCommentCount) { HRESULT hr = S_OK; // These are singleton objects so don't need to be released IUnknown *notSupported = NULL; IUnknown *mixedAttribute = NULL; hr = _automation->get_ReservedNotSupportedValue(&notSupported); if (FAILED(hr)) { wprintf(L"get_ReservedNotSupportedValue failed, HR: 0x%08x\n", hr); } else { hr = _automation->get_ReservedMixedAttributeValue(&mixedAttribute); if (FAILED(hr)) { wprintf(L"get_ReservedMixedAttributeValue failed, HR: 0x%08x\n", hr); } } // A way to prevent this from running into a loop if a provider doesn't implement Move properly int sanityCount = 100; while (!IsThisRangePastMyEndpoint(range) && SUCCEEDED(hr) && sanityCount-- > 0) { // Get the list of comments on the current range VARIANT varComments; hr = range->GetAttributeValue(UIA_AnnotationObjectsAttributeId, &varComments); if (FAILED(hr)) { wprintf(L"GetAttributeValue failed on range, HR: 0x%08x\n", hr); } else { if (varComments.vt != VT_EMPTY && varComments.vt != VT_UNKNOWN ) { wprintf(L"Unexpected Type for AnnotationObjectsAttribute, vt: 0x%08x\n", varComments.vt); hr = E_FAIL; } else if (varComments.vt == VT_UNKNOWN) { if (varComments.punkVal == notSupported) { wprintf(L"AnnotationObjectsAttribute not supported on this Range\n"); hr = E_FAIL; } else if (varComments.punkVal == mixedAttribute) { // Since we're walking by format, mixed Attribute value should never come up wprintf(L"Unexpected Mixed Attribute Value\n"); hr = E_FAIL; } else { IUIAutomationElementArray *commentElements; hr = varComments.punkVal->QueryInterface(IID_PPV_ARGS(&commentElements)); if (FAILED(hr)) { wprintf(L"Could not QI to IUIAutomationElementArray, HR: 0x%08x\n", hr); } else { hr = GetNewCommentsFromArray(commentElements, comments, commentCount, foundCommentCount); commentElements->Release(); } } } VariantClear(&varComments); } // If nothing has gone wrong, advance the range if (SUCCEEDED(hr)) { int moveCount; hr = range->Move(TextUnit_Format, 1, &moveCount); if (FAILED(hr)) { wprintf(L"Move by format failed on range, HR: 0x%08x\n", hr); } else if (moveCount != 1) { wprintf(L"Failed to advance forward for some reason, terminating loop\n"); hr = E_FAIL; } } } return hr; } HRESULT FindCommentsInRange(_Out_writes_to_(commentCount, *foundCommentCount) Comment **comments, _In_ int commentCount, _Out_ int *foundCommentCount) { *foundCommentCount = 0; IUIAutomationTextRange *movingRange; HRESULT hr = _range->Clone(&movingRange); if (FAILED(hr)) { wprintf(L"Clone failed on range, HR: 0x%08x\n", hr); } else { // First collapse the range to the starting endpoint by moving the end endpoint back by the whole document hr = movingRange->MoveEndpointByRange(TextPatternRangeEndpoint_End, movingRange, TextPatternRangeEndpoint_Start); if (FAILED(hr)) { wprintf(L"MoveEndpointByUnit failed on range, HR: 0x%08x\n", hr); } else { hr = movingRange->ExpandToEnclosingUnit(TextUnit_Format); if (FAILED(hr)) { wprintf(L"ExpandToEnclosingUnit failed on range, HR: 0x%08x\n", hr); } else { // Now walk through in Format units, getting the annotations hr = WalkForCommentsInRange(movingRange, comments, commentCount, foundCommentCount); } } movingRange->Release(); } return hr; } void FindAndPrintComments() { if (_range == NULL) { wprintf(L"Comments: <None>\n"); } else { wprintf(L"Comments:\n"); Comment **comments = new Comment*[maxComments]; if (comments == NULL) { wprintf(L"Not enough memory to create a Comment Array\n"); } else { int foundComments; HRESULT hr = FindCommentsInRange(comments, maxComments, &foundComments); if (SUCCEEDED(hr)) { for (int i = 0; i < foundComments; i++) { wprintf(L"%2d: ", i); comments[i]->Print(true); } for (int i = 0; i < foundComments; i++) { delete comments[i]; } } delete [] comments; } } } void SelectComment(_In_ int commentNum, _Outptr_result_maybenull_ Comment **comment) { *comment = NULL; if (_range != NULL) { Comment **comments = new Comment*[maxComments]; if (comments == NULL) { wprintf(L"Not enough memory to create a Comment Array\n"); } else { int foundComments; HRESULT hr = FindCommentsInRange(comments, maxComments, &foundComments); if (SUCCEEDED(hr)) { if (commentNum >= 0 && commentNum < foundComments) { *comment = comments[commentNum]; comments[commentNum] = NULL; } for (int i = 0; i < foundComments; i++) { if (i != commentNum) { delete comments[i]; } } } delete [] comments; } } } void PrintCaretInfo() { if (_range == NULL) { wprintf(L"No Caret Range\n"); } else { VARIANT var; HRESULT hr = _range->GetAttributeValue(UIA_IsActiveAttributeId, &var); if (FAILED(hr)) { wprintf(L"GetAttributeValue on UIA_IsActiveAttributeId failed, HR: 0x%08x\n", hr); } else { if (var.vt != VT_BOOL) { wprintf(L"Unexpected variant type for UIA_IsActiveAttributeId, vt: 0x%08x\n", var.vt); } else { if (var.boolVal == VARIANT_TRUE) { wprintf(L"Active\n"); } else { wprintf(L"Inactive\n"); } } } hr = _range->GetAttributeValue(UIA_CaretPositionAttributeId, &var); if (FAILED(hr)) { wprintf(L"GetAttributeValue on UIA_CaretPositionAttributeId failed, HR: 0x%08x\n", hr); } else { if (var.vt == VT_UNKNOWN) { wprintf(L"This provider does not support UIA_CaretPositionAttributeId\n"); } else if (var.vt != VT_I4) { wprintf(L"Unexpected variant type for UIA_CaretPositionAttributeId, vt: 0x%08x\n", var.vt); } else { // The caret Position attribute is only guaranteed to be accurate when the caret is at // the beginning or end of a line... otherwise, it is indeterminate. if (var.lVal == CaretPosition_EndOfLine) { wprintf(L"Position is at the end of a line\n"); } else if (var.lVal == CaretPosition_BeginningOfLine) { wprintf(L"Position is at the beginning of a line\n"); } else if (var.lVal == CaretPosition_Unknown) { wprintf(L"Position type is unknown (likely within a line)\n"); } else { wprintf(L"Position type is not a known enum value: 0x%08x\n", var.lVal); } } } hr = _range->GetAttributeValue(UIA_CaretBidiModeAttributeId, &var); if (FAILED(hr)) { wprintf(L"GetAttributeValue on UIA_CaretBidiModeAttributeId failed, HR: 0x%08x\n", hr); } else { if (var.vt == VT_UNKNOWN) { wprintf(L"This provider does not support UIA_CaretBidiModeAttributeId\n"); } else if (var.vt != VT_I4) { wprintf(L"Unexpected variant type for UIA_CaretBidiModeAttributeId, vt: 0x%08x\n", var.vt); } else { if (var.lVal == CaretBidiMode_LTR) { wprintf(L"Text at caret is Left-to-Right reading\n"); } else if (var.lVal == CaretBidiMode_RTL) { wprintf(L"Text at caret is Right-to-Left reading\n"); } else { wprintf(L"BiDi Mode type is not a known enum value: 0x%08x\n", var.lVal); } } } hr = _range->GetAttributeValue(UIA_SelectionActiveEndAttributeId, &var); if (FAILED(hr)) { wprintf(L"GetAttributeValue on UIA_SelectionActiveEndAttributeId failed, HR: 0x%08x\n", hr); } else { if (var.vt == VT_UNKNOWN) { wprintf(L"This provider does not support UIA_SelectionActiveEndAttributeId\n"); } else if (var.vt != VT_I4) { wprintf(L"Unexpected variant type for UIA_SelectionActiveEndAttributeId, vt: 0x%08x\n", var.vt); } else { if (var.lVal == ActiveEnd_None) { wprintf(L"The selection has no active end\n"); } else if (var.lVal == ActiveEnd_Start) { wprintf(L"Active end of selection is the start of the selection\n"); } else if (var.lVal == CaretBidiMode_RTL) { wprintf(L"Active end of selection is the end of the selection\n"); } else { wprintf(L"Active end value is not a known enum value: 0x%08x\n", var.lVal); } } } SAFEARRAY *psa = NULL; hr = _range->GetBoundingRectangles(&psa); if (FAILED(hr)) { wprintf(L"GetBoundingRectangles on caret range failed, HR: 0x%08x\n", hr); } else { if (psa != NULL) { RECT *pRectArray = NULL; int cRectCount = 0; hr = _automation->SafeArrayToRectNativeArray(psa, &pRectArray, &cRectCount); if (FAILED(hr)) { wprintf(L"SafeArrayToRectNativeArray on caret range rects failed, HR: 0x%08x\n", hr); } else if (pRectArray == NULL) { wprintf(L"SafeArrayToRectNativeArray returned a NULL rect array"); } else { // The caret range should never have more than one bounding rect. if (cRectCount > 1) { wprintf(L"Caret range has an unexpected count of bounding rects, count: %d\n", cRectCount); } else if (cRectCount == 0) { wprintf(L"Caret range has no bounding rect\n"); } else { wprintf(L"Caret range bounding rect is left: %d, top: %d, right: %d, bottom: %d\n", pRectArray[0].left, pRectArray[0].top, pRectArray[0].right, pRectArray[0].bottom); } ::CoTaskMemFree(pRectArray); } SafeArrayDestroy(psa); } else { wprintf(L"GetBoundingRectangles on caret range returned no rects.\n"); } } } } void Print(_In_ bool summary) { if (_range == NULL) { if (summary) { wprintf(L"Active Range: Empty [0 characters]\n"); } } else { BSTR text; HRESULT hr = _range->GetText(maxLength, &text); if (FAILED(hr)) { wprintf(L"GetText failed, HR: 0x%08x\n", hr); } else { if (summary) { UINT length = SysStringLen(text); WCHAR shortString[40]; hr = StringCchCopy(shortString, ARRAYSIZE(shortString), text); if (hr == STRSAFE_E_INSUFFICIENT_BUFFER) { WCHAR tail[] = L"..."; int pos = ARRAYSIZE(shortString) - ARRAYSIZE(tail); hr = StringCchCopy(&shortString[pos], ARRAYSIZE(tail), tail); } if (SUCCEEDED(hr)) { wprintf(L"Active Range: \"%s\" [%d characters]\n", shortString, length); } } else { wprintf(L"Active Range:\n%s\n", text); } SysFreeString(text); } } } private: IUIAutomationTextRange *_range; }; enum CommandId { CommandId_Invalid = -1, CommandId_Help = 0, CommandId_Print = 1, CommandId_Document = 2, CommandId_Selection = 3, CommandId_Visible = 4, CommandId_Headers = 5, CommandId_Comment = 6, CommandId_Comments = 7, CommandId_CommentRange=8, CommandId_PrintComment=9, CommandId_Exit = 10, CommandId_Caret = 11 }; PCWSTR CommandText[] = { L"help\n", L"print\n", L"document\n", L"selection\n", L"visible\n", L"headers\n", L"comment ", L"comments\n", L"commentrange\n", L"printcomment\n", L"exit\n", L"caret\n" }; class TextPatternExplorer { public: // This takes ownership and responsibility for releasing the element reference // So it does not AddRef it, the caller should not Release the element after // it has created the Comment object, as it has passed ownership to it. TextPatternExplorer(_In_ IUIAutomationElement *element) : _element(element) { _textPattern = NULL; } ~TextPatternExplorer() { _element->Release(); if (_textPattern != NULL) { _textPattern->Release(); } } void Run() { HRESULT hr = GetTextPattern(); if (SUCCEEDED(hr)) { Welcome(); Range *currentRange = GetRange(CommandId_Document, NULL); Comment *currentComment = NULL; while (currentRange != NULL) { currentRange->Print(true); if (currentComment != NULL) { wprintf(L"Active Comment:"); currentComment->Print(true); } WCHAR input[40]; wprintf(L">"); fgetws(input, ARRAYSIZE(input), stdin); CommandId cmdId = GetCommand(input, ARRAYSIZE(input)); switch(cmdId) { case CommandId_Help: { Welcome(); break; } case CommandId_Print: { currentRange->Print(false); break; } case CommandId_Document: case CommandId_Selection: case CommandId_Visible: { delete currentRange; currentRange = GetRange(cmdId, NULL); break; } case CommandId_Caret: { wprintf(L"Pausing for 2 seconds to allow you to focus the text control if desired...\n"); Sleep(2000); delete currentRange; bool isActive; currentRange = GetRange(cmdId, &isActive); if (currentRange != NULL) { wprintf(L"Got Caret Range (%s):\n", isActive ? L"active" : L"inactive" ); currentRange->PrintCaretInfo(); } break; } case CommandId_Headers: { currentRange->FindAndPrintHeaders(); break; } case CommandId_Comment: { SelectComment(input, currentRange, &currentComment); break; } case CommandId_Comments: { currentRange->FindAndPrintComments(); break; } case CommandId_CommentRange: { RangeFromComment(currentComment, &currentRange); break; } case CommandId_PrintComment: { if (currentComment != NULL) { currentComment->Print(false); } break; } case CommandId_Exit: { delete currentRange; currentRange = NULL; break; } default: wprintf(L"Invalid command, type help to see a list of valid commands.\n"); } } } } private: void SelectComment(_In_ PWSTR cmdString, _In_ Range *range, _Inout_ Comment **comment ) { if (*comment != NULL) { delete *comment; *comment = NULL; } int commentNumber; int retVal = swscanf_s(cmdString, L"comment %d", &commentNumber); if (retVal == 1) { range->SelectComment(commentNumber, comment); } } void RangeFromComment(_In_opt_ Comment *comment, _Inout_ Range **range) { Range *newRange= NULL; if (comment == NULL) { newRange = new Range(NULL); if (newRange == NULL) { wprintf(L"Not enough memory to create a new Range object\n"); } } else { IUIAutomationTextRange *textRange; HRESULT hr = comment->RangeFromAnnotation(_textPattern, &textRange); if (SUCCEEDED(hr)) { // We can validly get a NULL range, if the comment points to nothing newRange = new Range(textRange); if (newRange == NULL) { wprintf(L"Failed to create internal Range object\n"); if (textRange != NULL) { textRange->Release(); } } } } // Any failure to create a new Range object will result in the old range being kept if (newRange != NULL) { delete *range; *range = newRange; } } CommandId GetCommand(_In_reads_(cmdLength) PWSTR cmd, _In_ int cmdLength) { _wcslwr_s(cmd, cmdLength); CommandId ret = CommandId_Invalid; for (int i = 0; i < ARRAYSIZE(CommandText); i++) { size_t commandLength; HRESULT hr = StringCchLength(CommandText[i], cmdLength, &commandLength); // Compare the strings, and the terminating null if (SUCCEEDED(hr)) { if (wcsncmp(CommandText[i], cmd, commandLength) == 0) { ret = static_cast<CommandId>(i); break; } } } return ret; } void Welcome() { wprintf(L"Text Document Explorer:\n\n"); wprintf(L"Available Commands:\n"); wprintf(L" help Show this help screen\n"); wprintf(L" print Print the text of the current active range\n"); wprintf(L" document Set the active range to the whole document\n"); wprintf(L" selection Set the active range to the current selection\n"); wprintf(L" visible Set the active range to the currently visible text\n"); wprintf(L" headers Find all the header text in the active range and print it\n"); wprintf(L" comments List all the comments in the active range\n"); wprintf(L" comment {n} Set the active comment to comment {n} in the active range\n"); wprintf(L" commentrange Set the active range to the the active comment's range\n"); wprintf(L" printcomment Print the active comment\n"); wprintf(L" caret Gets the caret range and prints some caret specific information\n"); wprintf(L" exit Quit\n"); } Range* GetRange(_In_ CommandId cmd, _Out_opt_ bool *active) { Range* retVal = NULL; if (active != NULL) { *active = false; } IUIAutomationTextRange *uiaRange = NULL; HRESULT hr = E_FAIL; if (cmd == CommandId_Document) { hr = _textPattern->get_DocumentRange(&uiaRange); } else if (cmd == CommandId_Caret) { BOOL isActive; hr = _textPattern->GetCaretRange(&isActive, &uiaRange); if (SUCCEEDED(hr) && active != NULL) { *active = !!isActive; } } else { // These two properties return arrays of ranges, for complicated text patterns // for this example we just get the first range from the array IUIAutomationTextRangeArray *uiaRangeArray = NULL; if (cmd == CommandId_Selection) { hr = _textPattern->GetSelection(&uiaRangeArray); } else if (cmd == CommandId_Visible) { hr = _textPattern->GetVisibleRanges(&uiaRangeArray); } if (SUCCEEDED(hr) && uiaRangeArray != NULL) { int length; hr = uiaRangeArray->get_Length(&length); if (SUCCEEDED(hr) && length > 0) { hr = uiaRangeArray->GetElement(0, &uiaRange); } uiaRangeArray->Release(); } } if (FAILED(hr)) { wprintf(L"Failed to Get the Requested Range, HR: 0x%08x\n", hr); uiaRange = NULL; } // We can validly get a NULL range, if the selection is Empty, or nothing is Visible // And even if we have an error, we should wrap the NULL so we have a Range object // If the Range gets created it takes ownership of the IUIAutomationTextRange object retVal = new Range(uiaRange); if (retVal == NULL) { wprintf(L"Failed to create internal Range object\n"); if (uiaRange != NULL) { uiaRange->Release(); } } return retVal; } HRESULT GetTextPattern() { HRESULT hr = _element->GetCurrentPatternAs(UIA_TextPattern2Id, IID_PPV_ARGS(&_textPattern)); if (FAILED(hr)) { wprintf(L"Failed to Get Text Pattern, HR: 0x%08x\n", hr); } else if (_textPattern == NULL) { wprintf(L"Element does not actually support Text Pattern 2\n"); hr = E_FAIL; } return hr; } IUIAutomationTextPattern2 *_textPattern; IUIAutomationElement *_element; }; // Will search an element itself and all its children and descendants for the first element that supports Text Pattern 2 HRESULT FindTextPatternElement(_In_ IUIAutomationElement *element, _Outptr_result_maybenull_ IUIAutomationElement **textElement) { HRESULT hr = S_OK; // Create a condition that will be true for anything that supports Text Pattern 2 IUIAutomationCondition* textPatternCondition; VARIANT trueVar; trueVar.vt = VT_BOOL; trueVar.boolVal = VARIANT_TRUE; hr = _automation->CreatePropertyCondition(UIA_IsTextPattern2AvailablePropertyId, trueVar, &textPatternCondition); if (FAILED(hr)) { wprintf(L"Failed to CreatePropertyCondition, HR: 0x%08x\n", hr); } else { // Actually do the search hr = element->FindFirst(TreeScope_Subtree, textPatternCondition, textElement); if (FAILED(hr)) { wprintf(L"FindFirst failed, HR: 0x%08x\n", hr); } else if (*textElement == NULL) { wprintf(L"No element supporting TextPattern2 found.\n"); hr = E_FAIL; } textPatternCondition->Release(); } return hr; } void Usage() { wprintf(L"Usage:\n\n"); wprintf(L"UiaDocumentClient [hwnd]\n\n"); wprintf(L"Explore the text pattern for the specific [hwnd] (in hex)\n"); wprintf(L"If no [hwnd] is supplied, it will get the element under the mouse pointer.\n\n"); } int _cdecl wmain(_In_ int argc, _In_reads_(argc) WCHAR* argv[]) { UNREFERENCED_PARAMETER(argv); // We only take 0 or 1 argument, since the program name is the first argument this // means any arg count more than 2 is wrong. if (argc > 2) { Usage(); } else { // Initialize COM before using UI Automation HRESULT hr = CoInitialize(NULL); if (FAILED(hr)) { wprintf(L"CoInitialize failed, HR:0x%08x\n", hr); } else { hr = CoCreateInstance(__uuidof(CUIAutomation8), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&_automation)); if (FAILED(hr)) { wprintf(L"Failed to create a CUIAutomation8, HR: 0x%08x\n", hr); } else { IUIAutomationElement *element = NULL; if (argc == 1) { wprintf( L"Getting element at cursor in 3 seconds...\n" ); Sleep(3000); POINT pt; GetCursorPos(&pt); hr = _automation->ElementFromPoint(pt, &element); if (FAILED(hr)) { wprintf( L"Failed to ElementFromPoint, HR: 0x%08x\n\n", hr ); } } else if (argc == 2) { long hwndAsLong; int ret = swscanf_s(argv[1], L"%x", &hwndAsLong); if (ret != 1) { wprintf( L"The hwnd parameter needs to be a number in hex.\n" ); Usage(); hr = E_INVALIDARG; } else { HWND hwnd = static_cast<HWND>(LongToHandle(hwndAsLong)); if (!IsWindow(hwnd)) { wprintf( L"The hwnd specifier 0x%08x is not a valid HWND.\n", hwndAsLong ); hr = E_INVALIDARG; } else { hr = _automation->ElementFromHandle(hwnd, &element); if (FAILED(hr)) { wprintf( L"Failed to ElementFromHandle, HR: 0x%08x\n\n", hr ); } } } } if (SUCCEEDED(hr) && element != NULL) { IUIAutomationElement *textElement = NULL; hr = FindTextPatternElement(element, &textElement); if (SUCCEEDED(hr) && textElement != NULL) { // The TextPatternExplorer takes ownership of the textElement, so no need to release it here TextPatternExplorer explorer(textElement); explorer.Run(); } element->Release(); } _automation->Release(); } CoUninitialize(); } } return 0; }
35.827558
158
0.448518
[ "object" ]
f23b77d0b5c7e5c02ee58a55da4a31787f335f1d
2,512
cpp
C++
Stack-Queue/Stack.cpp
wilsonandusa/wilsonwu
512214c187550f05497732e943f3323c15caeee0
[ "Unlicense" ]
null
null
null
Stack-Queue/Stack.cpp
wilsonandusa/wilsonwu
512214c187550f05497732e943f3323c15caeee0
[ "Unlicense" ]
null
null
null
Stack-Queue/Stack.cpp
wilsonandusa/wilsonwu
512214c187550f05497732e943f3323c15caeee0
[ "Unlicense" ]
null
null
null
/** * @file stack.cpp * Implementation of the Stack class. * * @author CS 225 Course Staff * @date Fall 2009 * * @author Chase Geigle * @date Fall 2012 */ /** * Adds the parameter object to the top of the Stack. That is, the element * should go at the beginning of the list. * * @note This function must be O(1)! * * @param newItem The object to be added to the Stack. */ template<class T> void Stack<T>::push(T const & newItem) { myStack.push_front(newItem); } /** * Removes the object on top of the Stack, and returns it. That is, remove * the element at the beginning of the list. You may assume this function * is only called when the Stack is not empty. * * @note This function must be O(1)! * * @return The element that used to be at the top of the Stack. */ template<class T> T Stack<T>::pop() { T x = myStack.front(); myStack.pop_front(); /** * @todo Your code here! You will have to replace the following line. */ return x; } /** * Adds an element to the ordering structure. * * @see OrderingStructure::add() */ template <class T> void Stack<T>::add( const T & theItem ) { push(theItem); /** * @todo Your code here! Hint: this should call another Stack function * to add the element to the Stack. */ } /** * Removes an element from the ordering structure. * * @see OrderingStructure::remove() */ template <class T> T Stack<T>::remove() { /** * @todo Your code here! Hint: this should call another Stack function * to remove an element from the Stack and return it. You will need to * replace the following line. */ return pop(); } /** * Finds the object on top of the Stack, and returns it to the caller. * Unlike pop(), this operation does not alter the Stack itself. It should * look at the beginning of the list. You may assume this function is only * called when the Stack is not empty. * * @note This function must be O(1)! * * @return The element at the top of the Stack. */ template<class T> T Stack<T>::peek() { T x = myStack.front(); /** * @todo Your code here! You will need to replace the following line. */ return x; } /** * Determines if the Stack is empty. * * @note This function must be O(1)! * * @return Whether or not the stack is empty (bool). */ template<class T> bool Stack<T>::isEmpty() const { /** * @todo Your code here! You will need to replace the following line. */ return myStack.empty(); }
22.230088
75
0.64172
[ "object" ]
f245aa4e45291bafba9ed9e70a7f6fc4fa7ef08b
6,202
cpp
C++
CrashGuard/source/CrashGuard.cpp
macmade/CrashGuard
064ea5ab8721816e417870ae0b1465e0988e23a4
[ "MIT" ]
9
2017-04-13T20:24:11.000Z
2021-08-22T14:02:58.000Z
CrashGuard/source/CrashGuard.cpp
macmade/CrashGuard
064ea5ab8721816e417870ae0b1465e0988e23a4
[ "MIT" ]
null
null
null
CrashGuard/source/CrashGuard.cpp
macmade/CrashGuard
064ea5ab8721816e417870ae0b1465e0988e23a4
[ "MIT" ]
3
2017-03-27T09:27:31.000Z
2021-04-08T21:36:08.000Z
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.com / www.digidna.net * * 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. ******************************************************************************/ /*! * @copyright (c) 2017 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @brief ... */ #include <XS/CrashGuard.hpp> #include <XS/CrashGuard/Handler.hpp> #include <mutex> #include <vector> static std::once_flag once; static std::recursive_mutex * rmtx; static std::vector< XS::CrashGuard::Handler > * handlers; static void init( void ); namespace XS { namespace CrashGuard { uint64_t InstallHandler( std::function< void( void ) > handler ) { std::call_once( once, init ); { std::lock_guard< std::recursive_mutex > l( *( rmtx ) ); Handler h( handlers->size(), handler ); handlers->push_back( h ); return h.HandlerID(); } } void RemoveHandler( uint64_t handlerID ) { std::call_once( once, init ); { std::lock_guard< std::recursive_mutex > l( *( rmtx ) ); handlers->erase ( std::remove_if ( handlers->begin(), handlers->end(), [ = ]( const Handler & h ) { return h.HandlerID() == handlerID; } ), handlers->end() ); } } } } #ifdef _WIN32 static void init( void ) { rmtx = new std::recursive_mutex(); handlers = new std::vector< XS::CrashGuard::Handler >(); } #elif defined( __APPLE__ ) #include <signal.h> static void sig( int signo ); static struct sigaction sigaction_sigabrt = {}; static struct sigaction sigaction_sigsegv = {}; static struct sigaction sigaction_sigbus = {}; static struct sigaction sigaction_sigill = {}; static struct sigaction sigaction_sigfpe = {}; static struct sigaction sigaction_sigpipe = {}; static struct sigaction sigaction_prev_sigabrt = {}; static struct sigaction sigaction_prev_sigsegv = {}; static struct sigaction sigaction_prev_sigbus = {}; static struct sigaction sigaction_prev_sigill = {}; static struct sigaction sigaction_prev_sigfpe = {}; static struct sigaction sigaction_prev_sigpipe = {}; static void init( void ) { rmtx = new std::recursive_mutex(); handlers = new std::vector< XS::CrashGuard::Handler >(); memset( &sigaction_sigabrt, 0, sizeof( struct sigaction ) ); memset( &sigaction_sigsegv, 0, sizeof( struct sigaction ) ); memset( &sigaction_sigbus, 0, sizeof( struct sigaction ) ); memset( &sigaction_sigill, 0, sizeof( struct sigaction ) ); memset( &sigaction_sigfpe, 0, sizeof( struct sigaction ) ); memset( &sigaction_sigpipe, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigabrt, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigsegv, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigbus, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigill, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigfpe, 0, sizeof( struct sigaction ) ); memset( &sigaction_prev_sigpipe, 0, sizeof( struct sigaction ) ); sigaction_sigabrt.sa_handler = sig; sigaction_sigsegv.sa_handler = sig; sigaction_sigbus.sa_handler = sig; sigaction_sigill.sa_handler = sig; sigaction_sigfpe.sa_handler = sig; sigaction_sigpipe.sa_handler = sig; sigaction( SIGABRT, &sigaction_sigabrt, &sigaction_prev_sigabrt ); sigaction( SIGSEGV, &sigaction_sigsegv, &sigaction_prev_sigsegv ); sigaction( SIGBUS, &sigaction_sigbus, &sigaction_prev_sigbus ); sigaction( SIGILL, &sigaction_sigill, &sigaction_prev_sigill ); sigaction( SIGFPE, &sigaction_sigfpe, &sigaction_prev_sigfpe ); sigaction( SIGPIPE, &sigaction_sigpipe, &sigaction_prev_sigpipe ); } static void sig( int signo ) { for( const auto & h: *( handlers ) ) { h(); } handlers->clear(); switch( signo ) { case SIGABRT: sigaction( SIGABRT, &sigaction_prev_sigabrt, nullptr ); break; case SIGSEGV: sigaction( SIGSEGV, &sigaction_prev_sigsegv, nullptr ); break; case SIGBUS: sigaction( SIGBUS, &sigaction_prev_sigbus, nullptr ); break; case SIGILL: sigaction( SIGILL, &sigaction_prev_sigill, nullptr ); break; case SIGFPE: sigaction( SIGFPE, &sigaction_prev_sigfpe, nullptr ); break; case SIGPIPE: sigaction( SIGPIPE, &sigaction_prev_sigpipe, nullptr ); break; default: break; } } #endif
37.137725
87
0.602548
[ "vector" ]
f2596cebdc9fcb9778a7129a9d2454eaecf817ce
1,838
hpp
C++
include/boost/channels/detail/produce_op_interface.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
null
null
null
include/boost/channels/detail/produce_op_interface.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
null
null
null
include/boost/channels/detail/produce_op_interface.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2021 Richard Hodges (hodges.r@gmail.com) // // 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) // // Official repository: https://github.com/madmongo1/boost_channels // #ifndef BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_DETAIL_PRODUCE_OP_INTERFACE_HPP #define BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_DETAIL_PRODUCE_OP_INTERFACE_HPP #include <boost/channels/detail/io_op_interface_base.hpp> #include <boost/channels/error_code.hpp> #include <memory> namespace boost::channels::detail { template < class ValueType, concepts::Lockable Mutex = std::mutex > struct basic_produce_op_interface : basic_io_op_interface_base< Mutex > { virtual ~basic_produce_op_interface() = default; /// @brief Consume the value from the produce_op_interface. /// @pre completed() == false /// @post completed() == true /// @return the object held within the produce_op_interface, having been /// moved out of its temporary storeag virtual ValueType consume() = 0; /// @brief Complete the operation with an error code. /// /// Does not take the value from the producer. /// @pre completed() == false /// @post completed() == true virtual void fail(error_code ec) = 0; }; template < class ValueType, concepts::Lockable Mutex > using basic_producer_ptr = std::shared_ptr< basic_produce_op_interface< ValueType, Mutex > >; // common specialisations template < class ValueType > using produce_op_interface = basic_produce_op_interface< ValueType >; template < class ValueType > using producer_ptr = std::shared_ptr< produce_op_interface< ValueType > >; } // namespace boost::channels::detail #endif // BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_DETAIL_PRODUCE_OP_INTERFACE_HPP
33.418182
81
0.748096
[ "object" ]
f262f8b173d1a48d3ab724f11d25ea966af4e831
785
cpp
C++
google/code_jam/2020/r1c/overrandomized.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
google/code_jam/2020/r1c/overrandomized.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
google/code_jam/2020/r1c/overrandomized.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#include "common/stl/base.h" #include <string> #include <unordered_map> #include <unordered_set> int main_overrandomized() { unsigned T, U, M = 10000; int64_t Q; cin >> T; for (unsigned it = 1; it <= T; ++it) { cin >> U; string s; unordered_set<char> cs; unordered_map<char, unsigned> cmfd; for (unsigned i = 0; i < M; ++i) { cin >> Q >> s; if (s.size() == U) cmfd[s[0]] += 1; for (char c : s) cs.insert(c); } for (char c : cs) cmfd[c] += 1; vector<pair<unsigned, char>> v; for (auto p : cmfd) { v.push_back({p.second, p.first}); } sort(v.begin(), v.end()); reverse(v.begin() + 1, v.end()); cout << "Case #" << it << ": "; for (auto p : v) cout << p.second; cout << endl; } return 0; }
22.428571
41
0.518471
[ "vector" ]
f26385e45c8843353aaaf9c19ef8f3e112d6583d
299
hpp
C++
ds/SwapChainSupportDetails.hpp
seanballais/learn-vulkan
b73630e2423b5b27a93dddc59c13fa15a9d95697
[ "MIT" ]
null
null
null
ds/SwapChainSupportDetails.hpp
seanballais/learn-vulkan
b73630e2423b5b27a93dddc59c13fa15a9d95697
[ "MIT" ]
null
null
null
ds/SwapChainSupportDetails.hpp
seanballais/learn-vulkan
b73630e2423b5b27a93dddc59c13fa15a9d95697
[ "MIT" ]
null
null
null
#ifndef SWAP_CHAIN_SUPPORT_DETAILS_HPP #define SWAP_CHAIN_SUPPORT_DETAILS_HPP #include <vector> #include <vulkan/vulkan.h> struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; #endif
19.933333
45
0.822742
[ "vector" ]
f2644f7d5bcfbbcfd3121e996e337104a19187d7
15,286
hpp
C++
src/display.hpp
shaneapowell/EasySlackStatus
650fe40dbae0d217eeefa8bf94b9393845d8eb35
[ "MIT" ]
1
2022-03-04T20:17:17.000Z
2022-03-04T20:17:17.000Z
src/display.hpp
shaneapowell/EasySlackStatus
650fe40dbae0d217eeefa8bf94b9393845d8eb35
[ "MIT" ]
null
null
null
src/display.hpp
shaneapowell/EasySlackStatus
650fe40dbae0d217eeefa8bf94b9393845d8eb35
[ "MIT" ]
null
null
null
/************************************************************************** Easy Slack Status Updater By Shane Powell <shaneapowell@hotmail.com> Inspired by "Slack Status Updater ESP8266" by Becky Stern **************************************************************************/ #ifndef __LCD_HPP__ #define __LCD_HPP__ #include <Wire.h> #include "lcd/Adafruit_I2C_SH1106.h" #include "main.h" #define PIN_OLED_DATA D2 #define PIN_OLED_CLOCK D1 #define OLED_I2C_ADDR 0x3C #define OLED_SCREEN_WIDTH 128 #define OLED_SCREEN_HEIGHT 64 /* 60 minutes */ #define SCREEN_OFF_INTERVAL_MS (60 * 60 * 1000) /* Text Size 1 */ #define STATUS_BAR_HEIGHT 10 #define CURSOR_STATUS_BAR 0 /* Text Size 2 */ #define LINE_HEIGHT 18 #define LINE_COUNT 3 #define CURSOR_LINE1 10 #define CURSOR_LINE2 28 #define CURSOR_LINE3 46 // 64 - 18 #define TS1_LINE0 0 #define TS1_LINE1 17 #define TS1_LINE2 30 #define TS1_LINE3 43 #define TS1_LINE4 56 extern NTPClient _ntpClient; char STATUS_DISPLAY_BLANK[] = "---"; char STATUS_DISPLAY_ERROR[] = "ERROR"; char STATUS_DISPLAY_FETCHING[] = "..."; typedef enum { SCREEN_BOOT, SCREEN_MAIN, SCREEN_SET_EXPIRE, SCREEN_WIFI, SCREEN_AP } SCREEN; const SlackProfile FAKE_PROFILE_SENDING = { "", "Sending...", "", 0, false }; class LCD { private: Adafruit_I2C_SH1106 _display; ArduinoSlack* _slack; String _slackDisplayName = STATUS_DISPLAY_BLANK; String _slackStatusText = STATUS_DISPLAY_BLANK; bool _slackError = false; bool _isDirty = false; SCREEN _currentScreen = SCREEN_BOOT; bool _lockInSettingsScreen = true; int _currentStatusIndex = 0; int _mainScreenHighlightedIndex = 0; /* Which state is currently "highlghted" */ int _mainScreenScrollBy = 0; /* The rotary scroll by */ int _userSetExpiryInMinutes = -1; unsigned long _lastProfileFetchMillis = 0; unsigned long _lastUserInteractionMillis = 0; /************************************************* * ************************************************/ void renderScreen() { switch(_currentScreen) { case SCREEN_BOOT: /* Currently, do nothing, Might be nice to restore the hard-coded logo? Or .. pull it from an asset? */ break; case SCREEN_MAIN: renderMainScreen(); break; case SCREEN_SET_EXPIRE: renderSetExpireScreen(); break; case SCREEN_WIFI: renderWifiScreen(); break; case SCREEN_AP: renderAPScreen(); break; } /* Screen Saver */ if (millis() > _lastUserInteractionMillis + SCREEN_OFF_INTERVAL_MS) { _display.fillScreen(BLACK); } _display.flushDisplay(); } /***********************************************/ void renderMainScreen() { _display.fillScreen(BLACK); /* Current Status */ _display.setTextSize(1); _display.setTextColor(WHITE); /* Status */ String status = STATUS_DISPLAY_ERROR; if (!_slackError) { /* Status Output */ status = _slackStatusText; if (status.length() == 0) { status = STATUS_DISPLAY_BLANK; } else { /* Make sure the status fits within our 10 char limit */ if (status.length() > SLACK_STATUS_CHARS_MAX) { status = status.substring(0, SLACK_STATUS_CHARS_MAX); } } /* Make sure the "name" fits within our 10char limit. */ String name = _slackDisplayName; if (name != NULL && name.length() > 0) { /* First workd/name only */ int ndx = name.indexOf(' '); if (ndx != -1) { name = name.substring(0, ndx); } name = name.substring(0, SLACK_STATUS_CHARS_MAX); _display.setCursor(0, CURSOR_STATUS_BAR); _display.print(name); } } /* Render the status line, it's our current status, or error */ int x = _display.width() - (status.length() * 6); _display.setCursor(x, CURSOR_STATUS_BAR); _display.print(status); /* Time */ /* Selection List */ int index = _mainScreenScrollBy; renderStatusLine(CURSOR_LINE1, _slackStatusList[index], index == _mainScreenHighlightedIndex, _slackStatusList[index].expireInMinutes > 0); renderStatusLine(CURSOR_LINE2, _slackStatusList[index+1], index+1 == _mainScreenHighlightedIndex, _slackStatusList[index].expireInMinutes > 0); renderStatusLine(CURSOR_LINE3, _slackStatusList[index+2], index+2 == _mainScreenHighlightedIndex, _slackStatusList[index].expireInMinutes > 0); } /***********************************************/ void renderStatusLine(int cursorLine, SlackStatus status, bool active, bool hasDefaultExpiry) { _display.setTextSize(2); int textColor = WHITE; if (active) { textColor = BLACK; _display.fillRect(0, cursorLine-1, _display.width(), LINE_HEIGHT, WHITE); } _display.setTextColor(textColor); _display.setCursor(1, cursorLine); _display.print(status.title); } /***********************************************/ void renderSetExpireScreen() { _display.fillScreen(BLACK); /* Current Status */ _display.setTextSize(2); _display.setTextColor(WHITE); SlackStatus status = getHighlightedSlackStatus(); _display.setCursor(0, CURSOR_LINE1); _display.print(status.title); _display.setCursor(0, CURSOR_LINE2); _display.print(F("Expire In")); char expiryLine[32]; sprintf(expiryLine, "< %02d min >", _userSetExpiryInMinutes); _display.setCursor(_display.width() / 2 - ( strlen(expiryLine) / 2 * 12), CURSOR_LINE3); _display.print(expiryLine); } /***********************************************/ void renderWifiScreen() { _display.fillScreen(BLACK); _display.setTextSize(1); _display.setTextColor(WHITE); _display.setCursor(0, TS1_LINE0); _display.print(F("WiFi:")); _display.setCursor(0, TS1_LINE1); _display.print(WiFi.SSID()); if (!WiFi.isConnected()) { _display.setCursor(0, TS1_LINE2); _display.print(F("Connecting...")); } else if (WiFi.localIP().isSet()) { _display.setCursor(0, TS1_LINE2); _display.print(WiFi.localIP().toString()); char time[32]; sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d%s", year(), month(), day(), hourFormat12(), minute(), second(), (isPM() ? "pm" : "am")); _display.setCursor(0, TS1_LINE3); _display.print(time); _display.setCursor(0, TS1_LINE4); _display.print(currentTZName); } else { _display.setCursor(0, TS1_LINE2); _display.print(F("Obtaining IP...")); } } /***********************************************/ void renderAPScreen() { _display.fillScreen(BLACK); _display.setTextSize(1); _display.setTextColor(WHITE); _display.setCursor(0, TS1_LINE0); _display.print(F("Configure:")); _display.setCursor(0, TS1_LINE1); _display.print(F("Connect Phone or")); _display.setCursor(0, TS1_LINE2); _display.print(F("Laptop to this WiFi")); _display.setCursor(18, TS1_LINE3); _display.print(WiFi.softAPSSID()); _display.setCursor(0, TS1_LINE4); String url = "http://" + WiFi.softAPIP().toString() + "/"; _display.print(url); } public: /***********************************************/ void setSlack(ArduinoSlack* slack) { _slack = slack; } /***********************************************/ void setup() { _display.init(); _display.setTextWrap(false); /* Brief Version Display */ _display.setTextSize(1); _display.setTextColor(WHITE); _display.setCursor(0, TS1_LINE4); _display.print(APP_VERSION_NAME); _display.flushDisplay(); delay(1000); renderScreen(); } /***********************************************/ void loop() { /* I guess you can cal this a whopping 2fps */ static long lastRenderMs = 0; if (millis() - lastRenderMs > 500) { _isDirty = true; } if (_isDirty) { lastRenderMs = millis(); _isDirty = false; renderScreen(); } /* Every minute, query the current slack status */ if (_lastProfileFetchMillis == 0 || millis() - _lastProfileFetchMillis > (1000 * 60)) { if (_currentScreen == SCREEN_MAIN) { Serial.println(F("Fetching Current Slack Status")); _slackStatusText = STATUS_DISPLAY_FETCHING; renderScreen(); SlackProfile profile = _slack->getCurrentStatus(); setSlackProfile(profile); _lastProfileFetchMillis = millis(); } } } /***********************************************/ SlackStatus getHighlightedSlackStatus() { return _slackStatusList[_mainScreenHighlightedIndex]; } /********************************************/ void setSlackProfile(SlackProfile profile) { _lastProfileFetchMillis = millis(); _slackError = profile.error; if (!_slackError) { _slackDisplayName = profile.displayName; _slackStatusText = profile.statusText; Serial.println(F("--------- Profile ---------")); Serial.print(F("Display Name: [")); Serial.print(profile.displayName); Serial.println(F("]")); Serial.print(F("Status Text: [")); Serial.print(profile.statusText); Serial.println(F("]")); Serial.print(F("Status Emoji: [")); Serial.print(profile.statusEmoji); Serial.println(F("]")); Serial.print(F("Status Expiration: ")); Serial.println(profile.statusExpiration); Serial.println(F("------------------------")); } else { Serial.println(F("error getting profile")); } _isDirty = true; } /***********************************************/ void setScreen(SCREEN screen) { /* Only set the user to the main, if we're not locked in settings. Locked in settings is a result of the wifi not yet connected, or in the AP configure mode. */ if (screen == SCREEN_MAIN && _lockInSettingsScreen) { return; } /* If jumping to the expire set screen, pre-set the expire minutes */ if (screen == SCREEN_SET_EXPIRE) { _userSetExpiryInMinutes = atoi(getHighlightedSlackStatus().expireInMinutes); /* Another long-press goes back to the main screen. Aka.. cancel */ if (_currentScreen == SCREEN_SET_EXPIRE) { screen = SCREEN_MAIN; } } _currentScreen = screen; _isDirty = true; } /***********************************************/ void lockSettings(bool lock) { _lockInSettingsScreen = lock; } /***********************************************/ void onRotaryInput(boolean increase) { _lastUserInteractionMillis = millis(); /* MAIN screen */ if (_currentScreen == SCREEN_MAIN) { /* Move Highlight Bar */ _mainScreenHighlightedIndex += (increase ? 1 : -1); _mainScreenHighlightedIndex = max(_mainScreenHighlightedIndex, 0); _mainScreenHighlightedIndex = min(_mainScreenHighlightedIndex, SLACK_STATUS_COUNT-1); /* Calculate any change in the scroll by */ if (_mainScreenHighlightedIndex < _mainScreenScrollBy) { _mainScreenScrollBy = _mainScreenHighlightedIndex; } else if (_mainScreenHighlightedIndex >= _mainScreenScrollBy + LINE_COUNT) { _mainScreenScrollBy = _mainScreenHighlightedIndex - LINE_COUNT + 1; } } else if (_currentScreen == SCREEN_SET_EXPIRE) { if (increase) { _userSetExpiryInMinutes++; } else { _userSetExpiryInMinutes--; } _userSetExpiryInMinutes = max(_userSetExpiryInMinutes, 0); _userSetExpiryInMinutes = min(_userSetExpiryInMinutes, 999); } _isDirty = true; } /***********************************************/ void onRotaryClick() { _lastUserInteractionMillis = millis(); SlackStatus status = getHighlightedSlackStatus(); int expireInMinute = 0; int expireUTC = 0; switch(_currentScreen) { default: break; case(SCREEN_MAIN): break; case(SCREEN_SET_EXPIRE): expireInMinute = _userSetExpiryInMinutes; break; } setScreen(SCREEN_MAIN); setSlackProfile(FAKE_PROFILE_SENDING); _isDirty = true; renderScreen(); if (expireInMinute > 0) { expireUTC = _ntpClient.getEpochTime(); expireUTC += (expireInMinute * 60); } SlackProfile profile = _slack->setCustomStatus(status.title, status.icon, expireUTC); setSlackProfile(profile); _isDirty = true; } /***********************************************/ void onRotaryDoubleClick() { _lastUserInteractionMillis = millis(); switch(_currentScreen) { default: break; case SCREEN_MAIN: setScreen(SCREEN_SET_EXPIRE); break; case SCREEN_SET_EXPIRE: setScreen(SCREEN_MAIN); break; } } /***********************************************/ void onRotaryLongClick() { _lastUserInteractionMillis = millis(); switch (_currentScreen) { default: case SCREEN_BOOT: case SCREEN_SET_EXPIRE: break; case SCREEN_MAIN: setScreen(SCREEN_WIFI); break; case SCREEN_WIFI: setScreen(SCREEN_MAIN); break; case SCREEN_AP: setScreen(SCREEN_MAIN); break; } _isDirty = true; } }; extern LCD Display; #endif
27.296429
152
0.520345
[ "render" ]
f2680a1f7da7a216f3b176846701d1c27475dfee
1,212
cpp
C++
1088.cpp
viniciusmalloc/uri
e9554669a50a6d392e3bce49fc21cbfaa353c85f
[ "MIT" ]
1
2022-02-11T21:12:38.000Z
2022-02-11T21:12:38.000Z
BALDES.cpp
viniciusmalloc/spoj-br
cc5ac1491f87567c90f98510824284f08fa8a0f8
[ "MIT" ]
null
null
null
BALDES.cpp
viniciusmalloc/spoj-br
cc5ac1491f87567c90f98510824284f08fa8a0f8
[ "MIT" ]
1
2021-03-24T16:06:38.000Z
2021-03-24T16:06:38.000Z
/* Resolucao: Algoritmo que simula e gera o numero minimo de swaps necessarios para ordenar um array de numeros. Complexidade O(n) Se for par, Carlos ganha; sen�o Marcelo ganha */ #include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <string> #include <vector> #define mp make_pair #define pb push_back #define MAXV 100010 using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; int number[MAXV], pos[MAXV]; int main() { ios::sync_with_stdio(false); int a, n; while (cin >> n && n) { int qtd = 0; for (int i = 0; i < n; i++) { cin >> a; number[i] = a - 1; pos[a - 1] = i; } for (int i = 0; i < n; i++) { if (number[i] != i) { number[pos[i]] = number[i]; pos[number[i]] = pos[i]; number[i] = pos[i] = i; qtd++; } } if (qtd % 2 == 0) cout << "Carlos\n"; else cout << "Marcelo\n"; } return 0; }
21.642857
67
0.488449
[ "vector" ]
f26a5c0120e6d3ed80670f9f09cba847bcdbfed1
1,855
cc
C++
src/renderer/vulkan/vulkan_frame_buffer.cc
skaman/chronicle5
a187023f129ff1e552204b8a66ca4125d5c0a3a7
[ "MIT" ]
null
null
null
src/renderer/vulkan/vulkan_frame_buffer.cc
skaman/chronicle5
a187023f129ff1e552204b8a66ca4125d5c0a3a7
[ "MIT" ]
null
null
null
src/renderer/vulkan/vulkan_frame_buffer.cc
skaman/chronicle5
a187023f129ff1e552204b8a66ca4125d5c0a3a7
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Sandro Cavazzoni. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. #include "vulkan_frame_buffer.h" #include "common.h" #include "vulkan_device.h" #include "vulkan_image_view.h" #include "vulkan_render_pass.h" #include "vulkan_utils.h" namespace chr::renderer::internal { VulkanFrameBuffer::VulkanFrameBuffer(const VulkanDevice &device, const VulkanRenderPass &render_pass, const FrameBufferCreateInfo &info) : device_(device.GetNativeDevice()) { CHR_ZONE_SCOPED_VULKAN(); std::vector<VkImageView> attachments{}; attachments.reserve(info.attachments.size()); for (auto &attachment : info.attachments) { auto vulkanImageView = static_cast<VulkanImageView *>(attachment.get()); attachments.push_back(vulkanImageView->GetNativeImageView()); } VkFramebufferCreateInfo frame_buffer_info{}; frame_buffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; frame_buffer_info.renderPass = render_pass.GetNativeRenderPass(); frame_buffer_info.attachmentCount = static_cast<uint32_t>(attachments.size()); frame_buffer_info.pAttachments = attachments.data(); frame_buffer_info.width = info.extent.x; frame_buffer_info.height = info.extent.y; frame_buffer_info.layers = 1; if (auto result = vkCreateFramebuffer(device_, &frame_buffer_info, nullptr, &frame_buffer_); result != VK_SUCCESS) { frame_buffer_ = VK_NULL_HANDLE; throw VulkanException(result, "Failed to create framebuffer"); } } VulkanFrameBuffer::~VulkanFrameBuffer() { CHR_ZONE_SCOPED_VULKAN(); if (frame_buffer_ != VK_NULL_HANDLE) { vkDestroyFramebuffer(device_, frame_buffer_, nullptr); } } } // namespace chr::renderer::internal
34.351852
80
0.722911
[ "vector" ]
f27d1ae4a6b6cedfe545452325099673705cb151
1,706
cpp
C++
OJ/LeetCode/leetcode/problems/4.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
OJ/LeetCode/leetcode/problems/4.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
2
2021-10-31T10:05:45.000Z
2022-02-12T15:17:53.000Z
OJ/LeetCode/leetcode/problems/4.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <cstdio> #include <vector> #include <algorithm> #include "dbg.h" using namespace std; /* Leetcode */ /* Type: array */ /* 题目信息 */ /* *4. Median of Two Sorted Arrays(media: 中位数) Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. Example 3: Input: nums1 = [0,0], nums2 = [0,0] Output: 0.00000 Example 4: Input: nums1 = [], nums2 = [1] Output: 1.00000 Example 5: Input: nums1 = [2], nums2 = [] Output: 2.00000 Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106 */ /* my solution */ // solution-1, 56ms, 31.5% // brute force // 1. 将nums2中元素加入nums1中 // 2. sort nums1 // 3. 求出中间元素 class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { // merge nums2's elements to nums1 for (int i : nums2) { nums1.push_back(i); } // sort sort(nums1.begin(), nums1.end()); int n = nums1.size(); int left = n / 2; // even if (n % 2 == 0) return (double(nums1[left] + nums1[left-1]) / 2); return nums1[left]; } }; /* better solution */ /* 一些总结 */ // 1. 题意: // // 需要注意的点: // 1. 应该是可以使用二分法的 // 2. // 3.
18.543478
113
0.570926
[ "vector" ]
f281cf29781a4bd5a936737fc72f951ebaaeef5a
3,922
cpp
C++
hwmanagement.cpp
Kuzame/hwmanagement
7f1d181a2eae6524c083c40bad1075910dbfc919
[ "Apache-2.0" ]
null
null
null
hwmanagement.cpp
Kuzame/hwmanagement
7f1d181a2eae6524c083c40bad1075910dbfc919
[ "Apache-2.0" ]
null
null
null
hwmanagement.cpp
Kuzame/hwmanagement
7f1d181a2eae6524c083c40bad1075910dbfc919
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <time.h> void calculate(int t, int numbers, int *hrem, int *srem, int *mrem, int *tpernum, int *spernum); void timesup(); void finished(); using namespace std; class Time { public: Time(); int hour; int minute; int second; }; Time::Time() { hour=0; minute=0; second=0; } void main() { clock_t asdf; int t, numbers,num,done, tbank,tbank2,fraction; tbank=0;tbank2=0;fraction=0;done=0; Time *remaining=new Time(); Time *goal=new Time(); //#pernum Time *goal1=new Time(); //#pernum Time *elapsed=new Time(); Time *elapsed2=new Time(); system("cls"); cout<<"##Brought to you by Kuzame##\n\n"; cout<<"Total numbers: "; cin>>numbers; num=numbers; cout<<"Hours left: "; cin>>remaining->hour; cout<<"Mins left: "; cin>>remaining->minute; cout<<"Will begin after you press enter..\n"; system("pause"); t=remaining->hour*3600+remaining->minute*60; if (numbers>0) calculate(t, numbers, &remaining->hour, &remaining->minute, &remaining->second, &goal->minute, &goal->second); goal1->minute=goal->minute;goal1->second=goal->second; while (numbers>0) { asdf=clock(); system("cls"); cout<< "#################################\n"; cout<< "# #\n"; cout<< "# #\n"; printf("# Time remaining: %.2dh %.2dm %.2ds #\n", remaining->hour, remaining->minute,remaining->second); cout<< "# #\n"; printf("# Total Num: %.3d num #\n", num); printf("# Num remaining: %.3d num #\n", numbers); cout<< "# #\n"; printf("# Time goal: %.3dm/num %.2ds/num #\n", goal1->minute, goal1->second); printf("# (refresh): %.3dm/num %.2ds/num #\n", goal->minute, goal->second); cout<< "# #\n"; printf("# Time elapsed: %.2dh %.2dm %.2ds #\n", elapsed2->hour, elapsed2->minute,elapsed2->second); printf("# Total elapsed: %.2dh %.2dm %.2ds #\n", elapsed->hour, elapsed->minute,elapsed->second); cout<< "# #\n"; cout<< "# #\n"; cout<< "#################################\n"<<endl; cout<< "Press ENTER to refresh\n"; cout<< "Number you've finished (max 9): "; done=getchar(); if (done=='\n'||(done<'0'||done>'9')) {done=0;} else done=done-'0'; numbers-=done; t-=(clock()-asdf)/1000 + fraction/1000; tbank+=(clock()-asdf)/1000 + fraction/1000; elapsed->hour= (tbank-(tbank%3600))/3600; elapsed->minute=((tbank-(tbank%60))/60)%60; elapsed->second=tbank%60; if (t<0) numbers=0; if (numbers>0) calculate(t, numbers, &remaining->hour, &remaining->minute, &remaining->second, &goal->minute, &goal->second); if (done!=0) {tbank2=0; goal1->minute=goal->minute;goal1->second=goal->second;} else tbank2+=(clock()-asdf)/1000 + fraction/1000; elapsed2->hour= (tbank2-(tbank2%3600))/3600; elapsed2->minute=((tbank2-(tbank2%60))/60)%60; elapsed2->second=tbank2%60; if (fraction>1000) fraction-=1000; fraction+=(clock()-asdf)%1000; } if (t<0) { cout<<endl; timesup(); } else { cout<<endl; finished(); } system("pause"); } void timesup() { int i; cout<< "#################################\n"; cout<< "# TIME's UP!! D; #\n"; cout<< "#################################\n"; for (i=0;i<7;i++) printf("\07"); } void finished() { cout<< "#################################\n"; cout<< "#----- YAY finished!!! :D -----#\n"; cout<< "#################################\n"; } void calculate(int t,int numbers, int *hrem, int *mrem, int *srem, int *mpernum, int *spernum) { *hrem = (t-(t%3600))/3600; *mrem = (t%3600)/60; *srem = t%60; *mpernum= (t/numbers)/60; *spernum= (t/numbers)%60; } //Copyrighted by Adrian Harminto
29.268657
132
0.521928
[ "3d" ]
f284b52d5a7c0ddfb110900957d40320adcd337e
4,711
cpp
C++
src/buffer.cpp
adrisj7/graphics-engine
1315390badcdfb16f2ae10a152eb4285ac17f42f
[ "Unlicense" ]
null
null
null
src/buffer.cpp
adrisj7/graphics-engine
1315390badcdfb16f2ae10a152eb4285ac17f42f
[ "Unlicense" ]
null
null
null
src/buffer.cpp
adrisj7/graphics-engine
1315390badcdfb16f2ae10a152eb4285ac17f42f
[ "Unlicense" ]
null
null
null
#include<stdio.h> #include<math.h> #include "buffer.h" #include "matrix.h" #include "stack.h" Buffer::Buffer(Matrix *m) { points = m; transformations = new Stack<Matrix>(); Matrix *global = new Matrix(4,4); global->fillWithIdentity(); transformations->push(global); //transform = new Matrix(4,4); transformSetIdentity(); pointCount = 0; } Buffer::Buffer() : Buffer(new Matrix(0)) { //points = new Matrix(0); //transform = new Matrix(4,4); //transformSetIdentity(); //pointCount = 0; } Buffer::~Buffer() { delete points; delete transformations; } void Buffer::addPoint(float x, float y, float z) { // Put the point in this matrix (like a vector) // and apply the transformation to the point Matrix *temp = new Matrix(1); *temp->get(0, 0) = x; *temp->get(0, 1) = y; *temp->get(0, 2) = z; *temp->get(0, 3) = 1; temp->multiply(transformations->peek()); // Then copy the point on to the points matrix pointCount++; points->growColumns(pointCount); int i; for(i = 0; i < temp->getNumRows(); i++) { *points->get(pointCount - 1, i) = *temp->get(0, i); } // *points->get(pointCount - 1, 0) = x; // *points->get(pointCount - 1, 1) = y; // *points->get(pointCount - 1, 2) = z; // *points->get(pointCount - 1, 3) = 1; delete temp; } // Adds all the points from a matrix // and applies the current transformation when adding this shape void Buffer::addPoints(Matrix *m) { int col; for(col = 0; col < m->getNumColumns(); col++) { addPoint(*m->get(col, 0), *m->get(col, 1), *m->get(col, 2)); } } // Helper function for ease of use void Buffer::add_transform(float* trans_mat) { printf("[buffer.cpp] Lemme guess 1\n"); Matrix *trans = new Matrix(4,4, trans_mat); printf("[buffer.cpp] Lemme guess 2\n"); // Multiply trans mat by our current transformation, and replace // our current transformation mat with that new mat Matrix *top = transformations->peek(); trans->multiply(top); printf("[buffer.cpp] Lemme guess 3\n"); delete transformations->pop(); printf("[buffer.cpp] Lemme guess 4\n"); transformations->push(trans); printf("[buffer.cpp] Lemme guess 5\n"); //transformations->peek()->multiply(trans); //delete trans; } void Buffer::transformSetIdentity() { transformations->peek()->fillWithIdentity(); } void Buffer::translate(float dx, float dy, float dz) { float trans_mat[] = { 1, 0, 0, dx, 0, 1, 0, dy, 0, 0, 1, dz, 0, 0, 0, 1 }; add_transform(trans_mat); } void Buffer::scale(float sx, float sy, float sz) { float trans_mat[] = { sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1 }; add_transform(trans_mat); } void Buffer::rotate_x(float theta) { theta *= M_PI / 180.0f; float c = cos(theta); float s = sin(theta); float trans_mat[] = { 1, 0, 0, 0, 0, c, s, 0, // positive 0, -s, c, 0, // negative 0, 0, 0, 1 }; add_transform(trans_mat); } void Buffer::rotate_y(float theta) { theta *= M_PI / 180.0f; float c = cos(theta); float s = sin(theta); float trans_mat[] = { //0, 0, 1, 0, //c, -s, 0, 0, //s, c, 0, 0, //0, 0, 0, 1 c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1 }; add_transform(trans_mat); } void Buffer::rotate_z(float theta) { theta *= M_PI / 180.0f; float c = cos(theta); float s = sin(theta); float trans_mat[] = { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; add_transform(trans_mat); } void Buffer::transformPush() { printf("[buffer.cpp] 1\n"); Matrix *copy = new Matrix(4); printf("[buffer.cpp] 2\n"); printf("[buffer.cpp] 2: %d\n", transformations->getSize()); transformations->peek()->copyTo(copy); printf("[buffer.cpp] 3\n"); transformations->push(copy); printf("[buffer.cpp] 4\n"); } void Buffer::transformPop() { if (transformations->getSize() > 1) { Matrix *mat = transformations->pop(); delete mat; } } void Buffer::clear() { pointCount = 0; points->growColumns(0); transformations->empty(); //printf("[buffer.cpp] wtf 1\n"); Matrix *global = new Matrix(4,4); //printf("[buffer.cpp] wtf 2\n"); global->fillWithIdentity(); //printf("[buffer.cpp] wtf 3\n"); transformations->push(global); //printf("[buffer.cpp] wtf 4\n"); }
23.913706
68
0.547654
[ "shape", "vector", "transform" ]
f2880cb3cd57b6066094412fd757b222e366b9e9
12,794
cc
C++
src/player/es_dash_player/packets_manager.cc
kevinscroggins-youi/NativePlayer
8de394aeb964add1568ddcfc12216930bd895647
[ "MIT" ]
26
2017-02-24T15:17:19.000Z
2021-02-11T04:38:16.000Z
src/player/es_dash_player/packets_manager.cc
kevinscroggins-youi/NativePlayer
8de394aeb964add1568ddcfc12216930bd895647
[ "MIT" ]
8
2019-04-17T13:19:17.000Z
2021-09-21T13:49:53.000Z
src/player/es_dash_player/packets_manager.cc
kevinscroggins-youi/NativePlayer
8de394aeb964add1568ddcfc12216930bd895647
[ "MIT" ]
14
2016-08-31T08:40:36.000Z
2021-11-12T18:45:14.000Z
/*! * stream_manager.h (https://github.com/SamsungDForum/NativePlayer) * Copyright 2016, Samsung Electronics Co., Ltd * Licensed under the MIT license * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Piotr Bałut */ #include "player/es_dash_player/packets_manager.h" #include <limits> using Samsung::NaClPlayer::TimeTicks; namespace { constexpr int kAudioStreamId = static_cast<int>(StreamType::Audio); constexpr int kVideoStreamId = static_cast<int>(StreamType::Video); // Determines how many seconds worth of packets should be appended to NaCl // Player in advance. All available packets in a range: // (last appended packet; current_playback_time + kAppendPacketsThreshold] // will be appended upon every UpdateBuffer(). constexpr TimeTicks kAppendPacketsThreshold = 4.0f; // seconds class BufferedPacket : public PacketsManager::BufferedStreamObject { public: BufferedPacket(StreamType type, std::unique_ptr<ElementaryStreamPacket> packet) : BufferedStreamObject(type, packet->GetDts()), packet_(std::move(packet)) {} ~BufferedPacket() override = default; bool Append(StreamManager* stream_manager) override { LOG_DEBUG("demux_id: %d manager: %p dts: %f pts: %f dur: %f pts_end: %f" " key_frame: %d encrypted: %d size: %u", packet_->demux_id, stream_manager, packet_->GetDts(), packet_->GetPts(), packet_->GetDuration(), packet_->GetPts() + packet_->GetDuration(), packet_->IsKeyFrame(), packet_->IsEncrypted(), packet_->GetDataSize()); return !stream_manager->AppendPacket(std::move(packet_)); } bool IsKeyFrame() const override { return packet_->IsKeyFrame(); } bool IsConfig() const override { return false; } private: std::unique_ptr<ElementaryStreamPacket> packet_; }; template <typename ConfigT, StreamType stream_type> class BufferedConfig : public PacketsManager::BufferedStreamObject { public: BufferedConfig(TimeTicks time, const ConfigT& config) : BufferedStreamObject(stream_type, time), config_(config) {} ~BufferedConfig() override = default; bool Append(StreamManager* stream_manager) override { LOG_DEBUG("demux_id: %d dts: %f CONFIG", config_.demux_id, time()); return stream_manager->SetConfig(config_); } bool IsKeyFrame() const override { return false; } bool IsConfig() const override { return true; } private: ConfigT config_; }; typedef BufferedConfig<AudioConfig, StreamType::Audio> BufferedAudioConfig; typedef BufferedConfig<VideoConfig, StreamType::Video> BufferedVideoConfig; } // anonymous namespace PacketsManager::BufferedStreamObject::~BufferedStreamObject() = default; PacketsManager::PacketsManager() : seeking_(false), eos_count_(0), seek_segment_set_{ {false, false} }, seek_segment_video_time_(0), buffered_packets_timestamp_{ {0, 0} } { } PacketsManager::~PacketsManager() = default; void PacketsManager::PrepareForSeek(Samsung::NaClPlayer::TimeTicks to_time) { pp::AutoLock critical_section(packets_lock_); // Append pending representation changes BufferedStreamObjectPtr last_config; while (!packets_.empty()) { const auto& packet = packets_.top(); if (packet->IsConfig()) const_cast<decltype(last_config)&>(packets_.top()).swap(last_config); packets_.pop(); } if (last_config) { auto stream_id = static_cast<int>(last_config->type()); if (streams_[stream_id]) { last_config->Append(streams_[stream_id]); } } // Stream managers will not send packets while they are seeking streams. // If streamManager sends packet, it means stream is at a new position. This // manager seek ends when it receives a keyframe packet for each stream. seeking_ = true; seek_segment_set_[kAudioStreamId] = false; seek_segment_set_[kVideoStreamId] = false; seek_segment_video_time_ = 0; eos_count_ = 0; buffered_packets_timestamp_[kAudioStreamId] = 0; buffered_packets_timestamp_[kVideoStreamId] = 0; } void PacketsManager::OnEsPacket( StreamDemuxer::Message message, std::unique_ptr<ElementaryStreamPacket> packet) { switch (message) { case StreamDemuxer::kEndOfStream: ++eos_count_; break; case StreamDemuxer::kAudioPkt: case StreamDemuxer::kVideoPkt: { auto type = (message == StreamDemuxer::kAudioPkt ? StreamType::Audio : StreamType::Video); auto stream_index = static_cast<int32_t>(type); if (!streams_[stream_index]) { LOG_ERROR("Received a packet for a non-existing stream (%s).", type == StreamType::Video ? "VIDEO" : "AUDIO"); break; } if (streams_[stream_index]->IsSeeking()) { LOG_DEBUG("Stream %s is seeking dropping packet with pts: %f", type == StreamType::Video ? "VIDEO" : "AUDIO", packet->GetPts()); break; } LOG_DEBUG("Stream %s demux_id: %d got packet pts: %f dts: %f", type == StreamType::Video ? "VIDEO" : "AUDIO", packet->demux_id, packet->GetPts(), packet->GetDts()); pp::AutoLock critical_section(packets_lock_); buffered_packets_timestamp_[stream_index] = packet->GetDts(); packets_.emplace(MakeUnique<BufferedPacket>(type, std::move(packet))); break; }; default: LOG_ERROR("Received an unsupported message type!"); } } void PacketsManager::OnStreamConfig(const AudioConfig& config) { HandleStreamConfig(StreamType::Audio, config); } std::unique_ptr<PacketsManager::BufferedStreamObject> PacketsManager::CreateBufferedConfig(const AudioConfig& config) { return MakeUnique<BufferedAudioConfig>( buffered_packets_timestamp_[kAudioStreamId] + kEps, config); } void PacketsManager::OnStreamConfig(const VideoConfig& config) { HandleStreamConfig(StreamType::Video, config); } std::unique_ptr<PacketsManager::BufferedStreamObject> PacketsManager::CreateBufferedConfig(const VideoConfig& config) { return MakeUnique<BufferedVideoConfig>( buffered_packets_timestamp_[kVideoStreamId] + kEps, config); } void PacketsManager::OnNeedData(StreamType type, int32_t bytes_max) { } void PacketsManager::OnEnoughData(StreamType type) { } void PacketsManager::OnSeekData(StreamType type, TimeTicks new_time) { if (streams_[kAudioStreamId] && type == StreamType::Audio) { seek_segment_set_[kAudioStreamId] = true; } else if (streams_[kVideoStreamId] && type == StreamType::Video) { // If video track is present, we want to align seek to video keyframe // (which is at the beginning start of a segment). seek_segment_set_[kVideoStreamId] = true; TimeTicks video_segment_start; TimeTicks video_segment_duration; streams_[kVideoStreamId]->SetSegmentToTime(new_time, &video_segment_start, &video_segment_duration); seek_segment_video_time_ = video_segment_start; LOG_DEBUG("Seek to video segment: %f [s] ... %f [s]", video_segment_start, video_segment_start + video_segment_duration); } else { LOG_ERROR("Received an OnSeekData event for a non-existing stream (%s).", type == StreamType::Video ? "VIDEO" : "AUDIO"); return; } // If there is no video track, then just continue with seeking audio. // Otherwise allow seeking audio only after seeking video (i.e. when video // seek time is determined). auto video_segment_set = !streams_[kVideoStreamId] || seek_segment_set_[kVideoStreamId]; auto audio_segment_set = seek_segment_set_[kAudioStreamId]; if (streams_[kAudioStreamId] && audio_segment_set && video_segment_set) { // Align audio seek time to video seek time if video track is present. auto seek_audio_to_time = streams_[kVideoStreamId] ? seek_segment_video_time_ : new_time; TimeTicks audio_segment_start; TimeTicks audio_segment_duration; streams_[kAudioStreamId]->SetSegmentToTime(seek_audio_to_time, &audio_segment_start, &audio_segment_duration); LOG_DEBUG("Seek to audio segment: %f [s] ... %f [s]", audio_segment_start, audio_segment_start + audio_segment_duration); } } void PacketsManager::CheckSeekEndConditions( Samsung::NaClPlayer::TimeTicks buffered_time) { // Seeks ends when: // - a video keyframe is received (if video stream is present) // - an audio keyframe is received (otherwise) // All packets before the one that ends seek must be dropped. It's worth // noting that all audio frames are keyframes. assert(seeking_); BufferedStreamObjectPtr last_config; while (!packets_.empty()) { const auto& packet = packets_.top(); auto packet_playback_position = packet->time(); if (buffered_time < packet_playback_position) break; if (((streams_[kVideoStreamId] && packet->type() == StreamType::Video) || (!streams_[kVideoStreamId] && streams_[kAudioStreamId] && packet->type() == StreamType::Audio)) && packet->IsKeyFrame()) { seeking_ = false; LOG_DEBUG("Seek finishing at %f [s] %s packet... buffered packets: %u", packet->time(), packet->type() == StreamType::Video ? "VIDEO" : "AUDIO", packets_.size()); break; } else { if (packet->IsConfig()) const_cast<decltype(last_config)&>(packets_.top()).swap(last_config); packets_.pop(); } } if (last_config) packets_.push(std::move(last_config)); } void PacketsManager::AppendPackets(TimeTicks playback_time, TimeTicks buffered_time) { assert(!seeking_); if (packets_.empty()) return; // Append packets to respective streams: auto packet_playback_position = packets_.top()->time(); while (packet_playback_position - playback_time < kAppendPacketsThreshold && packet_playback_position < buffered_time) { auto stream_id = static_cast<int>(packets_.top()->type()); if (streams_[stream_id]) { std::unique_ptr<BufferedStreamObject> stream_object; // Moving object out of priority queue breaks it ordering, hence // const_cast immediately followed by a pop to simulate atomic // "pop top element from queue to local variable". const_cast<decltype(stream_object)&>(packets_.top()).swap(stream_object); packets_.pop(); // True means that we should break the loop and try again eg. audio/video // config has change and we need some time to finish initialization if (stream_object->Append(streams_[stream_id])) break; } else { LOG_ERROR("Invalid stream index: %d", stream_id); } if (packets_.empty()) break; } } bool PacketsManager::IsEosSignalled() const { int stream_count = 0; for (auto stream : streams_) { if (stream) ++stream_count; } return eos_count_ == stream_count; } bool PacketsManager::IsEosReached() const { return packets_.empty() && IsEosSignalled(); } bool PacketsManager::UpdateBuffer( Samsung::NaClPlayer::TimeTicks playback_time) { pp::AutoLock critical_section(packets_lock_); // Determine max time we have packets for: auto buffered_time = std::numeric_limits<TimeTicks>::max(); // Upon EOS all packets needs to be flushed, so checking max time should be // skipped. if (!IsEosSignalled()) { if (streams_[kVideoStreamId] && buffered_time > buffered_packets_timestamp_[kVideoStreamId]) buffered_time = buffered_packets_timestamp_[kVideoStreamId]; if (streams_[kAudioStreamId] && buffered_time > buffered_packets_timestamp_[kAudioStreamId]) buffered_time = buffered_packets_timestamp_[kAudioStreamId]; } if (seeking_) CheckSeekEndConditions(buffered_time); if (!seeking_) AppendPackets(playback_time, buffered_time); return !packets_.empty(); } void PacketsManager::SetStream(StreamType type, StreamManager* manager) { assert(type < StreamType::MaxStreamTypes); streams_[static_cast<int32_t>(type)] = manager; }
37.300292
80
0.701032
[ "object" ]
f28a8f17d4c8e8831325db13734c8125d6a66d76
2,007
cc
C++
src/decoder_cli.cc
UFAL-DSG/pykaldi2
511ae88bd2fa2e8e08cada7101795498904c3ca4
[ "Apache-2.0" ]
54
2015-11-19T08:24:01.000Z
2021-09-19T08:21:57.000Z
src/decoder_cli.cc
UFAL-DSG/pykaldi2
511ae88bd2fa2e8e08cada7101795498904c3ca4
[ "Apache-2.0" ]
4
2016-05-17T15:55:13.000Z
2019-12-25T13:14:47.000Z
src/decoder_cli.cc
UFAL-DSG/pykaldi2
511ae88bd2fa2e8e08cada7101795498904c3ca4
[ "Apache-2.0" ]
27
2015-11-25T07:37:51.000Z
2021-01-14T09:32:25.000Z
// // Created by zilka on 11/4/15. // #include <fstream> #include "feat/wave-reader.h" #include "src/decoder.h" using namespace kaldi; using namespace alex_asr; int main(int argc, const char* const* argv) { Decoder * decoder = new Decoder(argv[2]); WaveData wave_data; std::filebuf fb; if (fb.open (argv[1], std::ios::in)) { std::istream is(&fb); wave_data.Read(is); fb.close(); } KALDI_LOG << "Initialized."; // int32 num_chan = wave_data.Data().NumRows(), this_chan = 0; // if(this_chan != num_chan -1) // KALDI_ERR << "Wave should have only one channel"; SubVector<BaseFloat> waveform(wave_data.Data(), 0); for(int k = 0; k < 1; k++) { decoder->Reset(); int32 decoded_frames = 0; int32 decoded_now = 0; int32 max_decoded = 10; decoder->FrameIn(&waveform); decoder->InputFinished(); vector<int> words; float32 prob; do { decoded_frames += decoded_now; decoded_now = decoder->Decode(max_decoded); decoder->GetBestPath(&words, &prob); //vector<float> ivector; //decoder->GetIvector(&ivector); // std::cout << "trail_sil " << decoder->TrailingSilenceLength() << " "; // std::cout << "fin_cost " << decoder->FinalRelativeCost() << " "; // std::cout << "dec_frames " << decoder->NumFramesDecoded() << " "; std::cout << decoded_now << " hyp: "; for (int32 i = 0; i < words.size(); i++) { std::string s = decoder->GetWord(words[i]); std::cout << s << ' '; } // std::cout << " | Ivector: "; // for(int32 i = 0; i < ivector.size(); i++) { // std::cout << ivector[i] << " "; // } std::cout << std::endl; } while (decoded_now > 0); decoder->FinalizeDecoding(); } std::cerr << "Done."; return 0; }
24.180723
83
0.511211
[ "vector" ]
f28b510015099db1396bde73aeff32517480c646
1,683
hpp
C++
game/tools/guieditor/source/timelinewidget.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/tools/guieditor/source/timelinewidget.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/tools/guieditor/source/timelinewidget.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
#ifndef TIMELINE_WIDGET_HPP #define TIMELINE_WIDGET_HPP ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include <wx/wx.h> #include <vector> ////////////////////////////////////////////////////// // FORWARD DECLARATION ////////////////////////////////////////////////////// class GuiEditor; ////////////////////////////////////////////////////// // CONSTANTS ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////// class TimeLineWidget : public wxPanel { public: TimeLineWidget( wxWindow *parent, wxWindowID winid = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL | wxNO_BORDER, const wxString& name = wxPanelNameStr ); TimeLineWidget( wxPanel* parent, int id ); void SetGuiEditor( GuiEditor* guiEditor ) { mGuiEditor = guiEditor; } void AddKeyFrame( int keyFrame ); void ClearKeyFrames(); void SetAnimationLength( int length ); void OnSize( wxSizeEvent &event ); void OnPaint( wxPaintEvent &event ); void OnLeftDown( wxMouseEvent &event ); void OnLeftUp( wxMouseEvent &event ); void OnMove( wxMouseEvent &event ); void OnRightDown( wxMouseEvent &event ); int GetCurrentFrame() const; void SetCurrentFrame( int frame ); private: void SetCurrentFrameByPos( float xPos ); int FindClosestKeyFrame( float value ); std::vector<float> mKeyFrames; int mSelectedIndex; int mAnimationLength; int mCurrentFrame; bool mLeftMouseButtonDown; GuiEditor* mGuiEditor; }; #endif
22.743243
54
0.549614
[ "vector" ]
f28bf2fe0bde1f916f7628715e637706bae79c5a
1,164
cpp
C++
main.cpp
RomoAlamN/Chem2Json
c14dc732b78f4f9bfbba4ef93fb61ae72edf6649
[ "MIT" ]
null
null
null
main.cpp
RomoAlamN/Chem2Json
c14dc732b78f4f9bfbba4ef93fb61ae72edf6649
[ "MIT" ]
null
null
null
main.cpp
RomoAlamN/Chem2Json
c14dc732b78f4f9bfbba4ef93fb61ae72edf6649
[ "MIT" ]
null
null
null
// // Created by intermis on 10/2/18. // #include "include/CLI11.hpp" #include "stringUtils.hpp" #include "chemParser.hpp" #include "jsonWriter.hpp" int main(int argc, char *argv[]) { if (!(argc == 2 && !StringUtils::startsWith(argv[1], "-"))) { CLI::App app{"Converts .chem to .json"}; std::string files = "none.err"; app.add_option("-f,--files", files, "Comma separated list of .chem files to convert") ->required(true); CLI11_PARSE(app, argc, argv) std::vector<std::string> filesVector; StringUtils::split(filesVector, files, ','); for (const auto &file : filesVector) { ChemParser parser; // ChemWriter writer; std::cout << "Parsing : " << file << std::endl; parser.parse(file); JsonWriter writer; writer.generate(parser); writer.write(); } } else { std::cout << "Parsing : " << argv[1] << std::endl; ChemParser parser; parser.parse(argv[1]); JsonWriter writer; writer.generate(parser); writer.write(); } }
27.714286
79
0.534364
[ "vector" ]
f28e2ba14504d38c06bb772243f56f7636cbfa7e
1,508
hpp
C++
src/common/vector.hpp
ngc92/branchedflowsim
d38c0e7f892d07d0abd9b63d30570c41b3b83b34
[ "MIT" ]
null
null
null
src/common/vector.hpp
ngc92/branchedflowsim
d38c0e7f892d07d0abd9b63d30570c41b3b83b34
[ "MIT" ]
null
null
null
src/common/vector.hpp
ngc92/branchedflowsim
d38c0e7f892d07d0abd9b63d30570c41b3b83b34
[ "MIT" ]
null
null
null
#ifndef VEC2D_HPP_INCLUDED #define VEC2D_HPP_INCLUDED /*! \file vector.hpp \ingroup common \brief vector data types \details this file imports the vector data types from boost.ublas for use under less verbose type names. */ #include <cassert> #include <numeric> #include <boost/numeric/ublas/vector.hpp> //! \addtogroup common //! \{ //! vector of doubles with constant maximum length \p N template<int N> using c_vector = boost::numeric::ublas::c_vector<double, N>; /*! normal generic vector type with at most three entries. uses c_vector, i.e. preallocated space so it does not require any dynamic memory management to create these objects. */ using gen_vect = c_vector<3>; /// integer vector of at most three dimension. using int_vect = boost::numeric::ublas::c_vector<int, 3>; /// cross product function, very ugly, not generic or easy to use. /// \todo should be removed or significantly improved. template<class Result, class Vector> void crossProduct( Result& target, const Vector& v1, const Vector& v2) { assert( target.size() == 3 ); assert( v1.size() == 3); assert( v2.size() == 3 ); target[0] = v1[1]*v2[2] - v1[2]*v2[1]; target[1] = -v1[0]*v2[2] + v1[2]*v2[0]; target[2] = v1[0]*v2[1] - v1[1]*v2[0]; } template<class Vec1, class Vec2> double dotProduct(Vec1&& v1, Vec2&& v2) { using std::begin; using std::end; return std::inner_product(begin(v1), end(v1), begin(v2), 0.0); } //! \} #endif // VEC2D_HPP_INCLUDED
26.928571
96
0.671751
[ "vector" ]
f2901cfb47a747164345d6cd25a21fa06730eea9
18,176
cpp
C++
io/applications/io-buffer.cpp
3DTK/comma
a6b3173ae8cd9a28108d5b2c2c683f2b15525f60
[ "BSD-3-Clause" ]
21
2015-05-07T06:11:09.000Z
2022-02-01T09:55:46.000Z
io/applications/io-buffer.cpp
3DTK/comma
a6b3173ae8cd9a28108d5b2c2c683f2b15525f60
[ "BSD-3-Clause" ]
17
2015-01-16T01:38:08.000Z
2020-03-30T09:05:01.000Z
io/applications/io-buffer.cpp
3DTK/comma
a6b3173ae8cd9a28108d5b2c2c683f2b15525f60
[ "BSD-3-Clause" ]
13
2016-01-13T01:29:29.000Z
2022-02-01T09:55:49.000Z
// This file is part of comma, a generic and flexible library // Copyright (c) 2011 The University of Sydney // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// @author dewey nguyen #ifndef WIN32 #include <sysexits.h> #include <stdlib.h> #include <sys/ioctl.h> #endif #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <iostream> #include <cctype> #include <vector> #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/algorithm/string.hpp> #include "../../application/command_line_options.h" #include "../../application/contact_info.h" #include "../../base/exception.h" #include "../../base/types.h" #include "../../io/stream.h" #include "../../io/select.h" #include "../../string/string.h" #include "../../csv/stream.h" void usage( bool verbose = false ) { std::cerr << std::endl; std::cerr << "buffer stdin data to synchronised output data to stdout using a file lock" << std::endl; std::cerr << std::endl; std::cerr << "usage: io-buffer <in|out> --lock-file <file> [--size <size>] [--lines <num>] --buffer-size <size>" << std::endl; std::cerr << std::endl; std::cerr << "options" << std::endl; std::cerr << " * --lock-file,--lock=: an exiting or new filepath to be used as a file lock, content will be truncated if it exists." << std::endl; std::cerr << " --lines,-n=[<num>]: for line based text input data, buffers number of lines before attempting to write to stdout, default is 1" << std::endl; std::cerr << " --size,-s=[<bytes>]: for binary input data, where each message is of size x in bytes" << std::endl; std::cerr << " --buffer-size,-b=[<size>]: for binary input data, binary storage to store multiple of x sized messages." << std::endl; std::cerr << " see --size and buffer size suffixes below." << std::endl; std::cerr << " if not specified, no buffering of binary messages, each is written to stdout." << std::endl; std::cerr << " --strict; use with 'in' operation, exits with an error if a full message size (binary) is not found" << std::endl; std::cerr << std::endl; std::cerr << "operations" << std::endl; std::cerr << " out: read in standard input, attempt to write to stdout when buffer is full." << std::endl; std::cerr << " in: read in standard input, if buffer is full then write to standard output and exits" << std::endl; std::cerr << std::endl; std::cerr << std::endl; std::cerr << "<buffer size suffixes>" << std::endl; std::cerr << " Mb: megabytes e.g. 5Mb" << std::endl; std::cerr << " Kb: kilobytes e.g. 10Kb" << std::endl; std::cerr << " no suffix: bytes e.g. 256" << std::endl; std::cerr << std::endl; std::cerr << "supported address types: tcp, udp, local (unix) sockets, named pipes, files, zmq (todo)" << std::endl; std::cerr << std::endl; std::cerr << "examples" << std::endl; std::cerr << std::endl; std::cerr << "out operation" << std::endl; std::cerr << " text based input" << std::endl; std::cerr << " io-buffer out --lock-file=/tmp/lockfile " << std::endl; std::cerr << " Read each input line and write to standard output, no buffering" << std::endl; std::cerr << " io-buffer out --lock-file=/tmp/lockfile --lines=3" << std::endl; std::cerr << " Read each input line into the buffer that can store up to 3 lines" << std::endl; std::cerr << std::endl; std::cerr << " binary input" << std::endl; std::cerr << " io-buffer out --lock-file=/tmp/lockfile --size 512 " << std::endl; std::cerr << " Read each input message of 512 bytes and writes to standard output, no buffering" << std::endl; std::cerr << " io-buffer out --lock-file=/tmp/lockfile --size 512 --buffer-size 10kb " << std::endl; std::cerr << " Read each input message of 512 bytes and saves into 10Kb buffer (20 messages maximum). If buffer is full, output buffer." << std::endl; std::cerr << "in operation" << std::endl; std::cerr << " See 'out' operation, in this mode, the program write to standard output and exits when buffer is full." << std::endl; std::cerr << " Call io-buffer multiple times to read more input data." << std::endl; std::cerr << std::endl; std::cerr << comma::contact_info << std::endl; std::cerr << std::endl; exit( 0 ); } const char* name() { return "io-buffer: "; } typedef boost::optional< std::vector< std::string > > lines_buffer_type; typedef std::vector< char > char_buffer_t; typedef boost::optional< char_buffer_t > binary_buffer_type; lines_buffer_type lines_buffer; binary_buffer_type binary_buffer; static bool verbose = false; static comma::uint64 get_buffer_size( const std::string& str ) { std::string type; std::string digits; // Get size type, todo use something smarter for( std::size_t i=0; i<str.size(); ++i) { if( std::isdigit(str[i]) ) { digits += str[i]; } else { type = str.substr( i ); break; } } // std::cerr << "digits: " << digits << " type: " << type << std::endl; comma::uint64 bytes = 0; try { bytes = boost::lexical_cast< comma::uint64 >( digits ); } catch(...) { COMMA_THROW( comma::exception, "failed to parse buffer size: " << str ); } if( type.empty() ){ } else if ( boost::iequals(type, "mb") ) { bytes *= 1024000; } else if ( boost::iequals(type, "kb") ) { bytes *= 1024; } else { std::cerr << name() << "failed to parse buffer size argument: '" << str << "', please see --help" << std::endl; } return bytes; } using boost::interprocess::file_lock; using boost::interprocess::scoped_lock; static bool strict = false; static void output_binary( file_lock& lock ) { scoped_lock< file_lock > filelock( lock ); // Blocks until it has the lock std::cout.write( &(binary_buffer.get()[0]), binary_buffer->size() ); } static void output_text( file_lock& lock ) { scoped_lock< file_lock > filelock( lock ); // Blocks until it has the lock for( std::size_t i=0; i<lines_buffer->size(); ++i ) { std::cout << lines_buffer.get()[i] << std::endl; } } /// Because we need to use C code for IO input operations // This structure help manage the C code, memory allocation and de-allocation // ::getline() may actually re-allocate the buffer given to increase the size struct memory_buffer { char* buffer; size_t size; memory_buffer(); memory_buffer( size_t size ) { allocate( size ); } ~memory_buffer(); void allocate( size_t size ); // if strict is true, fails when less data then expected is received comma::uint32 read_binary_records( comma::uint32 size, comma::uint32 num_record=1, bool strict=false ); }; memory_buffer::memory_buffer() : buffer(NULL), size(0) {} memory_buffer::~memory_buffer() { if( buffer != NULL ) { free( (void*) buffer ); } } void memory_buffer::allocate(size_t size) { this->size = size; buffer = (char*) ::malloc( size ); if( buffer == NULL ) { std::cerr << name() << "failed to allocate memory buffer of size: " << size << std::endl; exit(1); } } comma::uint32 memory_buffer::read_binary_records( comma::uint32 size, comma::uint32 num_record, bool strict ) { static comma::uint32 one_record_size = size; comma::uint32 bytes_to_read = one_record_size * num_record; size_t bytes_read = 0; while ( bytes_read < bytes_to_read && !::feof( stdin ) && !::ferror(stdin) ) { bytes_read += ::fread( &buffer[bytes_read], 1, bytes_to_read - bytes_read, stdin ); } if ( bytes_read <= 0 ) { return bytes_read; } // signals end of stream, not an error if( bytes_read % one_record_size != 0 ) { std::cerr << name() << "expected " << one_record_size << " bytes, got only read: " << ( bytes_read % one_record_size ) << std::endl; exit( 1 ); } if ( strict && (bytes_read < bytes_to_read) ) { std::cerr << name() << "expected " << bytes_to_read << " bytes (" << ( bytes_to_read / one_record_size ) << " records); got only: " << bytes_read << " bytes (" << ( bytes_read / one_record_size ) << " records)" << std::endl; exit( 1 ); } return bytes_read; } int main( int argc, char** argv ) { try { if( argc < 2 ) { usage(); } comma::command_line_options options( argc, argv, usage ); comma::uint32 lines_num = options.value( "--lines,-n", 1 ); std::string lockfile_path = options.value< std::string >( "--lock-file,--lock" ); boost::optional< comma::uint32 > has_size = options.optional< comma::uint32 >( "--size,s" ); boost::optional< std::string > buffer_size_string = options.optional< std::string >( "--buffer-size,-b" ); const std::vector< std::string >& operation = options.unnamed( "--help,-h,--verbose,-v,--strict", "-.+" ); strict = options.exists("--strict"); verbose = options.value( "--verbose,-v", false ); if( verbose ) { std::cerr << name() << ": called as: " << options.string() << std::endl; } #ifdef WIN32 if( has_size || operation.size() == 1 ) { _setmode( _fileno( stdout ), _O_BINARY ); } #endif if( operation.empty() ) { std::cerr << "io-buffer: please specify operation" << std::endl; return 1; } else if ( operation.front() == "out" ){ } else if ( operation.front() == "in" ) { #ifdef WIN32 std::cerr << "io-buffer: 'in' operation not implemented on windows" << std::endl; return 1; #endif // #ifdef WIN32 } else { std::cerr << "unknown operation found: " << operation.front() << std::endl; return 1; } if( options.exists("--lines,-n") && options.exists("--size,-s") ) { std::cerr << name() << " option --lines(|-n) is not compatible with --size(|-s)." << std::endl; return 1; } bool output_last = options.exists("--no-last"); comma::uint32 message_size = 0; comma::uint64 buffer_size = 0; if( has_size ) { if( buffer_size_string ){ buffer_size = get_buffer_size( buffer_size_string.get() ); } else { buffer_size = has_size.get(); } message_size = has_size.get(); if( message_size == 0 ) { std::cerr << "io-buffer: message size cannot be zero" << std::endl; return 1; } if( message_size > buffer_size ) { std::cerr << "io-buffer: buffer size cannot be smaller than message size." << std::endl; return 1; } // make buffer size a multiple of message_size buffer_size = buffer_size - ( buffer_size % message_size ); if( verbose) { std::cerr << "io-buffer: create binary buffer of size " << buffer_size << '(' << comma::uint32(buffer_size / message_size) << " messages)" << std::endl; } } // Check the lockfile can be opened and truncated { std::ofstream lockfile( lockfile_path.c_str(), std::ios::trunc | std::ios::out ); if( !lockfile.is_open() ) { std::cerr << name() << "failed to open lockfile: " << lockfile_path << std::endl; return 1; } lockfile.close(); } file_lock lock( lockfile_path.c_str() ); // Note lock file must exists or an exception with crytic message is thrown if( operation.front() == "in" ) { // Everything IO in this code block must use C function, because we turn stdin buffering off ::setvbuf( stdin, (char *)NULL, _IONBF, 0 ); // stdin kernel buffering is off /// Reading data from standard input is guarded by file lock { scoped_lock< file_lock > filelock(lock); if( has_size ) { memory_buffer memory(message_size); while( !::feof( stdin ) && !::ferror(stdin) ) { // Read one message comma::uint32 bytes = memory.read_binary_records( message_size, 1, strict ); if( bytes == 0 ) { break; } // Put message into buffer binary_buffer->insert( binary_buffer->end(), memory.buffer, memory.buffer + memory.size ); // can't use emplace_back // if buffer is filled if( binary_buffer->size() >= buffer_size ) { break; } } } else { static const comma::uint32 max_size = 1024; while( true ) { memory_buffer memory( max_size ); std::stringstream sstream; bool has_end_of_line = false; bool has_data = false; while( !has_end_of_line && !::feof(stdin) ) { // getline may actually changes the buffer with realloc and extend the size ssize_t bytes_read = ::getline( &memory.buffer, &memory.size, stdin ); if ( bytes_read <= 0 ) { break; } // we are done, end of stream has_data = true; #ifndef WIN32 has_end_of_line = ( memory.buffer[bytes_read-1] == '\n' ); sstream.write( memory.buffer, has_end_of_line ? bytes_read-1 : bytes_read ); #else has_end_of_line = ( bytes_read > 1 && memory.buffer[bytes_read-2] == '\r' && memory.buffer[bytes_read-1] == '\n' ); sstream.write( memory.buffer, has_end_of_line ? bytes_read-2 : bytes_read ); #endif } if( !has_data ) { break; } lines_buffer->push_back( sstream.str() ); // if buffer is filled if( lines_buffer->size() >= lines_num ) { break; } } } } /// Output side is not guarded by file lock if( has_size && !binary_buffer->empty() ) { std::cout.write( &(binary_buffer.get()[0]), binary_buffer->size() ); return 0; } else { if( !lines_buffer->empty() ) { for( std::size_t i=0; i<lines_buffer->size(); ++i ) { std::cout << lines_buffer.get()[i] << std::endl; } return 0; } else { exit( EX_NOINPUT ); } } } else { if( has_size ) { binary_buffer = char_buffer_t(); binary_buffer->reserve( buffer_size ); while( true ) { char_buffer_t message( message_size ); std::cin.read( &message[0], message_size ); if( !std::cin.good() || std::cin.eof() ) { break; } binary_buffer->insert( binary_buffer->end(), message.begin(), message.end() ); // can't use emplace_back // If buffer is filled if( binary_buffer->size() >= buffer_size ) { output_binary(lock); binary_buffer->clear(); } } if( !binary_buffer->empty() ) { output_binary(lock); } } else { lines_buffer = std::vector< std::string >(); lines_buffer->reserve( lines_num ); while( std::cin.good() && !std::cin.eof() ) { std::string line; std::getline( std::cin, line ); if( !line.empty() ) { lines_buffer->push_back( line ); } // If buffer is filled if( lines_buffer->size() >= lines_num ) { output_text(lock); lines_buffer->clear(); } } if( !output_last && !lines_buffer->empty() ) { output_text(lock); } } } return 0; } catch( std::exception& ex ) { std::cerr << "io-buffer: " << ex.what() << std::endl; } catch( ... ) { std::cerr << "io-buffer: unknown exception" << std::endl; } return 1; }
49.391304
291
0.569982
[ "vector" ]
f293f174ad6fbd9e735955ca451e3d35da143925
798
cpp
C++
solutions/LeetCode/C++/651.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/651.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/651.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ class Solution { public: int maxA(int N) { int res = N; for (int i = 1; i < N - 2; ++i) { res = max(res, maxA(i) * (N - 1 - i)); } return res; } }; __________________________________________________________________________________________________ class Solution { public: int maxA(int N) { vector<int> dp(N + 1, 0); for (int i = 0; i <= N; ++i) { dp[i] = i; for (int j = 1; j < i - 2; ++j) { dp[i] = max(dp[i], dp[j] * (i - j - 1)); } } return dp[N]; } }; __________________________________________________________________________________________________
29.555556
98
0.581454
[ "vector" ]
f29bfc9a7e66a87bfb9bc6dc6219e35f8128859e
637
hpp
C++
include/PiFinders.hpp
echo-Mike/SARW-UEFITreeBuilder
e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6
[ "MIT" ]
null
null
null
include/PiFinders.hpp
echo-Mike/SARW-UEFITreeBuilder
e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6
[ "MIT" ]
null
null
null
include/PiFinders.hpp
echo-Mike/SARW-UEFITreeBuilder
e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6
[ "MIT" ]
null
null
null
#pragma once #ifndef PI_FINDERS_HPP__ #define PI_FINDERS_HPP__ "0.0.0@PiFinders.hpp" /// STD #include <vector> /// PROJECT #include "General.hpp" #include "PiViews.hpp" namespace Project { namespace Finders { /// Header vectors typedef std::vector< Pi::Section::Header > SectionsVec_t; typedef std::vector< Pi::File::Header > FilesVec_t; typedef std::vector< Pi::Volume::Header > VolumesVec_t; /// Finder functions SectionsVec_t SectionFinder(const MemoryView& buffer); FilesVec_t FileFinder(const MemoryView& buffer, Types::byte_t empty); VolumesVec_t VolumeFinder(const MemoryView& buffer); } } #endif
16.763158
71
0.728414
[ "vector" ]
f29c0cc0871b4e92e14bad4461c1ce6e088f25e1
6,744
cpp
C++
Modules/OpenGL/Private/OpenGLGraphicsDriver.cpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
2
2021-01-28T03:08:08.000Z
2021-01-28T03:08:21.000Z
Modules/OpenGL/Private/OpenGLGraphicsDriver.cpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
null
null
null
Modules/OpenGL/Private/OpenGLGraphicsDriver.cpp
benjinx/Toon
f21032b2f9ad5fbc9a3618a7719c33159257d954
[ "MIT" ]
null
null
null
#include <Toon/OpenGL/OpenGLGraphicsDriver.hpp> #include <Toon/Toon.hpp> #include <Toon/Log.hpp> #include <Toon/Scene.hpp> namespace Toon::OpenGL { TOON_OPENGL_API bool OpenGLGraphicsDriver::Initialize() { if (!SDL2GraphicsDriver::Initialize()) { return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, GL_TRUE); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); #if defined(TOON_BUILD_DEBUG) SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif if (!SDL2GraphicsDriver::CreateWindow(SDL_WINDOW_OPENGL)) { return false; } _glContext = SDL_GL_CreateContext(GetSDL2Window()); if (!_glContext) { ToonLogError("Failed to create OpenGL context, %s", SDL_GetError()); return false; } if (!gladLoadGL((GLADloadfunc) SDL_GL_GetProcAddress)) { ToonLogError("Failed to initialize OpenGL context"); return false; } #if defined(TOON_BUILD_DEBUG) InitDebugMessageCallback(); #endif SDL_GL_SetSwapInterval(0); ToonLogVerbose("OpenGL Version: %s", glGetString(GL_VERSION)); ToonLogVerbose("GLSL Version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); ToonLogVerbose("OpenGL Vendor: %s", glGetString(GL_VENDOR)); ToonLogVerbose("OpenGL Renderer: %s", glGetString(GL_RENDERER)); int value = 0; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &value); ToonLogVerbose("Max Vertex Attributes: %d", value); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &value); ToonLogVerbose("Max Vertex Uniform Components: %d", value); glGetIntegerv(GL_MAX_VERTEX_OUTPUT_COMPONENTS, &value); ToonLogVerbose("Max Vertex Output Components: %d", value); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &value); ToonLogVerbose("Max Fragment Uniform Components: %d", value); glGetIntegerv(GL_MAX_FRAGMENT_INPUT_COMPONENTS, &value); ToonLogVerbose("Max Fragment Input Components: %d", value); glGetIntegerv(GL_MAX_DRAW_BUFFERS, &value); ToonLogVerbose("Max Draw Buffers: %d", value); glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &value); ToonLogVerbose("Max Fragment Texture Image Units: %d", value); glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &value); ToonLogVerbose("Max Vertex Texture Image Units: %d", value); glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &value); ToonLogVerbose("Max Uniform Buffer Bindings: %d", value); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &value); ToonLogVerbose("Max Vertex Uniform Blocks: %d", value); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &value); ToonLogVerbose("Max Fragment Uniform Blocks: %d", value); glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &value); ToonLogVerbose("Max Uniform Block Size: %d", value); InitializeUpdateContext(); InitializeRenderContext(); if (!InitializeConstantBuffers()) { return false; } if (!InitializeDefaults()) { return false; } return true; } TOON_OPENGL_API void OpenGLGraphicsDriver::Terminate() { if (_glContext) { SDL_GL_DeleteContext(_glContext); _glContext = nullptr; } SDL2GraphicsDriver::Terminate(); } TOON_OPENGL_API void OpenGLGraphicsDriver::Render() { glm::vec4 cc = GetClearColor(); glClearColor(cc[0], cc[1], cc[2], cc[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GraphicsDriver::Render(); uint8_t * data = reinterpret_cast<uint8_t *>(_renderContext->GetShaderGlobals()); _shaderGlobalsBuffer->WriteTo(0, sizeof(ShaderGlobals), data); OpenGLBuffer * glGlobalsBuffer = TOON_OPENGL_BUFFER(_shaderGlobalsBuffer.get()); glBindBufferBase(GL_UNIFORM_BUFFER, TOON_SHADER_GLOBALS_BINDING, glGlobalsBuffer->GetGLID()); Scene * scene = GetCurrentScene(); if (scene) { scene->Render(_renderContext.get()); } SDL_GL_SwapWindow(GetSDL2Window()); } TOON_OPENGL_API std::shared_ptr<Buffer> OpenGLGraphicsDriver::CreateBuffer() { return std::shared_ptr<Buffer>(new OpenGLBuffer()); } TOON_OPENGL_API std::shared_ptr<Pipeline> OpenGLGraphicsDriver::CreatePipeline(std::shared_ptr<Shader> shader) { auto ptr = std::shared_ptr<Pipeline>(new OpenGLPipeline()); ptr->SetShader(shader); return ptr; } TOON_OPENGL_API std::shared_ptr<Texture> OpenGLGraphicsDriver::CreateTexture() { return std::shared_ptr<Texture>(new OpenGLTexture()); } TOON_OPENGL_API std::shared_ptr<Shader> OpenGLGraphicsDriver::CreateShader() { auto shader = std::shared_ptr<Shader>(new OpenGLShader()); _shaderList.push_back(shader); return shader; } TOON_OPENGL_API std::shared_ptr<Mesh> OpenGLGraphicsDriver::CreateMesh() { auto ptr = std::shared_ptr<Mesh>(new OpenGLMesh()); ptr->Initialize(); return ptr; } TOON_OPENGL_API std::shared_ptr<Material> OpenGLGraphicsDriver::CreateMaterial() { return std::shared_ptr<Material>(new OpenGLMaterial()); } TOON_OPENGL_API std::shared_ptr<Primitive> OpenGLGraphicsDriver::CreatePrimitive() { return std::shared_ptr<Primitive>(new OpenGLPrimitive()); } void GLAPIENTRY _OpenGLDebugMessageCallback( GLenum source, GLenum type, GLenum id, GLenum severity, GLsizei length, const GLchar * message, const void * userData) { if (type == GL_DEBUG_TYPE_PERFORMANCE) { Log(LogLevel::Performance, "[PERF](OpenGLDebugMessage) %s\n", message); } else { switch (severity) { case GL_DEBUG_SEVERITY_HIGH: case GL_DEBUG_SEVERITY_MEDIUM: Log(LogLevel::Error, "[ERRO](OpenGLDebugMessage) %s\n", message); break; case GL_DEBUG_SEVERITY_LOW: Log(LogLevel::Warning, "[WARN](OpenGLDebugMessage) %s\n", message); break; #if defined(TOON_BUILD_DEBUG) case GL_DEBUG_SEVERITY_NOTIFICATION: //if (IsVerboseLoggingEnabled()) { Log(LogLevel::Verbose, "[VERB](OpenGLDebugMessage) %s\n", message); //} break; #endif } } } TOON_OPENGL_API void OpenGLGraphicsDriver::InitDebugMessageCallback() { glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(_OpenGLDebugMessageCallback, nullptr); } } // namespace Toon::OpenGL
28.697872
97
0.70952
[ "mesh", "render" ]
f29d1054442074b7fe935edea716bb7e7e520ffe
3,048
cpp
C++
src/execution/operator/schema/physical_create_edge.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-08-30T16:08:17.000Z
2021-08-30T16:08:17.000Z
src/execution/operator/schema/physical_create_edge.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
1
2021-12-12T03:36:02.000Z
2021-12-12T03:36:02.000Z
src/execution/operator/schema/physical_create_edge.cpp
graindb/graindb-demonstration
be901b3e66fc991ea3ecfbcfabdcd07af82dd2d7
[ "MIT" ]
null
null
null
#include "duckdb/execution/operator/schema/physical_create_edge.hpp" #include "duckdb/catalog/catalog_entry/edge_catalog_entry.hpp" #include "duckdb/execution/index/rai/rel_adj_index.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/storage/storage_lock.hpp" using namespace duckdb; using namespace std; void PhysicalCreateEdge::GetChunkInternal(ClientContext &context, DataChunk &chunk, PhysicalOperatorState *state, SelectionVector *sel, Vector *rid_vector, DataChunk *rai_chunk) { assert(children.size() == 1); // Create edge catalog entry auto edge_entry = reinterpret_cast<EdgeCatalogEntry *>(info->schema->CreateEdge(context, info.get())); edge_entry->edge_table->correlated_edges.push_back(edge_entry); auto edge_table_name = edge_entry->edge_table->name; // Alter edge table to append join index columns vector<idx_t> join_index_column_ids(info->reference_column_ids.size()); auto isAdded = edge_entry->edge_table->AddJoinIndexColumns(info->reference_column_ids, join_index_column_ids); // Build join column index idx_t count = 0; vector<unique_ptr<ColumnAppendState>> append_states(join_index_column_ids.size()); // Initialize append states for (auto i = 0u; i < join_index_column_ids.size(); i++) { if (!isAdded[i]) { continue; } append_states[i] = make_unique<ColumnAppendState>(); edge_entry->edge_table->storage->GetColumn(join_index_column_ids[i])->InitializeAppend(*append_states[i]); } // Perform appending while (true) { children[0]->GetChunk(context, state->child_chunk, state->child_state.get()); idx_t chunk_count = state->child_chunk.size(); if (chunk_count == 0) { break; } for (auto i = 0u; i < join_index_column_ids.size(); i++) { // Join index column already exists. Skip appending it. if (!isAdded[i]) { continue; } edge_entry->edge_table->storage->GetColumn(join_index_column_ids[i]) ->Append(*append_states[i], state->child_chunk.data[i], chunk_count); } count += chunk_count; } // Release locke for (auto &append_state : append_states) { append_state.reset(); } // Build rai index vector<unique_ptr<Expression>> unbound_expressions(join_index_column_ids.size()); vector<unique_ptr<Expression>> index_expressions(join_index_column_ids.size()); for (auto i = 0u; i < join_index_column_ids.size(); i++) { auto column_ref_expression = make_unique<BoundReferenceExpression>(TypeId::INT64, i); unbound_expressions[i] = column_ref_expression->Copy(); index_expressions[i] = move(column_ref_expression); } auto rai_index = make_unique<RelAdjIndex>(edge_entry->name, join_index_column_ids, move(unbound_expressions), edge_entry->edge_direction, true /* keep edges */); edge_entry->rai_index = rai_index.get(); edge_entry->edge_table->storage->AddIndex(move(rai_index), index_expressions); // Return num of tuples appended as the result chunk.SetCardinality(1); chunk.SetValue(0, 0, Value::BIGINT(count)); state->finished = true; }
41.189189
113
0.734252
[ "vector" ]