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
174354a15aa415021dcea74908c9a0b8062e6a3c
8,426
cpp
C++
libs/vm-modules/benchmark/tensor/tensor.cpp
marcuswin/ledger
b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2
[ "Apache-2.0" ]
1
2019-09-11T09:46:04.000Z
2019-09-11T09:46:04.000Z
libs/vm-modules/benchmark/tensor/tensor.cpp
marcuswin/ledger
b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2
[ "Apache-2.0" ]
null
null
null
libs/vm-modules/benchmark/tensor/tensor.cpp
marcuswin/ledger
b79c5c4e7e92ff02ea4328fcc0885bf8ded2b8b2
[ "Apache-2.0" ]
1
2019-09-19T12:38:46.000Z
2019-09-19T12:38:46.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "math/tensor.hpp" #include "vectorise/fixed_point/fixed_point.hpp" #include "vm_modules/math/tensor/tensor.hpp" #include "vm_modules/ml/model/model.hpp" #include "vm_modules/ml/model/model_estimator.hpp" #include "vm_modules/vm_factory.hpp" #include "gmock/gmock.h" #include <sstream> #include "benchmark/benchmark.h" #include <vector> using namespace fetch::vm; namespace vm_modules { namespace benchmark { namespace ml { namespace tensor { void SetUp(std::shared_ptr<VM> &vm) { using VMFactory = fetch::vm_modules::VMFactory; // setup the VM auto module = VMFactory::GetModule(fetch::vm_modules::VMFactory::USE_ALL); vm = std::make_shared<VM>(module.get()); } Ptr<String> CreateString(std::shared_ptr<VM> &vm, std::string const &str) { return Ptr<String>{new String{vm.get(), str}}; } Ptr<Array<uint64_t>> CreateArray(std::shared_ptr<VM> &vm, std::vector<uint64_t> const &values) { std::size_t size = values.size(); Ptr<Array<uint64_t>> array = vm->CreateNewObject<Array<uint64_t>>(vm->GetTypeId<uint64_t>(), static_cast<int32_t>(size)); for (std::size_t i{0}; i < size; ++i) { array->elements[i] = values[i]; } return array; } Ptr<fetch::vm_modules::math::VMTensor> CreateTensor(std::shared_ptr<VM> & vm, std::vector<uint64_t> const &shape) { return vm->CreateNewObject<fetch::vm_modules::math::VMTensor>(shape); } void BM_Construct(::benchmark::State &state) { using VMPtr = std::shared_ptr<VM>; using SizeType = fetch::math::SizeType; using SizeVector = std::vector<SizeType>; SizeVector shape{}; auto elements = static_cast<SizeType>(state.range(0)); for (SizeType i{1}; i < elements + 1; i++) { shape.push_back(static_cast<SizeType>(state.range(i))); } state.counters["PaddedSize"] = static_cast<double>(fetch::math::Tensor<float>::PaddedSizeFromShape(shape)); for (auto _ : state) { state.PauseTiming(); VMPtr vm; SetUp(vm); state.ResumeTiming(); auto data = CreateTensor(vm, shape); } } BENCHMARK(BM_Construct)->Args({1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({2, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({2, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 100000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 100000, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 100000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 100000, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 100000, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 100000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 1, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 1, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 100000, 1, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 1, 100000, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 1, 1, 100000, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 1, 1, 1, 100000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 1, 1, 1, 1, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({6, 1, 1, 1, 1, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 100000, 1, 1, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 100000, 1, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 1, 100000, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 1, 1, 100000, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 1, 1, 1, 100000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 1, 1, 1, 1, 100000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({7, 1, 1, 1, 1, 1, 1, 100000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 10000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1000, 10000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000000, 1, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000000, 1000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1, 1000000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1000000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000000000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 10000000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1, 10000000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1, 1000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1000, 1, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1000, 1, 1, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1000, 1, 1000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1000, 1000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1000, 1, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({4, 1, 1000, 1000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({2, 1000000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({2, 1, 1000000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1000000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1, 1000000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1, 1000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1000, 1000})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({3, 1000, 1000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1000000, 1, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1000000, 1, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 1000000, 1, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 1, 1000000, 1})->Unit(::benchmark::kMicrosecond); BENCHMARK(BM_Construct)->Args({5, 1, 1, 1, 1, 1000000})->Unit(::benchmark::kMicrosecond); } // namespace tensor } // namespace ml } // namespace benchmark } // namespace vm_modules
46.296703
99
0.676596
[ "shape", "vector", "model" ]
174b10b0c4ae5924c025e72518817129ebe0e672
9,290
cc
C++
ui/gfx/rendering_pipeline.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
ui/gfx/rendering_pipeline.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
ui/gfx/rendering_pipeline.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/rendering_pipeline.h" #include "base/containers/flat_map.h" #include "base/task/current_thread.h" #include "base/task/sequence_manager/task_time_observer.h" #include "base/thread_annotations.h" #include "base/threading/thread_checker.h" #include "ui/gfx/rendering_stage_scheduler.h" namespace gfx { namespace { class ThreadSafeTimeObserver : public base::sequence_manager::TaskTimeObserver { public: explicit ThreadSafeTimeObserver( scoped_refptr<base::SingleThreadTaskRunner> task_runner) : task_runner_(std::move(task_runner)) {} ~ThreadSafeTimeObserver() override { // If the observer is being used on the target thread, unregister now. If it // was being used on a different thread, then the target thread should have // been torn down already. SetEnabled(false); } ThreadSafeTimeObserver(const ThreadSafeTimeObserver&) = delete; ThreadSafeTimeObserver& operator=(const ThreadSafeTimeObserver&) = delete; void SetEnabled(bool enabled) { { base::AutoLock hold(time_lock_); if (enabled_ == enabled) return; enabled_ = enabled; } if (!task_runner_) return; if (task_runner_->BelongsToCurrentThread()) { UpdateOnTargetThread(enabled); return; } task_runner_->PostTask( FROM_HERE, base::BindOnce(&ThreadSafeTimeObserver::UpdateOnTargetThread, base::Unretained(this), enabled)); } base::TimeDelta GetAndResetTimeSinceLastFrame() { base::AutoLock hold(time_lock_); if (!start_time_active_task_.is_null()) { auto now = base::TimeTicks::Now(); time_since_last_frame_ += now - start_time_active_task_; start_time_active_task_ = now; } auto result = time_since_last_frame_; time_since_last_frame_ = base::TimeDelta(); return result; } // TaskTimeObserver impl. void WillProcessTask(base::TimeTicks start_time) override { base::AutoLock hold(time_lock_); if (!enabled_) return; DCHECK(start_time_active_task_.is_null()); start_time_active_task_ = start_time; } void DidProcessTask(base::TimeTicks start_time, base::TimeTicks end_time) override { base::AutoLock hold(time_lock_); if (!enabled_) { start_time_active_task_ = base::TimeTicks(); return; } // This should be null for the task which adds this object to the observer // list. if (start_time_active_task_.is_null()) return; if (start_time_active_task_ <= end_time) { time_since_last_frame_ += (end_time - start_time_active_task_); } else { // This could happen if |GetAndResetTimeSinceLastFrame| is called on a // different thread and the observed thread had to wait to acquire the // lock to call DidProcessTask. Assume the time for this task is already // recorded in |GetAndResetTimeSinceLastFrame|. DCHECK_NE(start_time_active_task_, start_time); } start_time_active_task_ = base::TimeTicks(); } private: void UpdateOnTargetThread(bool enabled) { if (enabled) { base::CurrentThread::Get().AddTaskTimeObserver(this); base::AutoLock hold(time_lock_); start_time_active_task_ = base::TimeTicks(); time_since_last_frame_ = base::TimeDelta(); } else { base::CurrentThread::Get().RemoveTaskTimeObserver(this); } } // Accessed only on the calling thread. The caller ensures no concurrent // access. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Accessed on calling and target thread. base::Lock time_lock_; bool enabled_ GUARDED_BY(time_lock_) = false; base::TimeTicks start_time_active_task_ GUARDED_BY(time_lock_); base::TimeDelta time_since_last_frame_ GUARDED_BY(time_lock_); }; } // namespace class RenderingPipelineImpl final : public RenderingPipeline { public: explicit RenderingPipelineImpl(const char* pipeline_type) : pipeline_type_(pipeline_type) { DETACH_FROM_THREAD(bound_thread_); } ~RenderingPipelineImpl() override { TearDown(); } RenderingPipelineImpl(const RenderingPipelineImpl&) = delete; RenderingPipelineImpl& operator=(const RenderingPipelineImpl&) = delete; void SetTargetDuration(base::TimeDelta target_duration) override { DCHECK_CALLED_ON_VALID_THREAD(bound_thread_); DCHECK(!target_duration.is_zero()); if (target_duration_ == target_duration) return; target_duration_ = target_duration; if (should_use_scheduler()) SetUp(); } void AddSequenceManagerThread( base::PlatformThreadId thread_id, scoped_refptr<base::SingleThreadTaskRunner> task_runner) override { base::AutoLock lock(lock_); DCHECK(time_observers_.find(thread_id) == time_observers_.end()); time_observers_[thread_id] = std::make_unique<ThreadSafeTimeObserver>(task_runner); if (scheduler_) CreateSchedulerAndEnableWithLockAcquired(); } base::sequence_manager::TaskTimeObserver* AddSimpleThread( base::PlatformThreadId thread_id) override { base::AutoLock lock(lock_); DCHECK(time_observers_.find(thread_id) == time_observers_.end()); time_observers_[thread_id] = std::make_unique<ThreadSafeTimeObserver>(nullptr); if (scheduler_) CreateSchedulerAndEnableWithLockAcquired(); return time_observers_[thread_id].get(); } void NotifyFrameFinished() override { DCHECK_CALLED_ON_VALID_THREAD(bound_thread_); base::AutoLock lock(lock_); if (!scheduler_) return; // TODO(crbug.com/1157620): This can be optimized to exclude tasks which can // be paused during rendering. The best use-case is idle tasks on the // renderer main thread. If all non-optional work is close to the frame // budget then the scheduler dynamically adjusts to pause work like idle // tasks. base::TimeDelta total_time; for (auto& it : time_observers_) { total_time += it.second->GetAndResetTimeSinceLastFrame(); } scheduler_->ReportCpuCompletionTime(total_time + gpu_latency_); } void SetGpuLatency(base::TimeDelta gpu_latency) override { DCHECK_CALLED_ON_VALID_THREAD(bound_thread_); gpu_latency_ = gpu_latency; } void UpdateActiveCount(bool active) override { DCHECK_CALLED_ON_VALID_THREAD(bound_thread_); if (active) { active_count_++; } else { DCHECK_GT(active_count_, 0); active_count_--; } if (should_use_scheduler()) { SetUp(); } else { TearDown(); } } private: bool should_use_scheduler() const { // TODO(crbug.com/1157620) : Figure out what we should be doing if multiple // independent pipelines of a type are running simultaneously. The common // use-case for this in practice would be multi-window. The tabs could be // hosted in the same renderer process and each window is composited // independently by the GPU process. return active_count_ == 1 && !target_duration_.is_zero(); } void SetUp() { base::AutoLock lock(lock_); CreateSchedulerAndEnableWithLockAcquired(); } void CreateSchedulerAndEnableWithLockAcquired() { lock_.AssertAcquired(); scheduler_.reset(); std::vector<base::PlatformThreadId> platform_threads; for (auto& it : time_observers_) { platform_threads.push_back(it.first); it.second->SetEnabled(true); } scheduler_ = RenderingStageScheduler::CreateAdpf( pipeline_type_, std::move(platform_threads), target_duration_); } void TearDown() { base::AutoLock lock(lock_); for (auto& it : time_observers_) it.second->SetEnabled(false); scheduler_.reset(); } THREAD_CHECKER(bound_thread_); base::Lock lock_; base::flat_map<base::PlatformThreadId, std::unique_ptr<ThreadSafeTimeObserver>> time_observers_ GUARDED_BY(lock_); std::unique_ptr<RenderingStageScheduler> scheduler_ GUARDED_BY(lock_); // Pipeline name, for tracing and metrics. const char* pipeline_type_; // The number of currently active pipelines of this type. int active_count_ = 0; // The target time for this rendering stage for a frame. base::TimeDelta target_duration_; base::TimeDelta gpu_latency_; }; RenderingPipeline::ScopedPipelineActive::ScopedPipelineActive( RenderingPipeline* pipeline) : pipeline_(pipeline) { pipeline_->UpdateActiveCount(true); } RenderingPipeline::ScopedPipelineActive::~ScopedPipelineActive() { pipeline_->UpdateActiveCount(false); } std::unique_ptr<RenderingPipeline> RenderingPipeline::CreateRendererMain() { static constexpr char kRendererMain[] = "RendererMain"; return std::make_unique<RenderingPipelineImpl>(kRendererMain); } std::unique_ptr<RenderingPipeline> RenderingPipeline::CreateRendererCompositor() { static constexpr char kRendererCompositor[] = "RendererCompositor"; return std::make_unique<RenderingPipelineImpl>(kRendererCompositor); } std::unique_ptr<RenderingPipeline> RenderingPipeline::CreateGpu() { static constexpr char kGpu[] = "Gpu"; return std::make_unique<RenderingPipelineImpl>(kGpu); } } // namespace gfx
31.070234
80
0.718515
[ "object", "vector" ]
174e6b0aa080f3a17b9c82f91c7f0f955abee22e
886
hpp
C++
src/epecur/track.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
1
2021-06-25T13:41:19.000Z
2021-06-25T13:41:19.000Z
src/epecur/track.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
null
null
null
src/epecur/track.hpp
veprbl/libepecur
83167ac6220e69887c03b556f1a7ffc518cbb227
[ "Unlicense" ]
null
null
null
#ifndef __TRACK_HPP #define __TRACK_HPP #include "types.hpp" #include <vector> #include <boost/detail/scoped_enum_emulation.hpp> using namespace std; struct track_info_t { double c0; double c1; double chisq; double prev_chisq; vector<double> chamber_wires_pos; vector<wire_pos_ptr_t> wire_pos_ptr; vector<uint> used_chambers; }; BOOST_SCOPED_ENUM_START(track_type) { prop, drift }; BOOST_SCOPED_ENUM_END typedef BOOST_SCOPED_ENUM(track_type) track_type_t; const uint MIN_TRACK_CHAMBERS = 3; bool next_combination( vector<wire_pos_ptr_t> &wire_pos_ptr, const vector<int> &wire_count ); track_info_t reconstruct_track( const vector< vector<wire_pos_t>* > &data, const vector<double> &normal_pos ); template<track_type_t track_type> vector<track_info_t> reconstruct_all_tracks( vector< vector<wire_pos_t>* > data, vector<double> normal_pos, double max_chisq = -1 ); #endif
24.611111
132
0.795711
[ "vector" ]
174ec67ca015f43d52f6f92bff0afd0875b35838
16,684
cpp
C++
qCC/ccPointListPickingDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccPointListPickingDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccPointListPickingDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CLOUDCOMPARE # //# # //# This program is free software; you can redistribute it and/or modify # //# it under the terms of the GNU General Public License as published by # //# the Free Software Foundation; version 2 or later of the License. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU General Public License for more details. # //# # //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) # //# # //########################################################################## #include "ccPointListPickingDlg.h" //Qt #include <QSettings> #include <QFileDialog> #include <QMenu> #include <QClipboard> #include <QApplication> #include <QMessageBox> //CCLib #include <CCConst.h> //qCC_db #include <ccLog.h> #include <ccPointCloud.h> #include <cc2DLabel.h> #include <ccPolyline.h> //qCC_io #include <AsciiFilter.h> //local #include "ccGLWindow.h" #include "mainwindow.h" #include "db_tree/ccDBRoot.h" //system #include <assert.h> //semi persistent settings static unsigned s_pickedPointsStartIndex = 0; static bool s_showGlobalCoordsCheckBoxChecked = false; static const char s_pickedPointContainerName[] = "Picked points list"; static const char s_defaultLabelBaseName[] = "Point #"; ccPointListPickingDlg::ccPointListPickingDlg(ccPickingHub* pickingHub, QWidget* parent) : ccPointPickingGenericInterface(pickingHub, parent) , Ui::PointListPickingDlg() , m_associatedCloud(0) , m_lastPreviousID(0) , m_orderedLabelsContainer(0) { setupUi(this); exportToolButton->setPopupMode(QToolButton::MenuButtonPopup); QMenu* menu = new QMenu(exportToolButton); QAction* exportASCII_xyz = menu->addAction("x,y,z"); QAction* exportASCII_ixyz = menu->addAction("local index,x,y,z"); QAction* exportASCII_gxyz = menu->addAction("global index,x,y,z"); QAction* exportASCII_lxyz = menu->addAction("label name,x,y,z"); QAction* exportToNewCloud = menu->addAction("new cloud"); QAction* exportToNewPolyline = menu->addAction("new polyline"); exportToolButton->setMenu(menu); tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); startIndexSpinBox->setValue(s_pickedPointsStartIndex); showGlobalCoordsCheckBox->setChecked(s_showGlobalCoordsCheckBoxChecked); connect(cancelToolButton, SIGNAL(clicked()), this, SLOT(cancelAndExit())); connect(revertToolButton, SIGNAL(clicked()), this, SLOT(removeLastEntry())); connect(validToolButton, SIGNAL(clicked()), this, SLOT(applyAndExit())); connect(exportToolButton, SIGNAL(clicked()), exportToolButton, SLOT(showMenu())); connect(exportASCII_xyz, SIGNAL(triggered()), this, SLOT(exportToASCII_xyz())); connect(exportASCII_ixyz, SIGNAL(triggered()), this, SLOT(exportToASCII_ixyz())); connect(exportASCII_gxyz, SIGNAL(triggered()), this, SLOT(exportToASCII_gxyz())); connect(exportASCII_lxyz, SIGNAL(triggered()), this, SLOT(exportToASCII_lxyz())); connect(exportToNewCloud, SIGNAL(triggered()), this, SLOT(exportToNewCloud())); connect(exportToNewPolyline, SIGNAL(triggered()), this, SLOT(exportToNewPolyline())); connect(markerSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(markerSizeChanged(int))); connect(startIndexSpinBox, SIGNAL(valueChanged(int)), this, SLOT(startIndexChanged(int))); connect(showGlobalCoordsCheckBox, SIGNAL(clicked()), this, SLOT(updateList())); updateList(); } unsigned ccPointListPickingDlg::getPickedPoints(std::vector<cc2DLabel*>& pickedPoints) { pickedPoints.clear(); if (m_orderedLabelsContainer) { //get all labels ccHObject::Container labels; unsigned count = m_orderedLabelsContainer->filterChildren(labels, false, CC_TYPES::LABEL_2D); try { pickedPoints.reserve(count); } catch (const std::bad_alloc&) { ccLog::Error("Not enough memory!"); return 0; } for (unsigned i = 0; i < count; ++i) { if (labels[i]->isA(CC_TYPES::LABEL_2D)) //Warning: cc2DViewportLabel is also a kind of 'CC_TYPES::LABEL_2D'! { cc2DLabel* label = static_cast<cc2DLabel*>(labels[i]); if (label->isVisible() && label->size() == 1) { pickedPoints.push_back(label); } } } } return static_cast<unsigned>(pickedPoints.size()); } void ccPointListPickingDlg::linkWithCloud(ccPointCloud* cloud) { m_associatedCloud = cloud; m_lastPreviousID = 0; if (m_associatedCloud) { //find default container m_orderedLabelsContainer = 0; ccHObject::Container groups; m_associatedCloud->filterChildren(groups,true,CC_TYPES::HIERARCHY_OBJECT); for (ccHObject::Container::const_iterator it = groups.begin(); it != groups.end(); ++it) { if ((*it)->getName() == s_pickedPointContainerName) { m_orderedLabelsContainer = *it; break; } } std::vector<cc2DLabel*> previousPickedPoints; unsigned count = getPickedPoints(previousPickedPoints); //find highest unique ID among the VISIBLE labels for (unsigned i = 0; i < count; ++i) { m_lastPreviousID = std::max(m_lastPreviousID, previousPickedPoints[i]->getUniqueID()); } } showGlobalCoordsCheckBox->setEnabled(cloud ? cloud->isShifted() : false); updateList(); } void ccPointListPickingDlg::cancelAndExit() { ccDBRoot* dbRoot = MainWindow::TheInstance()->db(); if (!dbRoot) { assert(false); return; } if (m_orderedLabelsContainer) { //Restore previous state if (!m_toBeAdded.empty()) { dbRoot->removeElements(m_toBeAdded); } for (size_t j = 0; j < m_toBeDeleted.size(); ++j) { m_toBeDeleted[j]->prepareDisplayForRefresh(); m_toBeDeleted[j]->setEnabled(true); } if (m_orderedLabelsContainer->getChildrenNumber() == 0) { dbRoot->removeElement(m_orderedLabelsContainer); //m_associatedCloud->removeChild(m_orderedLabelsContainer); m_orderedLabelsContainer = 0; } } m_toBeDeleted.clear(); m_toBeAdded.clear(); m_associatedCloud = 0; m_orderedLabelsContainer = 0; MainWindow::RefreshAllGLWindow(); updateList(); stop(false); } void ccPointListPickingDlg::exportToNewCloud() { if (!m_associatedCloud) return; //get all labels std::vector<cc2DLabel*> labels; unsigned count = getPickedPoints(labels); if (count != 0) { ccPointCloud* cloud = new ccPointCloud(); if (cloud->reserve(count)) { cloud->setName("Picking list"); for (unsigned i = 0; i < count; ++i) { const cc2DLabel::PickedPoint& PP = labels[i]->getPoint(0); const CCVector3* P = PP.cloud->getPoint(PP.index); cloud->addPoint(*P); } cloud->setDisplay(m_associatedCloud->getDisplay()); cloud->setGlobalShift(m_associatedCloud->getGlobalShift()); cloud->setGlobalScale(m_associatedCloud->getGlobalScale()); MainWindow::TheInstance()->addToDB(cloud); } else { ccLog::Error("Can't export picked points as point cloud: not enough memory!"); delete cloud; cloud = 0; } } else { ccLog::Error("Pick some points first!"); } } void ccPointListPickingDlg::exportToNewPolyline() { if (!m_associatedCloud) return; //get all labels std::vector<cc2DLabel*> labels; unsigned count = getPickedPoints(labels); if (count > 1) { //we create an "independent" polyline ccPointCloud* vertices = new ccPointCloud("vertices"); ccPolyline* polyline = new ccPolyline(vertices); if (!vertices->reserve(count) || !polyline->reserve(count)) { ccLog::Error("Not enough memory!"); delete vertices; delete polyline; return; } for (unsigned i = 0; i < count; ++i) { const cc2DLabel::PickedPoint& PP = labels[i]->getPoint(0); vertices->addPoint(*PP.cloud->getPoint(PP.index)); } polyline->addPointIndex(0, count); polyline->setVisible(true); vertices->setEnabled(false); polyline->setGlobalShift(m_associatedCloud->getGlobalShift()); polyline->setGlobalScale(m_associatedCloud->getGlobalScale()); polyline->addChild(vertices); polyline->setDisplay_recursive(m_associatedCloud->getDisplay()); MainWindow::TheInstance()->addToDB(polyline); } else { ccLog::Error("Pick at least two points!"); } } void ccPointListPickingDlg::applyAndExit() { if (m_associatedCloud && !m_toBeDeleted.empty()) { //apply modifications MainWindow::TheInstance()->db()->removeElements(m_toBeDeleted); //no need to redraw as they should already be invisible m_associatedCloud = 0; } m_toBeDeleted.clear(); m_toBeAdded.clear(); m_orderedLabelsContainer = 0; updateList(); stop(true); } void ccPointListPickingDlg::removeLastEntry() { if (!m_associatedCloud) return; //get all labels std::vector<cc2DLabel*> labels; unsigned count = getPickedPoints(labels); if (count == 0) return; ccHObject* lastVisibleLabel = labels.back(); if (lastVisibleLabel->getUniqueID() <= m_lastPreviousID) { //old label: hide it and add it to the 'to be deleted' list (will be restored if process is cancelled) lastVisibleLabel->setEnabled(false); m_toBeDeleted.push_back(lastVisibleLabel); } else { if (!m_toBeAdded.empty()) { assert(m_toBeAdded.back() == lastVisibleLabel); m_toBeAdded.pop_back(); } if (m_orderedLabelsContainer) { if (lastVisibleLabel->getParent()) { lastVisibleLabel->getParent()->removeDependencyWith(lastVisibleLabel); lastVisibleLabel->removeDependencyWith(lastVisibleLabel->getParent()); } //m_orderedLabelsContainer->removeChild(lastVisibleLabel); MainWindow::TheInstance()->db()->removeElement(lastVisibleLabel); } else m_associatedCloud->detachChild(lastVisibleLabel); } updateList(); if (m_associatedWin) m_associatedWin->redraw(); } void ccPointListPickingDlg::startIndexChanged(int value) { unsigned int uValue = static_cast<unsigned int>(value); if (uValue != s_pickedPointsStartIndex) { s_pickedPointsStartIndex = uValue; updateList(); if (m_associatedWin) m_associatedWin->redraw(); } } void ccPointListPickingDlg::markerSizeChanged(int size) { if (size < 1 || !m_associatedWin) return; //display parameters ccGui::ParamStruct guiParams = m_associatedWin->getDisplayParameters(); if (guiParams.labelMarkerSize != static_cast<unsigned>(size)) { guiParams.labelMarkerSize = static_cast<unsigned>(size); m_associatedWin->setDisplayParameters(guiParams,m_associatedWin->hasOverridenDisplayParameters()); m_associatedWin->redraw(); } } void ccPointListPickingDlg::exportToASCII(ExportFormat format) { if (!m_associatedCloud) return; //get all labels std::vector<cc2DLabel*> labels; unsigned count = getPickedPoints(labels); if (count == 0) return; QSettings settings; settings.beginGroup("PointListPickingDlg"); QString filename = settings.value("filename", "picking_list.txt").toString(); settings.endGroup(); filename = QFileDialog::getSaveFileName(this, "Export to ASCII", filename, AsciiFilter::GetFileFilter()); if (filename.isEmpty()) return; settings.beginGroup("PointListPickingDlg"); settings.setValue("filename", filename); settings.endGroup(); FILE* fp = fopen(qPrintable(filename), "wt"); if (!fp) { ccLog::Error(QString("Failed to open file '%1' for saving!").arg(filename)); return; } //if a global shift exists, ask the user if it should be applied CCVector3d shift = m_associatedCloud->getGlobalShift(); double scale = m_associatedCloud->getGlobalScale(); if (shift.norm2() != 0 || scale != 1.0) { if (QMessageBox::warning( this, "Apply global shift", "Do you want to apply global shift/scale to exported points?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ) == QMessageBox::No) { //reset shift shift = CCVector3d(0,0,0); scale = 1.0; } } //starting index unsigned startIndex = static_cast<unsigned>(std::max(0, startIndexSpinBox->value())); for (unsigned i = 0; i < count; ++i) { assert(labels[i]->size() == 1); const cc2DLabel::PickedPoint& PP = labels[i]->getPoint(0); const CCVector3* P = PP.cloud->getPoint(PP.index); switch (format) { case PLP_ASCII_EXPORT_IXYZ: fprintf(fp, "%u,", i + startIndex); break; case PLP_ASCII_EXPORT_GXYZ: fprintf(fp, "%u,", PP.index); break; case PLP_ASCII_EXPORT_LXYZ: fprintf(fp, "%s,", qPrintable(labels[i]->getName())); break; default: //nothing to do break; } fprintf(fp, "%.12f,%.12f,%.12f\n", static_cast<double>(P->x) / scale - shift.x, static_cast<double>(P->y) / scale - shift.y, static_cast<double>(P->z) / scale - shift.z); } fclose(fp); ccLog::Print(QString("[I/O] File '%1' saved successfully").arg(filename)); } void ccPointListPickingDlg::updateList() { //get all labels std::vector<cc2DLabel*> labels; unsigned count = getPickedPoints(labels); revertToolButton->setEnabled(count); validToolButton->setEnabled(count); exportToolButton->setEnabled(count); countLineEdit->setText(QString::number(count)); tableWidget->setRowCount(count); if (!count) return; //starting index int startIndex = startIndexSpinBox->value(); int precision = m_associatedWin ? m_associatedWin->getDisplayParameters().displayedNumPrecision : 6; bool showAbsolute = showGlobalCoordsCheckBox->isEnabled() && showGlobalCoordsCheckBox->isChecked(); for (unsigned i = 0; i < count; ++i) { const cc2DLabel::PickedPoint& PP = labels[i]->getPoint(0); const CCVector3* P = PP.cloud->getPoint(PP.index); CCVector3d Pd = (showAbsolute ? PP.cloud->toGlobal3d(*P) : CCVector3d::fromArray(P->u)); //point index in list tableWidget->setVerticalHeaderItem(i, new QTableWidgetItem(QString("%1").arg(i + startIndex))); //update name as well if ( labels[i]->getUniqueID() > m_lastPreviousID || labels[i]->getName().startsWith(s_defaultLabelBaseName) ) //DGM: we don't change the name of old labels that have a non-default name { labels[i]->setName(s_defaultLabelBaseName + QString::number(i+startIndex)); } //point absolute index (in cloud) tableWidget->setItem(i, 0, new QTableWidgetItem(QString("%1").arg(PP.index))); for (unsigned j = 0; j < 3; ++j) tableWidget->setItem(i, j + 1, new QTableWidgetItem(QString("%1").arg(Pd.u[j], 0, 'f', precision))); } tableWidget->scrollToBottom(); } void ccPointListPickingDlg::processPickedPoint(ccPointCloud* cloud, unsigned pointIndex, int x, int y) { if (cloud != m_associatedCloud || !cloud || !MainWindow::TheInstance()) return; cc2DLabel* newLabel = new cc2DLabel(); newLabel->addPoint(cloud,pointIndex); newLabel->setVisible(true); newLabel->setDisplayedIn2D(false); newLabel->displayPointLegend(true); newLabel->setCollapsed(true); ccGenericGLDisplay* display = m_associatedCloud->getDisplay(); if (display) { newLabel->setDisplay(display); QSize size = display->getScreenSize(); newLabel->setPosition( static_cast<float>(x + 20) / size.width(), static_cast<float>(y + 20) / size.height() ); } //add default container if necessary if (!m_orderedLabelsContainer) { m_orderedLabelsContainer = new ccHObject(s_pickedPointContainerName); m_associatedCloud->addChild(m_orderedLabelsContainer); m_orderedLabelsContainer->setDisplay(display); MainWindow::TheInstance()->addToDB(m_orderedLabelsContainer, false, true, false, false); } assert(m_orderedLabelsContainer); m_orderedLabelsContainer->addChild(newLabel); MainWindow::TheInstance()->addToDB(newLabel, false, true, false, false); m_toBeAdded.push_back(newLabel); //automatically send the new point coordinates to the clipboard QClipboard* clipboard = QApplication::clipboard(); if (clipboard) { const CCVector3* P = cloud->getPoint(pointIndex); int precision = m_associatedWin ? m_associatedWin->getDisplayParameters().displayedNumPrecision : 6; int indexInList = startIndexSpinBox->value() + static_cast<int>(m_orderedLabelsContainer->getChildrenNumber()) - 1; clipboard->setText(QString("CC_POINT_#%0(%1;%2;%3)").arg(indexInList).arg(P->x, 0, 'f', precision).arg(P->y, 0, 'f', precision).arg(P->z, 0, 'f', precision)); } updateList(); if (m_associatedWin) m_associatedWin->redraw(); }
29.58156
160
0.686766
[ "vector" ]
17528f5f6907a61704913df12dfd13fd5c8e580e
2,571
cpp
C++
third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/layout/DepthOrderedLayoutObjectList.h" #include "core/frame/FrameView.h" #include "core/layout/LayoutObject.h" #include <algorithm> namespace blink { struct DepthOrderedLayoutObjectListData { // LayoutObjects sorted by depth (deepest first). This structure is only // populated at the beginning of enumerations. See ordered(). Vector<DepthOrderedLayoutObjectList::LayoutObjectWithDepth> m_orderedObjects; // Outside of layout, LayoutObjects can be added and removed as needed such // as when style was changed or destroyed. They're kept in this hashset to // keep those operations fast. HashSet<LayoutObject*> m_objects; }; DepthOrderedLayoutObjectList::DepthOrderedLayoutObjectList() : m_data(new DepthOrderedLayoutObjectListData) {} DepthOrderedLayoutObjectList::~DepthOrderedLayoutObjectList() { delete m_data; } int DepthOrderedLayoutObjectList::size() const { return m_data->m_objects.size(); } bool DepthOrderedLayoutObjectList::isEmpty() const { return m_data->m_objects.isEmpty(); } void DepthOrderedLayoutObjectList::add(LayoutObject& object) { ASSERT(!object.frameView()->isInPerformLayout()); m_data->m_objects.add(&object); m_data->m_orderedObjects.clear(); } void DepthOrderedLayoutObjectList::remove(LayoutObject& object) { auto it = m_data->m_objects.find(&object); if (it == m_data->m_objects.end()) return; ASSERT(!object.frameView()->isInPerformLayout()); m_data->m_objects.remove(it); m_data->m_orderedObjects.clear(); } void DepthOrderedLayoutObjectList::clear() { m_data->m_objects.clear(); m_data->m_orderedObjects.clear(); } unsigned DepthOrderedLayoutObjectList::LayoutObjectWithDepth::determineDepth( LayoutObject* object) { unsigned depth = 1; for (LayoutObject* parent = object->parent(); parent; parent = parent->parent()) ++depth; return depth; } const HashSet<LayoutObject*>& DepthOrderedLayoutObjectList::unordered() const { return m_data->m_objects; } const Vector<DepthOrderedLayoutObjectList::LayoutObjectWithDepth>& DepthOrderedLayoutObjectList::ordered() { if (m_data->m_objects.isEmpty() || !m_data->m_orderedObjects.isEmpty()) return m_data->m_orderedObjects; copyToVector(m_data->m_objects, m_data->m_orderedObjects); std::sort(m_data->m_orderedObjects.begin(), m_data->m_orderedObjects.end()); return m_data->m_orderedObjects; } } // namespace blink
30.975904
79
0.761571
[ "object", "vector" ]
17595d91edae363c6e6e7b7861a3c8e7007421bd
1,978
cpp
C++
Codes/2493.cpp
whitesimian/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
1
2019-10-13T03:43:59.000Z
2019-10-13T03:43:59.000Z
Codes/2493.cpp
rafflezs/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
null
null
null
Codes/2493.cpp
rafflezs/URI-Online-Judge
773b8a663d6eb113a030ea72aad3cefe758eed21
[ "MIT" ]
2
2021-02-16T05:47:06.000Z
2021-02-24T14:11:54.000Z
#include "bits/stdc++.h" #define f(inicio, fim) for(int i = inicio; i < fim; i++) #define ff(inicio, fim) for(int j = inicio; j < fim; j++) #define fff(inicio, fim) for(int k = inicio; k < fim; k++) #define print(vetor) for(auto elem : vetor) cout << elem << " " using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; while(cin >> t){ vector< vector<int> > vetor(t); f(0, t){ string tmp, foo; int aux; cin >> aux; vetor[i].push_back(aux); cin >> tmp; istringstream ss(tmp); while(getline(ss, foo, '=')) vetor[i].push_back(atoi(foo.c_str())); } set<string> nome; f(0, t){ string name; int pos; char op; cin >> name >> pos >> op; --pos; int prim = vetor[pos][0], seg = vetor[pos][1], ter = vetor[pos][2]; switch (op){ case '+': if(prim + seg != ter) nome.insert(name); break; case '-': if(prim - seg != ter) nome.insert(name); break; case '*': if(prim * seg != ter) nome.insert(name); break; case 'I': if(prim + seg == ter || prim - seg == ter || prim * seg == ter) nome.insert(name); break; } } if(nome.size() == 0) cout << "You Shall All Pass!\n"; else if(nome.size() == t) cout << "None Shall Pass!\n"; else{ auto it = nome.begin(); cout << *it; it = next(it); while(it != nome.end()){ cout << " " << *it; it = next(it); } cout << "\n"; } } return 0; }
26.026316
79
0.388777
[ "vector" ]
1759a5b5abdb48da509758193032f92fcbe5a36a
234
cpp
C++
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/ParamValModel/SimpleStateUpdater.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/ParamValModel/SimpleStateUpdater.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/LibBlackVision/Source/Engine/Models/Plugins/ParamValModel/SimpleStateUpdater.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "SimpleStateUpdater.h" #include "Memory/MemoryLeaks.h" namespace bv { namespace model { void removethisfileremovethisfileremovethisfileremovethisfile() { } } // model } // bvc
11.7
64
0.675214
[ "model" ]
176070245a10bb826b11e399d41d084b0560739d
2,763
cpp
C++
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSPB/G.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSPB/G.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSPB/G.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
#pragma GCC optimize ("O2") #include<bits/stdc++.h> #include<unistd.h> using namespace std; #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define IOS ios_base::sync_with_stdio(0); cin.tie(0) #define REP(i,x) for (int i=0; i<(x); i++) #define REP1(i,a,b) for (int i=(a); i<=(b); i++) #ifdef ONLINE_JUDGE #define FILEIO(name) \ freopen(name".in", "r", stdin); \ freopen(name".out", "w", stdout); #else #define FILEIO(name) #endif template<typename A, typename B> ostream& operator <<(ostream &s, const pair<A,B> &p) { return s<<"("<<p.first<<","<<p.second<<")"; } template<typename T> ostream& operator <<(ostream &s, const vector<T> &c) { s<<"[ "; for (auto it : c) s << it << " "; s<<"]"; return s; } // Let's Fight! int ip[4][4]; int calc(vector<int> vec) { int n = SZ(vec); vector<int> vst(n); fill(ALL(vst),0); int res = n; REP(i,n) { if (vst[i]) continue; int j = i; while (!vst[j]) { vst[j] = 1; j = vec[j]; } res--; } return res; } void swap_row(int i, int j) { cout<<char('a'+i)<<"-"<<char('a'+j)<<endl; } void swap_col(int i, int j) { cout<<(i+1)<<"-"<<(j+1)<<endl; } void swap_two(int i, int j) { char x1 = 'a'+i/4; int y1 = i%4+1; char x2 = 'a'+j/4; int y2 = j%4+1; cout<<x1<<y1<<"-"<<x2<<y2<<endl; } int main() { IOS; REP(i,4) REP(j,4) { cin>>ip[i][j]; ip[i][j]--; } int bcost = 1000; vector<int> brow, bcol, bvec; vector<int> row = {0,1,2,3}; do { vector<int> col = {0,1,2,3}; do { vector<int> vec(16); REP(i,4) REP(j,4) { vec[i*4+j] = ip[row[i]][col[j]]; } int tmp = calc(row) + calc(col) + calc(vec); if (tmp < bcost) { bcost = tmp; brow = row; bcol = col; bvec = vec; } } while (next_permutation(ALL(col))); } while (next_permutation(ALL(row))); assert(bcost != 1000); cout<<bcost<<endl; int at[16]; { auto vec = brow; REP(i,4) vec[brow[i]] = i; REP(i,4) at[vec[i]] = i; REP(i,4) { if (i != vec[i]) { int j = at[i]; swap_row(i,j); swap(vec[i], vec[j]); at[vec[i]] = i; at[vec[j]] = j; } } REP(i,4) assert(vec[i] == i); } { auto vec = bcol; REP(i,4) vec[bcol[i]] = i; REP(i,4) at[vec[i]] = i; REP(i,4) { if (i != vec[i]) { int j = at[i]; swap_col(i,j); swap(vec[i], vec[j]); at[vec[i]] = i; at[vec[j]] = j; } } REP(i,4) assert(vec[i] == i); } { auto &vec = bvec; REP(i,16) at[vec[i]] = i; REP(i,16) { if (i != vec[i]) { int j = at[i]; swap_two(i,j); swap(vec[i], vec[j]); at[vec[i]] = i; at[vec[j]] = j; } } REP(i,16) assert(vec[i] == i); } return 0; }
18.543624
54
0.514296
[ "vector" ]
1762dbec93724769886c658d693d3d7dbf14f7e6
1,206
hpp
C++
src/widgets/config/AppearanceConfigTab.hpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
60
2019-11-30T00:30:33.000Z
2022-03-26T03:44:53.000Z
src/widgets/config/AppearanceConfigTab.hpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
8
2019-12-16T07:55:54.000Z
2022-03-09T21:01:02.000Z
src/widgets/config/AppearanceConfigTab.hpp
stoneface86/trackerboy
68cbb4c56ec4bbccfd1fe172a57451bdaba91561
[ "MIT" ]
3
2021-08-06T07:17:15.000Z
2022-03-08T03:39:06.000Z
#pragma once #include "core/model/PaletteModel.hpp" #include "widgets/config/ConfigTab.hpp" #include <QCheckBox> #include <QColorDialog> #include <QDir> #include <QModelIndex> #include <QPushButton> #include <array> class AppearanceConfigTab : public ConfigTab { Q_OBJECT public: explicit AppearanceConfigTab(QWidget *parent = nullptr); void apply(AppearanceConfig &appearanceConfig, Palette &pal); void resetControls(AppearanceConfig const& appearanceConfig, Palette const& pal); protected: virtual void hideEvent(QHideEvent *evt) override; private slots: void chooseFont(); void chooseColor(QColor const& color); private: Q_DISABLE_COPY(AppearanceConfigTab) void setFont(size_t index, QFont const& font); void selectColor(QModelIndex const& index); void updateColorDialog(); static constexpr size_t FONT_COUNT = 3; std::array<QPushButton*, FONT_COUNT> mFontChooseButtons; std::array<QFont, FONT_COUNT> mFonts; QCheckBox *mShowFlatsCheck; QCheckBox *mShowPreviewsCheck; QPushButton *mDefaultButton; PaletteModel *mModel; QColorDialog *mColorDialog; QDir mSaveDir; QModelIndex mSelectedColor; };
19.142857
85
0.737977
[ "model" ]
1763589b432bfbaec048d3c8e1f400bab6dafd50
10,930
cpp
C++
src/kits/tracker/FavoritesMenu.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/kits/tracker/FavoritesMenu.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/kits/tracker/FavoritesMenu.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* Open Tracker License Terms and Conditions Copyright (c) 1991-2000, Be Incorporated. All rights reserved. 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 applies to all licensees and 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 TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL BE INCORPORATED 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. Except as contained in this notice, the name of Be Incorporated shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Be Incorporated. Tracker(TM), Be(R), BeOS(R), and BeIA(TM) are trademarks or registered trademarks of Be Incorporated in the United States and other countries. Other brand product names are registered trademarks or trademarks of their respective holders. All rights reserved. */ #include "FavoritesMenu.h" #include <compat/sys/stat.h> #include <Application.h> #include <Catalog.h> #include <FindDirectory.h> #include <FilePanel.h> #include <Locale.h> #include <Message.h> #include <Path.h> #include <Query.h> #include <Roster.h> #include <functional> #include <algorithm> #include "IconMenuItem.h" #include "PoseView.h" #include "QueryPoseView.h" #include "Tracker.h" #include "Utilities.h" #include "VirtualDirectoryEntryList.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "FavoritesMenu" // #pragma mark - FavoritesMenu FavoritesMenu::FavoritesMenu(const char* title, BMessage* openFolderMessage, BMessage* openFileMessage, const BMessenger &target, bool isSavePanel, BRefFilter* filter) : BSlowMenu(title), fOpenFolderMessage(openFolderMessage), fOpenFileMessage(openFileMessage), fTarget(target), fState(kStart), fIndex(-1), fSectionItemCount(-1), fAddedSeparatorForSection(false), fContainer(NULL), fItemList(NULL), fInitialItemCount(0), fIsSavePanel(isSavePanel), fRefFilter(filter) { } FavoritesMenu::~FavoritesMenu() { delete fOpenFolderMessage; delete fOpenFileMessage; delete fContainer; } void FavoritesMenu::SetRefFilter(BRefFilter* filter) { fRefFilter = filter; } bool FavoritesMenu::StartBuildingItemList() { // initialize the menu building state if (fInitialItemCount == 0) fInitialItemCount = CountItems(); else { // strip the old items so we can add new fresh ones int32 count = CountItems() - fInitialItemCount; // keep the items that were added by the FavoritesMenu creator while (count--) delete RemoveItem(fInitialItemCount); } fUniqueRefCheck.clear(); fState = kStart; return true; } bool FavoritesMenu::AddNextItem() { // run the next chunk of code for a given item adding state if (fState == kStart) { fState = kAddingFavorites; fSectionItemCount = 0; fAddedSeparatorForSection = false; // set up adding the GoTo menu items try { BPath path; ThrowOnError(find_directory(B_USER_SETTINGS_DIRECTORY, &path, true)); path.Append(kGoDirectory); mkdir(path.Path(), 0777); BEntry entry(path.Path()); Model startModel(&entry, true); ThrowOnInitCheckError(&startModel); if (!startModel.IsContainer()) throw B_ERROR; if (startModel.IsQuery()) fContainer = new QueryEntryListCollection(&startModel); else if (startModel.IsVirtualDirectory()) fContainer = new VirtualDirectoryEntryList(&startModel); else { BDirectory* directory = dynamic_cast<BDirectory*>(startModel.Node()); if (directory != NULL) fContainer = new DirectoryEntryList(*directory); } ThrowOnInitCheckError(fContainer); ThrowOnError(fContainer->Rewind()); } catch (...) { delete fContainer; fContainer = NULL; } } if (fState == kAddingFavorites) { entry_ref ref; if (fContainer != NULL && fContainer->GetNextRef(&ref) == B_OK) { Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, model.IsDirectory() ? fOpenFolderMessage : fOpenFileMessage, fTarget); if (item == NULL) return true; item->SetLabel(ref.name); // this is the name of the link in the Go dir if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem(B_TRANSLATE("Favorites"))); } fUniqueRefCheck.push_back(*model.EntryRef()); AddItem(item); fSectionItemCount++; return true; } // done with favorites, set up for adding recent files fState = kAddingFiles; fAddedSeparatorForSection = false; app_info info; be_app->GetAppInfo(&info); fItems.MakeEmpty(); int32 apps, docs, folders; TrackerSettings().RecentCounts(&apps, &docs, &folders); BRoster().GetRecentDocuments(&fItems, docs, NULL, info.signature); fIndex = 0; fSectionItemCount = 0; } if (fState == kAddingFiles) { // if this is a Save panel, not an Open panel // then don't add the recent documents if (!fIsSavePanel) { for (;;) { entry_ref ref; if (fItems.FindRef("refs", fIndex++, &ref) != B_OK) break; Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, fOpenFileMessage, fTarget); if (item) { if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem( B_TRANSLATE("Recent documents"))); } AddItem(item); fSectionItemCount++; return true; } } } // done with recent files, set up for adding recent folders fState = kAddingFolders; fAddedSeparatorForSection = false; app_info info; be_app->GetAppInfo(&info); fItems.MakeEmpty(); int32 apps, docs, folders; TrackerSettings().RecentCounts(&apps, &docs, &folders); BRoster().GetRecentFolders(&fItems, folders, info.signature); fIndex = 0; } if (fState == kAddingFolders) { for (;;) { entry_ref ref; if (fItems.FindRef("refs", fIndex++, &ref) != B_OK) break; // don't add folders that are already in the GoTo section if (find_if(fUniqueRefCheck.begin(), fUniqueRefCheck.end(), bind2nd(std::equal_to<entry_ref>(), ref)) != fUniqueRefCheck.end()) { continue; } Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, fOpenFolderMessage, fTarget, true); if (item != NULL) { if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem( B_TRANSLATE("Recent folders"))); } AddItem(item); item->SetEnabled(true); // BNavMenu::NewModelItem returns a disabled item here - // need to fix this in BNavMenu::NewModelItem return true; } } } return false; } void FavoritesMenu::DoneBuildingItemList() { SetTargetForItems(fTarget); } void FavoritesMenu::ClearMenuBuildingState() { delete fContainer; fContainer = NULL; fState = kDone; // force the menu to get rebuilt each time fMenuBuilt = false; } bool FavoritesMenu::ShouldShowModel(const Model* model) { if (fIsSavePanel && model->IsFile()) return false; if (!fRefFilter || model->Node() == NULL) return true; struct stat_beos statBeOS; convert_to_stat_beos(model->StatBuf(), &statBeOS); return fRefFilter->Filter(model->EntryRef(), model->Node(), &statBeOS, model->MimeType()); } // #pragma mark - RecentsMenu RecentsMenu::RecentsMenu(const char* name, int32 which, uint32 what, BHandler* target) : BNavMenu(name, what, target), fWhich(which), fRecentsCount(0), fItemIndex(0) { int32 applications; int32 documents; int32 folders; TrackerSettings().RecentCounts(&applications,&documents,&folders); if (fWhich == 0) fRecentsCount = documents; else if (fWhich == 1) fRecentsCount = applications; else if (fWhich == 2) fRecentsCount = folders; } void RecentsMenu::DetachedFromWindow() { // // BNavMenu::DetachedFromWindow sets the TypesList to NULL // BMenu::DetachedFromWindow(); } bool RecentsMenu::StartBuildingItemList() { int32 count = CountItems()-1; for (int32 index = count; index >= 0; index--) { BMenuItem* item = ItemAt(index); ASSERT(item); RemoveItem(index); delete item; } // // !! note: don't call inherited from here // the navref is not set for this menu // but it still needs to be a draggable navmenu // simply return true so that AddNextItem is called // // return BNavMenu::StartBuildingItemList(); return true; } bool RecentsMenu::AddNextItem() { if (fRecentsCount > 0 && AddRecents(fRecentsCount)) return true; fItemIndex = 0; return false; } bool RecentsMenu::AddRecents(int32 count) { if (fItemIndex == 0) { fRecentList.MakeEmpty(); BRoster roster; switch(fWhich) { case 0: roster.GetRecentDocuments(&fRecentList, count); break; case 1: roster.GetRecentApps(&fRecentList, count); break; case 2: roster.GetRecentFolders(&fRecentList, count); break; default: return false; break; } } for (;;) { entry_ref ref; if (fRecentList.FindRef("refs", fItemIndex++, &ref) != B_OK) break; if (ref.name != NULL && strlen(ref.name) > 0) { Model model(&ref, true); ModelMenuItem* item = BNavMenu::NewModelItem(&model, new BMessage(fMessage.what), Target(), false, NULL, TypesList()); if (item != NULL) { AddItem(item); // return true so that we know to reenter this list return true; } return true; } } // // return false if we are done with this list // return false; } void RecentsMenu::DoneBuildingItemList() { // // !! note: don't call inherited here // the object list is not built // and this list does not need to be sorted // BNavMenu::DoneBuildingItemList(); // if (CountItems() <= 0) { BMenuItem* item = new BMenuItem(B_TRANSLATE("<No recent items>"), 0); item->SetEnabled(false); AddItem(item); } else SetTargetForItems(Target()); } void RecentsMenu::ClearMenuBuildingState() { fMenuBuilt = false; BNavMenu::ClearMenuBuildingState(); }
22.489712
81
0.7043
[ "object", "model" ]
176d01844b4f71c0748380774b90721fd69c0456
3,059
hh
C++
src/modules/LCAcc/MergeSort.hh
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
31
2015-12-15T19:14:10.000Z
2021-12-31T17:40:21.000Z
src/modules/LCAcc/MergeSort.hh
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
5
2015-12-04T08:06:47.000Z
2020-08-09T21:49:46.000Z
src/modules/LCAcc/MergeSort.hh
cdsc-github/parade-ara-simulator
00c977200a8e7aa31b03d560886ec80840a3c416
[ "BSD-3-Clause" ]
21
2015-11-05T08:25:45.000Z
2021-06-19T02:24:50.000Z
#ifndef LCACC_MODE_MERGESORT_H #define LCACC_MODE_MERGESORT_H #include "LCAccOperatingMode.hh" #include "SPMInterface.hh" #include <vector> namespace LCAcc { class OperatingMode_MergeSort : public LCAccOperatingMode { public: inline OperatingMode_MergeSort(){} inline virtual void GetSPMReadIndexSet(int iteration, int maxIteration, int taskID, const std::vector<uint64_t>& argAddrVec, const std::vector<bool>& argActive, std::vector<uint64_t>& outputArgs) { assert(0 < argAddrVec.size()); uint64_t addr_dist = argAddrVec[0]; if(argActive[0]) { for(size_t i = 0; i < 128 * GetArgumentWidth(0); i += GetArgumentWidth(0)) { outputArgs.push_back(addr_dist + i); } } } inline virtual void GetSPMWriteIndexSet(int iteration, int maxIteration, int taskID, const std::vector<uint64_t>& argAddrVec, const std::vector<bool>& argActive, std::vector<uint64_t>& outputArgs) { } inline virtual void Compute(int iteration, int maxIteration, int taskID, const std::vector<uint64_t>& LCACC_INTERNAL_argAddrVec, const std::vector<bool>& LCACC_INTERNAL_argActive) { assert(LCACC_INTERNAL_argAddrVec.size() == 1); assert(0 < LCACC_INTERNAL_argAddrVec.size()); uint64_t addr_dist = LCACC_INTERNAL_argAddrVec[0]; double dist[128]; for(int i = 0; i < 128; i++) { dist[(i) % (128)] = (double)0; } for(size_t i = 0; i < 128; i++) { dist[(i) % (128)] = ReadSPMFlt(0, addr_dist, i); } #define SPMAddressOf(x) (addr_##x) #ifndef merge #define merge(a, start, m, stop) { \ float temp[128]; \ int i, j, k; \ for (i = start; i <= m; i++) { \ temp[i] = a[i]; \ } \ for (j = m + 1; j <= stop; j++) { \ temp[m + 1 + stop - j] = a[j]; \ } \ i = start; \ j = stop; \ for (k = start; k <= stop; k++) { \ float tmp_j = temp[j]; \ float tmp_i = temp[i]; \ if (tmp_j < tmp_i) { \ a[k] = tmp_j; \ j--; \ } else { \ a[k] = tmp_i; \ i++; \ } \ } \ } #endif int start, stop; int i, m, from, mid, to; start = 0; stop = 128; for (m = 1; m < stop - start; m += m) { for (i = start; i < stop; i += m + m) { from = i; mid = i + m - 1; to = i + m + m - 1; if (to < stop) { merge(dist, from, mid, to); } else { merge(dist, from, mid, stop); } } } #undef merge #undef SPMAddressOf } inline virtual void BeginComputation(){} inline virtual void EndComputation(){} inline virtual int CycleTime(){return 10;} inline virtual int InitiationInterval(){return 7;} inline virtual int PipelineDepth(){return 513;} inline virtual bool CallAllAtEnd(){return false;} inline static std::string GetModeName(){return "MergeSort";} inline virtual int ArgumentCount(){return 1;} inline virtual void SetRegisterValues(const std::vector<uint64_t>& regs) { assert(regs.size() == 0); } inline static int GetOpCode(){return 248;} }; } #endif
26.6
198
0.593331
[ "vector" ]
17734351ccec038475871f29236d5bae7d335133
14,087
cpp
C++
process.cpp
brian-sigurdson/CS5080-Operating-Systems-Project
be83fd3fb27c69b196d96bb101fc5df6115e2af9
[ "Apache-2.0" ]
null
null
null
process.cpp
brian-sigurdson/CS5080-Operating-Systems-Project
be83fd3fb27c69b196d96bb101fc5df6115e2af9
[ "Apache-2.0" ]
null
null
null
process.cpp
brian-sigurdson/CS5080-Operating-Systems-Project
be83fd3fb27c69b196d96bb101fc5df6115e2af9
[ "Apache-2.0" ]
null
null
null
/* * File Name : process.cpp * Descripton : Develope a Super Simple SHell (sssh), per project specs. * Author : Brian K. Sigurson * Course : CS5080 * Assignment : Project 01 * Due Date : 2017-03-27 * * Extra Credit : 1) Command History !! * : 2) Environment variables * : 3) Multiple Foreground Commands */ //================================= // forward declared dependencies //================================= // included dependencies #include "process.h" #include "sssh.h" //#include "job.h" #include <iostream> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <stdlib.h> // ============================================================================= /* * Description * constructor * * Parameters * none * * Return Value * nothing */ Process::Process() { theJob = NULL; } // ============================================================================= /* * Description * copy constructor * * Parameters * none * * Return Value * nothing */ Process::Process(Process &rhs) { theJob = rhs.getJob(); is_bg_Proc = rhs.isBGProcess(); is_piped_Proc = rhs.isPipedProcess(); is_empty = rhs.isEmpty(); } // ============================================================================= /* * Description * copy constructor * * Parameters * none * * Return Value * nothing */ Process::Process(Process *rhs) { // this instance is made of only primitives theJob = rhs->getJob(); // these are all primitives is_bg_Proc = rhs->isBGProcess(); is_piped_Proc = rhs->isPipedProcess(); is_empty = rhs->isEmpty(); } // ============================================================================= /* * Description * destructor * * Parameters * none * * Return Value * nothing */ Process::~Process() { // // delete pointers to jobs // for(std::vector<Job*>::iterator iter = myJobs.begin(); // iter != myJobs.end(); // iter++){ // delete *iter; // } // myJobs.clear(); } // ============================================================================= /* * Description * takes command line input and decides what to do: fg, bg, piped, etc... * * Parameters * command line input * * Return Value * void */ bool Process::processInput(std::vector<std::string> cmd_line_args) { /* for the moment this is just testing for the regular project criteria * I suppose this is the most natural place to hand the extra credit work also * * perhaps a quick test for the extra credit items, and if none to process, * then the code for the regular items run. */ // check if it is a foreground, background, or pipped job // piped job? Process::is_piped_Proc = Process::isPiped(cmd_line_args); if( is_piped_Proc ){ // piped job return( processPipedJobs(cmd_line_args) ); } // multiple fg job? if( Process::isMultipleFG(cmd_line_args) ){ // multiple fg job return( processMultipleFGJobs(cmd_line_args) ); } // environmental variables? if( Process::isEV(cmd_line_args) ){ // environmental var job return ( Process::processEV(cmd_line_args)); } // for this project, at this point if you're not any of the above // scenarios, then you're simply a bg or fg job // bg job? is_bg_Proc = Process::isBG(cmd_line_args); // non-piped, job // both fg & bg jobs are processed by processJobs() return( processJobs(cmd_line_args) ); } /* * Description * Process foreground jobs * * Parameters * command line input * * Return Value * void */ bool Process::processJobs(std::vector<std::string> cmd_line_args) { // fork a child int result = -10; pid_t childId = fork(); switch(childId){ case -1: // bad, fork() failed return false; case 0: // child processChild(cmd_line_args, result, Process::is_bg_Proc); if(result != 0){ // there was a problem std::cout << std::endl << "** WARNING: Problem with command. Please try again." << std::endl << std::endl; //std::cout << "child: result = " << result << std::endl; } _exit(EXIT_SUCCESS); break; default: // parent int status = -10; // if this is not a bg process if( !is_bg_Proc){ // wait for child waitpid(childId, &status, 0); if(status == -1){ // error std::cout << std::endl << "** WARNING: Problem with command. Please try again." << std::endl << std::endl; } // std::cout << "parent:parent id = " << getpid() << std::endl; // std::cout << "parent:child id = " << childId << std::endl; } else{ // this is a bg job, so save it to the list // create a new job instance and store it in the vector // tell it its pid #, sssh #,and its fg/bg status // Process::myJobs.push_back( theJob = new Job( cmd_line_args, childId, Process::is_bg_Proc, SSSH::getNextSsshId() ); } } return true; } /* Description * Process child * * Parameters * * * Return Value * void */ void Process::processChild(std::vector<std::string> cmd_line_args, int &result, bool isBGProc) const { //std::cout << "child:child id = " << getpid() << std::endl; // thanks to one of the comments on this page //http://stackoverflow.com/questions/26452771/if-i-have-a-vector-of-strings-how-i-can-use-the-strings-with-execvp-to-execute // I was able to make this work without a lot of code changes // I was having a terrible time trying to get my vector of strings // as an array of pointers to char arrays // needed for execvp() std::vector<char *> commandVector; // most processes will only have one job, so iterator overhead // probably not necessary size_t size = cmd_line_args.size(); for(size_t cnt = 0; cnt < size; cnt++){ // skip the & for bg processes if( (cnt == (size-1) && (isBGProc == true) )){ // if were at the last element of a background command // skip it so the & isnt' included in the system call // token for linux shell, but not when using system calls continue; } commandVector.push_back( &cmd_line_args[cnt][0] ); } // execvp expects null terminating commandVector.push_back(NULL); // pass the vector's internal array to execvp char **command = &commandVector[0]; result = execvp(command[0], command); } /* * Description * test for pipes * * Parameters * command line input * * Return Value * bool */ bool Process::isPiped(std::vector <std::string> cmd_line_args) const { for(std::vector<std::string>::iterator iter = cmd_line_args.begin(); iter != cmd_line_args.end(); iter++){ if( *iter == "|"){ return true; } } return false; } /* * Description * set if piped job * * Parameters * bool * * Return Value * bool */ void Process::setPiped(bool piped) { Process::is_piped_Proc = piped; } /* * Description * test for environmental variables * * Parameters * command line input * * Return Value * bool */ bool Process::isEV(std::vector <std::string> cmd_line_args) const { std::string tmp; for(std::vector<std::string>::iterator iter = cmd_line_args.begin(); iter != cmd_line_args.end(); iter++){ tmp = *iter; if( tmp.c_str()[0] == '$'){ return true; } } return false; } /* * Description * test for pipes * * Parameters * command line input * * Return Value * bool */ bool Process::processPipedJobs(std::vector <std::string> cmd_line_args) { /* The use of system() is from * * The Linux Programming Interface - Michael Kerrisk * Ch 27.6 Executing a Shell Command: system() * * Kerrisk suggests using system() over exec*() calls, * due to its ease in facilitating such programming, unless performance * is of critical concern, due to the additional overhead imposed by the * use of system(). */ // create space between cmd prompt and output std::cout << std::endl; std::string str = toString(cmd_line_args); int result = system( str.c_str() ); if(result < 0){ // alert if error std::cout << "Warning: Error processing piped command" << std::endl; std::cout << str << std::endl; } return true; } bool Process::processMultipleFGJobs(std::vector <std::string> cmd_line_args) { /* The use of system() is from * * The Linux Programming Interface - Michael Kerrisk * Ch 27.6 Executing a Shell Command: system() * * Kerrisk suggests using system() over exec*() calls, * due to its ease in facilitating such programming, unless performance * is of critical concern, due to the additional overhead imposed by the * use of system(). */ // create space between cmd prompt and output std::cout << std::endl; std::string str = toString(cmd_line_args); int result = system( str.c_str() ); if(result < 0){ // alert if error std::cout << "Warning: Error processing multiple foreground command" << std::endl; std::cout << str << std::endl; } return true; } /* * Description * test for background job * * Parameters * command line input * * Return Value * bool */ bool Process::processEV(std::vector <std::string> cmd_line_args) { /* The use of system() is from * * The Linux Programming Interface - Michael Kerrisk * Ch 27.6 Executing a Shell Command: system() * * Kerrisk suggests using system() over exec*() calls, * due to its ease in facilitating such programming, unless performance * is of critical concern, due to the additional overhead imposed by the * use of system(). */ // create space between cmd prompt and output std::cout << std::endl; std::string str = toString(cmd_line_args); int result = system( str.c_str() ); if(result < 0){ // alert if error std::cout << "Warning: Error processing command" << std::endl; std::cout << str << std::endl; } return true; } /* * Description * test for background job * * Parameters * command line input * * Return Value * bool */ bool Process::isBG(std::vector <std::string> cmd_line_args) const { if( !cmd_line_args.empty() ){ return (cmd_line_args.back() == "&"); }else{ return false; } } // ============================================================================= /* * Description * print status of running background processes * * Parameters * * Return Value * void */ void Process::printBGRunningJobs() { // get a copy Job *tmpJob = Process::theJob; if( tmpJob != NULL ){ if( tmpJob->isBGJob() && tmpJob->isRunning() ){ tmpJob->printPretty(); tmpJob->setPrintStatus(true); } } } // ============================================================================= /* * Description * print status of running background processes * * Parameters * * Return Value * void */ void Process::printBGFinishedJobs() { // get a copy (copy constructor should work) Job *tmpJob = Process::theJob; if( tmpJob != NULL ){ if( tmpJob->isBGJob() && !(tmpJob->isRunning()) ){ tmpJob->printPretty(); // decrement the count SSSH::decSsshId(); delete theJob; theJob = NULL; } } } // ============================================================================= /* * Description * how many jobs doe this process contain * * Parameters * * Return Value * number of jobs the process contains */ bool Process::isEmpty() { return Process::theJob == NULL; } // ============================================================================= /* * Description * is this a bg process * * Parameters * * Return Value * number of jobs the process contains */ bool Process::isBGProcess() { return Process::is_bg_Proc; } // ============================================================================= /* * Description * is this a piped process * * Parameters * * Return Value * bool */ bool Process::isPipedProcess() { return Process::is_piped_Proc; } // ============================================================================= /* * Description * return the job * * Parameters * * Return Value * the job */ Job* Process::getJob() { return Process::theJob; } // ============================================================================= /* * Description * multiple fg jobs? * * Parameters * * Return Value * bool */ bool Process::isMultipleFG(std::vector<std::string> cmd_line_args) { for(std::vector<std::string>::iterator iter = cmd_line_args.begin(); iter != cmd_line_args.end(); iter++){ if( *iter == ";"){ return true; } } return false; } // ============================================================================= /* * Description * change vector to string * * Parameters * vector of string * * Return Value * new string */ std::string Process::toString(std::vector<std::string> tmp_old) { std::string tmp_new; for(size_t i = 0; i < tmp_old.size(); i++){ if(i == 0){ // eliminates an empty char in position 0 tmp_new = tmp_old.at(i); }else{ tmp_new = tmp_new + " " + tmp_old.at(i); } } return tmp_new; }
22.324881
128
0.538085
[ "vector" ]
6afecfa203a58f35999bb1017ff44bef98815a4c
27,770
cc
C++
physics/tests/photoelectricTest/GeantV/photoelectricTest_GV.cc
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
2
2016-10-16T14:37:42.000Z
2018-04-05T15:49:09.000Z
physics/tests/photoelectricTest/GeantV/photoelectricTest_GV.cc
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
physics/tests/photoelectricTest/GeantV/photoelectricTest_GV.cc
Geant-RnD/geant
ffff95e23547531f3254ada2857c062a31f33e8f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * @brief photoelectricTest_GV: GeantV-Real-physics application to test models for gamma's photoelectric. * @author M Bandieramonte from M Novak example * @date April 2017 * * A GeantV-Real-physics application to test models for gamma's photoelectric available in the * given physics list: sauterGavrilaPhotoElectric (for the moment) The models are extracted from * the given physics list. Note, that the corresponding Geant4 application does not use a * physics-list to build-up and initialise the models but instead it creates and initialises * the models directly. * Both the energy and angular distributions of the emitted photoelectron can be tested * with the application (see the available options below by running with --help option) * * Run ./photoelectricTest_GV --help for more details! * The corresponding Geant4 test application is photoelectricTest_G4. */ #include <iostream> #include <iomanip> #include <vector> #include <cstdio> #include <ctime> #include <sstream> #include <getopt.h> #include <err.h> #include "Geant/Material.h" #include "Geant/Element.h" #include "Geant/MaterialCuts.h" // vecgeom includes #include "volumes/LogicalVolume.h" #include "volumes/Box.h" #include "Geant/Region.h" #include "Geant/PhysicsParameters.h" // just to clear them #include "Geant/ELossTableManager.h" #include "Geant/ELossTableRegister.h" #include "Geant/Particle.h" #include "Geant/Electron.h" #include "Geant/Positron.h" #include "Geant/Gamma.h" #include "Geant/EMModel.h" #include "Geant/SauterGavrilaPhotoElectricModel.h" #include "Geant/LightTrack.h" #include "Geant/PhysicsData.h" // from geantV #include "Geant/Typedefs.h" #include "Geant/TaskData.h" // a simple histogram class: can be changed later #include "Hist.h" using geantphysics::Material; using geantphysics::Element; using geantphysics::MaterialCuts; using geantphysics::PhysicsParameters; using geantphysics::Particle; using geantphysics::Electron; using geantphysics::Positron; using geantphysics::Gamma; using geantphysics::ELossTableManager; using geantphysics::ELossTableRegister; // the photoelectric model using geantphysics::EMModel; using geantphysics::SauterGavrilaPhotoElectricModel; using geantphysics::LightTrack; using geantphysics::PhysicsData; using userapplication::Hist; // // default values of the input parameters static std::string particleName("gamma"); // primary particle is gamma static std::string materialName("NIST_MAT_Pb"); // material is lead static std::string photoElectricModelName( "SauterGavrilaPhotoElectric"); // name of the sauterGavrilaPhotoElectric model to test static int numHistBins = 100; // number of histogram bins between min/max values static double numSamples = 1.e+07; // number of required final state samples - 1.e+07; static double primaryEnergy = 0.01; // primary particle energy in [GeV] - 0.01=10MeV static double prodCutValue = 0.1; // by default in length and internal units i.e. [cm] static bool isProdCutInLength = true; // is the production cut value given in length ? static bool isAlias = false; // is the Alias sampling active ? static struct option options[] = { {"particle-name (possible particle names: gamma) - default: gamma", required_argument, 0, 'p'}, {"material-name (with a NIST_MAT_ prefix; see more in material doc.) - default: NIST_MAT_Pb", required_argument, 0, 'm'}, {"primary-energy (in internal energy units i.e. [GeV]) - default: 0.01", required_argument, 0, 'E'}, {"number-of-samples (number of required final state samples) - default: 1.e+7", required_argument, 0, 'f'}, {"number-of-bins (number of bins in the histogram) - default: 100", required_argument, 0, 'n'}, {"model-name (sauterGavrilaPhotoElectric) - default: sauterGavrilaPhotoElectric", required_argument, 0, 'b'}, {"isAlias (is the Alias sampling active ?) - default: false", required_argument, 0, 's'}, {"cut-value (secondary production threshold value for all particles) - default: 0.1", required_argument, 0, 'c'}, {"cut-in-energy (is the production cut value given in energy ? ) - default: false", no_argument, 0, 'e'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; void help(); //***********************************************************************************************// //***** THIS WILL BE MODEL SPECIFIC: contains the final state sampling and hist. building ******// // method to create photon energy distribution using a SautergavrilaPhotoElectricModel as input argument double sampleDistribution(double numSamples, double primaryEnergy, const MaterialCuts *matCut, Particle *primParticle, EMModel *model, Hist *histo1, Hist *histo2, Hist *histo3); //***********************************************************************************************// double CalculateDiffCrossSection(double tau, double cosTheta); //===========================================================================================// // int main(int argc, char *argv[]) { // //============================== Get input parameters =====================================// while (true) { int c, optidx = 0; c = getopt_long(argc, argv, "eh:m:E:f:n:c:p:b:s:", options, &optidx); if (c == -1) break; switch (c) { case 0: c = options[optidx].val; /* fall through */ case 's': isAlias = true; break; case 'm': materialName = optarg; break; case 'E': primaryEnergy = (double)strtof(optarg, NULL); if (primaryEnergy <= 0) errx(1, "primary particle energy must be positive"); break; case 'f': numSamples = (double)strtof(optarg, NULL); if (numSamples <= 0) errx(1, "number of final state samples must be positive"); break; case 'n': numHistBins = (int)strtof(optarg, NULL); if (numHistBins <= 0) errx(1, "number of histogram bins must be positive"); break; case 'c': prodCutValue = (double)strtof(optarg, NULL); if (prodCutValue <= 0) errx(1, "production cut value must be positive"); break; case 'p': particleName = optarg; break; case 'b': photoElectricModelName = optarg; break; case 'e': isProdCutInLength = false; break; case 'h': help(); return 0; break; default: help(); errx(1, "unknown option %c", c); } } //===========================================================================================// //============================= Set user defined input data =================================// // Create target material: which is supposed to be a NIST Material Material *matDetector = Material::NISTMaterial(materialName); // // Set particle kinetic energy double kineticEnergy = primaryEnergy; // // Set production cuts if needed bool iscutinlength = isProdCutInLength; double gcut = prodCutValue; double emcut = prodCutValue; double epcut = prodCutValue; //===========================================================================================// // if (!(photoElectricModelName=="photoElectricSB" || photoElectricModelName=="photoElectricRel")) { // std::cout << " *** unknown photoElectric. model name = " << photoElectricModelName << std::endl; // help(); // return 0; //} // Create primary particle Particle *particle = Gamma::Definition(); // bool isElectron = true; std::string pname; //============= Initialization i.e. building up and init the physics ========================// // Create a dummy vecgeom::geometry: // - with only one volume i.e. world // - create a region and set production cuts // // create a vecgeom::LogicalVolume vecgeom::UnplacedBox worldParams = vecgeom::UnplacedBox(1., 1., 1.); vecgeom::LogicalVolume worldl(&worldParams); // create one region and assigne to the logical volume vecgeom::Region *aRegion = new vecgeom::Region("ARegion", iscutinlength, gcut, emcut, epcut); worldl.SetRegion(aRegion); // set the material pointer in the world logical volume worldl.SetMaterialPtr((void *)matDetector); vecgeom::GeoManager::Instance().SetWorld(worldl.Place()); vecgeom::GeoManager::Instance().CloseGeometry(); // Create all(we have only one) MaterialCuts MaterialCuts::CreateAll(); //===========================================================================================// // if primary particle energy < gamma production cut => there is no secondary gamma production // So get the MaterialCuts of the target: we have only one const MaterialCuts *matCut = MaterialCuts::GetMaterialCut(aRegion->GetIndex(), matDetector->GetIndex()); // and get the gamma production cut energy // double gammaCutEnergy = matCut->GetProductionCutsInEnergy()[0]; /*if (kineticEnergy<=gammaCutEnergy) { std::cout<< " *** Primary energy = " << kineticEnergy/geant::units::MeV << " [MeV] is <= gamma production cut = " << gammaCutEnergy/geant::units::MeV << " [MeV] so there is no secondary gamma production at this energy!" << std::endl; return 0; }*/ //*******************************************************************************************// //************ THIS CONTAINS MODEL SPECIFIC PARTS ***********// // // Create a SauterGavrilaPhotoElectricModel model for gammas: // - Create a SauterGavrilaPhotoElectricModel model std::cout << "Creating the model SauterGavrilaPhotoElectricModel\n"; EMModel *emModel = new SauterGavrilaPhotoElectricModel(photoElectricModelName, true); // true to use Alias Sampling method EMModel *emModel_rej = new SauterGavrilaPhotoElectricModel(photoElectricModelName, false); // true to use Alias Sampling method // - Set low/high energy usage limits to their min/max possible values emModel->SetLowEnergyUsageLimit(0.01 * geant::units::keV); emModel->SetHighEnergyUsageLimit(100.0 * geant::units::GeV); emModel_rej->SetLowEnergyUsageLimit(0.01 * geant::units::keV); emModel_rej->SetHighEnergyUsageLimit(100.0 * geant::units::GeV); // //*******************************************************************************************// // check is primary energy is within the usage limits of the model if (kineticEnergy < emModel->GetLowEnergyUsageLimit() || kineticEnergy > emModel->GetHighEnergyUsageLimit()) { std::cout << " *** Primary energy = " << kineticEnergy / geant::units::GeV << " [GeV] should be the min/max energy usage limits of the selected model: \n" << " - model name = " << emModel->GetName() << " \n" << " - low energy usage limit = " << emModel->GetLowEnergyUsageLimit() / geant::units::GeV << " [GeV]\n" << " - high energy usage limit = " << emModel->GetHighEnergyUsageLimit() / geant::units::GeV << " [GeV]\n" << " there is no secondary gamma production otherwise!" << std::endl; return 0; } //=========== Set the active regions of the model and one physics-parameter object ==========// // - Set the model to be active in region index 0 (emModel->GetListActiveRegions()).resize(1); // one region (emModel->GetListActiveRegions())[0] = true; // make it active there // - Create one PhysicsParameters object (with defult values) PhysicsParameters *physPars = new PhysicsParameters(); // - Set it to be active in region index 0 (physPars->GetListActiveRegions()).resize(1); (physPars->GetListActiveRegions())[0] = true; // - Initialisation of the model emModel->Initialize(); //===========================================================================================// //=========== Set the active regions of the model and one physics-parameter object ==========// // - Set the model to be active in region index 0 (emModel_rej->GetListActiveRegions()).resize(1); // one region (emModel_rej->GetListActiveRegions())[0] = true; // make it active there // - Create one PhysicsParameters object (with defult values) PhysicsParameters *physPars_rej = new PhysicsParameters(); // - Set it to be active in region index 0 (physPars_rej->GetListActiveRegions()).resize(1); (physPars_rej->GetListActiveRegions())[0] = true; // - Initialisation of the model emModel_rej->Initialize(); //===========================================================================================// //===========================================================================================// //== Use the EMModel interface methods of the model to compute some integrated quantities ==// // std::cout << " " << matCut->GetMaterial() << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " MaterialCuts: \n" << matCut; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Particle = " << particle->GetName() << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Kinetic energy = " << kineticEnergy / geant::units::MeV << " [MeV] " << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Model name = " << emModel->GetName() << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Alias sampling = " << isAlias << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; // check if we compute atomic-cross section: only for single elemnt materials bool isSingleElementMaterial = false; if (matCut->GetMaterial()->GetNumberOfElements() == 1) { isSingleElementMaterial = true; } // // Note: atomicCrossSection is computed only in case of materials that has single element double atomicCrossSection = 0.0; double macroscopicCrossSection = 0.0; // // use the model to compute atomic cross section (only in case of single element materials) std::cout << std::setw(14) << std::scientific << std::endl; if (isSingleElementMaterial) { const Element *elem = (matCut->GetMaterial()->GetElementVector())[0]; std::cout << std::setw(14) << std::scientific << std::endl; atomicCrossSection = emModel->ComputeXSectionPerAtom(elem, matCut, kineticEnergy, particle); } // UNCOMMENT TO TEST CrossSectionPerVolume method // clock_t start = clock(); // for (int i= 0; i<stat; i++) // use the model to compute macroscopic cross section macroscopicCrossSection = emModel->ComputeMacroscopicXSection(matCut, kineticEnergy, particle); // clock_t end = clock(); // std::cout<<"ComputeMacroscopicXSection ex-time: "<<(end-start)/(double(CLOCKS_PER_SEC))<<std::endl; // // print out integrated quantities: // -atomic cross section if (isSingleElementMaterial) { std::cout << " cross section per atom :"; std::cout << std::setw(14) << std::scientific << std::right << atomicCrossSection / (geant::units::barn) << std::setw(14) << std::left << " [barn]"; std::cout << std::endl; } // // -macroscopic cross section std::cout << " cross section per volume :"; std::cout << std::setw(14) << std::scientific << std::right << macroscopicCrossSection / (1. / geant::units::cm) << std::setw(14) << std::left << " [1/cm]"; std::cout << std::endl; //===========================================================================================// //*******************************************************************************************// //************ THIS CONTAINS MODEL SPECIFIC PARTS ***********// // // std::string hname = photoElectricModelName + "_GV_" + str; // energy distribution(k) is sampled in varibale log10(k/primaryEnergy) // angular distribution(theta) is sampled in variable log10(1-cos(theta)*0.5) // // set up a histogram for the secondary photoelectron energy(k) : log10(k/primaryEnergy) double xMin = -3.0; // std::log10(primaryEnergy);//std::log10(gammaCutEnergy/primaryEnergy); double xMax = 3.0; Hist *histo_photoelectron_energy = new Hist(xMin, xMax, numHistBins); Hist *histo_photoelectron_energy_rej = new Hist(xMin, xMax, numHistBins); // // set up histogram for the secondary photoelectron direction(theta) : log10(1-cos(theta)*0.5) xMin = -12.; xMax = 0.5; Hist *histo_photoelectron_angular = new Hist(xMin, xMax, numHistBins); Hist *histo_photoelectron_angular_rej = new Hist(xMin, xMax, numHistBins); xMin = -1.0001; xMax = 1.0001; Hist *histo_angle = new Hist(xMin, xMax, numHistBins); Hist *histo_angle_rej = new Hist(xMin, xMax, numHistBins); // THE PRIMARY DOES NOT SURVIVE TO THE P.E. PROCESS SO WE DON'T NEED OTHER HISTOGRAMS - THEY MUST BE EMPTY ////The primary does not survive to photoelectric effect, so these other histo are not needed // set up a histogram for the post interaction primary gamma energy(E1) : log10(E1/primaryEnergy) // xMin = -12;//std::log10(1.-gammaCutEnergy/primaryEnergy); // xMax = 0.1; // Hist *histo_prim_energy = new Hist(xMin, xMax, numHistBins); // // set up a histogram for the post interaction primary e-/e+ direction(theta) : log10(1-cos(theta)*0.5) // xMin = -16.; // xMax = 0.5; // Hist *histo_prim_angular = new Hist(xMin, xMax, numHistBins); // start sampling std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Sampling is running : ..................................................... " << std::endl; // call sampling method double timeInSec = sampleDistribution(numSamples, kineticEnergy, matCut, particle, emModel, histo_photoelectron_energy, histo_photoelectron_angular, histo_angle); double timeInSec_rej = sampleDistribution(numSamples, kineticEnergy, matCut, particle, emModel_rej, histo_photoelectron_energy_rej, histo_photoelectron_angular_rej, histo_angle_rej); std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Time of sampling Alias = " << timeInSec << " [s]" << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Time of sampling Rejection = " << timeInSec_rej << " [s]" << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; std::cout << " Writing histograms into files. " << std::endl; std::cout << " -------------------------------------------------------------------------------- " << std::endl; // print out histogram to file: fileName char fileName[512]; std::ostringstream strs; strs << primaryEnergy * 1000; std::string str = strs.str(); sprintf(fileName, "photoElectric_%s_GV_photoelectron_energy_%s_%sMeV.ascii", photoElectricModelName.c_str(), (matCut->GetMaterial()->GetName()).c_str(), str.c_str()); FILE *f = fopen(fileName, "w"); Hist *histo = histo_photoelectron_energy; double norm = 0.25 / numSamples; for (int i = 0; i < histo->GetNumBins(); ++i) { fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm); // printf("%d\t%.8g\t%.8g\n",i,histo->GetX()[i]+0.5*histo->GetDelta(),histo->GetY()[i]*norm); } fclose(f); delete histo; // sprintf(fileName, "photoElectric_%s_GV_photoelectron_angular_%s_%sMeV.ascii", photoElectricModelName.c_str(), (matCut->GetMaterial()->GetName()).c_str(), str.c_str()); f = fopen(fileName, "w"); histo = histo_photoelectron_angular; norm = 1. / numSamples; for (int i = 0; i < histo->GetNumBins(); ++i) { fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm); } fclose(f); delete histo; sprintf(fileName, "photoElectric_%s_GV_photoelectron_angular_rejection_%s_%sMeV.ascii", photoElectricModelName.c_str(), (matCut->GetMaterial()->GetName()).c_str(), str.c_str()); f = fopen(fileName, "w"); histo = histo_photoelectron_angular_rej; norm = 1. / numSamples; for (int i = 0; i < histo->GetNumBins(); ++i) { fprintf(f, "%d\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i] * norm); } fclose(f); delete histo; double xsec[numHistBins]; double cosTheta; // sprintf(fileName,"GV_%s_cosTheta_%s_%sMeV.ascii",photoElectricModelName.c_str(),(matCut->GetMaterial()->GetName()).c_str(), // str.c_str()); sprintf(fileName, "cosTheta_%sMeV.ascii", str.c_str()); f = fopen(fileName, "w"); histo = histo_angle; norm = 1. / numSamples; double sum = 0; for (int i = 0; i < histo->GetNumBins(); ++i) { cosTheta = histo->GetX()[i] + 0.5 * histo->GetDelta(); //+0.5*deltaTheta; xsec[i] = CalculateDiffCrossSection(kineticEnergy / geant::units::kElectronMassC2, cosTheta); sum += xsec[i]; } for (int i = 0; i < histo->GetNumBins(); ++i) { // fprintf(f,"%d\t%.8g\t%.8g\t%.8g\t%.8g\n",i,histo->GetX()[i]+0.5*histo->GetDelta(),histo->GetY()[i]*norm, // xsec[i]/sum,(histo->GetY()[i]*norm)/(xsec[i]/sum) ); fprintf(f, "%d\t%.8g\t%.8g\t%.8g\t%.8g\n", i, histo->GetX()[i] + 0.5 * histo->GetDelta(), histo->GetY()[i], histo_angle_rej->GetY()[i], ((histo->GetY()[i]) / (histo_angle_rej->GetY()[i]))); } fclose(f); delete histo; //*******************************************************************************************// // end std::cout << " ================================================================================ " << std::endl << std::endl; // delete some objects delete emModel; PhysicsParameters::Clear(); // clear the ELossTableManager(will alos delete all ELossTable-s) and ELossTableRegister ELossTableManager::Instance().Clear(); ELossTableRegister::Instance().Clear(); MaterialCuts::ClearAll(); Material::ClearAllMaterials(); // will delete all Elements and Isotoes as well return 0; } void help() { std::cout << "\n " << std::setw(120) << std::setfill('=') << "" << std::setfill(' ') << std::endl; std::cout << " Model-level GeantV test for testing GeantV e-/e+ models for photoElectric e- emission." << std::endl; std::cout << "\n Usage: photoElectricTest_GV [OPTIONS] \n" << std::endl; for (int i = 0; options[i].name != NULL; i++) { printf("\t-%c --%s\n", options[i].val, options[i].name); } std::cout << "\n " << std::setw(120) << std::setfill('=') << "" << std::setfill(' ') << std::endl; } double CalculateDiffCrossSection(double tau, double cosTheta) { // Based on Geant4 : G4SauterGavrilaAngularDistribution // SauterGavrila approximation for K-shell, correct to the first \alphaZ order // input : energy0 (incoming photon energy) // input : cosTheta (cons(theta) of photo-electron) // output : dsigma (differential cross section, K-shell only) // double tau = energy0 / geant::units::kElectronMassC2; // gamma and beta: Lorentz factors of the photoelectron double gamma = tau + 1.0; double beta = std::sqrt(tau * (tau + 2.0)) / gamma; double z = 1 - beta * cosTheta; double z2 = z * z; double z4 = z2 * z2; double y = 1 - cosTheta * cosTheta; // sen^2(theta) double dsigma = (y / z4) * (1 + 0.5 * gamma * (tau) * (gamma - 2) * z); return dsigma; } //*******************************************************************************************// //************ THIS CONTAINS MODEL SPECIFIC PARTS ***********// // // implementation of the final state distribution sampling double sampleDistribution(double numSamples, double primaryEnergy, const MaterialCuts *matCut, Particle *primParticle, EMModel *emModel, Hist *histo1, Hist *histo2, Hist * /*histo3*/) { double ekin = primaryEnergy; double dirx = 0.0; // direction double diry = 0.0; double dirz = 1.0; int gvcode = primParticle->GetInternalCode(); // internal code of the primary particle i.e. e- // Set up a dummy geant::TaskData and its geantphysics::PhysicsData member: they are needed in the final state // sampling geant::TaskData *td = new geant::TaskData(1, 1); PhysicsData *phd = new PhysicsData(); td->fPhysicsData = phd; // Set up a the primary light track for photoElectric. LightTrack primaryLT; // init time clock_t start_time = clock(); for (long int i = 0; i < numSamples; ++i) { // we will use members: // fMaterialCutCoupleIndex <==> // current MaterialCuts index // fKinE <==> fE-fMass // kinetic energy; will be set to the new kinetic energy // fGVcode <==> fGVcode // internal particle code // fIntLen <==> fIntLen // pre-step lambda for accounting energy loss i.e. to see if it is a delta inter. // fXdir <==> fXdir // direction vector x comp. will be set to the new direction x comp. // fYdir <==> fYdir // direction vector y comp. will be set to the new direction y comp. // fZdir <==> fZdir // direction vector z comp. will be set to the new direction z comp. primaryLT.SetMaterialCutCoupleIndex(matCut->GetIndex()); primaryLT.SetKinE(ekin); primaryLT.SetGVcode(gvcode); // primaryLT.SetTrackIndex(0); // not important now primaryLT.SetDirX(dirx); primaryLT.SetDirY(diry); primaryLT.SetDirZ(dirz); // primaryLT.SetTotalMFP(1.0); // not important now // // clean the number of secondary tracks used (in PhysicsData) td->fPhysicsData->ClearSecondaries(); // // invoke the interaction int numSecs = emModel->SampleSecondaries(primaryLT, td); // get the secondary track i.e. the gamma if (numSecs > 0) { LightTrack *secondaryLT = td->fPhysicsData->GetListOfSecondaries(); // reduced gamma energy double ePhotoElectron = secondaryLT[0].GetKinE(); if (ePhotoElectron > 0.0) { ePhotoElectron = log10((ekin - ePhotoElectron) * 1000000); histo1->Fill(ePhotoElectron, 1.0); } double costPhotoElectron = secondaryLT[0].GetDirZ(); // if(costPhotoElectron>1) costPhotoElectron=1; // else if (costPhotoElectron<-1) costPhotoElectron=-11; // histo3->Fill(costPhotoElectron, 1.0); costPhotoElectron = 0.5 * (1.0 - costPhotoElectron); if (costPhotoElectron > 0.0) { costPhotoElectron = std::log10(costPhotoElectron); if (costPhotoElectron > -12.) { histo2->Fill(costPhotoElectron, 1.0); } } } } clock_t end_time = clock(); return (end_time - start_time) / (double(CLOCKS_PER_SEC)); } //*******************************************************************************************//
44.935275
128
0.57807
[ "geometry", "object", "vector", "model" ]
ed08ca23f1c6e8a6caf30d09226151b99e0ece6f
7,584
cpp
C++
tests/gl-500-primitive-shading-nv.cpp
LRLVEC/OpenGLReading
827cd99f6dfa0c86a26b38d21495217465b1c731
[ "Unlicense" ]
2
2019-03-02T14:46:25.000Z
2020-06-27T09:34:08.000Z
tests/gl-500-primitive-shading-nv.cpp
LRLVEC/OpenGLReading
827cd99f6dfa0c86a26b38d21495217465b1c731
[ "Unlicense" ]
null
null
null
tests/gl-500-primitive-shading-nv.cpp
LRLVEC/OpenGLReading
827cd99f6dfa0c86a26b38d21495217465b1c731
[ "Unlicense" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Samples Pack (ogl-samples.g-truc.net) /// /// Copyright (c) 2004 - 2014 G-Truc Creation (www.g-truc.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. /////////////////////////////////////////////////////////////////////////////////// #include "test.hpp" namespace { char const * SAMPLE_VERT_SHADER("gl-500/primitive-shading-nv.vert"); char const * SAMPLE_GEOM_SHADER("gl-500/primitive-shading-nv.geom"); char const * SAMPLE_FRAG_SHADER("gl-500/primitive-shading-nv.frag"); GLsizei const VertexCount(4); GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v2fc4ub); glf::vertex_v2fc4ub const VertexData[VertexCount] = { glf::vertex_v2fc4ub(glm::vec2(-1.0f,-1.0f), glm::u8vec4(255, 0, 0, 255)), glf::vertex_v2fc4ub(glm::vec2( 1.0f,-1.0f), glm::u8vec4(255, 255, 255, 255)), glf::vertex_v2fc4ub(glm::vec2( 1.0f, 1.0f), glm::u8vec4( 0, 255, 0, 255)), glf::vertex_v2fc4ub(glm::vec2(-1.0f, 1.0f), glm::u8vec4( 0, 0, 255, 255)) }; GLsizei const ElementCount(6); GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort); GLushort const ElementData[ElementCount] = { 0, 1, 2, 2, 3, 0 }; namespace buffer { enum type { VERTEX, ELEMENT, TRANSFORM, CONSTANT, MAX }; }//namespace buffer GLuint ProgramName(0); GLuint VertexArrayName(0); std::vector<GLuint> BufferName(buffer::MAX); }//namespace class gl_500_primitive_shading_nv : public test { public: gl_500_primitive_shading_nv(int argc, char* argv[]) : test(argc, argv, "gl-500-primitive-shading-nv", test::CORE, 4, 5), QueryName(0) {} private: GLuint QueryName; bool testError() { compiler Compiler; Compiler.create(GL_GEOMETRY_SHADER, getDataDirectory() + SAMPLE_GEOM_SHADER, "--version 450 --profile core --define GEN_ERROR"); return !Compiler.check(); } bool initProgram() { bool Validated = true; if(Validated) { compiler Compiler; GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + SAMPLE_VERT_SHADER, "--version 450 --profile core"); GLuint GeomShaderName = Compiler.create(GL_GEOMETRY_SHADER, getDataDirectory() + SAMPLE_GEOM_SHADER, "--version 450 --profile core"); GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + SAMPLE_FRAG_SHADER, "--version 450 --profile core"); ProgramName = glCreateProgram(); glAttachShader(ProgramName, VertShaderName); glAttachShader(ProgramName, GeomShaderName); glAttachShader(ProgramName, FragShaderName); glLinkProgram(ProgramName); Validated = Validated && Compiler.check(); Validated = Validated && Compiler.checkProgram(ProgramName); } return Validated && this->checkError("initProgram"); } bool initVertexArray() { glGenVertexArrays(1, &VertexArrayName); glBindVertexArray(VertexArrayName); glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]); glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fc4ub), BUFFER_OFFSET(0)); glVertexAttribPointer(semantic::attr::COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(glf::vertex_v2fc4ub), BUFFER_OFFSET(sizeof(glm::vec2))); glEnableVertexAttribArray(semantic::attr::POSITION); glEnableVertexAttribArray(semantic::attr::COLOR); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]); glBindVertexArray(0); return this->checkError("initVertexArray"); } bool initBuffer() { glGenBuffers(buffer::MAX, &BufferName[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementSize, ElementData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]); glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLint UniformBufferOffset(0); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &UniformBufferOffset); GLint UniformBlockSize = glm::max(GLint(sizeof(glm::mat4)), UniformBufferOffset); glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]); glBufferData(GL_UNIFORM_BUFFER, UniformBlockSize, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); return this->checkError("initBuffer"); } bool initQuery() { glGenQueries(1, &QueryName); int QueryBits(0); glGetQueryiv(GL_PRIMITIVES_GENERATED, GL_QUERY_COUNTER_BITS, &QueryBits); bool Validated = QueryBits >= 32; return Validated && this->checkError("initQuery"); } bool begin() { bool Validated = true;//testError(); if(Validated) Validated = initQuery(); if(Validated) Validated = initProgram(); if(Validated) Validated = initBuffer(); if(Validated) Validated = initVertexArray(); return Validated && this->checkError("begin"); } bool end() { glDeleteBuffers(buffer::MAX, &BufferName[0]); glDeleteVertexArrays(1, &VertexArrayName); glDeleteProgram(ProgramName); return this->checkError("end"); } bool render() { glm::ivec2 WindowSize(this->getWindowSize()); { glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]); glm::mat4* Pointer = (glm::mat4*)glMapBufferRange( GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4) * 1, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); //glm::mat4 Projection = glm::perspectiveFov(glm::pi<float>() * 0.25f, 640.f, 480.f, 0.1f, 100.0f); glm::mat4 Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); *Pointer = Projection * this->view() * Model; // Make sure the uniform buffer is uploaded glUnmapBuffer(GL_UNIFORM_BUFFER); } glViewport(0, 0, WindowSize.x, WindowSize.y); glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)[0]); glUseProgram(ProgramName); glBindVertexArray(VertexArrayName); glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]); glBeginQuery(GL_PRIMITIVES_GENERATED, QueryName); glDrawElementsInstancedBaseVertex(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, 0, 1, 0); glEndQuery(GL_PRIMITIVES_GENERATED); GLuint64 PrimitivesGenerated = 0; glGetQueryObjectui64v(this->QueryName, GL_QUERY_RESULT, &PrimitivesGenerated); return PrimitivesGenerated > 0; } }; int main(int argc, char* argv[]) { int Error(0); gl_500_primitive_shading_nv Test(argc, argv); Error += Test(); return Error; }
32
141
0.716904
[ "render", "vector", "model", "transform" ]
ed092f46f2ce45729b1f307914d93b15d371d8d1
1,865
cc
C++
src/elasticize/gpu/framebuffer.cc
jaesung-cs/elasticize
b59f19c9fcddcbac623cb4e0efb3e6acf55b34b0
[ "MIT" ]
null
null
null
src/elasticize/gpu/framebuffer.cc
jaesung-cs/elasticize
b59f19c9fcddcbac623cb4e0efb3e6acf55b34b0
[ "MIT" ]
null
null
null
src/elasticize/gpu/framebuffer.cc
jaesung-cs/elasticize
b59f19c9fcddcbac623cb4e0efb3e6acf55b34b0
[ "MIT" ]
null
null
null
#include <elasticize/gpu/framebuffer.h> #include <elasticize/gpu/engine.h> #include <elasticize/gpu/graphics_shader.h> #include <elasticize/gpu/image.h> namespace elastic { namespace gpu { class Framebuffer::Impl { public: Impl() = delete; Impl(Engine engine, uint32_t width, uint32_t height, GraphicsShader graphicsShader, std::initializer_list<std::reference_wrapper<const Image>> attachments) : engine_(engine) , width_(width) , height_(height) { auto device = engine_.device(); std::vector<vk::ImageView> imageViews; for (const auto& attachment : attachments) imageViews.push_back(attachment.get().imageView()); auto framebufferInfo = vk::FramebufferCreateInfo() .setWidth(width) .setHeight(height) .setRenderPass(graphicsShader.renderPass()) .setAttachments(imageViews) .setLayers(1); framebuffer_ = device.createFramebuffer(framebufferInfo); } ~Impl() { auto device = engine_.device(); if (framebuffer_) device.destroyFramebuffer(framebuffer_); } operator vk::Framebuffer() const noexcept { return framebuffer_; } auto width() const noexcept { return width_; } auto height() const noexcept { return height_; } private: Engine engine_; uint32_t width_; uint32_t height_; vk::Framebuffer framebuffer_; }; Framebuffer::Framebuffer(Engine engine, uint32_t width, uint32_t height, GraphicsShader graphicsShader, std::initializer_list<std::reference_wrapper<const Image>> attachments) : impl_(std::make_shared<Impl>(engine, width, height, graphicsShader, attachments)) { } Framebuffer::~Framebuffer() = default; Framebuffer::operator vk::Framebuffer() const noexcept { return *impl_; } uint32_t Framebuffer::width() const noexcept { return impl_->width(); } uint32_t Framebuffer::height() const noexcept { return impl_->height(); } } }
25.902778
175
0.724397
[ "vector" ]
ed0b626d8c9f5dd9a8c66e4b5467e437e60b99f1
6,076
cpp
C++
visa/iga/IGALibrary/Frontend/SendDescriptorDecoding.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
440
2018-01-30T00:43:22.000Z
2022-03-24T17:28:37.000Z
visa/iga/IGALibrary/Frontend/SendDescriptorDecoding.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
225
2018-02-02T03:10:47.000Z
2022-03-31T10:50:37.000Z
visa/iga/IGALibrary/Frontend/SendDescriptorDecoding.cpp
kurapov-peter/intel-graphics-compiler
98f7c938df0617912288385d243d6918135f0713
[ "Intel", "MIT" ]
138
2018-01-30T08:15:11.000Z
2022-03-22T14:16:39.000Z
/*========================== begin_copyright_notice ============================ Copyright (C) 2020-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include "SendDescriptorDecoding.hpp" #include "../bits.hpp" #include "../IR/Messages.hpp" #include "../strings.hpp" #include <algorithm> using namespace iga; static const char *getSFIDString(Platform p, uint32_t sfid) { static const char *HSWBDW_SFIDS[] { "null", // 0000b the null function nullptr, // 0001b "sampler", // 0010b new sampler "gateway", // 0011b gateway "sampler", // 0100b (old sampler encoding) "hdc.rc", // 0101b render cache "hdc.urb", // 0110b unified return buffer "spawner", // 0111b thread spawner "vme", // 1000b video motion estimation "hdc.ccdp", // 1001b constant cache "hdc.dc0", // 1010b "pi", // 1011b pixel interpolator "hdc.dc1", // 1100b data-cache 1 "cre", // 1101b check and refinement nullptr, nullptr, }; static const char *SKL_SFIDS[] { "null", // 0000b the null function nullptr, // 0001b "sampler", // 0010b new sampler "gateway", // 0011b gateway "hdc.dc2", // 0100b data cache 2 (old sampler) "hdc.rc", // 0101b render cache "hdc.urb", // 0110b unified return buffer "spawner", // 0111b thread spawner "vme", // 1000b video motion estimation "hdc.dcro", // 1001b data cache read only (renaming) "hdc.dc0", // 1010b "pi", // 1011b pixel interpolator "hdc.dc1", // 1100b data-cache 1 "cre", // 1101b check and refinement nullptr, nullptr, }; const char **sfidTable = p < Platform::GEN9 ? HSWBDW_SFIDS : SKL_SFIDS; if (sfidTable[sfid] == nullptr) { return "?"; } return sfidTable[sfid]; } static uint32_t getHeaderBit(uint32_t desc) {return getBits(desc, 19, 1);} void iga::EmitSendDescriptorInfo( Platform p, SFID sfid, ExecSize execSize, bool dstNonNull, int dstLen, int src0Len, int src1Len, const SendDesc &exDesc, const SendDesc &desc, std::stringstream &ss) { DiagnosticList ws, es; ////////////////////////////////////// // emit the: "wr:1h+2, rd:4" part ss << "wr:"; if (src0Len >= 0) { ss << src0Len; } else if (desc.isReg()) { ss << "a0." << (int)desc.reg.subRegNum << "[28:25]"; } else { ss << "?"; } bool hasHeaderBit = true; bool hasEncodedDstLen = true; if (hasHeaderBit && desc.isImm() && getHeaderBit(desc.imm)) { ss << "h"; } // ss << "+"; if (src1Len >= 0) { ss << src1Len; } else if (exDesc.isReg()) { ss << "a0." << (int)exDesc.reg.subRegNum << "[10:6]"; } else { ss << "?"; } ss << ", rd:"; if (desc.isReg()) { ss << "a0." << (int)desc.reg.subRegNum << "[24:20]"; } else if (hasEncodedDstLen) { ss << dstLen; } else { if (dstNonNull) { if (dstLen < 0) { PayloadLengths lens(p, sfid, execSize, desc.imm); dstLen = lens.dstLen; } if (dstLen >= 0) { ss << dstLen; } else { // we cannot decode this message and thus cannot infer the // destination length; so we just say so ss << "non-zero"; } } else { ss << "0"; } } // //////////////////////////////// // now the message description if (p < Platform::XE) { // pre-XE, emit the SFID first since it's not part of the op yet if (exDesc.isReg()) { ss << "; sfid a0." << (int)exDesc.reg.subRegNum << "[3:0]"; } else { // no a0.0 ss << "; " << getSFIDString(p, exDesc.imm & 0xF); } } if (desc.isImm()) { const DecodeResult dr = tryDecode(p, sfid, execSize, exDesc, desc, nullptr); if (dr.syntax.isValid()) { ss << "; " << dr.syntax.sym(); } else if (!dr.info.description.empty()) { ss << "; " << dr.info.description; } else { if (!es.empty() && es.back().second.find("unsupported sfid") == std::string::npos) { ss << "; " << es.back().second << "?"; } // skip unsupported SFIDs } bool appendUvrLod = dr.info.hasAttr(MessageInfo::Attr::HAS_UVRLOD) && src0Len > 0; if (appendUvrLod) { // Deduce the number of typed coordinates included // (e.g. U, V, R, LOD) const int BITS_PER_REG = 256; // We do this by assuming address coordinates are in GRF padded // SOA order: // - U's registers, then V's, then R's, the LOD's // - if a cooridate takes less than a full GRF, then we pad it up // to that // - not all decoded combinations are supported in hardware, but // that's between the user and their deity; we're an assembler // and can't track the endlessly changing spec // Typical usage is the default message and a GRF's worth of A32 // elements as the SIMD size (e.g. 8 for TGL) // // bits for a full vector's worth of U's, V's, etc.... const int regsPerCoord = std::max<int>(1, dr.info.execWidth*dr.info.addrSizeBits/BITS_PER_REG); switch (src0Len/regsPerCoord) { case 1: ss << "; u"; break; case 2: ss << "; u,v"; break; case 3: ss << "; u,v,r"; break; case 4: ss << "; u,v,r,lod"; break; } } // U,V,R,LOD } } // iga::EmitSendDescriptorInfo
31.319588
80
0.488479
[ "render", "vector" ]
ed0bd488adcde875cec52ec4d433be1a54bbbf9d
3,665
cpp
C++
runtime/test_util.cpp
samee/oalex
cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8
[ "Apache-2.0" ]
null
null
null
runtime/test_util.cpp
samee/oalex
cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8
[ "Apache-2.0" ]
null
null
null
runtime/test_util.cpp
samee/oalex
cacdd0bf744f3092e721e7e0a48a4ef0d6194fe8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019-2020 The oalex authors. 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 https://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 "fmt/format.h" #include "test_util.h" #include "util_impl.h" using oalex::assertHasDiagWithSubstr; using oalex::Bug; using oalex::BugWarn; using oalex::Diag; using oalex::Input; using oalex::InputDiags; using oalex::isSubstr; using oalex::showDiags; using oalex::UserErrorEx; using fmt::format_to; using fmt::memory_buffer; using fmt::print; using fmt::to_string; using std::string; using std::string_view; using std::vector; auto fmt::formatter<std::vector<std::string>>::format( const vector<string>& v, fmt::format_context& ctx) -> decltype(format_to(ctx.out(), "")) { if(v.empty()) return format_to(ctx.out(), "{{}}"); format_to(ctx.out(), "{{{}", v[0]); for(size_t i=1;i<v.size();++i) format_to(ctx.out(), ", {}", v[i]); return format_to(ctx.out(), "}}"); } namespace oalex{ void showDiags(const vector<Diag>& diags) { memory_buffer buf; format_to(buf, "diags:\n"); for(const auto& d : diags) format_to(buf, " {}\n", string(d)); BugWarn("{}", to_string(buf)); } void assertHasDiagWithSubstr(string_view testName, const vector<Diag>& diags, string_view expectedDiag) { for(const Diag& d : diags) if(isSubstr(expectedDiag, d.msg)) return; showDiags(diags); Bug("{} didn't get the expected diag: {}", testName, expectedDiag); } void assertHasDiagWithSubstrOnce( string_view testName, const vector<Diag>& diags, string_view expectedDiag) { size_t c = 0; for(const Diag& d : diags) if(isSubstr(expectedDiag, d.msg)) c++; if(c == 1) return; showDiags(diags); if(c == 0) Bug("{} didn't get the expected diag: {}", testName, expectedDiag); else Bug("{} emitted the expected diag too many times", testName); } void assertHasDiagWithSubstrAt(string_view testName, const vector<Diag>& diags, string_view expectedDiag, size_t expectedStPos) { for(const Diag& d : diags) { if(d.stPos != expectedStPos+1) continue; // The +1 is from Diags() ctor if(!isSubstr(expectedDiag, d.msg)) continue; return; } showDiags(diags); Bug("{} didn't get the expected diag at position {}: {}", testName, expectedStPos, expectedDiag); } void assertEmptyDiags(string_view testName, const vector<Diag>& diags) { if(diags.empty()) return; for(const auto& d:diags) print(stderr, "{}\n", string(d)); Bug("{} had unexpected errors", testName); } class GetFromString : public InputStream { std::string src; size_t i=0; public: explicit GetFromString(std::string_view src):src(src) {} int16_t getch() override { return i<src.size()?src[i++]:-1; } }; void assertProducesDiag(std::string_view testName, std::string_view input, std::string_view err, void (*cb)(oalex::InputDiags&, size_t&)) { GetFromString si{input}; InputDiags ctx{Input{&si}}; size_t i = 0; try { cb(ctx, i); }catch(UserErrorEx& ex) { Error(ctx,0,0,ex.what()); // demote Fatal() error to non-fatal. } assertHasDiagWithSubstr(testName, ctx.diags, err); } } // namespace oalex
32.149123
80
0.67176
[ "vector" ]
ed0cad5313d07344536e01805c6ac226f023922f
24,230
hpp
C++
pywraps/py_kernwin_choose.hpp
cclauss/src
701bb1b44e1fd9e716661bebd896b87086665cfd
[ "BSD-3-Clause" ]
2
2019-07-08T11:58:27.000Z
2019-07-08T13:23:57.000Z
pywraps/py_kernwin_choose.hpp
Bia10/src
15b9ab2535222e492cd21b8528c27f763fb799d6
[ "BSD-3-Clause" ]
null
null
null
pywraps/py_kernwin_choose.hpp
Bia10/src
15b9ab2535222e492cd21b8528c27f763fb799d6
[ "BSD-3-Clause" ]
null
null
null
#ifndef __PY_KERNWIN_CHOOSE__ #define __PY_KERNWIN_CHOOSE__ //<code(py_kernwin_choose)> //------------------------------------------------------------------------ // Helper functions class py_choose_t; typedef std::map<PyObject *, py_choose_t *> py2c_choose_map_t; static py2c_choose_map_t choosers; py_choose_t *choose_find_instance(PyObject *self) { py2c_choose_map_t::iterator it = choosers.find(self); return it == choosers.end() ? NULL : it->second; } void choose_add_instance(PyObject *self, py_choose_t *pych) { choosers[self] = pych; } void choose_del_instance(PyObject *self) { py2c_choose_map_t::iterator it = choosers.find(self); if ( it != choosers.end() ) choosers.erase(it); } // set `prm` to the integer value of the `name` attribute template <class T> static void py_get_int(PyObject *self, T *prm, const char *name) { ref_t attr(PyW_TryGetAttrString(self, name)); if ( attr != NULL && attr.o != Py_None ) *prm = T(PyInt_AsLong(attr.o)); } //------------------------------------------------------------------------ // Python's chooser class class py_choose_t { public: // Python object link PyObject *self; // the chooser object will be created in the create() method chooser_base_t *chobj; enum { CHOOSE_HAVE_INIT = 0x0001, CHOOSE_HAVE_GETICON = 0x0002, CHOOSE_HAVE_GETATTR = 0x0004, CHOOSE_HAVE_INS = 0x0008, CHOOSE_HAVE_DEL = 0x0010, CHOOSE_HAVE_EDIT = 0x0020, CHOOSE_HAVE_ENTER = 0x0040, CHOOSE_HAVE_REFRESH = 0x0080, CHOOSE_HAVE_SELECT = 0x0100, CHOOSE_HAVE_ONCLOSE = 0x0200, CHOOSE_IS_EMBEDDED = 0x0400, }; // Callback flags (to tell which callback exists and which not) // One of CHOOSE_xxxx uint32 cb_flags; // Chooser title qstring title; // Column widths intvec_t widths; // Chooser headers qstrvec_t header_strings; qvector<const char *> header; public: py_choose_t(PyObject *self_) : self(self_), chobj(NULL), cb_flags(0) { PYW_GIL_GET; choose_add_instance(self, this); // Increase object reference Py_INCREF(self); } // if the chooser object was created it will delete linked Python's // chooser. // if it was not created (e.g. because of the lack of a mandatory // callback) it will be deleted in choose_close(). ~py_choose_t() { PYW_GIL_GET; // Remove from list choose_del_instance(self); Py_XDECREF(self); } // common callbacks bool idaapi init() { if ( (cb_flags & CHOOSE_HAVE_INIT) == 0 ) return chobj->chooser_base_t::init(); PYW_GIL_GET; pycall_res_t pyres(PyObject_CallMethod(self, (char *)S_ON_INIT, NULL)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chobj->chooser_base_t::init(); return bool(PyInt_AsLong(pyres.result.o)); } size_t idaapi get_count() const { PYW_GIL_GET; pycall_res_t pyres(PyObject_CallMethod(self, (char *)S_ON_GET_SIZE, NULL)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return 0; return size_t(PyInt_AsLong(pyres.result.o)); } void idaapi get_row( qstrvec_t *cols, int *icon_, chooser_item_attrs_t *attrs, size_t n) const { PYW_GIL_GET; // Call Python PYW_GIL_CHECK_LOCKED_SCOPE(); pycall_res_t list( PyObject_CallMethod( self, (char *)S_ON_GET_LINE, "i", int(n))); if ( list.result != NULL ) { // Go over the List returned by Python and convert to C strings for ( int i = chobj->columns - 1; i >= 0; --i ) { borref_t item(PyList_GetItem(list.result.o, Py_ssize_t(i))); if ( item == NULL ) continue; const char *str = PyString_AsString(item.o); if ( str != NULL ) (*cols)[i] = str; } } *icon_ = chobj->icon; if ( (cb_flags & CHOOSE_HAVE_GETICON) != 0 ) { pycall_res_t pyres( PyObject_CallMethod( self, (char *)S_ON_GET_ICON, "i", int(n))); if ( pyres.result != NULL ) *icon_ = PyInt_AsLong(pyres.result.o); } if ( (cb_flags & CHOOSE_HAVE_GETATTR) != 0 ) { pycall_res_t pyres( PyObject_CallMethod( self, (char *)S_ON_GET_LINE_ATTR, "i", int(n))); if ( pyres.result != NULL && PyList_Check(pyres.result.o) ) { PyObject *item; if ( (item = PyList_GetItem(pyres.result.o, 0)) != NULL ) attrs->color = PyInt_AsLong(item); if ( (item = PyList_GetItem(pyres.result.o, 1)) != NULL ) attrs->flags = PyInt_AsLong(item); } } } void idaapi closed() { if ( (cb_flags & CHOOSE_HAVE_ONCLOSE) == 0 ) { chobj->chooser_base_t::closed(); return; } PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod(self, (char *)S_ON_CLOSE, NULL)); // delete UI hook PyObject_DelAttrString(self, "ui_hooks_trampoline"); } public: static py_choose_t *find_chooser(const char *title) { return static_cast<py_choose_t *>(::get_chooser_obj(title)); } void close() { // will trigger closed() close_chooser(chobj->title); } bool activate() { TWidget *widget = get_widget(); if ( widget == NULL ) return false; activate_widget(widget, true); return true; } TWidget *get_widget() { return find_widget(chobj->title); } // Create a chooser. // If it doesn't detect the "embedded" attribute, then the chooser window // is created and displayed. // See ::choose() for the returned values. // \retval NO_ATTR some mandatory attribute is missing int create(); inline PyObject *get_self() { return self; } void do_refresh() { refresh_chooser(chobj->title); } chooser_base_t *get_chobj() const { return chobj; } bool is_valid() const { return chobj != NULL; } bool is_embedded() const { return (cb_flags & CHOOSE_IS_EMBEDDED) != 0; } }; //------------------------------------------------------------------------ // link from the chooser object to the Python's chooser struct py_chooser_link_t { py_choose_t *link; // link to Python's chooser py_chooser_link_t(py_choose_t *pych) : link(pych) {} ~py_chooser_link_t() { delete link; } }; //------------------------------------------------------------------------ // we do not use virtual subclasses so we use #define for common code #define DEFINE_COMMON_CALLBACKS \ virtual void *get_chooser_obj() ida_override { return link; } \ virtual bool idaapi init() ida_override { return link->init(); } \ virtual size_t idaapi get_count() const ida_override \ { \ return link->get_count(); \ } \ virtual void idaapi get_row( \ qstrvec_t *cols, \ int *icon_, \ chooser_item_attrs_t *attrs, \ size_t n) const ida_override \ { \ link->get_row(cols, icon_, attrs, n); \ } \ virtual void idaapi closed() ida_override { link->closed(); } //------------------------------------------------------------------------ // chooser class without multi-selection class py_chooser_single_t : public py_chooser_link_t, public chooser_t { public: py_chooser_single_t( py_choose_t *pych, uint32 flags_ = 0, int columns_ = 0, const int *widths_ = NULL, const char *const *header_ = NULL, const char *title_ = NULL) : py_chooser_link_t(pych), chooser_t(flags_, columns_, widths_, header_, title_) {} DEFINE_COMMON_CALLBACKS virtual cbret_t idaapi ins(ssize_t n) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_INS) == 0 ) return chooser_t::ins(n); PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_INSERT_LINE, "i", int(n))); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_t::ins(n); return py_as_cbret(pyres.result.o); } virtual cbret_t idaapi del(size_t n) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_DEL) == 0 ) return chooser_t::del(n); PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_DELETE_LINE, "i", int(n))); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_t::del(n); return py_as_cbret(pyres.result.o); } virtual cbret_t idaapi edit(size_t n) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_EDIT) == 0 ) return chooser_t::edit(n); PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_EDIT_LINE, "i", int(n))); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_t::edit(n); return py_as_cbret(pyres.result.o); } virtual cbret_t idaapi enter(size_t n) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_ENTER) == 0 ) return chooser_t::enter(n); PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_SELECT_LINE, "i", int(n))); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_t::enter(n); return py_as_cbret(pyres.result.o); } virtual cbret_t idaapi refresh(ssize_t n) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_REFRESH) == 0 ) return chooser_t::refresh(n); PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_REFRESH, "i", int(n))); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_t::refresh(n); return py_as_cbret(pyres.result.o); } virtual void idaapi select(ssize_t n) const ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_SELECT) == 0 ) { chooser_t::select(n); return; } PYW_GIL_GET; pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_SELECTION_CHANGE, "i", int(n))); } protected: // [ changed, idx ] static cbret_t py_as_cbret(PyObject *py_ret) { cbret_t ret; if ( PySequence_Check(py_ret) ) { { newref_t item(PySequence_GetItem(py_ret, 0)); if ( item.o != NULL && PyInt_Check(item.o) ) ret.changed = cbres_t(PyInt_AsLong(item.o)); } if ( ret.changed != NOTHING_CHANGED ) { newref_t item(PySequence_GetItem(py_ret, 1)); if ( item.o != NULL && PyInt_Check(item.o) ) ret.idx = ssize_t(PyInt_AsSsize_t(item.o)); } } return ret; } }; //------------------------------------------------------------------------ // chooser class with multi-selection class py_chooser_multi_t : public py_chooser_link_t, public chooser_multi_t { public: py_chooser_multi_t( py_choose_t *pych, uint32 flags_ = 0, int columns_ = 0, const int *widths_ = NULL, const char *const *header_ = NULL, const char *title_ = NULL) : py_chooser_link_t(pych), chooser_multi_t(flags_, columns_, widths_, header_, title_) {} DEFINE_COMMON_CALLBACKS virtual cbres_t idaapi ins(sizevec_t *sel) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_INS) == 0 ) return chooser_multi_t::ins(sel); PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(*sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_INSERT_LINE, "O", py_list.o)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_multi_t::ins(sel); return py_as_cbres_sel(sel, pyres.result.o); } virtual cbres_t idaapi del(sizevec_t *sel) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_DEL) == 0 ) return chooser_multi_t::del(sel); PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(*sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_DELETE_LINE, "O", py_list.o)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_multi_t::del(sel); return py_as_cbres_sel(sel, pyres.result.o); } virtual cbres_t idaapi edit(sizevec_t *sel) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_EDIT) == 0 ) return chooser_multi_t::edit(sel); PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(*sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_EDIT_LINE, "O", py_list.o)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_multi_t::edit(sel); return py_as_cbres_sel(sel, pyres.result.o); } virtual cbres_t idaapi enter(sizevec_t *sel) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_ENTER) == 0 ) return chooser_multi_t::enter(sel); PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(*sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_SELECT_LINE, "O", py_list.o)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_multi_t::enter(sel); return py_as_cbres_sel(sel, pyres.result.o); } virtual cbres_t idaapi refresh(sizevec_t *sel) ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_REFRESH) == 0 ) return chooser_multi_t::refresh(sel); PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(*sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_REFRESH, "O", py_list.o)); if ( pyres.result == NULL || pyres.result.o == Py_None ) return chooser_multi_t::refresh(sel); return py_as_cbres_sel(sel, pyres.result.o); } virtual void idaapi select(const sizevec_t &sel) const ida_override { if ( (link->cb_flags & py_choose_t::CHOOSE_HAVE_SELECT) == 0 ) { chooser_multi_t::select(sel); return; } PYW_GIL_GET; ref_t py_list(PyW_SizeVecToPyList(sel)); pycall_res_t pyres( PyObject_CallMethod( link->self, (char *)S_ON_SELECTION_CHANGE, "O", py_list.o)); } protected: // [ changed, idx, ... ] static cbres_t py_as_cbres_sel(sizevec_t *sel, PyObject *py_ret) { // this is an easy but not an optimal way of converting if ( !PySequence_Check(py_ret) || PyW_PyListToSizeVec(sel, py_ret) <= 0 ) { sel->clear(); return NOTHING_CHANGED; } cbres_t res = cbres_t(sel->front()); sel->erase(sel->begin()); return res; } }; //------------------------------------------------------------------------ int py_choose_t::create() { PYW_GIL_CHECK_LOCKED_SCOPE(); // Get flags uint32 flags; ref_t flags_attr(PyW_TryGetAttrString(self, S_FLAGS)); if ( flags_attr == NULL ) return chooser_base_t::NO_ATTR; if ( PyInt_Check(flags_attr.o) ) flags = uint32(PyInt_AsLong(flags_attr.o)); // instruct TChooser destructor to delete this chooser when window // closes flags &= ~CH_KEEP; // Get the title if ( !PyW_GetStringAttr(self, S_TITLE, &title) ) return chooser_base_t::NO_ATTR; // Get columns ref_t cols_attr(PyW_TryGetAttrString(self, "cols")); if ( cols_attr == NULL ) return chooser_base_t::NO_ATTR; // Get col count int columns = int(PyList_Size(cols_attr.o)); if ( columns < 1 ) return chooser_base_t::NO_ATTR; // Get columns caption and widthes header_strings.resize(columns); header.resize(columns); widths.resize(columns); for ( int i = 0; i < columns; ++i ) { // get list item: [name, width] borref_t list(PyList_GetItem(cols_attr.o, i)); borref_t v(PyList_GetItem(list.o, 0)); // Extract string const char *str = v == NULL ? "" : PyString_AsString(v.o); header_strings[i] = str; header[i] = header_strings[i].c_str(); // Extract width int width; borref_t v2(PyList_GetItem(list.o, 1)); // No width? Guess width from column title if ( v2 == NULL ) width = strlen(str); else width = PyInt_AsLong(v2.o); widths[i] = width; } // Check what callbacks we have static const struct { const char *name; unsigned int have; // 0 = mandatory callback int chooser_t_flags; } callbacks[] = { { S_ON_INIT, CHOOSE_HAVE_INIT, 0 }, { S_ON_GET_SIZE, 0 }, { S_ON_GET_LINE, 0 }, { S_ON_GET_ICON, CHOOSE_HAVE_GETICON, 0 }, { S_ON_GET_LINE_ATTR, CHOOSE_HAVE_GETATTR, 0 }, { S_ON_INSERT_LINE, CHOOSE_HAVE_INS, CH_CAN_INS }, { S_ON_DELETE_LINE, CHOOSE_HAVE_DEL, CH_CAN_DEL }, { S_ON_EDIT_LINE, CHOOSE_HAVE_EDIT, CH_CAN_EDIT }, { S_ON_SELECT_LINE, CHOOSE_HAVE_ENTER, 0 }, { S_ON_REFRESH, CHOOSE_HAVE_REFRESH, CH_CAN_REFRESH }, { S_ON_SELECTION_CHANGE, CHOOSE_HAVE_SELECT, 0 }, { S_ON_CLOSE, CHOOSE_HAVE_ONCLOSE, 0 }, }; // we can forbid some callbacks explicitly uint32 forbidden_cb = 0; ref_t forbidden_cb_attr(PyW_TryGetAttrString(self, "forbidden_cb")); if ( forbidden_cb_attr != NULL && PyInt_Check(forbidden_cb_attr.o) ) forbidden_cb = uint32(PyInt_AsLong(forbidden_cb_attr.o)); cb_flags = 0; for ( int i = 0; i < qnumber(callbacks); ++i ) { ref_t cb_attr(PyW_TryGetAttrString(self, callbacks[i].name)); bool have_cb = cb_attr != NULL && PyCallable_Check(cb_attr.o); if ( have_cb && (forbidden_cb & callbacks[i].have) == 0 ) { cb_flags |= callbacks[i].have; flags |= callbacks[i].chooser_t_flags; } else { // Mandatory field? if ( callbacks[i].have == 0 ) return chooser_base_t::NO_ATTR; } } // create chooser object if ( (flags & CH_MULTI) == 0 ) { chobj = new py_chooser_single_t( this, flags, columns, widths.begin(), header.begin(), title.c_str()); } else { chobj = new py_chooser_multi_t( this, flags, columns, widths.begin(), header.begin(), title.c_str()); } // Get *x1,y1,x2,y2 py_get_int(self, &chobj->x0, "x1"); py_get_int(self, &chobj->y0, "y1"); py_get_int(self, &chobj->x1, "x2"); py_get_int(self, &chobj->y1, "y2"); // Get *icon py_get_int(self, &chobj->icon, "icon"); // Get *popup names // An array of 4 strings: ("Insert", "Delete", "Edit", "Refresh") ref_t pn_attr(PyW_TryGetAttrString(self, S_POPUP_NAMES)); if ( pn_attr != NULL && PyList_Check(pn_attr.o) ) { int npopups = int(PyList_Size(pn_attr.o)); if ( npopups > chooser_base_t::NSTDPOPUPS ) npopups = chooser_base_t::NSTDPOPUPS; for ( int i = 0; i < npopups; ++i ) { const char *str = PyString_AsString(PyList_GetItem(pn_attr.o, i)); chobj->popup_names[i] = str; } } // Check if *embedded ref_t emb_attr(PyW_TryGetAttrString(self, S_EMBEDDED)); if ( emb_attr != NULL && PyObject_IsTrue(emb_attr.o) == 1 ) { cb_flags |= CHOOSE_IS_EMBEDDED; py_get_int(self, &chobj->width, "width"); py_get_int(self, &chobj->height, "height"); return 0; // success } // run ssize_t res; if ( !chobj->is_multi() ) { // Get *deflt ssize_t deflt = 0; py_get_int(self, &deflt, "deflt"); res = ((chooser_t *)chobj)->choose(deflt); } else { // Get *deflt sizevec_t deflt; ref_t deflt_attr(PyW_TryGetAttrString(self, "deflt")); if ( deflt_attr != NULL && PyList_Check(deflt_attr.o) && PyW_PyListToSizeVec(&deflt, deflt_attr.o) < 0 ) { deflt.clear(); } res = ((chooser_multi_t *)chobj)->choose(deflt); } // assert: `this` is deleted in the case of the modal chooser return res; } //------------------------------------------------------------------------ int choose_create(PyObject *self) { py_choose_t *pych; pych = choose_find_instance(self); if ( pych != NULL && pych->is_valid() ) { if ( !pych->is_embedded() ) pych->activate(); return chooser_base_t::ALREADY_EXISTS; } if ( pych == NULL ) pych = new py_choose_t(self); // assert: returned value != chooser_base_t::ALREADY_EXISTS return pych->create(); } //------------------------------------------------------------------------ void choose_close(PyObject *self) { py_choose_t *pych = choose_find_instance(self); if ( pych == NULL ) return; if ( !pych->is_valid() ) { // the chooser object is not created // so we delete Python's chooser ourself delete pych; return; } // embedded chooser is deleted by form if ( pych->is_embedded() ) return; // modal chooser is closed and deleted in py_choose_t::create() // assert: !pych->is_modal() // close the non-modal chooser, // in turn this will lead to the deletion of the object pych->close(); } //------------------------------------------------------------------------ void choose_refresh(PyObject *self) { py_choose_t *pych = choose_find_instance(self); if ( pych != NULL && pych->is_valid() ) pych->do_refresh(); } //------------------------------------------------------------------------ void choose_activate(PyObject *self) { py_choose_t *pych = choose_find_instance(self); if ( pych != NULL && pych->is_valid() ) pych->activate(); } //------------------------------------------------------------------------ // Return the C instance as 64bit number uint64 _choose_get_embedded_chobj_pointer(PyObject *self) { PYW_GIL_CHECK_LOCKED_SCOPE(); uint64 ptr = 0; py_choose_t *pych = choose_find_instance(self); if ( pych != NULL && pych->is_valid() && pych->is_embedded() ) ptr = uint64(pych->get_chobj()); return ptr; } //------------------------------------------------------------------------ PyObject *choose_find(const char *title) { py_choose_t *pych = py_choose_t::find_chooser(title); if ( pych == NULL || !pych->is_valid() ) Py_RETURN_NONE; PyObject *self = pych->get_self(); Py_INCREF(self); return self; } //</code(py_kernwin_choose)> //--------------------------------------------------------------------------- //<inline(py_kernwin_choose)> PyObject *choose_find(const char *title); void choose_refresh(PyObject *self); void choose_close(PyObject *self); int choose_create(PyObject *self); void choose_activate(PyObject *self); uint64 _choose_get_embedded_chobj_pointer(PyObject *self); PyObject *py_get_chooser_data(const char *chooser_caption, int n) { qstrvec_t data; if ( !get_chooser_data(&data, chooser_caption, n) ) Py_RETURN_NONE; PyObject *py_list = PyList_New(data.size()); for ( size_t i = 0; i < data.size(); ++i ) PyList_SetItem(py_list, i, PyString_FromString(data[i].c_str())); return py_list; } //------------------------------------------------------------------------- TWidget *choose_get_widget(PyObject *self) { py_choose_t *pych = choose_find_instance(self); if ( pych == NULL || !pych->is_valid() ) return NULL; return pych->get_widget(); } //</inline(py_kernwin_choose)> #endif // __PY_KERNWIN_CHOOSE__
29.122596
79
0.576847
[ "object" ]
ed0da9b432b11173b30aff4980b0a810ecadd8fe
4,584
hpp
C++
include/EFE.hpp
libingzheren/dna_rs_coding
70ba95627e72a0e90a38d51a6c8f18ede46255e4
[ "Apache-2.0" ]
21
2019-12-01T11:55:24.000Z
2021-12-18T01:57:11.000Z
include/EFE.hpp
libingzheren/dna_rs_coding
70ba95627e72a0e90a38d51a6c8f18ede46255e4
[ "Apache-2.0" ]
4
2021-01-26T09:13:23.000Z
2021-05-26T15:19:01.000Z
include/EFE.hpp
libingzheren/dna_rs_coding
70ba95627e72a0e90a38d51a6c8f18ede46255e4
[ "Apache-2.0" ]
6
2019-12-05T06:14:13.000Z
2021-07-25T09:10:36.000Z
/* A class to represent an extension field */ #ifndef EXTENSION_FIELD #define EXTENSION_FIELD #include <boost/operators.hpp> #include <iostream> #include <ostream> #include <vector> #include "polynomial.hpp" using namespace std; // extension field element (EFE) template<class PFE> class EFE: boost::field_operators< EFE<PFE>, boost::equality_comparable< EFE<PFE> > > { public: //! an element of the extension field is a polynomial with coefficients in the prime field PFE polynomial<PFE> el; //! the degree of the extension static unsigned m; //! primitive polynomial defining the extension field static polynomial<PFE> prim_poly; //! constructors EFE(vector<PFE>& v): el(polynomial<PFE>(v)) {}; EFE(polynomial<PFE>& el_): el(el_) {}; EFE(unsigned x){ // set the coeff with exponent zero to x vector<PFE> tmpv(m, PFE(0) ); tmpv[0] = PFE(x); el = polynomial<PFE>(tmpv); } EFE(){}; EFE& operator += (const EFE& x){ el += x.el; return *this; } EFE& operator -= (const EFE& x){ el -= x.el; return *this; } EFE& operator *= (const EFE& x){ // multiply polynomial<PFE> ptmp = el*x.el; // modulo the primitive polynomial int exp; while( (exp = ptmp.degree() - prim_poly.degree()) >= 0 ){ // difference in exponents //unsigned exp = ptmp.degree() - prim_poly.degree(); // primitive polynomial; to be muliplied.. polynomial<PFE> primtmp = prim_poly; PFE co_mo = ptmp.poly[ptmp.degree()]; co_mo /= prim_poly.poly[prim_poly.degree()]; primtmp.multiply_monomial( co_mo , exp ); ptmp -= primtmp; } ptmp.poly.resize(ptmp.degree()+1); el = ptmp; return *this; } EFE& operator /= (const EFE& x){ *this = (x.inverse() * (*this)); return *this; } //! compute the multiplicative inverse via the extended Euclidean algorithm EFE inverse() const { polynomial<PFE> rem1 = prim_poly; polynomial<PFE> rem2 = el; polynomial<PFE> aux1 = polynomial<PFE>(0); polynomial<PFE> aux2 = polynomial<PFE>(1); while(! rem2.iszero() ){ // res.first = quotient(rem1/rem2) // res.second = remainder(rem1/rem2) pair<polynomial<PFE>, polynomial<PFE> > res = divide<PFE>(rem1,rem2); polynomial<PFE> aux_new = polynomial<PFE>(0) - res.first*aux2 + aux1; // prepare for the next step rem1 = rem2; rem2 = res.second; aux1 = aux2; aux2 = aux_new; } aux1.multiply_monomial(pow(rem1.poly[0],-1), 0); return aux1; } unsigned order() const { // multiplicative neutral element = 1 //PFE one = PFE(1); vector<PFE> vecone = vector<PFE>(1,PFE(1)); EFE one = EFE(vecone); EFE tmp = *this; //EFE(el); unsigned ord = 1; while(!(tmp == one)){ ord++; tmp *= *this; //cout << tmp << endl; } return ord; } /* // not a good solution vector<unsigned> tovec() const { vector<unsigned> vec(m,0); for(unsigned i=0;i<el.poly.size();++i){ vec[i] = el.poly[i].element; } return vec; } */ vector<PFE> tovec() const { if(el.poly.size()!=m){ vector<PFE> tmp(m,PFE(0)); for(unsigned i=0;i<el.poly.size();++i){ tmp[i] = el.poly[i]; } return tmp; }else return el.poly; } bool iszero() const { vector<PFE> veczero = vector<PFE>(1,PFE(0)); EFE zero = EFE(veczero); return (zero == *this); } bool isempty() const { return (el.poly.size() == 0); } bool operator ==(const EFE& x) const { for(unsigned i = 0; i < min(el.poly.size(),x.el.poly.size()); ++i) if(!(x.el.poly[i] == el.poly[i]) ) return false; // need to verify if the coefficients of the larger vector that are necessarily zero in the smaller vector are also zero in the larger vector if(el.poly.size() > x.el.poly.size()){ for(unsigned i = x.el.poly.size() ; i<el.poly.size(); ++i) if( !(el.poly[i].iszero()) ) return false; } else if(el.poly.size() < x.el.poly.size()){ for(unsigned i = el.poly.size(); i<x.el.poly.size(); ++i) if( !(x.el.poly[i].iszero()) ) return false; } return true; } }; template<class PFE> ostream &operator<<(ostream &stream, const EFE<PFE> x) { stream << x.el; return stream; // must return stream }; template<class PFE> EFE<PFE> pow(const EFE<PFE>& a, int exp){ if(a.iszero()) return a; if(exp == 0) { vector<PFE> vecone = vector<PFE>(1,PFE(1)); return EFE<PFE>(vecone); } EFE<PFE> tmp; if(exp < 0){ EFE<PFE> am = a.inverse(); tmp = am; for(unsigned i =1; i < abs(exp); ++i) tmp *= am; } else { // exp > 0 tmp = a; for(unsigned i =1; i < abs(exp); ++i) tmp *= a; } return tmp; }; #endif
22.252427
144
0.611257
[ "vector" ]
ed0e67fa84a6323bf7e523b54142da41a0765728
58,457
cpp
C++
source/adam.cpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
null
null
null
source/adam.cpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
null
null
null
source/adam.cpp
ilelann/adobe_source_libraries
82224d13335398dfebfc77addabab28c4296ecba
[ "BSL-1.0" ]
null
null
null
/* Copyright 2013 Adobe Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /**************************************************************************************************/ #include <adobe/adam.hpp> #include <deque> #include <string> #include <utility> #include <vector> #include <boost/bind/bind.hpp> #include <boost/tuple/tuple.hpp> #include <boost/function.hpp> #include <adobe/algorithm/find.hpp> #include <adobe/algorithm/for_each.hpp> #include <adobe/algorithm/unique.hpp> #include <adobe/algorithm/sort.hpp> #include <adobe/array.hpp> #include <adobe/dictionary.hpp> #include <adobe/name.hpp> #include <adobe/any_regular.hpp> #include <adobe/functional.hpp> #include <adobe/istream.hpp> #include <adobe/table_index.hpp> #include <adobe/virtual_machine.hpp> #ifndef NDEBUG #include <iostream> #endif // NDEBUG /**************************************************************************************************/ using namespace std; using namespace boost::placeholders; /**************************************************************************************************/ namespace anonymous_adam_cpp { // can't instantiate templates on types from real anonymous /**************************************************************************************************/ #ifndef NDEBUG struct check_reentrancy { check_reentrancy(bool& x) : check_m(x) { assert(!x && "FATAL (sparent) : Function Not Reentrant."); check_m = true; } ~check_reentrancy() { check_m = false; } bool& check_m; }; #endif // NDEBUG /**************************************************************************************************/ /* REVISIT (sparent) : Move to utility? This is generally useful to provide a copy for non-copyable types such as boost::signals2::signal<>. */ template <typename T> // T models default constructable struct empty_copy : T { empty_copy() : T() {} empty_copy(const empty_copy&) : T() {} empty_copy& operator=(const empty_copy&) { return *this; } }; /**************************************************************************************************/ typedef adobe::sheet_t sheet_t; // This currently establishes an upperbound on the number of cells in the sheet at 1K. typedef std::bitset<1024> cell_bits_t; typedef int priority_t; struct compare_contributing_t; enum access_specifier_t { access_input, access_interface_input, access_interface_output, access_output, access_logic, access_constant, access_invariant }; /**************************************************************************************************/ /* REVISIT (sparent) : A thought - this could be packaged as a general template function for converting exceptions on function object calls. */ /* REVIST (sparent) : Some version of MSVC didn't like function level try blocks. Need to test. */ void evaluate(adobe::virtual_machine_t& machine, const adobe::line_position_t& position, const adobe::array_t& expression) #ifdef BOOST_MSVC { #endif try { machine.evaluate(expression); } catch (const std::exception& error) { throw adobe::stream_error_t(error, position); } #ifdef BOOST_MSVC } #endif /**************************************************************************************************/ struct scope_count : boost::noncopyable { scope_count(std::size_t& x) : value_m(x) { ++value_m; } ~scope_count() { --value_m; } private: std::size_t& value_m; }; template <typename T> struct scope_value_t : boost::noncopyable { scope_value_t(T& x, const T& v) : value_m(x), store_m(x) { x = v; } ~scope_value_t() { value_m = store_m; } private: T& value_m; T store_m; }; /**************************************************************************************************/ } // namespace anonymous_adam_cpp using namespace anonymous_adam_cpp; /**************************************************************************************************/ namespace adobe { /**************************************************************************************************/ class sheet_t::implementation_t : boost::noncopyable { public: typedef sheet_t::connection_t connection_t; explicit implementation_t(virtual_machine_t& machine); any_regular_t inspect(const array_t& expression); void set(name_t, const any_regular_t&); // input cell. void touch(const name_t*, const name_t*); // range of input cells. any_regular_t get(name_t); const any_regular_t& operator[](name_t) const; void add_input(name_t, const line_position_t&, const array_t& initializer); void add_output(name_t, const line_position_t&, const array_t& expression); void add_constant(name_t, const line_position_t&, const array_t& initializer); void add_constant(name_t, any_regular_t value); void add_logic(name_t, const line_position_t&, const array_t& expression); void add_invariant(name_t, const line_position_t&, const array_t& expression); void add_interface(name_t, bool linked, const line_position_t&, const array_t& initializer, const line_position_t&, const array_t& expression); void add_interface(name_t, any_regular_t initial); void add_relation(const line_position_t&, const array_t& conditional, const relation_t* first, const relation_t* last); connection_t monitor_value(name_t, const monitor_value_t&); // output only // input only connection_t monitor_enabled(name_t, const name_t* first, const name_t* last, const monitor_enabled_t&); connection_t monitor_contributing(name_t, const dictionary_t&, const monitor_contributing_t&); #if 0 connection_t monitor_invariant_contributing(name_t invariant, const monitor_invariant_t&); // REVISIT (sparent) : UNIMPLEMENTED #endif connection_t monitor_invariant_dependent(name_t invariant, const monitor_invariant_t&); bool has_input(name_t) const; bool has_output(name_t) const; void update(); void reinitialize(); void set(const dictionary_t& dictionary); // set input cells to corresponding values in dictionary. dictionary_t contributing(const dictionary_t&) const; // all contributing values that have changed since mark dictionary_t contributing_to_cell(name_t) const; private: struct relation_cell_t; struct cell_t; typedef vector<relation_cell_t*> relation_index_t; typedef vector<relation_t> relation_set_t; struct relation_cell_t { relation_cell_t(const line_position_t& position, const array_t& conditional, const relation_t* first, const relation_t* last) : resolved_m(false), position_m(position), conditional_m(conditional), terms_m(first, last) {} bool resolved_m; line_position_t position_m; array_t conditional_m; relation_set_t terms_m; vector<cell_t*> edges_m; // REVISIT (sparent) : There should be a function object to set members void clear_resolved() { resolved_m = false; } }; struct cell_t { typedef boost::function<any_regular_t()> calculator_t; typedef empty_copy<boost::signals2::signal<void(bool)>> monitor_invariant_list_t; typedef empty_copy<boost::signals2::signal<void(const any_regular_t&)>> monitor_value_list_t; typedef empty_copy<boost::signals2::signal<void(const cell_bits_t&)>> monitor_contributing_list_t; cell_t(access_specifier_t specifier, name_t, const calculator_t& calculator, std::size_t cell_set_pos, cell_t*); // output cell_t(access_specifier_t specifier, name_t, any_regular_t, std::size_t cell_set_pos); // constant cell_t(name_t, any_regular_t, std::size_t cell_set_pos); // input cell cell_t(name_t, bool linked, const calculator_t& init_expression, std::size_t cell_set_pos); // interface cell (input) #if 0 // compiler generated. cell_t(const cell_t& x); cell_t& operator=(const cell_t& x); #endif access_specifier_t specifier_m; name_t name_m; calculator_t calculator_m; bool linked_m; bool invariant_m; priority_t priority_m; // For linked input cells only - zero otherwise bool resolved_m; // For interface cells only - false if cell hasn't been flowed bool evaluated_m; // true if cell has been calculated (or has no calculator). std::size_t relation_count_m; std::size_t initial_relation_count_m; bool dirty_m; // denotes change state_m value any_regular_t state_m; cell_bits_t contributing_m; cell_bits_t init_contributing_m; std::size_t cell_set_pos_m; // self index in sheet_t::cell_set_m calculator_t term_m; // For output half of interface cells this points to corresponding input half. NULL // otherwise. cell_t* interface_input_m; priority_t priority() const { assert((specifier_m == access_interface_input || specifier_m == access_interface_output) && "should not read priority of this cell type"); return interface_input_m ? interface_input_m->priority_m : priority_m; } // For output half of interface cells this points to any possible connected relations. relation_index_t relation_index_m; monitor_value_list_t monitor_value_m; monitor_contributing_list_t monitor_contributing_m; monitor_invariant_list_t monitor_invariant_m; void calculate(); void clear_dirty() { dirty_m = false; relation_count_m = initial_relation_count_m; term_m.clear(); evaluated_m = specifier_m == access_input || specifier_m == access_constant /* || calculator_m.empty() */; /* REVISIT (sparent) : What exactly is the distinction between evaluated and resolved. */ resolved_m = evaluated_m; } /* REVISIT (sparent) : A member wise implementation of swap would be better - but I'm going to swap this way for expendiancy since cell_t will likely change a lot when I get around to rewriting Adam. */ // friend void swap(cell_t& x, cell_t&y) { std::swap(x, y); } }; friend struct cell_t; friend struct compare_contributing_t; any_regular_t calculate_expression(const line_position_t& position, const array_t& expression); any_regular_t calculate_indexed(const line_position_t& position, const array_t& expression, std::size_t index) { return calculate_expression(position, expression).cast<array_t>()[index]; } dictionary_t contributing_set(const dictionary_t&, const cell_bits_t&) const; void initialize_one(cell_t& cell); void enabled_filter(const cell_bits_t& touch_set, std::size_t contributing_index_pos, monitor_enabled_t monitor, const cell_bits_t& new_priority_accessed_bits, const cell_bits_t& new_active_bits); // std::size_t cell_set_to_contributing(std::size_t cell_set_pos) const; priority_t name_to_priority(name_t name) const; void flow(cell_bits_t& priority_accessed); /* NOTE (sparent) : cell_t contains boost::signals2::signal<> which is not copyable. The cells support limited copying until they have monitors attached - this allows them to be placed into a container prior to any connections being made. A deque is used rather than a vector because it does not reallocate when it grows. */ typedef std::deque<cell_t> cell_set_t; typedef std::deque<relation_cell_t> relation_cell_set_t; typedef std::vector<pair<name_t, bool>> get_stack_t; typedef std::vector<cell_t*> index_vector_t; typedef hash_index<cell_t, std::hash<name_t>, equal_to, mem_data_t<cell_t, const name_t>> index_t; index_t name_index_m; index_t setable_index_m; // input of interface or input; index_t input_index_m; index_t output_index_m; index_vector_t invariant_index_m; priority_t priority_high_m; priority_t priority_low_m; cell_bits_t conditional_indirect_contributing_m; virtual_machine_t& machine_m; get_stack_t get_stack_m; std::size_t get_count_m; cell_bits_t init_dirty_m; cell_bits_t priority_accessed_m; cell_bits_t value_accessed_m; cell_bits_t active_m; typedef boost::signals2::signal<void(const cell_bits_t&, const cell_bits_t&)> monitor_enabled_list_t; monitor_enabled_list_t monitor_enabled_m; cell_bits_t accumulate_contributing_m; bool has_output_m; // true if there are any output cells. bool initialize_mode_m; // true during reinitialize call. // Actual cell storage - every thing else is index or state. cell_set_t cell_set_m; relation_cell_set_t relation_cell_set_m; #ifndef NEBUG bool updated_m; bool check_update_reentrancy_m; #endif }; /**************************************************************************************************/ void sheet_t::implementation_t::enabled_filter(const cell_bits_t& touch_set, std::size_t contributing_index_pos, monitor_enabled_t monitor, const cell_bits_t& new_priority_accessed_bits, const cell_bits_t& new_active_bits) { cell_bits_t new_priority_accessed_touch = new_priority_accessed_bits & touch_set; cell_bits_t old_priority_accessed_touch = priority_accessed_m & touch_set; bool unchanged_priority_accessed_touch = (new_priority_accessed_touch ^ old_priority_accessed_touch).none(); cell_t& cell = cell_set_m[contributing_index_pos]; bool active(active_m.test(contributing_index_pos)); bool new_active(new_active_bits.test(contributing_index_pos)); /* REVIST <sean_parent@mac.com> : This is check seems to missing a check on value_accessed_m. A change there might go unnoticed and cause the control active state to go out of sync. */ if (unchanged_priority_accessed_touch && (active == new_active)) return; monitor(new_active || (value_accessed_m.test(cell.cell_set_pos_m) && new_priority_accessed_touch.any())); } /**************************************************************************************************/ /* REVISIT (sparent) : Need to figure out what happens if this is called on an input cell during initialization (before it is resolved). */ void sheet_t::implementation_t::cell_t::calculate() { if (evaluated_m) return; // REVISIT (sparent) : review resolved_m resolved issue. // assert(resolved_m && "Cell in an invalid state?"); // This is to handle conditionals which refer to cells involved in relate clauses if (relation_count_m) throw std::logic_error( make_string("cell ", name_m.c_str(), " is attached to an unresolved relate clause.")); any_regular_t result = calculator_m(); dirty_m = (result != state_m); state_m = std::move(result); evaluated_m = true; } /**************************************************************************************************/ sheet_t::implementation_t::cell_t::cell_t(name_t name, any_regular_t x, std::size_t cell_set_pos) : specifier_m(access_input), name_m(name), invariant_m(false), priority_m(0), resolved_m(true), evaluated_m(true), relation_count_m(0), initial_relation_count_m(0), dirty_m(false), state_m(std::move(x)), cell_set_pos_m(cell_set_pos), interface_input_m(0) { init_contributing_m.set(cell_set_pos); } /**************************************************************************************************/ sheet_t::implementation_t::cell_t::cell_t(name_t name, bool linked, const calculator_t& initializer, std::size_t cell_set_pos) : specifier_m(access_interface_input), name_m(name), calculator_m(initializer), linked_m(linked), invariant_m(false), priority_m(0), resolved_m(true), evaluated_m(true), relation_count_m(0), initial_relation_count_m(0), cell_set_pos_m(cell_set_pos), interface_input_m(0) { contributing_m.set(cell_set_pos); } /**************************************************************************************************/ sheet_t::implementation_t::cell_t::cell_t(access_specifier_t specifier, name_t name, const calculator_t& calculator, std::size_t cell_set_pos, cell_t* input) : specifier_m(specifier), name_m(name), calculator_m(calculator), linked_m(false), invariant_m(false), priority_m(0), resolved_m(false), evaluated_m(calculator_m.empty()), relation_count_m(0), initial_relation_count_m(0), cell_set_pos_m(cell_set_pos), interface_input_m(input) {} /**************************************************************************************************/ sheet_t::implementation_t::cell_t::cell_t(access_specifier_t specifier, name_t name, any_regular_t x, std::size_t cell_set_pos) : specifier_m(specifier), name_m(name), linked_m(false), invariant_m(false), priority_m(0), resolved_m(true), evaluated_m(true), relation_count_m(0), initial_relation_count_m(0), state_m(std::move(x)), cell_set_pos_m(cell_set_pos), interface_input_m(0) {} /**************************************************************************************************/ sheet_t::sheet_t() : object_m(new implementation_t(machine_m)) {} sheet_t::~sheet_t() { delete object_m; } any_regular_t sheet_t::inspect(const array_t& expression) { return object_m->inspect(expression); } void sheet_t::set(name_t input, const any_regular_t& value) { object_m->set(input, value); } void sheet_t::touch(const name_t* first, const name_t* last) { object_m->touch(first, last); } void sheet_t::add_input(name_t input, const line_position_t& position, const array_t& initializer) { object_m->add_input(input, position, initializer); } void sheet_t::add_output(name_t output, const line_position_t& position, const array_t& expression) { object_m->add_output(output, position, expression); } void sheet_t::add_constant(name_t constant, const line_position_t& position, const array_t& initializer) { object_m->add_constant(constant, position, initializer); } void sheet_t::add_constant(name_t name, any_regular_t value) { object_m->add_constant(name, std::move(value)); } void sheet_t::add_logic(name_t logic, const line_position_t& position, const array_t& expression) { object_m->add_logic(logic, position, expression); } void sheet_t::add_invariant(name_t invariant, const line_position_t& position, const array_t& expression) { object_m->add_invariant(invariant, position, expression); } void sheet_t::add_interface(name_t name, bool linked, const line_position_t& position1, const array_t& initializer, const line_position_t& position2, const array_t& expression) { object_m->add_interface(name, linked, position1, initializer, position2, expression); } void sheet_t::add_interface(name_t name, any_regular_t initial) { object_m->add_interface(name, std::move(initial)); } void sheet_t::add_relation(const line_position_t& position, const array_t& conditional, const relation_t* first, const relation_t* last) { object_m->add_relation(position, conditional, first, last); } sheet_t::connection_t sheet_t::monitor_value(name_t output, const monitor_value_t& monitor) { return object_m->monitor_value(output, monitor); } sheet_t::connection_t sheet_t::monitor_contributing(name_t output, const dictionary_t& mark, const monitor_contributing_t& monitor) { return object_m->monitor_contributing(output, mark, monitor); } sheet_t::connection_t sheet_t::monitor_enabled(name_t input, const name_t* first, const name_t* last, const monitor_enabled_t& monitor) { return object_m->monitor_enabled(input, first, last, monitor); } #if 0 sheet_t::connection_t sheet_t::monitor_invariant_contributing(name_t input, const monitor_invariant_t& monitor) { return object_m->monitor_invariant_contributing(input, monitor); } #endif sheet_t::connection_t sheet_t::monitor_invariant_dependent(name_t output, const monitor_invariant_t& monitor) { return object_m->monitor_invariant_dependent(output, monitor); } bool sheet_t::has_input(name_t name) const { return object_m->has_input(name); } bool sheet_t::has_output(name_t name) const { return object_m->has_output(name); } void sheet_t::update() { object_m->update(); } void sheet_t::reinitialize() { object_m->reinitialize(); } void sheet_t::set(const dictionary_t& dictionary) { object_m->set(dictionary); } any_regular_t sheet_t::get(name_t cell) { return object_m->get(cell); } const any_regular_t& sheet_t::operator[](name_t x) const { return (*object_m)[x]; } dictionary_t sheet_t::contributing(const dictionary_t& mark) const { return object_m->contributing(mark); } dictionary_t sheet_t::contributing() const { return object_m->contributing(dictionary_t()); } dictionary_t sheet_t::contributing_to_cell(name_t x) const { return object_m->contributing_to_cell(x); } /**************************************************************************************************/ sheet_t::implementation_t::implementation_t(virtual_machine_t& machine) : name_index_m(std::hash<name_t>(), equal_to(), &cell_t::name_m), input_index_m(std::hash<name_t>(), equal_to(), &cell_t::name_m), output_index_m(std::hash<name_t>(), equal_to(), &cell_t::name_m), priority_high_m(0), priority_low_m(0), machine_m(machine), get_count_m(0), has_output_m(false), initialize_mode_m(false) #ifndef NDEBUG , updated_m(false), check_update_reentrancy_m(false) #endif { } /**************************************************************************************************/ any_regular_t sheet_t::implementation_t::inspect(const array_t& expression) { machine_m.evaluate(expression); any_regular_t result = std::move(machine_m.back()); machine_m.pop_back(); return result; } /**************************************************************************************************/ void sheet_t::implementation_t::set(name_t n, const any_regular_t& v) { #ifndef NDEBUG assert(!check_update_reentrancy_m && "sheet_t::set() cannot be called during call to sheet_t::update()."); updated_m = false; #endif index_t::iterator iter(input_index_m.find(n)); if (iter == input_index_m.end()) { throw std::logic_error(make_string("input cell ", n.c_str(), " does not exist.")); } ++priority_high_m; iter->state_m = v; iter->priority_m = priority_high_m; // Leave contributing untouched. if (iter->specifier_m == access_input) init_dirty_m.set(iter->cell_set_pos_m); } /**************************************************************************************************/ void sheet_t::implementation_t::touch(const name_t* first, const name_t* last) { // REVISIT (sparent) : This should be constrained to interface cells only. // REVISIT (sparent) : This logic is similar to the logic in flow and should be the same. // build an index of the cells to touch sorted by current priority. typedef table_index<priority_t, cell_t> priority_index_t; priority_index_t index(&cell_t::priority_m); // REVISIT (sparent) : This loop is transform but the soft condition in the middle breaks that. // If we resolve the REVISIT() inside the loop so failure on find is a throw then this loop // is transform. while (first != last) { index_t::iterator iter(input_index_m.find(*first)); /* REVISIT (sparent) : Cells that aren't present are ignored because sheets get "scoped" so if a cell isn't touched in a local sheet it might be in a more global scope. Perhaps the client should be keeping two lists and this would go back to an error. */ if (iter != input_index_m.end()) index.push_back(*iter); ++first; } index.sort(); // Touch the cells - keeping their relative priority for (priority_index_t::iterator f(index.begin()), l(index.end()); f != l; ++f) { ++priority_high_m; f->priority_m = priority_high_m; } } /**************************************************************************************************/ void sheet_t::implementation_t::add_input(name_t name, const line_position_t& position, const array_t& initializer) { scope_value_t<bool> scope(initialize_mode_m, true); any_regular_t initial_value; if (initializer.size()) initial_value = calculate_expression(position, initializer); cell_set_m.push_back(cell_t(name, std::move(initial_value), cell_set_m.size())); // REVISIT (sparent) : Non-transactional on failure. input_index_m.insert(cell_set_m.back()); if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", name.c_str(), "'already exists."), position); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_output(name_t name, const line_position_t& position, const array_t& expression) { // REVISIT (sparent) : Non-transactional on failure. cell_set_m.push_back(cell_t(access_output, name, boost::bind(&implementation_t::calculate_expression, boost::ref(*this), position, expression), cell_set_m.size(), nullptr)); output_index_m.insert(cell_set_m.back()); if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", name.c_str(), "'already exists."), position); } has_output_m = true; } /**************************************************************************************************/ // REVISIT (sparent) : Hacked glom of input/output pair. void sheet_t::implementation_t::add_interface(name_t name, bool linked, const line_position_t& position1, const array_t& initializer_expression, const line_position_t& position2, const array_t& expression) { scope_value_t<bool> scope(initialize_mode_m, true); if (initializer_expression.size()) { cell_set_m.push_back( cell_t(name, linked, boost::bind(&implementation_t::calculate_expression, boost::ref(*this), position1, initializer_expression), cell_set_m.size())); } else { cell_set_m.push_back(cell_t(name, linked, cell_t::calculator_t(), cell_set_m.size())); } // REVISIT (sparent) : Non-transactional on failure. input_index_m.insert(cell_set_m.back()); if (initializer_expression.size()) initialize_one(cell_set_m.back()); if (expression.size()) { // REVISIT (sparent) : Non-transactional on failure. cell_set_m.push_back(cell_t(access_interface_output, name, boost::bind(&implementation_t::calculate_expression, boost::ref(*this), position2, expression), cell_set_m.size(), &cell_set_m.back())); } else { cell_set_m.push_back(cell_t(access_interface_output, name, boost::bind(&implementation_t::get, boost::ref(*this), name), cell_set_m.size(), &cell_set_m.back())); } output_index_m.insert(cell_set_m.back()); if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", name.c_str(), "'already exists."), position2); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_interface(name_t name, any_regular_t initial) { cell_set_m.push_back(cell_t(name, true, cell_t::calculator_t(), cell_set_m.size())); cell_t& cell = cell_set_m.back(); input_index_m.insert(cell); cell.state_m = std::move(initial); cell.priority_m = ++priority_high_m; cell_set_m.push_back(cell_t(access_interface_output, name, boost::bind(&implementation_t::get, boost::ref(*this), name), cell_set_m.size(), &cell)); output_index_m.insert(cell_set_m.back()); if (!name_index_m.insert(cell_set_m.back()).second) { throw std::logic_error(make_string("cell named '", name.c_str(), "'already exists.")); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_constant(name_t name, const line_position_t& position, const array_t& initializer) { scope_value_t<bool> scope(initialize_mode_m, true); cell_set_m.push_back(cell_t(access_constant, name, calculate_expression(position, initializer), cell_set_m.size())); // REVISIT (sparent) : Non-transactional on failure. if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", name.c_str(), "'already exists."), position); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_constant(name_t name, any_regular_t value) { cell_set_m.push_back(cell_t(access_constant, name, std::move(value), cell_set_m.size())); if (!name_index_m.insert(cell_set_m.back()).second) { throw std::logic_error(make_string("cell named '", name.c_str(), "'already exists.")); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_logic(name_t logic, const line_position_t& position, const array_t& expression) { cell_set_m.push_back(cell_t(access_logic, logic, boost::bind(&implementation_t::calculate_expression, boost::ref(*this), position, expression), cell_set_m.size(), nullptr)); if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", logic.c_str(), "'already exists."), position); } } /**************************************************************************************************/ void sheet_t::implementation_t::add_invariant(name_t name, const line_position_t& position, const array_t& expression) { // REVISIT (sparent) : Non-transactional on failure. cell_set_m.push_back(cell_t(access_invariant, name, boost::bind(&implementation_t::calculate_expression, boost::ref(*this), position, expression), cell_set_m.size(), nullptr)); output_index_m.insert(cell_set_m.back()); if (!name_index_m.insert(cell_set_m.back()).second) { throw stream_error_t(make_string("cell named '", name.c_str(), "'already exists."), position); } invariant_index_m.push_back(&cell_set_m.back()); } /**************************************************************************************************/ void sheet_t::implementation_t::add_relation(const line_position_t& position, const array_t& conditional, const relation_t* first, const relation_t* last) { relation_cell_set_m.push_back(relation_cell_t(position, conditional, first, last)); relation_cell_t& relation = relation_cell_set_m.back(); // build a unique list of lhs cells vector<name_t> cell_set; for (; first != last; ++first) { cell_set.insert(cell_set.end(), first->name_set_m.begin(), first->name_set_m.end()); } sort(cell_set); cell_set.erase(unique(cell_set), cell_set.end()); for (vector<name_t>::iterator f = cell_set.begin(), l = cell_set.end(); f != l; ++f) { index_t::iterator p = output_index_m.find(*f); if (p == output_index_m.end() || !p->interface_input_m) throw stream_error_t(make_string("interface cell ", f->c_str(), " does not exist."), position); relation.edges_m.push_back(&(*p)); p->relation_index_m.push_back(&relation); ++p->initial_relation_count_m; } } /**************************************************************************************************/ any_regular_t sheet_t::implementation_t::calculate_expression(const line_position_t& position, const array_t& expression) { evaluate(machine_m, position, expression); any_regular_t result = std::move(machine_m.back()); machine_m.pop_back(); return result; } /**************************************************************************************************/ sheet_t::connection_t sheet_t::implementation_t::monitor_enabled(name_t n, const name_t* first, const name_t* last, const monitor_enabled_t& monitor) { assert(updated_m && "Must call sheet_t::update() prior to monitor_enabled."); index_t::iterator iter(input_index_m.find(n)); if (iter == input_index_m.end()) throw std::logic_error(make_string("Attempt to monitor nonexistent cell: ", n.c_str())); cell_bits_t touch_set; while (first != last) { index_t::iterator i(input_index_m.find(*first)); if (i == input_index_m.end()) throw std::logic_error( make_string("Attempt to monitor nonexistent cell: ", first->c_str())); touch_set.set(i->cell_set_pos_m); ++first; } /* REVISIT <sean_parent@mac.com> : This is a complex test that is duplicated in enabled_filter and should be distilled down to a simply the test of active_m. */ monitor(active_m.test(iter->cell_set_pos_m) || (value_accessed_m.test(iter->cell_set_pos_m) && (touch_set & priority_accessed_m).any())); return monitor_enabled_m.connect(boost::bind(&sheet_t::implementation_t::enabled_filter, this, touch_set, iter->cell_set_pos_m, monitor, _1, _2)); } /**************************************************************************************************/ sheet_t::connection_t sheet_t::implementation_t::monitor_invariant_dependent(name_t n, const monitor_invariant_t& monitor) { assert(updated_m && "Must call sheet_t::update() prior to monitor_invariant_dependent."); index_t::iterator iter(output_index_m.find(n)); if (iter == output_index_m.end()) throw std::logic_error(make_string("Attempt to monitor nonexistent cell: ", n.c_str())); monitor(iter->invariant_m); return iter->monitor_invariant_m.connect(monitor); } /**************************************************************************************************/ sheet_t::connection_t sheet_t::implementation_t::monitor_value(name_t name, const monitor_value_t& monitor) { assert(updated_m && "Must call sheet_t::update() prior to monitor_value."); index_t::iterator iter = output_index_m.find(name); if (iter == output_index_m.end()) { throw std::logic_error(make_string("Attempt to monitor nonexistent cell: ", name.c_str())); } monitor(iter->state_m); return iter->monitor_value_m.connect(monitor); } /**************************************************************************************************/ sheet_t::connection_t sheet_t::implementation_t::monitor_contributing(name_t n, const dictionary_t& mark, const monitor_contributing_t& monitor) { assert(updated_m && "Must call sheet_t::update() prior to monitor_contributing."); index_t::iterator iter(output_index_m.find(n)); if (iter == output_index_m.end()) { throw std::logic_error(make_string("Attempt to monitor nonexistent cell: ", n.c_str())); } monitor(contributing_set(mark, iter->contributing_m)); return iter->monitor_contributing_m.connect( boost::bind(monitor, boost::bind(&sheet_t::implementation_t::contributing_set, boost::ref(*this), mark, _1))); } /**************************************************************************************************/ inline bool sheet_t::implementation_t::has_input(name_t name) const { return input_index_m.find(name) != input_index_m.end(); } /**************************************************************************************************/ inline bool sheet_t::implementation_t::has_output(name_t name) const { return output_index_m.find(name) != output_index_m.end(); } /**************************************************************************************************/ priority_t sheet_t::implementation_t::name_to_priority(name_t name) const { index_t::const_iterator i = input_index_m.find(name); assert(i != input_index_m.end() && i->specifier_m == access_interface_input && "interface cell not found, should not be possible - preflight in add_interface."); return i->priority_m; } /**************************************************************************************************/ void sheet_t::implementation_t::flow(cell_bits_t& priority_accessed) { // Generate the set of cells connected to unresolved relations vector<cell_t*> cells; for (relation_cell_set_t::iterator f(relation_cell_set_m.begin()), l(relation_cell_set_m.end()); f != l; ++f) { if (!f->resolved_m) cells.insert(cells.end(), f->edges_m.begin(), f->edges_m.end()); } sort(cells); cells.erase(unique(cells), cells.end()); // sort the cells by priority sort(cells, less(), &cell_t::priority); // mark that the priority of these cells was accessed for enablement // REVISIT <seanparent@google.com> : This is an approximation for enablement that could do // better with connected components for (vector<cell_t*>::iterator f = cells.begin(), l = cells.end(); f != l; ++f) { priority_accessed.set((*f)->interface_input_m->cell_set_pos_m); } /* pop the top cell from the stack if the cell is not resolved then resolve as a contributor find which relations the cell contributes to if any- if there is only one unresolved cell on the relation then resolve that cell as derived (need to have the cell refer to the deriving term in the relation?) push the cell to the top of stack loop until stack is empty. */ while (!cells.empty()) { cell_t& cell = *cells.back(); cells.pop_back(); if (cell.relation_count_m == 0) continue; cell.resolved_m = true; for (relation_index_t::iterator f = cell.relation_index_m.begin(), l = cell.relation_index_m.end(); f != l; ++f) { if ((*f)->resolved_m) continue; --cell.relation_count_m; const relation_t* term = 0; bool at_least_one = false; for (relation_set_t::iterator tf((*f)->terms_m.begin()), tl((*f)->terms_m.end()); tf != tl; ++tf) { // each term has a set of cells. If any cell is resolved then the term is resolved. bool resolved = false; for (vector<name_t>::iterator fc = tf->name_set_m.begin(), lc = tf->name_set_m.end(); fc != lc; ++fc) { index_t::iterator iter = output_index_m.find(*fc); assert(iter != output_index_m.end()); if (iter->resolved_m) { resolved = true; break; } } if (resolved) continue; if (!term) { term = &(*tf); at_least_one = true; } else { term = NULL; break; } } // REVISIT (sparent) : Better error reporting here. if (!at_least_one) { throw std::logic_error("all terms of relation resolve but relation not applied."); } if (!term) continue; // Flow out to lhs cells (*f)->resolved_m = true; for (std::size_t n = 0, count = term->name_set_m.size(); n != count; ++n) { index_t::iterator iter = output_index_m.find(term->name_set_m[n]); assert(iter != output_index_m.end()); cell_t& cell = *iter; // REVISIT (sparent) : Better error reporting here. if (cell.term_m) throw logic_error("over constrained."); if (count == 1) { cell.term_m = boost::bind(&implementation_t::calculate_expression, boost::ref(*this), term->position_m, term->expression_m); } else { cell.term_m = boost::bind(&implementation_t::calculate_indexed, boost::ref(*this), term->position_m, term->expression_m, n); } --cell.relation_count_m; // This will be a derived cell and will have a priority lower than any cell // contributing to it assert(cell.interface_input_m && "Missing input half of interface cell."); if (cell.interface_input_m->linked_m) { cell.interface_input_m->priority_m = --priority_low_m; } if (cell.relation_count_m) cells.push_back(&cell); else cell.resolved_m = true; } // Remove the relation from any cells to which it is still attached. That is, // any cell which is still attached is an "in edge". vector<name_t> remaining_cells; for (relation_set_t::iterator tf((*f)->terms_m.begin()), tl((*f)->terms_m.end()); tf != tl; ++tf) { if (&(*tf) == term) continue; remaining_cells.insert(remaining_cells.end(), tf->name_set_m.begin(), tf->name_set_m.end()); } sort(remaining_cells); remaining_cells.erase(unique(remaining_cells), remaining_cells.end()); for (vector<name_t>::iterator fc = remaining_cells.begin(), lc = remaining_cells.end(); fc != lc; ++fc) { index_t::iterator iter = output_index_m.find(*fc); assert(iter != output_index_m.end()); if (iter->resolved_m) continue; --iter->relation_count_m; } } assert(cell.relation_count_m == 0 && "Cell still belongs to relation but all relations resolved."); } } /**************************************************************************************************/ void sheet_t::implementation_t::update() { #ifndef NDEBUG check_reentrancy checker(check_update_reentrancy_m); #endif conditional_indirect_contributing_m.reset(); value_accessed_m.reset(); for_each(cell_set_m, &cell_t::clear_dirty); for_each(relation_cell_set_m, &relation_cell_t::clear_resolved); // Solve the conditionals. accumulate_contributing_m.reset(); for (relation_cell_set_t::iterator current_cell(relation_cell_set_m.begin()), last_cell(relation_cell_set_m.end()); current_cell != last_cell; ++current_cell) { if (current_cell->conditional_m.empty()) continue; if (!calculate_expression(current_cell->position_m, current_cell->conditional_m) .cast<bool>()) { for (vector<cell_t*>::iterator f = current_cell->edges_m.begin(), l = current_cell->edges_m.end(); f != l; ++f) { --(*f)->relation_count_m; } current_cell->resolved_m = true; } } conditional_indirect_contributing_m = accumulate_contributing_m; cell_bits_t priority_accessed; flow(priority_accessed); #ifndef NDEBUG for (relation_cell_set_t::iterator first(relation_cell_set_m.begin()), last(relation_cell_set_m.end()); first != last; ++first) { if (first->resolved_m) continue; std::clog << "(warning) relation unnecessary and ignored\n" << first->position_m; } #endif // calculate the output/interface_output/invariant cells and apply. for (index_t::const_iterator iter(output_index_m.begin()), last(output_index_m.end()); iter != last; ++iter) { cell_t& cell(*iter); // REVISIT (sparent) : This is a copy/paste of get(); if (!cell.evaluated_m) { accumulate_contributing_m.reset(); if (cell.specifier_m == access_interface_output) get_stack_m.push_back(std::make_pair(cell.name_m, false)); cell.calculate(); if (cell.specifier_m == access_interface_output) get_stack_m.pop_back(); cell.contributing_m = accumulate_contributing_m; cell.contributing_m |= conditional_indirect_contributing_m; } /* REVISIT (sparent) : This would be slightly more efficient if I moved the link flag to the output side. */ // Apply the interface output to interface inputs of linked cells. if (cell.interface_input_m && cell.interface_input_m->linked_m) { cell.interface_input_m->state_m = cell.state_m; } } // Then we can check the invariants - cell_bits_t poison; for (index_vector_t::const_iterator iter(invariant_index_m.begin()), last(invariant_index_m.end()); iter != last; ++iter) { cell_t& cell(**iter); if (!cell.state_m.cast<bool>()) poison |= cell.contributing_m; } /* REVISIT (sparent) : Shoule we report conditional_indirect_contributing with the invariants? */ /* REVISIT (sparent): Monitoring a value should return all of - value contributing invariant_dependent Otherwise the client risks getting out of sync. */ /* REVISIT (sparent) : enabling everything with priority_accessed is to granular. Need connected components. */ cell_bits_t active = priority_accessed; // REVIST (sparent) : input monitor should recieve priority_accessed and poison bits. for (index_t::const_iterator iter(output_index_m.begin()), last(output_index_m.end()); iter != last; ++iter) { cell_t& cell(*iter); bool invariant((poison & cell.contributing_m).none()); if (invariant != cell.invariant_m) cell.monitor_invariant_m(invariant); cell.invariant_m = invariant; if (cell.dirty_m) cell.monitor_value_m(cell.state_m); /* REVISIT (sparent) : Is there any way to prune this down a bit? Calculating the contributing each time is expensive. */ if (!cell.monitor_contributing_m.empty()) { // REVISIT (sparent) : no need to notify if contributing didn't change... cell.monitor_contributing_m(cell.contributing_m); } if ((cell.specifier_m == access_output) || (!has_output_m && cell.specifier_m == access_interface_output)) { active |= cell.contributing_m; } } // update monitor_enabled_m(priority_accessed, active); priority_accessed_m = priority_accessed; active_m = active; #ifndef NDEBUG updated_m = true; #endif } /**************************************************************************************************/ void sheet_t::implementation_t::initialize_one(cell_t& cell) { /* REVISIT (sparent) : Should have more checking here - detecting cycles (and forward references?) */ accumulate_contributing_m.reset(); cell.state_m = cell.calculator_m(); cell.priority_m = ++priority_high_m; cell.init_contributing_m |= accumulate_contributing_m; } /**************************************************************************************************/ void sheet_t::implementation_t::reinitialize() { scope_value_t<bool> scope(initialize_mode_m, true); for (index_t::iterator f = output_index_m.begin(), l = output_index_m.end(); f != l; ++f) { if (!f->interface_input_m) continue; cell_t& cell = *f->interface_input_m; if ((init_dirty_m & cell.init_contributing_m).none()) continue; initialize_one(cell); } init_dirty_m.reset(); } /**************************************************************************************************/ dictionary_t sheet_t::implementation_t::contributing(const dictionary_t& mark) const { cell_bits_t contributing; for (index_t::const_iterator iter(output_index_m.begin()), last(output_index_m.end()); iter != last; ++iter) { if ((iter->specifier_m == access_output) || (!has_output_m && iter->specifier_m == access_interface_output)) { contributing |= iter->contributing_m; } } return contributing_set(mark, contributing); } /**************************************************************************************************/ dictionary_t sheet_t::implementation_t::contributing_to_cell(name_t x) const { index_t::iterator iter = output_index_m.find(x); if (iter == output_index_m.end()) throw std::logic_error(make_string("No monitorable cell: ", x.c_str())); return contributing_set(dictionary_t(), iter->contributing_m); } /**************************************************************************************************/ /* NOTE (sparent) : A mark containes a dictionary of contributing values. If a contributing value has changed or been added since the mark then it will be reported in the dictionary result. If a value is contributing, and the set of values which are contributing has changed, then the value will be reported as having been touched. */ dictionary_t sheet_t::implementation_t::contributing_set(const dictionary_t& mark, const cell_bits_t& contributing) const { dictionary_t changed; dictionary_t touched; bool include_touched(false); for (std::size_t index(0), last(cell_set_m.size()); index != last; ++index) { if (contributing[index]) { const cell_t& cell = cell_set_m[index]; const name_t& name(cell.name_m); const any_regular_t& value(cell.state_m); bool priority_accessed(priority_accessed_m.test(cell.cell_set_pos_m)); if (!mark.count(name)) { include_touched = true; changed.insert(make_pair(name, value)); } else if (get_value(mark, name) != value) changed.insert(make_pair(name, value)); else if (priority_accessed) touched.insert(make_pair(name, value)); } } if (include_touched) { changed.insert(touched.begin(), touched.end()); } return changed; } /**************************************************************************************************/ void sheet_t::implementation_t::set(const dictionary_t& dict) { for (dictionary_t::const_iterator iter(dict.begin()), last(dict.end()); iter != last; ++iter) { set(iter->first, iter->second); } } /**************************************************************************************************/ const any_regular_t& sheet_t::implementation_t::operator[](name_t variable_name) const { assert(updated_m && "Must call sheet_t::update() prior to operator[]."); index_t::iterator iter = name_index_m.find(variable_name); if (iter == name_index_m.end()) { throw std::logic_error(make_string("variable ", variable_name.c_str(), " not found.")); } assert(iter->evaluated_m && "Cell was not evaluated!"); return iter->state_m; } /**************************************************************************************************/ any_regular_t sheet_t::implementation_t::get(name_t variable_name) { #if 0 // REVISIT (sparent) : I can't currently turn this assert on because of inspect. // However, it would be good to seperate out this get from the operator[] and // only use this one for updates. The problem is that inspect shares the same VM // so enabling this assert has to wait until I seperate the VM from the sheet_t. assert(check_update_reentrancy_m && "sheet_t::get() can only be called from sheet_t::update()."); #endif if (initialize_mode_m) { index_t::iterator iter(input_index_m.find(variable_name)); if (iter == input_index_m.end()) { iter = name_index_m.find(variable_name); if (iter == name_index_m.end() || iter->specifier_m != access_constant) { throw std::logic_error( make_string("variable ", variable_name.c_str(), " not found.")); } } cell_t& cell = *iter; accumulate_contributing_m |= cell.init_contributing_m; return cell.state_m; } scope_count scope(get_count_m); /* REVISIT (sparent) - If we go to three pass on interface cells then the max count is number of cells plus number of interface cells. */ if (get_count_m > cell_set_m.size()) { throw std::logic_error(std::string("cycle detected, consider using a relate { } clause.")); } index_t::iterator iter = name_index_m.find(variable_name); if (iter == name_index_m.end()) { throw std::logic_error(make_string("variable ", variable_name.c_str(), " not found.")); } cell_t& cell = *iter; // If the variable is on the top of the stack then we assume it // must refer to an input cell. if (get_stack_m.size() && (get_stack_m.back().first == variable_name)) { assert(cell.interface_input_m && "FATAL (sparent) : Only interface cells should be on the get stack."); if (!get_stack_m.back().second && !cell.term_m.empty()) { get_stack_m.back().second = true; return cell.term_m(); } else { value_accessed_m.set(cell.interface_input_m->cell_set_pos_m); accumulate_contributing_m |= cell.interface_input_m->contributing_m; return cell.interface_input_m->state_m; } } if (cell.specifier_m == access_interface_output) get_stack_m.push_back(std::make_pair(variable_name, false)); // REVISIT (sparent) : paired call should be ctor/dtor try { // REVISIT (sparent) : First pass getting the logic correct. if (cell.evaluated_m) accumulate_contributing_m |= cell.contributing_m; else { cell_bits_t old = accumulate_contributing_m; accumulate_contributing_m.reset(); cell.calculate(); cell.contributing_m = accumulate_contributing_m; accumulate_contributing_m |= old; } if (cell.specifier_m != access_input && cell.specifier_m != access_constant) cell.contributing_m |= conditional_indirect_contributing_m; } catch (...) { if (cell.specifier_m == access_interface_output) get_stack_m.pop_back(); throw; } if (cell.specifier_m == access_interface_output) get_stack_m.pop_back(); return cell.state_m; } /**************************************************************************************************/ } // namespace adobe /**************************************************************************************************/
37.021533
100
0.579007
[ "object", "vector", "transform" ]
ed13b8c34521dec0d414bd7ce4dccca9ed970ecb
19,000
cpp
C++
sdk/howto/cpp/HowTo-MechanicalVentilation.cpp
isuhao/engine1
4b928612290150c2a3e0455e38e52d13d90a7340
[ "Apache-2.0" ]
2
2019-03-15T04:20:11.000Z
2019-05-02T18:39:45.000Z
sdk/howto/cpp/HowTo-MechanicalVentilation.cpp
sinmx/engine1
4b928612290150c2a3e0455e38e52d13d90a7340
[ "Apache-2.0" ]
null
null
null
sdk/howto/cpp/HowTo-MechanicalVentilation.cpp
sinmx/engine1
4b928612290150c2a3e0455e38e52d13d90a7340
[ "Apache-2.0" ]
1
2018-09-22T04:10:37.000Z
2018-09-22T04:10:37.000Z
/* Distributed under the Apache License, Version 2.0. See accompanying NOTICE file for details.*/ #define _USE_MATH_DEFINES #include "EngineHowTo.h" // Include the various types you will be using in your code #include "system/physiology/SEBloodChemistrySystem.h" #include "system/physiology/SECardiovascularSystem.h" #include "system/physiology/SERespiratorySystem.h" #include "system/environment/actions/SEChangeEnvironmentConditions.h" #include "patient/actions/SEMechanicalVentilation.h" #include "patient/actions/SEAirwayObstruction.h" #include "patient/actions/SEAsthmaAttack.h" #include "patient/actions/SEAcuteStress.h" #include "patient/actions/SEApnea.h" #include "patient/actions/SETensionPneumothorax.h" #include "patient/actions/SEBrainInjury.h" #include "patient/actions/SESubstanceBolus.h" #include "patient/actions/SEConsciousRespiration.h" #include "patient/actions/SEForcedInhale.h" #include "patient/actions/SEForcedExhale.h" #include "patient/actions/SEBreathHold.h" #include "properties/SEScalar0To1.h" #include "properties/SEScalarFrequency.h" #include "properties/SEScalarMassPerVolume.h" #include "properties/SEScalarPressure.h" #include "properties/SEScalarTemperature.h" #include "properties/SEScalarTime.h" #include "properties/SEScalarVolume.h" #include "properties/SEScalarVolumePerTime.h" #include "properties/SEScalarFlowResistance.h" #include "properties/SEScalarFlowCompliance.h" #include "properties/SEScalarVolumePerTimeArea.h" #include "properties/SEScalarPressureTimePerVolumeArea.h" #include "properties/SEScalarLengthPerTime.h" #include "properties/SEScalar0To1.h" #include "engine/SEEngineTracker.h" #include "substance/SESubstance.h" #include "substance/SESubstanceFraction.h" #include "substance/SESubstanceManager.h" #include "patient/conditions/SEChronicObstructivePulmonaryDisease.h" #include "patient/conditions/SELobarPneumonia.h" #include "patient/conditions/SEImpairedAlveolarExchange.h" #include "utils/SEEventHandler.h" #include <math.h> // Make a custom event handler that you can connect to your code (See EngineUse for more info) class MechVentHandler : public SEEventHandler { public: MechVentHandler(Logger *logger) : SEEventHandler(logger) { } virtual void HandlePatientEvent(cdm::PatientData_eEvent type, bool active, const SEScalarTime* time = nullptr) { switch (type) { case cdm::PatientData_eEvent_MildAcuteRespiratoryDistress: { if (active) m_Logger->Info("Do something for MildAcuteRespiratoryDistress"); else m_Logger->Info("Stop doing something for MildAcuteRespiratoryDistress"); break; } case cdm::PatientData_eEvent_ModerateAcuteRespiratoryDistress: { if (active) m_Logger->Info("Do something for ModerateAcuteRespiratoryDistress"); else m_Logger->Info("Stop doing something for ModerateAcuteRespiratoryDistress"); break; } case cdm::PatientData_eEvent_SevereAcuteRespiratoryDistress: { if (active) m_Logger->Info("Do something for SevereAcuteRespiratoryDistress"); else m_Logger->Info("Stop doing something for SevereAcuteRespiratoryDistress"); break; } case cdm::PatientData_eEvent_CardiogenicShock: { if (active) m_Logger->Info("Do something for CardiogenicShock"); else m_Logger->Info("Stop doing something for CardiogenicShock"); break; } } } virtual void HandleAnesthesiaMachineEvent(cdm::AnesthesiaMachineData_eEvent type, bool active, const SEScalarTime* time = nullptr) { } }; //-------------------------------------------------------------------------------------------------- /// \brief /// Usage for the Mechanical Ventilation Patient Action /// Drive respiration with your own driver /// /// \details /// Refer to the SEMechanicalVentilation class //-------------------------------------------------------------------------------------------------- void HowToMechanicalVentilation() { //Note: Setting circuit values (resistance/compliances/etc.) needs to be done in the engine code - they currently are not directly exposed std::stringstream ss; // Create a Pulse Engine and load the standard patient std::unique_ptr<PhysiologyEngine> pe = CreatePulseEngine("HowToMechanicalVentilation.log"); pe->GetLogger()->Info("HowToMechanicalVentilation"); //Initialize the patient with any conditions //Change the following true/false flags to give the patient different conditions //If no conditions, just load the serialized healthy state std::vector<const SECondition*> conditions; if (true) //Healthy - i.e., no chronic conditions { if (!pe->LoadStateFile("./states/StandardMale@0s.pba")) //Select which patient { pe->GetLogger()->Error("Could not load state, check the error"); return; } } else { if (false) //COPD { SEChronicObstructivePulmonaryDisease COPD; COPD.GetBronchitisSeverity().SetValue(0.5); COPD.GetEmphysemaSeverity().SetValue(0.7); conditions.push_back(&COPD); } if (false) //LobarPneumonia { SELobarPneumonia lobarPneumonia; lobarPneumonia.GetSeverity().SetValue(0.2); lobarPneumonia.GetLeftLungAffected().SetValue(1.0); lobarPneumonia.GetRightLungAffected().SetValue(1.0); conditions.push_back(&lobarPneumonia); } if (false) //Generic ImpairedAlveolarExchange (no specified reason) { SEImpairedAlveolarExchange ImpairedAlveolarExchange; ImpairedAlveolarExchange.GetImpairedFraction().SetValue(0.5); conditions.push_back(&ImpairedAlveolarExchange); } //Select the patient and initialize with conditions //You can optionally define the patient here - see HowTo-CreateAPatient.cpp if (!pe->InitializeEngine("StandardMale.pba", &conditions)) { pe->GetLogger()->Error("Could not load initialize engine, check the error"); return; } } // Let's add our event listener callback MechVentHandler myEventHandler(pe->GetLogger()); pe->SetEventHandler(&myEventHandler); // The tracker is responsible for advancing the engine time and outputting the data requests below at each time step HowToTracker tracker(*pe); // Create data requests for each value that should be written to the output log as the engine is executing // Physiology System Names are defined on the System Objects //System data pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("HeartRate", FrequencyUnit::Per_min); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("SystolicArterialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("DiastolicArterialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("RespirationRate", FrequencyUnit::Per_min); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("TidalVolume", VolumeUnit::mL); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("TotalLungVolume", VolumeUnit::mL); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("OxygenSaturation"); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("MeanArterialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("RespirationMusclePressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryResistance", FlowResistanceUnit::cmH2O_s_Per_L); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryCompliance", FlowComplianceUnit::L_Per_cmH2O); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryCapillariesWedgePressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryArterialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryMeanArterialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("CardiacIndex", VolumePerTimeAreaUnit::L_Per_min_m2); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("SystemicVascularResistance", FlowResistanceUnit::cmH2O_s_Per_L); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryVascularResistance", FlowResistanceUnit::cmH2O_s_Per_L); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("PulmonaryVascularResistanceIndex", PressureTimePerVolumeAreaUnit::dyn_s_Per_cm5_m2); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("BloodPH"); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("ArterialOxygenPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("ArterialCarbonDioxidePressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("VenousOxygenPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("VenousCarbonDioxidePressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("TotalPulmonaryVentilation", VolumePerTimeUnit::L_Per_min); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("IntracranialPressure", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("CarricoIndex", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("AlveolarArterialGradient", PressureUnit::mmHg); pe->GetEngineTracker()->GetDataRequestManager().CreatePhysiologyDataRequest("SedationLevel"); //Patient data pe->GetEngineTracker()->GetDataRequestManager().CreatePatientDataRequest("FunctionalResidualCapacity", VolumeUnit::L); pe->GetEngineTracker()->GetDataRequestManager().CreatePatientDataRequest("VitalCapacity", VolumeUnit::L); //Compartment data //Arteriole bicarbonate SESubstance* HCO3 = pe->GetSubstanceManager().GetSubstance("Bicarbonate"); pe->GetEngineTracker()->GetDataRequestManager().CreateLiquidCompartmentDataRequest(pulse::VascularCompartment::Aorta, *HCO3, "Concentration", MassPerVolumeUnit::ug_Per_mL); //Lactate - this should have a relationship to lactic acid SESubstance* Lactate = pe->GetSubstanceManager().GetSubstance("Lactate"); pe->GetEngineTracker()->GetDataRequestManager().CreateSubstanceDataRequest(*Lactate, "BloodConcentration", MassPerVolumeUnit::ug_Per_mL); pe->GetEngineTracker()->GetDataRequestManager().SetResultsFilename("HowToMechanicalVentilation.txt"); //Output some random stuff to the log pe->GetLogger()->Info(std::stringstream() << "Tidal Volume : " << pe->GetRespiratorySystem()->GetTidalVolume(VolumeUnit::mL) << VolumeUnit::mL); pe->GetLogger()->Info(std::stringstream() << "Systolic Pressure : " << pe->GetCardiovascularSystem()->GetSystolicArterialPressure(PressureUnit::mmHg) << PressureUnit::mmHg); pe->GetLogger()->Info(std::stringstream() << "Diastolic Pressure : " << pe->GetCardiovascularSystem()->GetDiastolicArterialPressure(PressureUnit::mmHg) << PressureUnit::mmHg); pe->GetLogger()->Info(std::stringstream() << "Heart Rate : " << pe->GetCardiovascularSystem()->GetHeartRate(FrequencyUnit::Per_min) << "bpm"); pe->GetLogger()->Info(std::stringstream() << "Respiration Rate : " << pe->GetRespiratorySystem()->GetRespirationRate(FrequencyUnit::Per_min) << "bpm"); pe->GetLogger()->Info(std::stringstream() << "Oxygen Saturation : " << pe->GetBloodChemistrySystem()->GetOxygenSaturation()); //Go 1 min before doing anything //The patient is just doing spontaneous breathing tracker.AdvanceModelTime(60.0); //Let's do a bunch of different actions at the same time! //Use conscious respiration to cough - as expected, this won't do much to the patient's physiology //Conscious respiration could be used force certain breathing patterns, but will no longer take into account any feedback SEConsciousRespiration consciousRespiration; // Create commands in the order you want them processed. // Inhale is the first command we want to process SEForcedInhale& forcedInhale = consciousRespiration.AddForcedInhale(); forcedInhale.GetInspiratoryCapacityFraction().SetValue(0.25); forcedInhale.GetPeriod().SetValue(0.7, TimeUnit::s); // Next we will hold our breath consciousRespiration.AddBreathHold().GetPeriod().SetValue(0.25, TimeUnit::s); // Then exhale SEForcedExhale& forcedExhale = consciousRespiration.AddForcedExhale(); forcedExhale.GetExpiratoryReserveVolumeFraction().SetValue(0.0); forcedExhale.GetPeriod().SetValue(0.05, TimeUnit::s); // Then hold our breath again consciousRespiration.AddBreathHold().GetPeriod().SetValue(0.5, TimeUnit::s); // Once ProcessAction is called, the engine will make a copy of these commands. // You cannont modify them, // you will need to either clear out this command and reprocess it, // or process a whole new command. // If you plan on reusing this consciousRespiration action, you need to clear it if you want to add a new set of commands. pe->ProcessAction(consciousRespiration); // NOTE : The engine is going to need to run for the total sum of the command periods provided above // for the action to be completly processed by the engine // You can add other actions while this action is being processed. // Just be aware that this action is still being processed. // It is recommended that you advance time for at least the sum of the command periods. tracker.AdvanceModelTime(60.0); //Airway obstruction SEAirwayObstruction obstruction; obstruction.GetSeverity().SetValue(0.2); pe->ProcessAction(obstruction); tracker.AdvanceModelTime(60.0); //Pneumothorax // Create a Tension Pnuemothorax // Set the severity (a fraction between 0 and 1) SETensionPneumothorax pneumo; // You can have a Closed or Open Tension Pneumothorax pneumo.SetType(cdm::eGate::Open); //pneumo.SetType(CDM::enumPneumothoraxType::Open); pneumo.GetSeverity().SetValue(0.3); // It can be on the Left or right side pneumo.SetSide(cdm::eSide::Right); //pneumo.SetSide(CDM::enumSide::Left); pe->ProcessAction(pneumo); tracker.AdvanceModelTime(60.0); //Asthma attack SEAsthmaAttack asthmaAttack; asthmaAttack.GetSeverity().SetValue(0.3); pe->ProcessAction(asthmaAttack); //Stress response - release epinephrine SEAcuteStress acuteStress; acuteStress.GetSeverity().SetValue(0.3); pe->ProcessAction(acuteStress); //TBI //See HowTo-BrainInjury for an example of getting the Glasgow Scale SEBrainInjury tbi; tbi.SetType(cdm::BrainInjuryData_eType_Diffuse);// Can also be LeftFocal or RightFocal, and you will get pupillary effects in only one eye tbi.GetSeverity().SetValue(0.2); pe->ProcessAction(tbi); //Environment change SEChangeEnvironmentConditions env(pe->GetSubstanceManager()); SEEnvironmentalConditions& envConditions = env.GetConditions(); envConditions.GetAirVelocity().SetValue(2.0, LengthPerTimeUnit::m_Per_s); envConditions.GetAmbientTemperature().SetValue(15.0, TemperatureUnit::C); envConditions.GetAtmosphericPressure().SetValue(740., PressureUnit::mmHg); envConditions.GetMeanRadiantTemperature().SetValue(15.0, TemperatureUnit::C); pe->ProcessAction(env); tracker.AdvanceModelTime(60.0); //Apnea //Maybe the muscles are getting weak? SEApnea apnea; apnea.GetSeverity().SetValue(0.3); pe->ProcessAction(apnea); //Succs //Make the patient stop breathing // Get the Succinylcholine substance from the substance manager const SESubstance* succs = pe->GetSubstanceManager().GetSubstance("Succinylcholine"); // Create a substance bolus action to administer the substance SESubstanceBolus bolus(*succs); bolus.GetConcentration().SetValue(4820, MassPerVolumeUnit::ug_Per_mL); bolus.GetDose().SetValue(20, VolumeUnit::mL); bolus.SetAdminRoute(cdm::SubstanceBolusData_eAdministrationRoute_Intravenous); pe->ProcessAction(bolus); tracker.AdvanceModelTime(60.0); //Mechanical Ventilation // Create an SEMechanicalVentilation object SEMechanicalVentilation mechVent; mechVent.SetState(cdm::eSwitch::On);// Turn it on // Grab the substance fractions so we can quickly modify them SESubstanceFraction& O2frac = mechVent.GetGasFraction(*pe->GetSubstanceManager().GetSubstance("Oxygen")); SESubstanceFraction& CO2frac = mechVent.GetGasFraction(*pe->GetSubstanceManager().GetSubstance("CarbonDioxide")); SESubstanceFraction& N2frac = mechVent.GetGasFraction(*pe->GetSubstanceManager().GetSubstance("Nitrogen")); //We'll mimic inputs from real-time sensors by just driving the mechanical ventilation pressure using a sinusoid //Pressure waveform parameters double period = 5.0; double alpha = (2 * M_PI) / (period); double inputPressure_cmH2O = 0.0; double amplitude_cmH2O = 6.0; double yOffset = 10.0; // Drive the system for 5 mins for (unsigned int time_s = 0; time_s < 300; time_s++) { // Going to update values every second //The tracker with write to the results file every time-step //Difference from ambient pressure inputPressure_cmH2O = yOffset + amplitude_cmH2O * sin(alpha * time_s); //compute new pressure mechVent.GetPressure().SetValue(inputPressure_cmH2O, PressureUnit::cmH2O); //You can set flow, but we aren't O2frac.GetFractionAmount().SetValue(0.21); CO2frac.GetFractionAmount().SetValue(4.0E-4); N2frac.GetFractionAmount().SetValue(0.7896); pe->ProcessAction(mechVent); tracker.AdvanceModelTime(1); //Output some random stuff to the log pe->GetLogger()->Info(std::stringstream() << "Tidal Volume : " << pe->GetRespiratorySystem()->GetTidalVolume(VolumeUnit::mL) << VolumeUnit::mL); pe->GetLogger()->Info(std::stringstream() << "Systolic Pressure : " << pe->GetCardiovascularSystem()->GetSystolicArterialPressure(PressureUnit::mmHg) << PressureUnit::mmHg); pe->GetLogger()->Info(std::stringstream() << "Diastolic Pressure : " << pe->GetCardiovascularSystem()->GetDiastolicArterialPressure(PressureUnit::mmHg) << PressureUnit::mmHg); pe->GetLogger()->Info(std::stringstream() << "Heart Rate : " << pe->GetCardiovascularSystem()->GetHeartRate(FrequencyUnit::Per_min) << "bpm"); pe->GetLogger()->Info(std::stringstream() << "Respiration Rate : " << pe->GetRespiratorySystem()->GetRespirationRate(FrequencyUnit::Per_min) << "bpm"); pe->GetLogger()->Info(std::stringstream() << "Oxygen Saturation : " << pe->GetBloodChemistrySystem()->GetOxygenSaturation()); } pe->GetLogger()->Info("Finished"); }
51.771117
179
0.752789
[ "object", "vector" ]
ed14e8f72271b327978da4d42b94aacd2b2ee1c3
7,687
hpp
C++
transit/transit_graph_data.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
transit/transit_graph_data.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
transit/transit_graph_data.hpp
EVi1b7wO/omim
1aafdb102a200149f7ad0cd3173aa7ca2cc32300
[ "Apache-2.0" ]
null
null
null
#pragma once #include "transit/transit_types.hpp" #include "geometry/point2d.hpp" #include "geometry/region2d.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include "base/exception.hpp" #include "base/geo_object_id.hpp" #include "base/visitor.hpp" #include "3party/jansson/myjansson.hpp" #include <cstdint> #include <cstring> #include <map> #include <string> #include <type_traits> #include <vector> namespace routing { namespace transit { using OsmIdToFeatureIdsMap = std::map<base::GeoObjectId, std::vector<FeatureId>>; class DeserializerFromJson { public: DeserializerFromJson(json_struct_t * node, OsmIdToFeatureIdsMap const & osmIdToFeatureIds); template <typename T> typename std::enable_if<std::is_integral<T>::value || std::is_enum<T>::value || std::is_same<T, double>::value>::type operator()(T & t, char const * name = nullptr) { GetField(t, name); return; } void operator()(std::string & s, char const * name = nullptr) { GetField(s, name); } void operator()(m2::PointD & p, char const * name = nullptr); void operator()(FeatureIdentifiers & id, char const * name = nullptr); void operator()(EdgeFlags & edgeFlags, char const * name = nullptr); void operator()(StopIdRanges & rs, char const * name = nullptr); template <typename T> typename std::enable_if<std::is_same<T, Edge::WrappedEdgeId>::value || std::is_same<T, Stop::WrappedStopId>::value>::type operator()(T & t, char const * name = nullptr) { typename T::RepType id; operator()(id, name); t.Set(id); } template <typename T> void operator()(std::vector<T> & vs, char const * name = nullptr) { auto * arr = my::GetJSONOptionalField(m_node, name); if (arr == nullptr) return; if (!json_is_array(arr)) MYTHROW(my::Json::Exception, ("The field", name, "must contain a json array.")); size_t const sz = json_array_size(arr); vs.resize(sz); for (size_t i = 0; i < sz; ++i) { DeserializerFromJson arrayItem(json_array_get(arr, i), m_osmIdToFeatureIds); arrayItem(vs[i]); } } template <typename T> typename std::enable_if<std::is_class<T>::value && !std::is_same<T, Edge::WrappedEdgeId>::value && !std::is_same<T, Stop::WrappedStopId>::value>::type operator()(T & t, char const * name = nullptr) { if (name != nullptr && json_is_object(m_node)) { json_t * dictNode = my::GetJSONOptionalField(m_node, name); if (dictNode == nullptr) return; // No such field in json. DeserializerFromJson dict(dictNode, m_osmIdToFeatureIds); t.Visit(dict); return; } t.Visit(*this); } private: template <typename T> void GetField(T & t, char const * name = nullptr) { if (name == nullptr) { // |name| is not set in case of array items FromJSON(m_node, t); return; } json_struct_t * field = my::GetJSONOptionalField(m_node, name); if (field == nullptr) { // No optional field |name| at |m_node|. In that case the default value should be set to |t|. // This default value is set at constructor of corresponding class which is filled with // |DeserializerFromJson|. And the value (|t|) is not changed at this method. return; } FromJSON(field, t); } json_struct_t * m_node; OsmIdToFeatureIdsMap const & m_osmIdToFeatureIds; }; /// \brief The class contains all the information to make TRANSIT_FILE_TAG section. class GraphData { public: void DeserializeFromJson(my::Json const & root, OsmIdToFeatureIdsMap const & mapping); /// \note This method changes only |m_header| and fills it with correct offsets. void Serialize(Writer & writer); void DeserializeAll(Reader & reader); void DeserializeForRouting(Reader & reader); void DeserializeForRendering(Reader & reader); void DeserializeForCrossMwm(Reader & reader); void AppendTo(GraphData const & rhs); void Clear(); void CheckValidSortedUnique() const; bool IsEmpty() const; /// \brief Sorts all class fields by their ids. void Sort(); /// \brief Removes some items from all the class fields if they are outside |borders|. /// Please see description for the other Clip*() method for excact rules of clipping. /// \note Before call of the method every line in |m_stopIds| should contain |m_stopIds| /// with only one stop range. void ClipGraph(std::vector<m2::RegionD> const & borders); void SetGateBestPedestrianSegment(size_t gateIdx, SingleMwmSegment const & s); std::vector<Stop> const & GetStops() const { return m_stops; } std::vector<Gate> const & GetGates() const { return m_gates; } std::vector<Edge> const & GetEdges() const { return m_edges; } std::vector<Transfer> const & GetTransfers() const { return m_transfers; } std::vector<Line> const & GetLines() const { return m_lines; } std::vector<Shape> const & GetShapes() const { return m_shapes; } std::vector<Network> const & GetNetworks() const { return m_networks; } private: DECLARE_VISITOR_AND_DEBUG_PRINT(GraphData, visitor(m_stops, "stops"), visitor(m_gates, "gates"), visitor(m_edges, "edges"), visitor(m_transfers, "transfers"), visitor(m_lines, "lines"), visitor(m_shapes, "shapes"), visitor(m_networks, "networks")) /// \brief Clipping |m_lines| with |borders|. /// \details After a call of the method the following stop ids in |m_lines| are left: /// * stops inside |borders| /// * stops which are connected with an edge from |m_edges| with stops inside |borders| /// \note Lines without stops are removed from |m_lines|. /// \note Before call of the method every line in |m_lines| should contain |m_stopIds| /// with only one stop range. void ClipLines(std::vector<m2::RegionD> const & borders); /// \brief Removes all stops from |m_stops| which are not contained in |m_lines| at field |m_stopIds|. /// \note Only stops which stop ids contained in |m_lines| will left in |m_stops| /// after call of this method. void ClipStops(); /// \brief Removes all networks from |m_networks| which are not contained in |m_lines| /// at field |m_networkId|. void ClipNetworks(); /// \brief Removes gates from |m_gates| if there's no stop in |m_stops| with their stop ids. void ClipGates(); /// \brief Removes transfers from |m_transfers| if there's no stop in |m_stops| with their stop ids. void ClipTransfer(); /// \brief Removes edges from |m_edges| if their ends are not contained in |m_stops|. void ClipEdges(); /// \brief Removes all shapes from |m_shapes| which are not reffered form |m_edges|. void ClipShapes(); /// \brief Read a transit table form |srs|. /// \note Before calling any of the method except for ReadHeader() |m_header| has to be filled. void ReadHeader(NonOwningReaderSource & src); void ReadStops(NonOwningReaderSource & src); void ReadGates(NonOwningReaderSource & src); void ReadEdges(NonOwningReaderSource & src); void ReadTransfers(NonOwningReaderSource & src); void ReadLines(NonOwningReaderSource & src); void ReadShapes(NonOwningReaderSource & src); void ReadNetworks(NonOwningReaderSource & src); template <typename Fn> void DeserializeWith(Reader & reader, Fn && fn) { NonOwningReaderSource src(reader); ReadHeader(src); fn(src); } TransitHeader m_header; std::vector<Stop> m_stops; std::vector<Gate> m_gates; std::vector<Edge> m_edges; std::vector<Transfer> m_transfers; std::vector<Line> m_lines; std::vector<Shape> m_shapes; std::vector<Network> m_networks; }; } // namespace transit } // namespace routing
35.423963
104
0.683622
[ "geometry", "shape", "vector" ]
ed1857127ac7291e9fc610c4e4c2f40e40651748
3,264
cc
C++
src/processor/proc_maps_linux.cc
zzilla/gbreakpad
02fd5a078bda4eb2fd7ee881c8d301bea2bf87fe
[ "BSD-3-Clause" ]
19
2018-06-25T09:35:22.000Z
2021-12-04T19:09:52.000Z
src/processor/proc_maps_linux.cc
zzilla/gbreakpad
02fd5a078bda4eb2fd7ee881c8d301bea2bf87fe
[ "BSD-3-Clause" ]
2
2020-09-22T20:42:16.000Z
2020-11-11T04:08:57.000Z
src/processor/proc_maps_linux.cc
zzilla/gbreakpad
02fd5a078bda4eb2fd7ee881c8d301bea2bf87fe
[ "BSD-3-Clause" ]
11
2020-07-04T03:03:18.000Z
2022-03-17T10:19:19.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "google_breakpad/processor/proc_maps_linux.h" #include <fcntl.h> #include <inttypes.h> #include <stdio.h> #include "processor/logging.h" #if defined(OS_ANDROID) && !defined(__LP64__) // In 32-bit mode, Bionic's inttypes.h defines PRI/SCNxPTR as an // unsigned long int, which is incompatible with Bionic's stdint.h // defining uintptr_t as an unsigned int: // https://code.google.com/p/android/issues/detail?id=57218 #undef SCNxPTR #define SCNxPTR "x" #endif namespace google_breakpad { bool ParseProcMaps(const std::string& input, std::vector<MappedMemoryRegion>* regions_out) { std::vector<MappedMemoryRegion> regions; // This isn't async safe nor terribly efficient, but it doesn't need to be at // this point in time. // Split the string by newlines. std::vector<std::string> lines; std::string line = ""; for (size_t i = 0; i < input.size(); i++) { if (input[i] != '\n' && input[i] != '\r') { line.push_back(input[i]); } else if (line.size() > 0) { lines.push_back(line); line.clear(); } } if (line.size() > 0) { BPLOG(ERROR) << "Input doesn't end in newline"; return false; } for (size_t i = 0; i < lines.size(); ++i) { MappedMemoryRegion region; const char* line = lines[i].c_str(); char permissions[5] = {'\0'}; // Ensure NUL-terminated string. int path_index = 0; // Sample format from man 5 proc: // // address perms offset dev inode pathname // 08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm // // The final %n term captures the offset in the input string, which is used // to determine the path name. It *does not* increment the return value. // Refer to man 3 sscanf for details. if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %4c %" SCNx64" %hhx:%hhx %" SCNd64 " %n", &region.start, &region.end, permissions, &region.offset, &region.major_device, &region.minor_device, &region.inode, &path_index) < 7) { BPLOG(ERROR) << "sscanf failed for line: " << line; return false; } region.permissions = 0; if (permissions[0] == 'r') region.permissions |= MappedMemoryRegion::READ; else if (permissions[0] != '-') return false; if (permissions[1] == 'w') region.permissions |= MappedMemoryRegion::WRITE; else if (permissions[1] != '-') return false; if (permissions[2] == 'x') region.permissions |= MappedMemoryRegion::EXECUTE; else if (permissions[2] != '-') return false; if (permissions[3] == 'p') region.permissions |= MappedMemoryRegion::PRIVATE; else if (permissions[3] != 's' && permissions[3] != 'S') // Shared memory. return false; // Pushing then assigning saves us a string copy. regions.push_back(region); regions.back().path.assign(line + path_index); regions.back().line.assign(line); } regions_out->swap(regions); return true; } } // namespace google_breakpad
30.792453
79
0.635417
[ "vector" ]
ed1b555512ceeeae25ffe9000357e19617603e6e
16,503
cpp
C++
src/main.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
src/main.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
src/main.cpp
dgraves/RayTracerChallenge
c052f1f270354c46c60abdcce303fe9314181b3c
[ "MIT" ]
null
null
null
/* ** Copyright(c) 2020-2021 Dustin Graves ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this softwareand 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 "camera.h" #include "canvas.h" #include "checkers_pattern.h" #include "color.h" #include "double_util.h" #include "gradient_pattern.h" #include "intersections.h" #include "material.h" #include "phong.h" #include "plane.h" #include "point.h" #include "point_light.h" #include "ppm_writer.h" #include "ray.h" #include "ring_pattern.h" #include "sphere.h" #include "stripe_pattern.h" #include "vector.h" #include "world.h" #include <chrono> #include <cstdio> #include <future> #include <string> // Render the silhouette of a sphere (a circle), from Chapter 5 "Putting it together". void RenderSphereSilhouette(const std::string& filename) { // Parameters for a 'wall' to project the surface on and the render canvas. const auto wall_z = 10.0; const auto wall_size = 7.0; const auto canvas_pixels = 100u; const auto pixel_size = wall_size / static_cast<double>(canvas_pixels); const auto half = wall_size / 2.0; auto canvas = rtc::Canvas{ canvas_pixels, canvas_pixels }; const auto color = rtc::Color{ 1.0, 0.0, 0.0 }; // Red const auto ray_origin = rtc::Point{ 0.0, 0.0, -5.0 }; const auto shape = rtc::Sphere::Create(); for (auto y = 0u; y < canvas_pixels; ++y) { // Compute the world y coordinate (top = +half, bottom = -half). const auto world_y = half - pixel_size * static_cast<double>(y); for (auto x = 0u; x < canvas_pixels; ++x) { // Compute the world x coordinate (left = -half, right = +half). const auto world_x = -half + pixel_size * static_cast<double>(x); // Describe the point on the wall that the ray will target. const auto position = rtc::Point(world_x, world_y, wall_z); const auto r = rtc::Ray{ ray_origin, rtc::Vector::Normalize(rtc::Point::Subtract(position, ray_origin)) }; const auto xs = shape->Intersect(r); if (xs.Hit() != nullptr) { canvas.WritePixel(x, y, color); } } } rtc::PpmWriter::WriteFile(filename, canvas); } // Render a sphere, from Chapter 6 "Putting it together". void RenderSphere(const std::string& filename) { // Parameters for a 'wall' to project the surface on and the render canvas. const auto wall_z = 10.0; const auto wall_size = 7.0; const auto canvas_pixels = 500u; const auto pixel_size = wall_size / static_cast<double>(canvas_pixels); const auto half = wall_size / 2.0; auto canvas = rtc::Canvas{ canvas_pixels, canvas_pixels }; const auto ray_origin = rtc::Point{ 0.0, 0.0, -5.0 }; auto shape = rtc::Sphere::Create(); auto material = rtc::Material{}; const auto light = rtc::PointLight{ rtc::Point{ -10.0, 10.0, -10.0 }, rtc::Color{ 1.0, 1.0, 1.0 } }; material.SetColor(rtc::Color{ 1.0, 0.2, 1.0 }); shape->SetMaterial(material); for (auto y = 0u; y < canvas_pixels; ++y) { // Compute the world y coordinate (top = +half, bottom = -half). const auto world_y = half - pixel_size * static_cast<double>(y); for (auto x = 0u; x < canvas_pixels; ++x) { // Compute the world x coordinate (left = -half, right = +half). const auto world_x = -half + pixel_size * static_cast<double>(x); // Describe the point on the wall that the ray will target. const auto position = rtc::Point(world_x, world_y, wall_z); const auto r = rtc::Ray(ray_origin, rtc::Vector::Normalize(rtc::Point::Subtract(position, ray_origin))); const auto xs = shape->Intersect(r); const auto hit = xs.Hit(); if (hit != nullptr) { const auto object = hit->GetObject(); const auto point = r.GetPosition(hit->GetT()); const auto normal = object->NormalAt(point); const auto eye = rtc::Vector::Negate(r.GetDirection()); const auto color = rtc::Phong::Lighting(object->GetMaterial(), rtc::Matrix44::Identity(), light, point, eye, normal, false); canvas.WritePixel(x, y, color); } } } rtc::PpmWriter::WriteFile(filename, canvas); } // Render a scene, from Chapter 7 "Making a scene". void RenderScene(const std::string& filename) { const auto floor_material = rtc::Material{ rtc::Color{ 1.0, 0.9, 0.9 }, rtc::Material::GetDefaultAmbient(), rtc::Material::GetDefaultDiffuse(), 0.0, rtc::Material::GetDefaultShininess() }; const auto world = rtc::World{ { rtc::PointLight{ rtc::Point{ -10.0, 10.0, -10.0 }, rtc::Color{ 1.0, 1.0, 1.0 } } }, { // Parameters for the floor, constructed from an extremely flattened sphere with a matte texture. rtc::Sphere::Create(rtc::Material{ floor_material }, rtc::Matrix44::Scaling(10.0, 0.01, 10.0)), // Parameters for the left wall, with the same scale and color as the floor, but rotated and translated into place. rtc::Sphere::Create( rtc::Material{ floor_material }, rtc::Matrix44::Multiply( rtc::Matrix44::Translation(0.0, 0.0, 5.0), rtc::Matrix44::RotationY(-rtc::kPi / 4.0), rtc::Matrix44::RotationX(rtc::kPi / 2.0), rtc::Matrix44::Scaling(10.0, 0.01, 10.0))), // Parameters for the right wall, which is identical to the left, but rotated the opposite direction in y. rtc::Sphere::Create( rtc::Material{ floor_material }, rtc::Matrix44::Multiply( rtc::Matrix44::Translation(0.0, 0.0, 5.0), rtc::Matrix44::RotationY(rtc::kPi / 4.0), rtc::Matrix44::RotationX(rtc::kPi / 2.0), rtc::Matrix44::Scaling(10.0, 0.01, 10.0))), // Parameters for the large sphere in the middle, which is a unit sphere, translated upward slightly and colored green. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 0.1, 1.0, 0.5 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Translation(-0.5, 1.0, 0.5)), // Parameters for the smaller green sphere on the right, which is scaled by half. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 0.5, 1.0, 0.1 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(1.5, 0.5, -0.5), rtc::Matrix44::Scaling(0.5, 0.5, 0.5))), // Parameters for the smallest sphere, which is scaled by a third before being translated. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 1.0, 0.8, 0.1 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(-1.5, 0.33, -0.75), rtc::Matrix44::Scaling(0.33, 0.33, 0.33))) } }; // Construct the camera and render the world. const auto from = rtc::Point{ 0.0, 1.5, -5.0 }; const auto to = rtc::Point{ 0.0, 1.0, 0.0 }; const auto up = rtc::Vector{ 0.0, 1.0, 0.0 }; const auto camera = rtc::Camera{ 1000u, 500u, rtc::kPi / 3.0, rtc::Matrix44::ViewTransform(from, to, up) }; const auto canvas = camera.Render(world); rtc::PpmWriter::WriteFile(filename, canvas); } // Render a scene with a plane, from Chapter 9 "Planes". void RenderPlaneScene(const std::string& filename) { const auto world = rtc::World{ { rtc::PointLight{ rtc::Point{ -10.0, 10.0, -10.0 }, rtc::Color{ 1.0, 1.0, 1.0 } } }, { // Parameters for the floor, constructed from a plane with a matte texture. rtc::Plane::Create( rtc::Material{ rtc::Color{ 1.0, 0.9, 0.9 }, rtc::Material::GetDefaultAmbient(), rtc::Material::GetDefaultDiffuse(), 0.0, rtc::Material::GetDefaultShininess() }), // Parameters for the large sphere in the middle, which is a unit sphere, translated upward slightly and colored green. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 0.1, 1.0, 0.5 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Translation(-0.5, 1.0, 0.5)), // Parameters for the smaller green sphere on the right, which is scaled by half. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 0.5, 1.0, 0.1 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(1.5, 0.5, -0.5), rtc::Matrix44::Scaling(0.5, 0.5, 0.5))), // Parameters for the smallest sphere, which is scaled by a third before being translated. rtc::Sphere::Create( rtc::Material{ rtc::Color{ 1.0, 0.8, 0.1 }, rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(-1.5, 0.33, -0.75), rtc::Matrix44::Scaling(0.33, 0.33, 0.33))) } }; // Construct the camera and render the world. const auto from = rtc::Point{ 0.0, 1.5, -5.0 }; const auto to = rtc::Point{ 0.0, 1.0, 0.0 }; const auto up = rtc::Vector{ 0.0, 1.0, 0.0 }; const auto camera = rtc::Camera{ 1000u, 500u, rtc::kPi / 3.0, rtc::Matrix44::ViewTransform(from, to, up) }; const auto canvas = camera.Render(world); rtc::PpmWriter::WriteFile(filename, canvas); } // Render a scene with a pattern, from Chapter 10 "Patterns". void RenderPatternScene(const std::string& filename) { const auto world = rtc::World{ { rtc::PointLight{ rtc::Point{ -10.0, 10.0, -10.0 }, rtc::Color{ 1.0, 1.0, 1.0 } }, rtc::PointLight{ rtc::Point{ 10.0, 10.0, -10.0 }, rtc::Color{ 0.0, 0.0, 1.0 } } }, { // Parameters for the floor, constructed from a plane with a matte texture. rtc::Plane::Create( rtc::Material{ rtc::CheckersPattern::Create(rtc::Color{ 0.8, 0.8, 0.8 }, rtc::Color{ 0.2, 0.2, 0.2 }), rtc::Material::GetDefaultAmbient(), rtc::Material::GetDefaultDiffuse(), 0.0, rtc::Material::GetDefaultShininess() }), // Parameters for the wall, constructed from a plane with a matte texture. rtc::Plane::Create( rtc::Material{ rtc::RingPattern::Create(rtc::Color{ 0.7, 0.7, 0.7 }, rtc::Color{ 0.1, 0.1, 0.1 }, rtc::Matrix44::Scaling(0.2, 0.2, 0.2)), rtc::Material::GetDefaultAmbient(), rtc::Material::GetDefaultDiffuse(), 0.0, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(0.0, 0.0, 5.0), rtc::Matrix44::RotationX(rtc::DegreesToRadians(90.0)))), // Parameters for the large sphere in the middle, which is a unit sphere, translated upward slightly and colored green. rtc::Sphere::Create( rtc::Material{ rtc::StripePattern::Create(rtc::Color{ 0.8, 0.8, 0.0 }, rtc::Color{ 0.0, 0.8, 0.0 }, rtc::Matrix44::Multiply(rtc::Matrix44::RotationZ(rtc::DegreesToRadians(90.0)), rtc::Matrix44::Scaling(0.3, 0.3, 0.3))), rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Translation(-0.5, 1.0, 0.5)), // Parameters for the smaller green sphere on the right, which is scaled by half. rtc::Sphere::Create( rtc::Material{ rtc::GradientPattern::Create(rtc::Color{ 0.8, 0.0, 0.0 }, rtc::Color{ 0.0, 0.0, 0.5 }, rtc::Matrix44::RotationY(rtc::DegreesToRadians(-45.0))), rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(1.5, 0.5, -0.5), rtc::Matrix44::Scaling(0.5, 0.5, 0.5))), // Parameters for the smallest sphere, which is scaled by a third before being translated. rtc::Sphere::Create( rtc::Material{ rtc::CheckersPattern::Create(rtc::Color{ 0.0, 0.8, 0.8 }, rtc::Color{ 1.0, 1.0, 1.0 }, rtc::Matrix44::Scaling(0.3, 0.3, 0.3)), rtc::Material::GetDefaultAmbient(), 0.7, 0.3, rtc::Material::GetDefaultShininess() }, rtc::Matrix44::Multiply(rtc::Matrix44::Translation(-1.5, 0.33, -0.75), rtc::Matrix44::Scaling(0.33, 0.33, 0.33))) } }; // Construct the camera and render the world. const auto from = rtc::Point{ -1.5, 1.5, -5.0 }; const auto to = rtc::Point{ 0.0, 1.0, 0.0 }; const auto up = rtc::Vector{ 0.0, 1.0, 0.0 }; const auto camera = rtc::Camera{ 1000u, 500u, rtc::kPi / 3.0, rtc::Matrix44::ViewTransform(from, to, up) }; const auto canvas = camera.Render(world); rtc::PpmWriter::WriteFile(filename, canvas); } void RenderAsync(std::launch policy) { auto render1 = std::async(policy, RenderSphereSilhouette, "silhouette.ppm"); auto render2 = std::async(policy, RenderSphere, "sphere.ppm"); auto render3 = std::async(policy, RenderScene, "scene.ppm"); auto render4 = std::async(policy, RenderPlaneScene, "plane.ppm"); auto render5 = std::async(policy, RenderPatternScene, "pattern.ppm"); render1.wait(); render2.wait(); render3.wait(); render4.wait(); render5.wait(); } void Render() { RenderSphereSilhouette("silhouette.ppm"); RenderSphere("sphere.ppm"); RenderScene("scene.ppm"); RenderPlaneScene("plane.ppm"); RenderPatternScene("pattern.ppm"); } int main() { const auto start = std::chrono::steady_clock::now(); RenderAsync(std::launch::async); const auto stop = std::chrono::steady_clock::now(); printf("Total run time: %f seconds\n", std::chrono::duration<double>(stop - start).count()); return 0; }
43.314961
224
0.561171
[ "render", "object", "shape", "vector" ]
ed1dd5fdf38fa5d05b16c5a40f69f797ea598088
1,694
cpp
C++
c++/specify derived class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
c++/specify derived class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
c++/specify derived class.cpp
zexhan17/Problem-Solving
94a4d2181ada7152a584a7b03dcedef6c915e18f
[ "MIT" ]
null
null
null
/* Specifying a Derived Class: Specifying derived class is same as specifying a simple class. Reference of parent class is specified along with derived class name to inherit the capabilities of parent class. Syntax: class sub_class : access_specifier parent_class { body of class; }; */ #include <iostream> //Header file using namespace std; class Move{ // Declaring class protected: // access specifier it s accessible from derived class int p; public: // acccess specifier Move(){ // constructor p = 0; // initializing } void forward(){ //function declaration p++ ; // increment } void show(){ cout <<"P = "<< p <<endl; //display the value } }; //End of class //Declaring 2nd class and inheriting Move class class Move2 : public Move { public: void backward() //defining function for decrement { p-- ; } }; //End of class int main(){ Move2 m; //declaring object of child class m.show(); //calling show funtion of parent class m.forward(); // calling forward function of parent class for increment m.show(); m.backward(); // function of child class for decrement m.show(); return 0; } /* Declaring two classes "Move" & "Move2". class Move is parent with data member "p" as protected so that it may be accessed in derived class. child class "Move2" derives parent class "Move" & decalares a member function. creating object of child class constructor will assign value (p=0) and show function will show p=0 then forward function increment in p and show p=1 then backward function will decrement and again value of p=0 */
24.911765
100
0.664699
[ "object" ]
ed1f5aefa608c9d2db3426f0db625ed3df71cc2d
798
cpp
C++
Dynamic Programming/palindrome-partitioning.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/palindrome-partitioning.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/palindrome-partitioning.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: string reverse(string s) { for(int i=0,j=s.size()-1;i<j;i++,j--) s[i]^=s[j]^=s[i]^=s[j]; return s; } void solve(string &s,vector<vector<string>> &x,vector<string> &a,int start) { if(start==s.size()) { x.push_back(a); return; } for(int c=1;c<=s.size()&&start<s.size();c++) { if(s.substr(start,c)==reverse(s.substr(start,c))) { a.push_back(s.substr(start,c)); solve(s,x,a,start+c); a.pop_back(); } } } vector<vector<string>> partition(string s) { vector<vector<string>> x; vector<string> a; solve(s,x,a,0); return x; } };
23.470588
79
0.433584
[ "vector" ]
ed1fae3ad34a2682b65f4913055316d172d0e97c
5,258
cpp
C++
cpp/lib/fps_ipc/shared_memory.cpp
blakewoolbright/fps_platform
cd81f799432cfc3700c2dfda4e01fc6c154d53f9
[ "Unlicense" ]
null
null
null
cpp/lib/fps_ipc/shared_memory.cpp
blakewoolbright/fps_platform
cd81f799432cfc3700c2dfda4e01fc6c154d53f9
[ "Unlicense" ]
null
null
null
cpp/lib/fps_ipc/shared_memory.cpp
blakewoolbright/fps_platform
cd81f799432cfc3700c2dfda4e01fc6c154d53f9
[ "Unlicense" ]
null
null
null
#include "fps_ipc/shared_memory.h" #include "fps_string/fps_string.h" #include "fps_except/fps_except.h" #include "fps_fs/path.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/types.h> #include <errno.h> namespace fps { namespace ipc { //------------------------------------------------------------------------------------------- SharedMemory::SharedMemory() : fd_ ( -1 ) , size_ ( 0 ) , flags_( 0 ) , error_( 0 ) { } //------------------------------------------------------------------------------------------- SharedMemory::~SharedMemory() { close( false ) ; } //------------------------------------------------------------------------------------------- // Sanitize user provided shm file names. //------------------------------------------------------------------------------------------- bool SharedMemory::sanitize_name() { // Remove whitespace. string::strip( name_ ) ; // Remove acceptable directory prefix. std::string sys_shm_dir( "/dev/shm/" ) ; if( string::starts_with( name_, sys_shm_dir ) ) name_.erase( 0, (sys_shm_dir.length() - 1) ) ; // Count filesystem delimiters. uint32_t slash_count = 0 ; for( auto itr = name_.begin() ; itr != name_.end() ; ++itr ) { if( *itr == '/' ) ++slash_count ; } if( slash_count > 1 ) { error_ = EINVAL ; return false ; } if( slash_count == 0 ) name_.insert( name_.begin(), '/' ) ; return true ; } //------------------------------------------------------------------------------------------- bool SharedMemory::load_size_from_filesystem() { if( name_.empty() ) { error_ = EINVAL ; return false ; } // The fps::fs::Path class has a size() member that can tell us how big our // shm segment is currently. fs::Path shm_path = this->path() ; // Make sure the path object constructed properly or fail if( !shm_path.valid() ) { error_ = ( shm_path.last_error() == 0 ) ? shm_path.last_error() : EINVAL ; return false ; } // Make sure this shm segment actually exists. if( !shm_path.exists() ) { error_ = EBADF ; return false ; } // Update our size_ member size_ = shm_path.size() ; return true ; } //------------------------------------------------------------------------------------------- bool SharedMemory::open( const std::string & name, uint32_t access_flags ) { if( is_open() ) close( false ) ; error_ = 0 ; size_ = 0 ; flags_ = 0 ; name_ = name ; // // Verify that "name" argument meets basic requirements, and normalize it. // if( !sanitize_name() ) { error_ = EINVAL ; name_.clear() ; return false ; } // // Build flagset that will be passed to shm_open() // if( access_flags & access::Read_Write ) flags_ |= O_RDWR ; if( access_flags & access::Create ) flags_ |= O_CREAT ; if( access_flags & access::Exclusive ) flags_ |= O_EXCL ; // // Attempt to open the desired shared memory file // fd_ = ::shm_open( name_.c_str(), flags_, 0666 ) ; if( fd_ < 0 ) { error_ = errno ; fd_ = -1 ; return false ; } // // Query the filesystem to determine the initial shm segment size. // if( !load_size_from_filesystem() ) { int32_t last_err = error_ ; close( false ) ; error_ = last_err ; return false ; } return true ; } //------------------------------------------------------------------------------------------- bool SharedMemory::close( bool remove_from_fs ) { bool rv = true ; if( is_open() ) { // Close underlying file handle if( ::close( fd_ ) != 0 ) { if( error_ == 0 ) { error_ = errno ; rv = false ; } } else { if( remove_from_fs ) path().rm() ; } } // Clear members size_ = 0 ; flags_ = 0 ; fd_ = -1 ; error_ = 0 ; return rv ; } //------------------------------------------------------------------------------------------- bool SharedMemory::resize( uint32_t bytes ) { error_ = 0 ; if( !is_open() ) { error_ = EBADF ; return false ; } if( !is_writable() ) { error_ = EACCES ; return false ; } // // Resize underlying shm file via ::ftruncate() system function. // Note: ftruncate() is called in a loop so we can retry if it fails // and sets errno to EINTR/EAGAIN. // for( uint32_t idx = 0 ; idx < 5 ; ++idx ) { error_ = 0 ; int result = ::ftruncate( fd_, bytes ) ; if( result == 0 ) { size_ = bytes ; return true ; } error_ = errno ; if( error_ == EINTR || error_ == EAGAIN ) continue ; break ; } return false ; } }}
22.279661
95
0.445226
[ "object" ]
ed208e5c6139066b7f5697a5a8196b9bc6fe87e1
929
cpp
C++
Array/Rearrange the array.cpp
DY-2001/DSA-Practice
d17491d8bc7a80daf2034e7d64d842d1e28424c3
[ "MIT" ]
null
null
null
Array/Rearrange the array.cpp
DY-2001/DSA-Practice
d17491d8bc7a80daf2034e7d64d842d1e28424c3
[ "MIT" ]
null
null
null
Array/Rearrange the array.cpp
DY-2001/DSA-Practice
d17491d8bc7a80daf2034e7d64d842d1e28424c3
[ "MIT" ]
null
null
null
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: void rearrangeArray(int arr[], int n) { sort(arr, arr + n); vector<int> v; int even = 0, odd = n - 1; for(int i = 0; i < n; i++) { if(i % 2 != 0) { v.push_back(arr[odd--]); } else { v.push_back(arr[even++]); } } for(int i = 0; i < n; i++) { arr[i] = v[i]; } } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } Solution obj; obj.rearrangeArray(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << "\n"; } return 0; } // } Driver Code Ends
17.865385
43
0.38859
[ "vector" ]
ed20eb38bb4b70c5e46cd11b4d97435fdc08e62d
10,714
cc
C++
trunks/policy_session_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
trunks/policy_session_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
trunks/policy_session_test.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2015 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "trunks/policy_session_impl.h" #include <crypto/sha2.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "trunks/error_codes.h" #include "trunks/mock_session_manager.h" #include "trunks/mock_tpm.h" #include "trunks/tpm_generated.h" #include "trunks/trunks_factory_for_test.h" using testing::_; using testing::DoAll; using testing::NiceMock; using testing::Return; using testing::SaveArg; using testing::SetArgPointee; namespace { // Returns the total number of bits set in the first |size| elements from // |array|. int CountSetBits(const uint8_t* array, size_t size) { int res = 0; for (size_t i = 0; i < size; ++i) { for (int bit_position = 0; bit_position < 8; ++bit_position) { if ((array[i] & (1 << bit_position)) != 0) { ++res; } } } return res; } } // namespace namespace trunks { class PolicySessionTest : public testing::Test { public: PolicySessionTest() {} ~PolicySessionTest() override {} void SetUp() override { factory_.set_session_manager(&mock_session_manager_); factory_.set_tpm(&mock_tpm_); } HmacAuthorizationDelegate* GetHmacDelegate(PolicySessionImpl* session) { return &(session->hmac_delegate_); } protected: TrunksFactoryForTest factory_; NiceMock<MockSessionManager> mock_session_manager_; NiceMock<MockTpm> mock_tpm_; }; TEST_F(PolicySessionTest, GetDelegateUninitialized) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_session_manager_, GetSessionHandle()) .WillRepeatedly(Return(kUninitializedHandle)); EXPECT_EQ(nullptr, session.GetDelegate()); } TEST_F(PolicySessionTest, GetDelegateSuccess) { PolicySessionImpl session(factory_); EXPECT_EQ(GetHmacDelegate(&session), session.GetDelegate()); } TEST_F(PolicySessionTest, StartBoundSessionSuccess) { PolicySessionImpl session(factory_); EXPECT_EQ(TPM_RC_SUCCESS, session.StartBoundSession(TPM_RH_FIRST, "auth", true, true)); } TEST_F(PolicySessionTest, StartBoundSessionFailure) { PolicySessionImpl session(factory_); TPM_HANDLE handle = TPM_RH_FIRST; EXPECT_CALL(mock_session_manager_, StartSession(TPM_SE_POLICY, handle, _, true, true, _)) .WillRepeatedly(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.StartBoundSession(handle, "auth", true, true)); } TEST_F(PolicySessionTest, StartBoundSessionBadType) { PolicySessionImpl session(factory_, TPM_SE_HMAC); EXPECT_EQ(SAPI_RC_INVALID_SESSIONS, session.StartBoundSession(TPM_RH_FIRST, "auth", true, true)); } TEST_F(PolicySessionTest, StartUnboundSessionSuccess) { PolicySessionImpl session(factory_); EXPECT_EQ(TPM_RC_SUCCESS, session.StartUnboundSession(true, true)); } TEST_F(PolicySessionTest, StartUnboundSessionFailure) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_session_manager_, StartSession(TPM_SE_POLICY, TPM_RH_NULL, _, true, true, _)) .WillRepeatedly(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.StartUnboundSession(true, true)); } TEST_F(PolicySessionTest, GetDigestSuccess) { PolicySessionImpl session(factory_); std::string digest; TPM2B_DIGEST policy_digest; policy_digest.size = SHA256_DIGEST_SIZE; EXPECT_CALL(mock_tpm_, PolicyGetDigestSync(_, _, _, _)) .WillOnce(DoAll(SetArgPointee<2>(policy_digest), Return(TPM_RC_SUCCESS))); EXPECT_EQ(TPM_RC_SUCCESS, session.GetDigest(&digest)); EXPECT_EQ(static_cast<size_t>(SHA256_DIGEST_SIZE), digest.size()); } TEST_F(PolicySessionTest, GetDigestFailure) { PolicySessionImpl session(factory_); std::string digest; EXPECT_CALL(mock_tpm_, PolicyGetDigestSync(_, _, _, _)) .WillOnce(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.GetDigest(&digest)); } TEST_F(PolicySessionTest, PolicyORSuccess) { PolicySessionImpl session(factory_); std::vector<std::string> digests; digests.push_back("digest1"); digests.push_back("digest2"); digests.push_back("digest3"); TPML_DIGEST tpm_digests; EXPECT_CALL(mock_tpm_, PolicyORSync(_, _, _, _)) .WillOnce(DoAll(SaveArg<2>(&tpm_digests), Return(TPM_RC_SUCCESS))); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyOR(digests)); EXPECT_EQ(tpm_digests.count, digests.size()); EXPECT_EQ(StringFrom_TPM2B_DIGEST(tpm_digests.digests[0]), digests[0]); EXPECT_EQ(StringFrom_TPM2B_DIGEST(tpm_digests.digests[1]), digests[1]); EXPECT_EQ(StringFrom_TPM2B_DIGEST(tpm_digests.digests[2]), digests[2]); } TEST_F(PolicySessionTest, PolicyORBadParam) { PolicySessionImpl session(factory_); std::vector<std::string> digests; // We use 9 here because the maximum number of digests allowed by the TPM // is 8. Therefore having 9 digests here should cause the code to fail. digests.resize(9); EXPECT_EQ(SAPI_RC_BAD_PARAMETER, session.PolicyOR(digests)); } TEST_F(PolicySessionTest, PolicyORFailure) { PolicySessionImpl session(factory_); std::vector<std::string> digests; EXPECT_CALL(mock_tpm_, PolicyORSync(_, _, _, _)) .WillOnce(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.PolicyOR(digests)); } TEST_F(PolicySessionTest, PolicyPCRSuccess) { PolicySessionImpl session(factory_); std::string pcr_digest("digest"); uint32_t pcr_index = 1; TPML_PCR_SELECTION pcr_select; TPM2B_DIGEST pcr_value; EXPECT_CALL(mock_tpm_, PolicyPCRSync(_, _, _, _, _)) .WillOnce(DoAll(SaveArg<2>(&pcr_value), SaveArg<3>(&pcr_select), Return(TPM_RC_SUCCESS))); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyPCR(std::map<uint32_t, std::string>( {{pcr_index, pcr_digest}}))); uint8_t pcr_select_index = pcr_index / 8; uint8_t pcr_select_byte = 1 << (pcr_index % 8); EXPECT_EQ(pcr_select.count, 1u); EXPECT_EQ(pcr_select.pcr_selections[0].hash, TPM_ALG_SHA256); EXPECT_EQ(pcr_select.pcr_selections[0].sizeof_select, PCR_SELECT_MIN); EXPECT_EQ(pcr_select.pcr_selections[0].pcr_select[pcr_select_index], pcr_select_byte); EXPECT_EQ(StringFrom_TPM2B_DIGEST(pcr_value), crypto::SHA256HashString(pcr_digest)); } TEST_F(PolicySessionTest, PolicyMultiplePCRSuccess) { PolicySessionImpl session(factory_); std::string pcr_digest1("digest1"); std::string pcr_digest2("digest2"); std::string pcr_digest3("digest3"); uint32_t pcr_index1 = 1; uint32_t pcr_index2 = 9; uint32_t pcr_index3 = 15; std::map<uint32_t, std::string> pcr_map({{pcr_index1, pcr_digest1}, {pcr_index2, pcr_digest2}, {pcr_index3, pcr_digest3}}); TPML_PCR_SELECTION pcr_select; TPM2B_DIGEST pcr_value; EXPECT_CALL(mock_tpm_, PolicyPCRSync(_, _, _, _, _)) .WillOnce(DoAll(SaveArg<2>(&pcr_value), SaveArg<3>(&pcr_select), Return(TPM_RC_SUCCESS))); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyPCR(pcr_map)); EXPECT_EQ(pcr_select.count, 1u); TPMS_PCR_SELECTION pcr_selection = pcr_select.pcr_selections[0]; EXPECT_EQ(pcr_selection.hash, TPM_ALG_SHA256); EXPECT_EQ(pcr_selection.sizeof_select, PCR_SELECT_MIN); EXPECT_EQ(3, CountSetBits(pcr_selection.pcr_select, PCR_SELECT_MIN)); uint8_t pcr_select_index1 = pcr_index1 / 8; uint8_t pcr_select_mask1 = 1 << (pcr_index1 % 8); uint8_t pcr_select_index2 = pcr_index2 / 8; uint8_t pcr_select_mask2 = 1 << (pcr_index2 % 8); uint8_t pcr_select_index3 = pcr_index3 / 8; uint8_t pcr_select_mask3 = 1 << (pcr_index3 % 8); EXPECT_TRUE(pcr_selection.pcr_select[pcr_select_index1] & pcr_select_mask1); EXPECT_TRUE(pcr_selection.pcr_select[pcr_select_index2] & pcr_select_mask2); EXPECT_TRUE(pcr_selection.pcr_select[pcr_select_index3] & pcr_select_mask3); EXPECT_EQ(StringFrom_TPM2B_DIGEST(pcr_value), crypto::SHA256HashString(pcr_digest1 + pcr_digest2 + pcr_digest3)); } TEST_F(PolicySessionTest, PolicyPCRFailure) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicyPCRSync(_, _, _, _, _)) .WillOnce(Return(TPM_RC_FAILURE)); EXPECT_EQ( TPM_RC_FAILURE, session.PolicyPCR(std::map<uint32_t, std::string>({{1, "pcr_digest"}}))); } TEST_F(PolicySessionTest, PolicyPCRTrialWithNoDigest) { PolicySessionImpl session(factory_, TPM_SE_TRIAL); EXPECT_EQ(SAPI_RC_BAD_PARAMETER, session.PolicyPCR(std::map<uint32_t, std::string>({{1, ""}}))); } TEST_F(PolicySessionTest, PolicyCommandCodeSuccess) { PolicySessionImpl session(factory_); TPM_CC command_code = TPM_CC_FIRST; EXPECT_CALL(mock_tpm_, PolicyCommandCodeSync(_, _, command_code, _)) .WillOnce(Return(TPM_RC_SUCCESS)); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyCommandCode(TPM_CC_FIRST)); } TEST_F(PolicySessionTest, PolicyCommandCodeFailure) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicyCommandCodeSync(_, _, _, _)) .WillOnce(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.PolicyCommandCode(TPM_CC_FIRST)); } TEST_F(PolicySessionTest, PolicySigned) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicySignedSyncShort(_, _, _, _, _, _, _, _, _, _)) .WillOnce(Return(TPM_RC_SUCCESS)); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicySigned(1, "", "", "", "", 0, TPMT_SIGNATURE(), GetHmacDelegate(&session))); } TEST_F(PolicySessionTest, PolicyFidoSigned) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicyFidoSignedSync(_, _, _, _, _, _, _, _)) .WillOnce(Return(TPM_RC_SUCCESS)); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyFidoSigned(1, "", "", {}, TPMT_SIGNATURE(), GetHmacDelegate(&session))); } TEST_F(PolicySessionTest, PolicyAuthValueSuccess) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicyAuthValueSync(_, _, _)) .WillOnce(Return(TPM_RC_SUCCESS)); EXPECT_EQ(TPM_RC_SUCCESS, session.PolicyAuthValue()); } TEST_F(PolicySessionTest, PolicyAuthValueFailure) { PolicySessionImpl session(factory_); EXPECT_CALL(mock_tpm_, PolicyAuthValueSync(_, _, _)) .WillOnce(Return(TPM_RC_FAILURE)); EXPECT_EQ(TPM_RC_FAILURE, session.PolicyAuthValue()); } TEST_F(PolicySessionTest, EntityAuthorizationForwardingTest) { PolicySessionImpl session(factory_); std::string test_auth("test_auth"); session.SetEntityAuthorizationValue(test_auth); HmacAuthorizationDelegate* hmac_delegate = GetHmacDelegate(&session); std::string entity_auth = hmac_delegate->entity_authorization_value(); EXPECT_EQ(0, test_auth.compare(entity_auth)); } } // namespace trunks
36.691781
80
0.73838
[ "vector" ]
ed21412f4b3ce2d7e8b82b53eeeff5c1c70d3a13
28,523
cc
C++
src/backends/backend/tensorflow/model_instance.cc
kpedro88/triton-inference-server
37b3441e59bd0da314f428e1dcddf0a2f67d52e1
[ "BSD-3-Clause" ]
null
null
null
src/backends/backend/tensorflow/model_instance.cc
kpedro88/triton-inference-server
37b3441e59bd0da314f428e1dcddf0a2f67d52e1
[ "BSD-3-Clause" ]
null
null
null
src/backends/backend/tensorflow/model_instance.cc
kpedro88/triton-inference-server
37b3441e59bd0da314f428e1dcddf0a2f67d52e1
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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. #include "src/backends/backend/tensorflow/model_instance.h" #include "src/backends/backend/examples/backend_utils.h" namespace nvidia { namespace inferenceserver { namespace backend { namespace { TRITONSERVER_MemoryType GetUsePinnedMemoryType(TRITONSERVER_MemoryType ref_buffer_type) { // The following matrix is used for both input and output. // src \ dest | non-pinned | pinned | device // non-pinned | memcpy | memcpy | buffer needed // pinned | memcpy | memcpy | cudaMemcpy // device | buffer needed | cudaMemcpy | cudaMemcpy if (ref_buffer_type == TRITONSERVER_MEMORY_CPU_PINNED) { return TRITONSERVER_MEMORY_CPU_PINNED; } return (ref_buffer_type == TRITONSERVER_MEMORY_CPU) ? TRITONSERVER_MEMORY_GPU : TRITONSERVER_MEMORY_CPU; } } // namespace // // ModelInstance // ModelInstance::ModelInstance( const std::string& name, const int gpu_device, const int max_batch_size, const bool enable_pinned_input, const bool enable_pinned_output) : name_(name), gpu_device_(gpu_device), max_batch_size_(max_batch_size), enable_pinned_input_(enable_pinned_input), enable_pinned_output_(enable_pinned_output) { #ifdef TRITON_ENABLE_GPU stream_ = nullptr; #endif // TRITON_ENABLE_GPU } ModelInstance::~ModelInstance() { #ifdef TRITON_ENABLE_GPU if (stream_ != nullptr) { cudaError_t err = cudaStreamDestroy(stream_); if (err != cudaSuccess) { TRITONSERVER_LogMessage( TRITONSERVER_LOG_ERROR, __FILE__, __LINE__, (std::string("~ModelInstance: model ") + name_ + " failed to destroy cuda stream: " + cudaGetErrorString(err)) .c_str()); } stream_ = nullptr; } #endif // TRITON_ENABLE_GPU } TRITONSERVER_Error* ModelInstance::CreateCudaStream( const int cuda_stream_priority, cudaStream_t* stream) { #ifdef TRITON_ENABLE_GPU if (gpu_device_ != NO_GPU_DEVICE) { // Make sure that correct device is set before creating stream and // then restore the device to what was set by the caller. int current_device; auto cuerr = cudaGetDevice(&current_device); bool overridden = false; if (cuerr == cudaSuccess) { overridden = (current_device != gpu_device_); if (overridden) { cuerr = cudaSetDevice(gpu_device_); } } if (cuerr == cudaSuccess) { cudaStream_t* s = (stream == nullptr) ? &stream_ : stream; cuerr = cudaStreamCreateWithPriority( s, cudaStreamDefault, cuda_stream_priority); } if (overridden) { cudaSetDevice(current_device); } if (cuerr != cudaSuccess) { return TRITONSERVER_ErrorNew( TRITONSERVER_ERROR_INTERNAL, (std::string("unable to create stream for ") + name_ + ": " + cudaGetErrorString(cuerr)) .c_str()); } } #endif // TRITON_ENABLE_GPU return nullptr; // success } // // ModelResponder // ModelResponder::~ModelResponder() { #ifdef TRITON_ENABLE_GPU for (auto& pinned_memory : pinned_memories_) { cudaFreeHost(pinned_memory); } #endif // TRITON_ENABLE_GPU } void ModelResponder::ProcessTensor( const std::string& output_name, const TRITONSERVER_DataType datatype, std::vector<int64_t>& batchn_shape, const char* buffer, const TRITONSERVER_MemoryType memory_type, const int64_t memory_type_id) { // A value of CPU_PINNED indicates that pinned memory buffer is not // needed for this tensor. Any other value indicates that a pinned // memory buffer is needed when the target memory type matches // 'use_pinned_memory_type'. TRITONSERVER_MemoryType use_pinned_memory_type = TRITONSERVER_MEMORY_CPU_PINNED; if (pinned_enabled_) { use_pinned_memory_type = GetUsePinnedMemoryType(memory_type); } size_t tensor_offset = 0; for (size_t idx = 0; idx < responses_->size(); idx++) { auto& request = requests_[idx]; auto& response = (*responses_)[idx]; // If then pending copies are from tensor buffer that is not // contiguous with 'response's part of that buffer, then need to // go ahead and perform the pending copies so that can start a // new contiguous region if necessary. if ((pending_pinned_byte_size_ > 0) && (tensor_offset != (pending_pinned_byte_size_ + pending_pinned_offset_))) { need_sync_ |= FlushPendingPinned(buffer, memory_type, memory_type_id); } // Override shape to be correct for this response. if (max_batch_size_ != ModelInstance::NO_BATCHING) { const char* name; TRITONBACKEND_RequestInputName(request, 0, &name); TRITONBACKEND_Input* input; TRITONBACKEND_RequestInput(request, name, &input); const int64_t* shape; TRITONBACKEND_InputProperties( input, nullptr, nullptr, &shape, nullptr, nullptr, nullptr); batchn_shape[0] = shape[0]; } const size_t tensor_byte_size = GetByteSize(datatype, batchn_shape); TRITONBACKEND_Output* response_output; if (response != nullptr) { uint32_t output_count; RESPOND_AND_SET_NULL_IF_ERROR( &response, TRITONBACKEND_RequestOutputCount(request, &output_count)); if (response != nullptr) { for (uint32_t output_idx = 0; output_idx < output_count; output_idx++) { const char* name; RESPOND_AND_SET_NULL_IF_ERROR( &response, TRITONBACKEND_RequestOutputName(request, output_idx, &name)); if ((response != nullptr) && (output_name == name)) { RESPOND_AND_SET_NULL_IF_ERROR( &response, TRITONBACKEND_ResponseOutput( response, &response_output, name, datatype, batchn_shape.data(), batchn_shape.size())); if (response != nullptr) { need_sync_ |= SetFixedSizeOutputBuffer( &response, response_output, output_name, tensor_byte_size, tensor_offset, buffer, memory_type, memory_type_id, use_pinned_memory_type); } } } } } tensor_offset += tensor_byte_size; } // Done with the tensor, flush any pending pinned copies. need_sync_ |= FlushPendingPinned(buffer, memory_type, memory_type_id); #ifdef TRITON_ENABLE_GPU if (need_sync_ && (event_ != nullptr)) { cudaEventRecord(event_, stream_); } #endif // TRITON_ENABLE_GPU } bool ModelResponder::Finalize() { #ifdef TRITON_ENABLE_GPU if ((!deferred_pinned_.empty()) && need_sync_) { if (event_ != nullptr) { cudaEventSynchronize(event_); } else { cudaStreamSynchronize(stream_); } need_sync_ = false; } #endif // TRITON_ENABLE_GPU // After the above sync all the GPU->pinned copies are complete. Any // deferred copies of pinned->CPU can now be done. for (auto& def : deferred_pinned_) { auto pinned_memory_type = TRITONSERVER_MEMORY_CPU_PINNED; int64_t pinned_memory_id = 0; char* pinned_buffer = def.pinned_memory_; size_t offset = 0; for (auto& pr : def.responses_) { auto& response = pr.first; auto& response_output = pr.second; bool cuda_used = false; RESPOND_AND_SET_NULL_IF_ERROR( response, CopyBuffer( response_output.name_, pinned_memory_type, pinned_memory_id, response_output.memory_type_, response_output.memory_type_id_, response_output.buffer_byte_size_, pinned_buffer + offset, const_cast<void*>(response_output.buffer_), stream_, &cuda_used)); need_sync_ |= cuda_used; offset += response_output.buffer_byte_size_; } } #ifdef TRITON_ENABLE_GPU // Record the new event location if deferred copies occur if ((!deferred_pinned_.empty()) && need_sync_ && (event_ != nullptr)) { cudaEventRecord(event_, stream_); } #endif // TRITON_ENABLE_GPU deferred_pinned_.clear(); return need_sync_; } bool ModelResponder::SetFixedSizeOutputBuffer( TRITONBACKEND_Response** response, TRITONBACKEND_Output* response_output, const std::string& output_name, const size_t tensor_byte_size, const size_t tensor_offset, const char* tensor_buffer, const TRITONSERVER_MemoryType tensor_memory_type, const int64_t tensor_memory_type_id, const TRITONSERVER_MemoryType use_pinned_memory_type) { void* buffer = nullptr; bool cuda_copy = false; TRITONSERVER_MemoryType actual_memory_type = tensor_memory_type; int64_t actual_memory_type_id = tensor_memory_type_id; auto err = TRITONBACKEND_OutputBuffer( response_output, &buffer, tensor_byte_size, &actual_memory_type, &actual_memory_type_id); if (err != nullptr) { RESPOND_AND_SET_NULL_IF_ERROR(response, err); return cuda_copy; } // If the response buffer matches the memory type that should use an // intermediate pinned memory buffer for the transfer, then just // record the response as pending and increase the size required for // the intermediate pinned buffer. if ((use_pinned_memory_type != TRITONSERVER_MEMORY_CPU_PINNED) && (actual_memory_type == use_pinned_memory_type)) { if (pending_pinned_byte_size_ == 0) { pending_pinned_offset_ = tensor_offset; } pending_pinned_byte_size_ += tensor_byte_size; pending_pinned_outputs_.push_back(std::make_pair( response, OutputData( output_name, buffer, tensor_byte_size, actual_memory_type, actual_memory_type_id))); } else { // Direct copy without intermediate pinned memory. bool cuda_used = false; err = CopyBuffer( output_name, tensor_memory_type, tensor_memory_type_id, actual_memory_type, actual_memory_type_id, tensor_byte_size, tensor_buffer + tensor_offset, buffer, stream_, &cuda_used); cuda_copy |= cuda_used; if (err != nullptr) { RESPOND_AND_SET_NULL_IF_ERROR(response, err); return cuda_copy; } } return cuda_copy; } bool ModelResponder::FlushPendingPinned( const char* tensor_buffer, const TRITONSERVER_MemoryType tensor_memory_type, const int64_t tensor_memory_type_id) { bool cuda_copy = false; // Will be copying from CPU->pinned->GPU or GPU->pinned->CPU // Always need a pinned buffer... auto pinned_memory_type = TRITONSERVER_MEMORY_CPU_PINNED; int64_t pinned_memory_id = 0; char* pinned_memory = nullptr; #ifdef TRITON_ENABLE_GPU auto cuerr = cudaHostAlloc( (void**)&pinned_memory, pending_pinned_byte_size_, cudaHostAllocPortable); if (cuerr != cudaSuccess) { pinned_memory_type = TRITONSERVER_MEMORY_CPU; } #else pinned_memory_type = TRITONSERVER_MEMORY_CPU; #endif // TRITON_ENABLE_GPU // If the pinned buffer isn't actually pinned memory then just // perform a direct copy. In this case 'pinned_memory' is just // deallocated and not used. if (pinned_memory_type != TRITONSERVER_MEMORY_CPU_PINNED) { pinned_memory = nullptr; size_t offset = 0; for (auto& pr : pending_pinned_outputs_) { auto& response = pr.first; auto& response_output = pr.second; bool cuda_used = false; RESPOND_AND_SET_NULL_IF_ERROR( response, CopyBuffer( response_output.name_, tensor_memory_type, tensor_memory_type_id, response_output.memory_type_, response_output.memory_type_id_, response_output.buffer_byte_size_, tensor_buffer + pending_pinned_offset_ + offset, const_cast<void*>(response_output.buffer_), stream_, &cuda_used)); cuda_copy |= cuda_used; offset += response_output.buffer_byte_size_; } } // We have a pinned buffer so do a single copy of a block of tensor // data to the pinned buffer. else { // pinned_memory_type == TRITONSERVER_MEMORY_CPU_PINNED bool cuda_used = false; auto err = CopyBuffer( "pinned buffer", tensor_memory_type, tensor_memory_type_id, pinned_memory_type, pinned_memory_id, pending_pinned_byte_size_, tensor_buffer + pending_pinned_offset_, pinned_memory, stream_, &cuda_used); cuda_copy |= cuda_used; // If something goes wrong with the copy all the pending // responses fail... if (err != nullptr) { for (auto& pr : pending_pinned_outputs_) { auto& response = pr.first; if (*response != nullptr) { LOG_IF_ERROR( TRITONBACKEND_ResponseSend( *response, TRITONSERVER_RESPONSE_COMPLETE_FINAL, err), "failed to send TensorFlow error response"); *response = nullptr; } } TRITONSERVER_ErrorDelete(err); } // If the copy was not async (i.e. if tensor was in CPU so a // CPU->CPU-PINNED copy was performed above), then the pinned // buffer now holds the tensor contents and we can immediately // issue the copies from the pinned buffer to the // responses. // // Otherwise the GPU->CPU-PINNED async copies are in flight and we // simply remember the pinned buffer and the corresponding // response outputs so that we can do the pinned->CPU copies in // finalize after we have waited for all async copies to complete. if (!cuda_used) { size_t offset = 0; for (auto& pr : pending_pinned_outputs_) { auto& response = pr.first; auto& response_output = pr.second; bool cuda_used = false; RESPOND_AND_SET_NULL_IF_ERROR( response, CopyBuffer( response_output.name_, pinned_memory_type, pinned_memory_id, response_output.memory_type_, response_output.memory_type_id_, response_output.buffer_byte_size_, pinned_memory + offset, const_cast<void*>(response_output.buffer_), stream_, &cuda_used)); cuda_copy |= cuda_used; offset += response_output.buffer_byte_size_; } } else { deferred_pinned_.emplace_back( pinned_memory, pending_pinned_byte_size_, std::move(pending_pinned_outputs_)); } } // Pending pinned copies are handled... pending_pinned_byte_size_ = 0; pending_pinned_offset_ = 0; pending_pinned_outputs_.clear(); // Need to hold on to the allocated pinned buffer as there are still // copies in flight. Will delete it in finalize. if (pinned_memory != nullptr) { pinned_memories_.push_back(pinned_memory); } return cuda_copy; } // // ModelInputCollector // ModelInputCollector::~ModelInputCollector() { #ifdef TRITON_ENABLE_GPU for (auto& pinned_memory : pinned_memories_) { cudaFreeHost(pinned_memory); } #endif // TRITON_ENABLE_GPU } void ModelInputCollector::ProcessTensor( const char* input_name, char* buffer, const size_t buffer_byte_size, const TRITONSERVER_MemoryType memory_type, const int64_t memory_type_id) { // A value of CPU_PINNED indicates that pinned memory buffer is not // needed for this tensor. Any other value indicates that a pinned // memory buffer is needed when the target memory type matches // 'use_pinned_memory_type'. TRITONSERVER_MemoryType use_pinned_memory_type = TRITONSERVER_MEMORY_CPU_PINNED; if (pinned_enabled_) { use_pinned_memory_type = GetUsePinnedMemoryType(memory_type); } size_t buffer_offset = 0; for (size_t idx = 0; idx < request_count_; idx++) { auto& request = requests_[idx]; auto& response = (*responses_)[idx]; // If there are pending copies from tensor buffer that is not // contiguous with 'response's part of that buffer, then need to // go ahead and perform the pending copies so that can start a new // contiguous region if necessary. if ((pending_pinned_byte_size_ > 0) && (buffer_offset != (pending_pinned_byte_size_ + pending_pinned_offset_))) { need_sync_ |= FlushPendingPinned( buffer, buffer_byte_size, memory_type, memory_type_id); } TRITONBACKEND_Input* input; RESPOND_AND_SET_NULL_IF_ERROR( &response, TRITONBACKEND_RequestInput(request, input_name, &input)); uint64_t byte_size; RESPOND_AND_SET_NULL_IF_ERROR( &response, TRITONBACKEND_InputProperties( input, nullptr, nullptr, nullptr, nullptr, &byte_size, nullptr)); if (response != nullptr) { need_sync_ |= SetFixedSizeInputTensor( input, buffer_offset, buffer, buffer_byte_size, memory_type, memory_type_id, use_pinned_memory_type, &response); } buffer_offset += byte_size; } // Done with the tensor, flush any pending pinned copies. need_sync_ |= FlushPendingPinned(buffer, buffer_byte_size, memory_type, memory_type_id); #ifdef TRITON_ENABLE_GPU if (need_sync_ && (event_ != nullptr)) { cudaEventRecord(event_, stream_); } #endif // TRITON_ENABLE_GPU } bool ModelInputCollector::Finalize() { #ifdef TRITON_ENABLE_GPU if ((!deferred_pinned_.empty()) && need_sync_) { if (event_ != nullptr) { cudaEventSynchronize(event_); } else { cudaStreamSynchronize(stream_); } need_sync_ = false; } #endif // TRITON_ENABLE_GPU // After the above sync all the GPU->pinned copies are complete. Any // deferred copies of pinned->CPU can now be done. for (auto& def : deferred_pinned_) { bool cuda_used = false; auto err = CopyBuffer( "pinned buffer", TRITONSERVER_MEMORY_CPU_PINNED, 0, def.tensor_memory_type_, def.tensor_memory_id_, def.pinned_memory_size_, def.pinned_memory_, def.tensor_buffer_ + def.tensor_buffer_offset_, stream_, &cuda_used); need_sync_ |= cuda_used; // If something goes wrong with the copy all the pending // responses fail... if (err != nullptr) { for (auto& pr : def.requests_) { auto& response = pr.first; if (*response != nullptr) { LOG_IF_ERROR( TRITONBACKEND_ResponseSend( *response, TRITONSERVER_RESPONSE_COMPLETE_FINAL, err), "failed to send error response"); *response = nullptr; } } TRITONSERVER_ErrorDelete(err); } } #ifdef TRITON_ENABLE_GPU // Record the new event location if deferred copies occur if ((!deferred_pinned_.empty()) && need_sync_ && (event_ != nullptr)) { cudaEventRecord(event_, stream_); } #endif // TRITON_ENABLE_GPU deferred_pinned_.clear(); return need_sync_; } bool ModelInputCollector::SetFixedSizeInputTensor( TRITONBACKEND_Input* request_input, const size_t tensor_buffer_offset, char* tensor_buffer, const size_t tensor_buffer_byte_size, const TRITONSERVER_MemoryType tensor_memory_type, const int64_t tensor_memory_type_id, const TRITONSERVER_MemoryType use_pinned_memory_type, TRITONBACKEND_Response** response) { bool cuda_copy = false; const char* name; uint32_t buffer_count; RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONBACKEND_InputProperties( request_input, &name, nullptr, nullptr, nullptr, nullptr, &buffer_count)); if (*response == nullptr) { return cuda_copy; } // First iterate through the buffers to ensure the byte size is proper size_t total_byte_size = 0; for (size_t idx = 0; idx < buffer_count; ++idx) { const void* src_buffer; size_t src_byte_size; TRITONSERVER_MemoryType src_memory_type; int64_t src_memory_type_id; RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONBACKEND_InputBuffer( request_input, idx, &src_buffer, &src_byte_size, &src_memory_type, &src_memory_type_id)); total_byte_size += src_byte_size; } if ((tensor_buffer_offset + total_byte_size) > tensor_buffer_byte_size) { RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONSERVER_ErrorNew( TRITONSERVER_ERROR_INVALID_ARG, std::string( "unexpected total byte size " + std::to_string(tensor_buffer_offset + total_byte_size) + " for input '" + name + "', expecting " + std::to_string(tensor_buffer_byte_size)) .c_str())); return cuda_copy; } else if (response == nullptr) { return cuda_copy; } // Request input tensor data may be in multiple non-contiguous // buffers. size_t input_offset = 0; for (size_t idx = 0; idx < buffer_count; ++idx) { const void* src_buffer; size_t src_byte_size; TRITONSERVER_MemoryType src_memory_type; int64_t src_memory_type_id; RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONBACKEND_InputBuffer( request_input, idx, &src_buffer, &src_byte_size, &src_memory_type, &src_memory_type_id)); if (*response == nullptr) { return cuda_copy; } // If the request buffer matches the memory type that should use an // intermediate pinned memory buffer for the transfer, then just // record the input as pending and increase the size required for // the intermediate pinned buffer. We only do this check for the // first buffer of an input and apply the same policy for all // buffers. So if an inputs data is split over different memory // types this may not be ideal but that should be a very rare // situation. if ((idx == 0) && (use_pinned_memory_type != TRITONSERVER_MEMORY_CPU_PINNED) && (src_memory_type == use_pinned_memory_type)) { if (pending_pinned_byte_size_ == 0) { pending_pinned_offset_ = tensor_buffer_offset; } pending_pinned_byte_size_ += total_byte_size; pending_pinned_inputs_.push_back(std::make_pair(response, request_input)); return cuda_copy; } // Direct copy without intermediate pinned memory. bool cuda_used = false; RESPOND_AND_SET_NULL_IF_ERROR( response, CopyBuffer( name, src_memory_type, src_memory_type_id, tensor_memory_type, tensor_memory_type_id, src_byte_size, src_buffer, tensor_buffer + tensor_buffer_offset + input_offset, stream_, &cuda_used)); cuda_copy |= cuda_used; if (*response == nullptr) { return cuda_copy; } input_offset += src_byte_size; } return cuda_copy; } bool ModelInputCollector::FlushPendingPinned( char* tensor_buffer, const size_t tensor_buffer_byte_size, const TRITONSERVER_MemoryType tensor_memory_type, const int64_t tensor_memory_type_id) { bool cuda_copy = false; // Will be copying from CPU->pinned->GPU or GPU->pinned->CPU // Always need a pinned buffer... auto pinned_memory_type = TRITONSERVER_MEMORY_CPU_PINNED; int64_t pinned_memory_id = 0; char* pinned_memory = nullptr; #ifdef TRITON_ENABLE_GPU auto cuerr = cudaHostAlloc( (void**)&pinned_memory, pending_pinned_byte_size_, cudaHostAllocPortable); if (cuerr != cudaSuccess) { pinned_memory_type = TRITONSERVER_MEMORY_CPU; } #else pinned_memory_type = TRITONSERVER_MEMORY_CPU; #endif // TRITON_ENABLE_GPU // If the pinned buffer isn't actually pinned memory then just // perform a direct copy. In this case 'pinned_memory' is just // deallocated and not used. if (pinned_memory_type != TRITONSERVER_MEMORY_CPU_PINNED) { pinned_memory = nullptr; size_t offset = 0; for (auto& pr : pending_pinned_inputs_) { auto& response = pr.first; auto& request_input = pr.second; uint64_t byte_size; RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONBACKEND_InputProperties( request_input, nullptr, nullptr, nullptr, nullptr, &byte_size, nullptr)); cuda_copy |= SetFixedSizeInputTensor( request_input, pending_pinned_offset_ + offset, tensor_buffer, tensor_buffer_byte_size, tensor_memory_type, tensor_memory_type_id, TRITONSERVER_MEMORY_CPU_PINNED, response); offset += byte_size; } } // We have a pinned buffer so copy the pending input buffer(s) into // the pinned memory. else { // pinned_memory_type == TRITONSERVER_MEMORY_CPU_PINNED bool cuda_used = false; size_t offset = 0; for (auto& pr : pending_pinned_inputs_) { auto& response = pr.first; auto& request_input = pr.second; uint64_t byte_size; RESPOND_AND_SET_NULL_IF_ERROR( response, TRITONBACKEND_InputProperties( request_input, nullptr, nullptr, nullptr, nullptr, &byte_size, nullptr)); cuda_used |= SetFixedSizeInputTensor( request_input, offset, pinned_memory, pending_pinned_byte_size_, pinned_memory_type, pinned_memory_id, TRITONSERVER_MEMORY_CPU_PINNED, response); offset += byte_size; } cuda_copy |= cuda_used; // If the copy was not async (i.e. if request input was in CPU so // a CPU->CPU-PINNED copy was performed above), then the pinned // buffer now holds the tensor contents and we can immediately // issue the copies from the pinned buffer to the tensor. // // Otherwise the GPU->CPU-PINNED async copies are in flight and we // simply remember the pinned buffer and the corresponding // request inputs so that we can do the pinned->CPU copies in // finalize after we have waited for all async copies to complete. if (!cuda_used) { auto err = CopyBuffer( "pinned buffer", pinned_memory_type, pinned_memory_id, tensor_memory_type, tensor_memory_type_id, pending_pinned_byte_size_, pinned_memory, tensor_buffer + pending_pinned_offset_, stream_, &cuda_used); cuda_copy |= cuda_used; // If something goes wrong with the copy all the pending // responses fail... if (err != nullptr) { for (auto& pr : pending_pinned_inputs_) { auto& response = pr.first; if (*response != nullptr) { LOG_IF_ERROR( TRITONBACKEND_ResponseSend( *response, TRITONSERVER_RESPONSE_COMPLETE_FINAL, err), "failed to send error response"); *response = nullptr; } } TRITONSERVER_ErrorDelete(err); } } else { // cuda_used deferred_pinned_.emplace_back( pinned_memory, pending_pinned_byte_size_, tensor_buffer, pending_pinned_offset_, tensor_memory_type, tensor_memory_type_id, std::move(pending_pinned_inputs_)); } } // Pending pinned copies are handled... pending_pinned_byte_size_ = 0; pending_pinned_offset_ = 0; pending_pinned_inputs_.clear(); // Need to hold on to the allocated pinned buffer as there are still // copies in flight. Will delete it in finalize. if (pinned_memory != nullptr) { pinned_memories_.push_back(pinned_memory); } return cuda_copy; } }}} // namespace nvidia::inferenceserver::backend
34.869193
80
0.68727
[ "shape", "vector", "model" ]
ed2191abd307860a007d57594f178b3dddd90608
5,424
cc
C++
insert-friend.cc
highperformancecoder/classdesc
15ff06aded75498ef85cf63da4870022aef37ad2
[ "MIT" ]
1
2021-01-31T22:53:35.000Z
2021-01-31T22:53:35.000Z
insert-friend.cc
highperformancecoder/classdesc
15ff06aded75498ef85cf63da4870022aef37ad2
[ "MIT" ]
9
2017-11-26T23:08:07.000Z
2018-07-04T00:59:26.000Z
insert-friend.cc
highperformancecoder/classdesc
15ff06aded75498ef85cf63da4870022aef37ad2
[ "MIT" ]
3
2017-07-23T19:29:05.000Z
2018-04-19T12:02:25.000Z
/* @copyright Russell Standish 2000-2013 @author Russell Standish This file is part of Classdesc Open source licensed under the MIT license. See LICENSE for details. */ /* process a header file, inserting the macro CLASSDESC_ACCESS(classname) into each class or struct encountered conatining private definitions. CLASSDESC_ACCESS(classname) can then be defined to be a list of friend statments: eg #define CLASSDESC_ACCESS(type)\ friend void pack(pack_t *,eco_string,type&); */ #include <string> #include <vector> #include <stdio.h> //#include <fstream> using namespace std; #include "tokeninput.h" /* mapping of template arguments as how insert-friend sees them, to how they should really be */ hash_map<string,string> targ_map; /* create list of arguments used in a template */ string extract_targs(string targs) { if (targs.empty()) return targs; /* nothing to do */ string r="<", tok; const char *targsptr=targs.c_str()+1; for (; *targsptr; targsptr++) { if (isalnum(*targsptr)||*targsptr=='_') tok+=*targsptr; else { while (isspace(*targsptr)) targsptr++;/* skip any spaces */ if (*targsptr=='<') /* skip over stuff between <..> */ { int angle_count=1; while (angle_count) { targsptr++; if (*targsptr=='<') angle_count++; else if (*targsptr=='>') angle_count--; } } else if (*targsptr=='=') { for (int angle_count=0; !strchr(">,",*(targsptr)) || angle_count; targsptr++) if (*targsptr=='<') angle_count++; else if (*targsptr=='>') angle_count--; r+=tok+*targsptr; } else if (strchr(">,",*targsptr)) r+=tok+*targsptr; else if (isalnum(*targsptr)||*targsptr=='_') targsptr--; /* rewind ptr so next loop starts token */ tok.erase(); } } return r; } void deal_with_commas(string& classname) { if (classname.find(',')!=classname.npos) { // must deal with typenames containing ',' static int cnt=0; char tname[20]; sprintf(tname,"___ecotif%-10d",cnt++); printf("typedef %s %s;\n",classname.c_str(),tname); classname=tname; } } void insert_friend(tokeninput& input, string prefix, string targs, int is_struct) { string classname = prefix + input.token; input.nexttok(); if (input.token=="<") /* template specialisation */ classname += get_template_args(input); if (strchr(":{",input.token[0])) { for (;input.token!="{"; input.nexttok() ); /* structs are complicated by the possibility of protected and private members - if none, then no friend statement is necessary */ if (is_struct) { int numbraces=0; for (input.nexttok(); input.token!="}" || numbraces>0; input.nexttok() ) { if (input.token=="{") numbraces++; if (input.token=="}") numbraces--; if (input.token==":" && (input.lasttoken=="protected" || input.lasttoken=="private")) goto really_insert_friend; } return; /* struct has no protected or private members, nothing to do */ } really_insert_friend: puts(""); /* check if typename is mapped to something else */ if (targ_map.count(classname)) classname=targ_map[classname]; deal_with_commas(classname); if (targs=="") printf("CLASSDESC_ACCESS(%s);\n",classname.c_str()); else printf("CLASSDESC_ACCESS_TEMPLATE(%s);\n",classname.c_str()); /* emit a CLASSDESC_FDEF to handle g++'s requirements */ if (targs.size()) { /* advance to end of class definition */ if (input.token!="}") gobble_delimited(input,"{","}"); printf("\n#define CLASSDESC_TDEC template%s\n",targs.c_str()); if (classname.find('<')==classname.npos) classname += extract_targs(targs); deal_with_commas(classname); printf("CLASSDESC_FDEF(%s);\n",classname.c_str()); } } } int main(int argc, char* argv[]) { tokeninput input(stdin,stdout); string targs; while (argc>1 && argv[1][0]=='-') /* process options */ { // if (strcmp(argv[1],"-targ_map")==0) /* read in targ map */ // { // ifstream targmapfile(argv[2]); // string guessed_type, real_type; // while (targmapfile>>guessed_type>>real_type) // targ_map[guessed_type]=real_type; // argc-=2; argv+=2; // } } try { for (;;) { if (input.token=="template") { input.nexttok(); if (input.token!="<") /* g++'s explicit instantiation syntax */ { /* we must parse until end of declaration */ for (int nbraces=0; nbraces>0 || input.token!=";"; input.nexttok()) { if (input.token=="{") nbraces++; if (input.token=="}") nbraces--; } continue; } targs=get_template_args(input); if (input.token!="class" && input.token!="struct") { targs.erase(); /* not a template class */ continue; } } if ((input.token=="class" || input.token=="struct") && input.lasttoken!="friend") { input.nexttok(); #if (defined(__osf__) && !defined(__GNUC__)) /* handle a rogue wave hack for Windoze support - aarrgh! */ if (input.token.substr(0,12)=="_RWSTDExport") input.nexttok(); #endif if (isalpha(input.token[0])) /* named class */ insert_friend(input,"",targs,input.lasttoken=="struct"); targs.erase(); } input.nexttok(); } } catch(tokeninput::eof) {} return 0; }
26.851485
70
0.607117
[ "vector" ]
ed2748811c76b3ce40161a09d8ae74c1d21a16ab
583
cpp
C++
LeetCode/Problems/Algorithms/#581_ShortestUnsortedContinuousSubarray_sol2_sort_O(NlogN)_time_O(N)_extra_space_84ms_27.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#581_ShortestUnsortedContinuousSubarray_sol2_sort_O(NlogN)_time_O(N)_extra_space_84ms_27.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#581_ShortestUnsortedContinuousSubarray_sol2_sort_O(NlogN)_time_O(N)_extra_space_84ms_27.4MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> sorted_nums(nums); sort(sorted_nums.begin(), sorted_nums.end()); const int N = nums.size(); int l = N + 1; int r = -1; for(int i = 0; i < N; ++i){ if(sorted_nums[i] != nums[i]){ l = min(i, l); r = max(i, r); } } int answer = r - l + 1; if(answer <= 1){ answer = 0; } return answer; } };
24.291667
54
0.382504
[ "vector" ]
ed2ac16d20f85e21fcf5be27aaba1ed86981b4a5
4,411
cpp
C++
source/RDP/Models/DriverLogBackgroundWorker.cpp
play704611/dev_driver_tools
312d40afb533b623e441139797410a33ecab3182
[ "MIT" ]
null
null
null
source/RDP/Models/DriverLogBackgroundWorker.cpp
play704611/dev_driver_tools
312d40afb533b623e441139797410a33ecab3182
[ "MIT" ]
null
null
null
source/RDP/Models/DriverLogBackgroundWorker.cpp
play704611/dev_driver_tools
312d40afb533b623e441139797410a33ecab3182
[ "MIT" ]
null
null
null
//============================================================================= /// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief A background worker thread responsible for processing incoming driver log messages. //============================================================================= #include <QCoreApplication>// Read incoming driver log messages. #include "DriverLogBackgroundWorker.h" #include "DeveloperPanelModel.h" #include "DriverLogfileModel.h" #include "../RDPDefinitions.h" #include "../../DevDriverComponents/inc/util/vector.h" using namespace DevDriver; using namespace DevDriver::LoggingProtocol; //----------------------------------------------------------------------------- /// Constructor for DriverLogBackgroundWorker. //----------------------------------------------------------------------------- DriverLogBackgroundWorker::DriverLogBackgroundWorker() : m_pLoggingClient(nullptr) , m_pDriverLogfileModel(nullptr) , m_retrievingLogMessages(false) { connect(this, &DriverLogBackgroundWorker::EmitStopProcessingLogMessages, this, &DriverLogBackgroundWorker::StopProcessingLogMessages); } //----------------------------------------------------------------------------- /// Destructor for DriverLogBackgroundWorker. //----------------------------------------------------------------------------- DriverLogBackgroundWorker::~DriverLogBackgroundWorker() { } //----------------------------------------------------------------------------- /// Initialize the driver log reader background worker. /// \param pLoggingClient The driver logging client instance to read log messages with. /// \param pDriverLogfileModel The model to update with new log lines. /// \returns True when the worker is initialized successfully, and false if it failed. //----------------------------------------------------------------------------- bool DriverLogBackgroundWorker::InitializeLogReader(LoggingClient* pLoggingClient, DriverLogfileModel* pDriverLogfileModel) { // @HACK: Temporarily disable the log functionality while the protocol client is being reworked. Q_UNUSED(pLoggingClient); Q_UNUSED(pDriverLogfileModel); if (pLoggingClient != nullptr && pLoggingClient->IsConnected()) { m_pLoggingClient = pLoggingClient; } return m_retrievingLogMessages; } //----------------------------------------------------------------------------- /// Read incoming driver log messages. //----------------------------------------------------------------------------- void DriverLogBackgroundWorker::ReadIncomingDriverLogMessages() { while (m_retrievingLogMessages) { if (m_pLoggingClient != nullptr && m_pLoggingClient->IsConnected()) { DevDriver::Vector<LogMessage> logLines(GenericAllocCb); Result result = m_pLoggingClient->ReadLogMessages(logLines); size_t numLines = logLines.Size(); if (result == Result::Success && numLines > 0) { for (uint32 messageIndex = 0; messageIndex < numLines; ++messageIndex) { const QString& logLine = QString(logLines[messageIndex].message); m_pDriverLogfileModel->AddLogLine(logLine); } } } else { m_retrievingLogMessages = false; } // This thread needs to process any incoming events in order to signal completion. QCoreApplication::processEvents(); } } //----------------------------------------------------------------------------- /// A slot that disables reading new log messages from the connected RDS. //----------------------------------------------------------------------------- void DriverLogBackgroundWorker::StopProcessingLogMessages() { if (m_retrievingLogMessages) { m_retrievingLogMessages = false; } } //----------------------------------------------------------------------------- /// Handle shutting down the log worker when the thread is finished. //----------------------------------------------------------------------------- void DriverLogBackgroundWorker::ThreadFinished() { if (m_pLoggingClient != nullptr && m_pLoggingClient->IsConnected()) { m_pLoggingClient->DisableLogging(); m_retrievingLogMessages = false; } }
40.46789
138
0.531172
[ "vector", "model" ]
ed3211a1c9ec7ab1d9dca8b0e44ace57681369b9
10,708
cpp
C++
REALSPACE/Source/RSObject.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
REALSPACE/Source/RSObject.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
REALSPACE/Source/RSObject.cpp
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
#include "RealSpace.h" #include "RSObject.h" #include "rutils.h" #include "stdio.h" #include "crtdbg.h" #include "RSMaterialManager.h" #include "RSDebug.h" #include "RSAnimationInfo.h" #include "rtexture.h" #include "FileInfo.h" CMesh::CMesh() { ver=NULL; name=NULL; nV=nFaces=0; faceshead=NULL; m_align=RS_ALIGNSTYLE_NONE; } CMesh::~CMesh() { if (ver) delete []ver; if (name) delete []name; if (faceshead) delete []faceshead; } CFaces::CFaces() { nv=0;ni=0; iMaterial=0; tnlvertices=NULL; indicies=NULL; indicies_original=NULL; pVertexBuffer=NULL; pIndexBuffer=NULL; } CFaces::~CFaces() { if(tnlvertices) delete tnlvertices; if(indicies) delete indicies; if(indicies_original) delete indicies_original; if(pVertexBuffer) { for(int i=0;i<RSGetDeviceCount();i++) { if(pVertexBuffer[i]) pVertexBuffer[i]->Release(); } delete pVertexBuffer; } if(pIndexBuffer) { for(int i=0;i<RSGetDeviceCount();i++) { if(pIndexBuffer[i]) pIndexBuffer[i]->Release(); } delete pIndexBuffer; } } void CFaces::Draw() { /* int k; //RSDrawFaceArray(faces->face,faces->nf);/* rface *f=face; for(k=0;k<nf;k++) { if(f->isValid) RSDrawFace(f); f++; }//*/ } RSObject::RSObject() { RefferenceCount=0; nMesh=0; nMaterial=0; nAnimSet=0; m_BoundingSphereRadius=0; m_BoundingSphereRadiusXY=0; m_bbox.Minz=m_bbox.Miny=m_bbox.Minx=100000000; m_bbox.Maxz=m_bbox.Maxy=m_bbox.Maxx=-100000000; materials=NULL; meshes=NULL; m_hShadowTexture=NULL; m_pMM=NULL; b_needdelMM=false; } RSObject::~RSObject() { Destroy(); } bool RSObject::Destroy() { if( materials ) { delete []materials; materials=NULL; } if( meshes ) { delete []meshes; meshes=NULL; } if(m_hShadowTexture) { RSDeleteTexture(m_hShadowTexture); m_hShadowTexture=NULL; } if(b_needdelMM && m_pMM) { delete m_pMM; m_pMM=NULL; b_needdelMM=false; } return TRUE; } static float g_fTemp; #define ReadBool(x) fread(&(x),sizeof(BOOL),1,file) #define ReadWord(x) fread(&(x),sizeof(WORD),1,file) #define ReadInt(x) fread(&(x),sizeof(int),1,file) #define ReadFloat(x) fread(&(x),sizeof(float),1,file) #define ReadVector(x) fread(&(x),sizeof(rvector),1,file) #define ReadString(x) {int l=fgetc(file);if(l) {x=new char[l+1];x[l]=0;fread(x,l,1,file);}} #define ReadMatrix(m) {ReadFloat(m._11);ReadFloat(m._12);ReadFloat(m._13);ReadFloat(g_fTemp);\ ReadFloat(m._21);ReadFloat(m._22);ReadFloat(m._23);ReadFloat(g_fTemp);\ ReadFloat(m._31);ReadFloat(m._32);ReadFloat(m._33);ReadFloat(g_fTemp);\ ReadFloat(m._41);ReadFloat(m._42);ReadFloat(m._43);ReadFloat(g_fTemp);} #define IsSameTime(x,y) ((x.dwHighDateTime==y.dwHighDateTime)&&(x.dwLowDateTime==y.dwLowDateTime)) static int g_obj_cnt; bool RSObject::Load(FILE *file,RSMaterialManager *pMM) { int i,j,k; fread(&m_Header,sizeof(m_Header),1,file); if((m_Header.RSMID!=HEADER_RSMID)||(m_Header.Build!=HEADER_BUILD)) { rslog("Incorrect file format. rsm build #%d. #%d required.\n",m_Header.Build,HEADER_BUILD); return false; } m_pMM=pMM; fread(&m_bbox,sizeof(rboundingbox),1,file); m_bbox.Minz=m_bbox.Miny=m_bbox.Minx=100000000; m_bbox.Maxz=m_bbox.Maxy=m_bbox.Maxx=-100000000; ReadInt(nMaterial); materials=new RSMaterial*[nMaterial+1]; // rslog("[ load object :%d mtrl_num %d ]\n",g_obj_cnt,nMaterial); materials[0]=&RSDefaultMaterial; for (i=0;i<nMaterial;i++) { char buf[256]; {int l=fgetc(file);buf[l]=0;if(l) fread(buf,l,1,file);} RSMaterial *pmat=pMM->GetMaterial(buf); materials[i+1]=pmat ? pmat : &RSDefaultMaterial; // rslog("\t-mtrl :%d name %s \n",i,buf); } nMaterial++; // for default material; ReadInt(nMesh); CMesh *mesh=meshes=new CMesh[nMesh]; // rslog("\n\t-mesh num :%d \n\n",nMesh); for(i=0;i<nMesh;i++) { ReadString(mesh->name);strlwr(mesh->name); ReadMatrix(mesh->mat); fread(&mesh->m_bbox,sizeof(rboundingbox),1,file); mesh->m_bbox.Minz=mesh->m_bbox.Miny=mesh->m_bbox.Minx=100000000; mesh->m_bbox.Maxz=mesh->m_bbox.Maxy=mesh->m_bbox.Maxx=-100000000; mesh->center=rvector(0,0,0); ReadInt(mesh->nFaces); CFaces *faces=mesh->faceshead=mesh->nFaces?new CFaces[mesh->nFaces]:NULL; // rslog("\t-mesh face num :%d \n",mesh->nFaces); for(j=0;j<mesh->nFaces;j++) { ReadInt(faces->iMaterial);faces->iMaterial++; // convert to 1-base index ReadInt(faces->nv); faces->tnlvertices=new VERTEX[faces->nv]; fread(faces->tnlvertices,sizeof(VERTEX),faces->nv,file); for(k=0;k<faces->nv;k++) { rvector *pv=(rvector*)(&faces->tnlvertices[k].x); m_BoundingSphereRadius=max(m_BoundingSphereRadius,pv->GetMagnitude()); m_BoundingSphereRadiusXY=max(m_BoundingSphereRadiusXY,rvector(pv->x,pv->y,0).GetMagnitude()); mesh->m_bbox.Minx=min(mesh->m_bbox.Minx,pv->x); mesh->m_bbox.Maxx=max(mesh->m_bbox.Maxx,pv->x); mesh->m_bbox.Miny=min(mesh->m_bbox.Miny,pv->y); mesh->m_bbox.Maxy=max(mesh->m_bbox.Maxy,pv->y); mesh->m_bbox.Minz=min(mesh->m_bbox.Minz,pv->z); mesh->m_bbox.Maxz=max(mesh->m_bbox.Maxz,pv->z); } // rslog("\t\t-mesh face v num :%d \n",faces->nv); if(fgetc(file)==1) { faces->indicies_original=new WORD[faces->nv]; fread(faces->indicies_original,sizeof(WORD),faces->nv,file); } else { ReadInt(faces->ni); faces->indicies=new WORD[faces->ni]; fread(faces->indicies,sizeof(WORD),faces->ni,file); } faces++; } if(strstr(mesh->name,ALIGN_POINT_STRING)) mesh->m_align=RS_ALIGNSTYLE_POINT; else if(strstr(mesh->name,ALIGN_LINE_STRING)) mesh->m_align=RS_ALIGNSTYLE_LINE; else mesh->m_align=RS_ALIGNSTYLE_NONE; MergeBoundingBox(&m_bbox,&mesh->m_bbox); mesh++; } m_ShadowTexture.Create(file); /*// save test { char buf[256]; ReplaceExtension(buf,name,"bmp"); m_ShadowTexture.SaveAsBMP(buf); } //*/ m_hShadowTexture=RSCreateTexture( m_ShadowTexture.GetWidth(),m_ShadowTexture.GetHeight(), (char*)m_ShadowTexture.GetData(),NULL,true,"Object:ShadowTexture"); /* rtexture temp;temp.Create(file); CreateShadowTexture(); */ ReadInt(nAnimSet); if(nAnimSet) { for(i=0;i<nAnimSet;i++) { RSAnimationInfo *ai=new RSAnimationInfo; ai->Load(file); AnimationList.Add(ai); } } GenerateVertexBuffers(); // rslog("\t-mesh ani num :%d \n",nAnimSet); // g_obj_cnt++; return true; } void RSObject::CreateShadowTexture() { #define EFFECTIVE_SIZE 0.99f #define SHADOW_COLOR 0xa0a0a0 rtexture rt; rt.New(256,256,RTEXTUREFORMAT_24); rt.Fill(0xffffff); rmatrix44 tm; int i,j,k; float f_max=m_BoundingSphereRadiusXY; tm=ScaleMatrix44(128.0f*EFFECTIVE_SIZE/f_max) *ViewMatrix44(rvector(0,0,0),rvector(1,2,-1),rvector(0,1,0)) *TranslateMatrix44(128,128,0); for(i=0;i<nMesh;i++) { CMesh *mesh=meshes+i; for(j=0;j<mesh->nFaces;j++) { CFaces *faces=mesh->faceshead+j; for(k=0;k<faces->ni;k+=3) { rvector a=TransformVector(*(rvector*)(&faces->tnlvertices[faces->indicies[k]].x),tm); rvector b=TransformVector(*(rvector*)(&faces->tnlvertices[faces->indicies[k+1]].x),tm); rvector c=TransformVector(*(rvector*)(&faces->tnlvertices[faces->indicies[k+2]].x),tm); #define CHECK(x) _ASSERT((x>=0)&&(x<256)) rt.FillTriangle(a.x,a.y,b.x,b.y,c.x,c.y,SHADOW_COLOR); CHECK(a.x);CHECK(a.y); CHECK(b.x);CHECK(b.y); CHECK(c.x);CHECK(c.y); } } } rtexture newrt1;newrt1.CreateAsHalf(&rt); // 128 rtexture newrt2;newrt2.CreateAsHalf(&newrt1); // 64 newrt2.FillBoundary(0xffffff); newrt2.SaveAsBMP("testtest.bmp"); m_hShadowTexture=RSCreateTexture( newrt2.GetWidth(),newrt2.GetHeight(), (char*)newrt2.GetData(),NULL,true,"Object:ShadowTexture"); } bool RSObject::Load(const char *filename,RSMaterialManager *pMM) { strcpy(name,filename); FILE *file; file=fopen(filename,"rb"); if(!file) { rslog("File Open Failed. : %s \n",filename); return false; } bool ret=Load(file,pMM); fclose(file); return ret; } bool RSObject::Load(const char *filename,const char *RMLName) { m_pMM=new RSMaterialManager; if(!m_pMM->Open(RMLName)) return false; b_needdelMM=true; return Load(filename,m_pMM); } void RSObject::ClearVertexBuffers() { int i,j,k; for(i=0;i<nMesh;i++) { CMesh *mesh=&meshes[i]; for(j=0;j<mesh->nFaces;j++) { CFaces *faces=&mesh->faceshead[j]; if(faces->pVertexBuffer) { for(k=0;k<RSGetDeviceCount();k++) faces->pVertexBuffer[k]->Release(); delete faces->pVertexBuffer; faces->pVertexBuffer=NULL; } if(faces->pIndexBuffer) { for(k=0;k<RSGetDeviceCount();k++) faces->pIndexBuffer[k]->Release(); delete faces->pIndexBuffer; faces->pIndexBuffer=NULL; } } } } void RSObject::GenerateVertexBuffers() { ClearVertexBuffers(); int i,j,k; for(i=0;i<nMesh;i++) { CMesh *mesh=&meshes[i]; for(j=0;j<mesh->nFaces;j++) { CFaces *faces=&mesh->faceshead[j]; // _ASSERT(faces->nv && faces->ni); { faces->pVertexBuffer=new LPDIRECT3DVERTEXBUFFER8[RSGetDeviceCount()]; if(faces->ni) faces->pIndexBuffer=new LPDIRECT3DINDEXBUFFER8[RSGetDeviceCount()]; for(k=0;k<RSGetDeviceCount();k++) { faces->pVertexBuffer[k]=NULL; g_pDevices[k]->EndScene(); // create vertex buffer if( FAILED( g_pDevices[k]->CreateVertexBuffer( sizeof(VERTEX)*faces->nv, 0 , RSFVF, D3DPOOL_MANAGED, &faces->pVertexBuffer[k] ) ) ) { rslog("create vertex buffer failed.\n"); delete faces->pVertexBuffer; delete faces->pIndexBuffer; return; } VOID* pVertices; faces->pVertexBuffer[k]->Lock( 0, 0, (BYTE**)&pVertices, 0 ) ; memcpy( pVertices, faces->tnlvertices, sizeof(VERTEX)*faces->nv); faces->pVertexBuffer[k]->Unlock(); // create index buffer if(faces->pIndexBuffer) { if( FAILED( g_pDevices[k]->CreateIndexBuffer( sizeof(WORD)*faces->ni, 0 , D3DFMT_INDEX16 , D3DPOOL_MANAGED, &faces->pIndexBuffer[k] ) ) ) { rslog("create index buffer failed.\n"); delete faces->pVertexBuffer; delete faces->pIndexBuffer; return; } WORD* pIndicies; faces->pIndexBuffer[k]->Lock( 0, sizeof(WORD)*faces->ni, (BYTE**)&pIndicies, 0 ) ; memcpy( pIndicies,faces->indicies,sizeof(WORD)*faces->ni); faces->pIndexBuffer[k]->Unlock(); } g_pDevices[k]->BeginScene(); //*/ } } } } /*// dump model rslog("%d",faces->nv); for(k=0;k<faces->nv;k++) { if(k%2==0) rslog("\n"); VERTEX *pv=&faces->tnlvertices[k]; rslog("{%3.3ff,%3.3ff,%3.3ff,%x,%x,%3.3ff,%3.3ff},\t",pv->x,pv->y,pv->z,0,0,pv->tu1,pv->tv1); } rslog("\n %d ",faces->ni); int a=0; for(k=0;k<faces->ni;k++) { if(k%20==0) rslog("\n"); rslog("%d,",faces->indicies[k]); a=max(a,faces->indicies[k]); } //*/ }
22.734607
98
0.664083
[ "mesh", "object", "model" ]
ed3ce53d10f72debb3f0611198e299114d870aa5
1,854
cc
C++
src/stumble.cc
aveday/stumple
21c17166b57a8e5de4640c0d377d024bf6afb068
[ "MIT" ]
null
null
null
src/stumble.cc
aveday/stumple
21c17166b57a8e5de4640c0d377d024bf6afb068
[ "MIT" ]
null
null
null
src/stumble.cc
aveday/stumple
21c17166b57a8e5de4640c0d377d024bf6afb068
[ "MIT" ]
null
null
null
#include "stumble.h" #include "modeldefs.h" int main(int argc, char *argv[]) { double z = (argc > 1) ? atof(argv[1]) : 1; // Create engine objects b2Vec2 gravity(0, 9.8); Grid grid(0xff101010, 0xff000000); World world(gravity); Graphics graphics(grid, z); Control control; Editor editor; Clock clock; // Load textures and create models LoadModels(Model::cache, modeldefs); int tx = SCR_W/(z*PPM); int ty = SCR_H/(z*PPM); // Create player Character *player = new Character(world, "human", b2Vec2(tx/2, ty-2), world.characters.size()+1); world.Add(player); // Create some other characters for(int x = 1; x < 3; x++) world.Add( new Character(world, "human", b2Vec2(tx/2 - x, ty-2), world.characters.size()+1) ); // Create tiles for(int y = 0; y < ty; y++) { world.Tile("brick", 0, y); world.Tile("brick", tx-1, y); } for(int x = 0; x < tx; x++) { world.Tile("brick", x, ty); world.Tile("brick", x, 0); } // Create some objects for(float y = ty/2; y < ty; y+=0.25) for(float x = tx/2+1 + 0.25 * ((int)(y*4)%2) ; x < tx/2+3; x+=0.5) world.Add( new Entity(world, "rock", b2Vec2(x,y), 0, 0) ); // Accept input while(control.GetInput(graphics, *player, editor)) { int ms = clock.Sleep(); // Delay to maintain FPS switch(Control::mode) { case EDIT: editor.Update(ms); graphics.Draw(editor); // Draw to the screen break; case RUN: world.Update(ms); // Update the game world graphics.Draw(world); // Draw to the screen break; } } return 0; }
28.523077
74
0.505933
[ "model" ]
ed3ee4b44e9d231c99909b70e051444bd1a35d47
4,966
cpp
C++
src/layer/cuda/concat_cuda.cpp
DaChengTechnology/ncnn-with-cuda
ea2d722275a62c3752b22253cdd19260435b8e80
[ "BSD-2-Clause", "BSD-3-Clause" ]
59
2020-12-28T02:46:58.000Z
2022-02-10T14:50:48.000Z
src/layer/cuda/concat_cuda.cpp
DaChengTechnology/ncnn-with-cuda
ea2d722275a62c3752b22253cdd19260435b8e80
[ "BSD-2-Clause", "BSD-3-Clause" ]
1
2020-12-30T03:41:35.000Z
2021-01-11T04:32:01.000Z
src/layer/cuda/concat_cuda.cpp
DaChengTechnology/ncnn-with-cuda
ea2d722275a62c3752b22253cdd19260435b8e80
[ "BSD-2-Clause", "BSD-3-Clause" ]
13
2020-12-28T02:49:01.000Z
2022-03-12T11:58:33.000Z
// // Author: Marko Atanasievski // // Copyright (C) 2020 TANCOM SOFTWARE SOLUTIONS Ltd. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. // // Parts of this file are originally copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. #include "concat_cuda.h" #include <chrono> namespace ncnn { int concat_cuda_forward(const std::vector<CudaMat>& bottom_blobs, CudaMat& top_blob, const int axis); Concat_cuda::Concat_cuda() { support_cuda = true; } int Concat_cuda::forward(const std::vector<CudaMat>& bottom_blobs, std::vector<CudaMat>& top_blobs, const Option& opt) const { #if LOG_LAYERS LOGL("Concat_cuda forward"); #endif int dims = bottom_blobs[0].dims; size_t elemsize = bottom_blobs[0].elemsize; int positive_axis = axis < 0 ? dims + axis : axis; if (dims == 1) // positive_axis == 0 { // concat vector // total length int top_w = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_w += bottom_blob.w; } CudaMat& top_blob = top_blobs[0]; top_blob.create(top_w, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } if (dims == 2 && positive_axis == 0) { // concat image int w = bottom_blobs[0].w; // total height int top_h = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_h += bottom_blob.h; } CudaMat& top_blob = top_blobs[0]; top_blob.create(w, top_h, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } if (dims == 2 && positive_axis == 1) { // interleave image row int h = bottom_blobs[0].h; // total width int top_w = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_w += bottom_blob.w; } CudaMat& top_blob = top_blobs[0]; top_blob.create(top_w, h, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } if (dims == 3 && positive_axis == 1) { // interleave dim height int w = bottom_blobs[0].w; int channels = bottom_blobs[0].c; // total height int top_h = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_h += bottom_blob.h; } CudaMat& top_blob = top_blobs[0]; top_blob.create(w, top_h, channels, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } if (dims == 3 && positive_axis == 2) { // interleave dim width int h = bottom_blobs[0].h; int channels = bottom_blobs[0].c; // total height int top_w = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_w += bottom_blob.w; } CudaMat& top_blob = top_blobs[0]; top_blob.create(top_w, h, channels, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } if (dims == 3 && positive_axis == 0) { // concat dim int w = bottom_blobs[0].w; int h = bottom_blobs[0].h; // total channels int top_channels = 0; for (size_t b = 0; b < bottom_blobs.size(); b++) { const CudaMat& bottom_blob = bottom_blobs[b]; top_channels += bottom_blob.c; } CudaMat& top_blob = top_blobs[0]; top_blob.create(w, h, top_channels, elemsize, opt.blob_cuda_allocator); if (top_blob.empty()) return -100; return concat_cuda_forward(bottom_blobs, top_blob, positive_axis); } return 0; } } // namespace ncnn
27.743017
124
0.59565
[ "vector" ]
ed468df4f5aa910a91808ce61aa6195bb370baaa
4,303
cpp
C++
Source/NansTimelineSystemUE4/Private/Event/EventBase.cpp
NansPellicari/UE4-NansTimelineSystem
0fdd79f4510875f45e813f34555fa705ea7b9d46
[ "Apache-2.0" ]
8
2020-10-20T01:51:02.000Z
2022-01-17T04:49:58.000Z
Source/NansTimelineSystemUE4/Private/Event/EventBase.cpp
NansPellicari/UE4-NansTimelineSystem
0fdd79f4510875f45e813f34555fa705ea7b9d46
[ "Apache-2.0" ]
1
2021-10-30T10:21:25.000Z
2021-10-30T10:21:25.000Z
Source/NansTimelineSystemUE4/Private/Event/EventBase.cpp
NansPellicari/UE4-NansTimelineSystem
0fdd79f4510875f45e813f34555fa705ea7b9d46
[ "Apache-2.0" ]
2
2021-09-30T04:23:20.000Z
2022-01-07T07:28:39.000Z
// Copyright 2020-present Nans Pellicari (nans.pellicari@gmail.com). // // 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 "Event/EventBase.h" #define CHECK_EVENT_V() if (!ensureMsgf(Event.IsValid(), TEXT("An NEvent object is mandatory! Please use Init before anything else!"))) return; #define CHECK_EVENT(ReturnValue) if (!ensureMsgf(Event.IsValid(), TEXT("An NEvent object is mandatory! Please use Init before anything else!"))) return ReturnValue; void UNEventBase::Init(const TSharedPtr<INEvent>& InEvent, const float& InLocalTime, UWorld* InWorld, APlayerController* InPlayer) { Event = InEvent; OnInit(InLocalTime, InWorld, InPlayer); } bool UNEventBase::IsExpired() const { CHECK_EVENT(false); return Event->IsExpired(); } float UNEventBase::GetLocalTime() const { CHECK_EVENT(0); return Event->GetLocalTime(); } float UNEventBase::GetStartedAt() const { CHECK_EVENT(0); return Event->GetStartedAt(); } float UNEventBase::GetDuration() const { CHECK_EVENT(0); return Event->GetDuration(); } float UNEventBase::GetDelay() const { CHECK_EVENT(0); return Event->GetDelay(); } FName UNEventBase::GetEventLabel() const { CHECK_EVENT(NAME_None); return Event->GetEventLabel(); } FString UNEventBase::GetUID() const { CHECK_EVENT(TEXT("")); return Event->GetUID(); } float UNEventBase::GetAttachedTime() const { CHECK_EVENT(0); return Event->GetAttachedTime(); } bool UNEventBase::IsAttachable() const { CHECK_EVENT(false); return Event->IsAttachable(); } float UNEventBase::GetExpiredTime() const { CHECK_EVENT(0); return Event->GetExpiredTime(); } void UNEventBase::Stop() { CHECK_EVENT_V(); return Event->Stop(); } void UNEventBase::SetEventLabel(const FName& InEventLabel) { CHECK_EVENT_V(); Event->SetEventLabel(InEventLabel); } TSharedPtr<INEvent> UNEventBase::GetEvent() { CHECK_EVENT(nullptr); return Event; } #if WITH_EDITOR FColor UNEventBase::GetDebugColor_Implementation() const { return FColor(255, 140, 255, 255); } FString UNEventBase::GetDebugTooltipText_Implementation() const { FString TooltipBuilder; TooltipBuilder += FString::Format(TEXT("Name: {0}"), {GetEventLabel().ToString()}); if (IsExpired()) { TooltipBuilder += TEXT(" (expired)"); } TooltipBuilder += FString::Format(TEXT("\nAttached at: {0}"), {GetAttachedTime()}); TooltipBuilder += FString::Format(TEXT("\nStarted at: {0}"), {GetStartedAt()}); TooltipBuilder += FString::Format(TEXT("\nDuration: {0}"), {GetDuration()}); TooltipBuilder += FString::Format(TEXT("\nDelay(Expected): {0}"), {GetDelay()}); TooltipBuilder += FString::Format(TEXT("\nDelay(Real): {0}"), {GetStartedAt() - GetAttachedTime()}); TooltipBuilder += FString::Format(TEXT("\nUId: {0}"), {GetUID()}); return TooltipBuilder; } #endif void UNEventBase::BeginDestroy() { if (Event.IsValid()) { // cause it is only a view object, // it will not altered object by calling PreDelete or clear. Event.Reset(); } Super::BeginDestroy(); } #if WITH_EDITOR bool UNEventBaseBlueprint::SupportedByDefaultBlueprintFactory() const { return false; } /** Returns the most base UNEventBase blueprint for a given blueprint (if it is inherited from another event blueprint, returning null if only native / non-event BP classes are it's parent) */ UNEventBaseBlueprint* UNEventBaseBlueprint::FindRootEventBlueprint(UNEventBaseBlueprint* DerivedBlueprint) { UNEventBaseBlueprint* ParentBP = nullptr; // Determine if there is a UNEventBase blueprint in the ancestry of this class for (UClass* ParentClass = DerivedBlueprint->ParentClass; ParentClass != UObject::StaticClass(); ParentClass = ParentClass->GetSuperClass()) { if (UNEventBaseBlueprint* TestBP = Cast<UNEventBaseBlueprint>(ParentClass->ClassGeneratedBy)) { ParentBP = TestBP; } } return ParentBP; } #endif
26.078788
192
0.73809
[ "object" ]
ed46db8e6be6c29b6a2abaa7e07839699590fe70
9,485
cpp
C++
lldb/unittests/SymbolFile/DWARF/DWARFASTParserClangTests.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
lldb/unittests/SymbolFile/DWARF/DWARFASTParserClangTests.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
lldb/unittests/SymbolFile/DWARF/DWARFASTParserClangTests.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===-- DWARFASTParserClangTests.cpp --------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h" #include "Plugins/SymbolFile/DWARF/DWARFCompileUnit.h" #include "Plugins/SymbolFile/DWARF/DWARFDIE.h" #include "TestingSupport/Symbol/YAMLModuleTester.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::dwarf; namespace { class DWARFASTParserClangTests : public testing::Test {}; class DWARFASTParserClangStub : public DWARFASTParserClang { public: using DWARFASTParserClang::DWARFASTParserClang; using DWARFASTParserClang::LinkDeclContextToDIE; std::vector<const clang::DeclContext *> GetDeclContextToDIEMapKeys() { std::vector<const clang::DeclContext *> keys; for (const auto &it : m_decl_ctx_to_die) keys.push_back(it.first); return keys; } }; } // namespace // If your implementation needs to dereference the dummy pointers we are // defining here, causing this test to fail, feel free to delete it. TEST_F(DWARFASTParserClangTests, EnsureAllDIEsInDeclContextHaveBeenParsedParsesOnlyMatchingEntries) { /// Auxiliary debug info. const char *yamldata = R"( --- !ELF FileHeader: Class: ELFCLASS64 Data: ELFDATA2LSB Type: ET_EXEC Machine: EM_386 DWARF: debug_abbrev: - Table: - Code: 0x00000001 Tag: DW_TAG_compile_unit Children: DW_CHILDREN_yes Attributes: - Attribute: DW_AT_language Form: DW_FORM_data2 - Code: 0x00000002 Tag: DW_TAG_base_type Children: DW_CHILDREN_no Attributes: - Attribute: DW_AT_encoding Form: DW_FORM_data1 - Attribute: DW_AT_byte_size Form: DW_FORM_data1 debug_info: - Version: 4 AddrSize: 8 Entries: - AbbrCode: 0x00000001 Values: - Value: 0x000000000000000C - AbbrCode: 0x00000002 Values: - Value: 0x0000000000000007 # DW_ATE_unsigned - Value: 0x0000000000000004 - AbbrCode: 0x00000002 Values: - Value: 0x0000000000000007 # DW_ATE_unsigned - Value: 0x0000000000000008 - AbbrCode: 0x00000002 Values: - Value: 0x0000000000000005 # DW_ATE_signed - Value: 0x0000000000000008 - AbbrCode: 0x00000002 Values: - Value: 0x0000000000000008 # DW_ATE_unsigned_char - Value: 0x0000000000000001 - AbbrCode: 0x00000000 )"; YAMLModuleTester t(yamldata); ASSERT_TRUE((bool)t.GetDwarfUnit()); TypeSystemClang ast_ctx("dummy ASTContext", HostInfoBase::GetTargetTriple()); DWARFASTParserClangStub ast_parser(ast_ctx); DWARFUnit *unit = t.GetDwarfUnit(); const DWARFDebugInfoEntry *die_first = unit->DIE().GetDIE(); const DWARFDebugInfoEntry *die_child0 = die_first->GetFirstChild(); const DWARFDebugInfoEntry *die_child1 = die_child0->GetSibling(); const DWARFDebugInfoEntry *die_child2 = die_child1->GetSibling(); const DWARFDebugInfoEntry *die_child3 = die_child2->GetSibling(); std::vector<DWARFDIE> dies = { DWARFDIE(unit, die_child0), DWARFDIE(unit, die_child1), DWARFDIE(unit, die_child2), DWARFDIE(unit, die_child3)}; std::vector<clang::DeclContext *> decl_ctxs = { (clang::DeclContext *)1LL, (clang::DeclContext *)2LL, (clang::DeclContext *)2LL, (clang::DeclContext *)3LL}; for (int i = 0; i < 4; ++i) ast_parser.LinkDeclContextToDIE(decl_ctxs[i], dies[i]); ast_parser.EnsureAllDIEsInDeclContextHaveBeenParsed( CompilerDeclContext(nullptr, decl_ctxs[1])); EXPECT_THAT(ast_parser.GetDeclContextToDIEMapKeys(), testing::UnorderedElementsAre(decl_ctxs[0], decl_ctxs[3])); } TEST_F(DWARFASTParserClangTests, TestCallingConventionParsing) { // Tests parsing DW_AT_calling_convention values. // The DWARF below just declares a list of function types with // DW_AT_calling_convention on them. const char *yamldata = R"( --- !ELF FileHeader: Class: ELFCLASS32 Data: ELFDATA2LSB Type: ET_EXEC Machine: EM_386 DWARF: debug_str: - func1 - func2 - func3 - func4 - func5 - func6 - func7 - func8 - func9 debug_abbrev: - ID: 0 Table: - Code: 0x1 Tag: DW_TAG_compile_unit Children: DW_CHILDREN_yes Attributes: - Attribute: DW_AT_language Form: DW_FORM_data2 - Code: 0x2 Tag: DW_TAG_subprogram Children: DW_CHILDREN_no Attributes: - Attribute: DW_AT_low_pc Form: DW_FORM_addr - Attribute: DW_AT_high_pc Form: DW_FORM_data4 - Attribute: DW_AT_name Form: DW_FORM_strp - Attribute: DW_AT_calling_convention Form: DW_FORM_data1 - Attribute: DW_AT_external Form: DW_FORM_flag_present debug_info: - Version: 4 AddrSize: 4 Entries: - AbbrCode: 0x1 Values: - Value: 0xC - AbbrCode: 0x2 Values: - Value: 0x0 - Value: 0x5 - Value: 0x00 - Value: 0xCB - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x10 - Value: 0x5 - Value: 0x06 - Value: 0xB3 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x20 - Value: 0x5 - Value: 0x0C - Value: 0xB1 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x30 - Value: 0x5 - Value: 0x12 - Value: 0xC0 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x40 - Value: 0x5 - Value: 0x18 - Value: 0xB2 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x50 - Value: 0x5 - Value: 0x1E - Value: 0xC1 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x60 - Value: 0x5 - Value: 0x24 - Value: 0xC2 - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x70 - Value: 0x5 - Value: 0x2a - Value: 0xEE - Value: 0x1 - AbbrCode: 0x2 Values: - Value: 0x80 - Value: 0x5 - Value: 0x30 - Value: 0x01 - Value: 0x1 - AbbrCode: 0x0 ... )"; YAMLModuleTester t(yamldata); DWARFUnit *unit = t.GetDwarfUnit(); ASSERT_NE(unit, nullptr); const DWARFDebugInfoEntry *cu_entry = unit->DIE().GetDIE(); ASSERT_EQ(cu_entry->Tag(), DW_TAG_compile_unit); DWARFDIE cu_die(unit, cu_entry); TypeSystemClang ast_ctx("dummy ASTContext", HostInfoBase::GetTargetTriple()); DWARFASTParserClangStub ast_parser(ast_ctx); std::vector<std::string> found_function_types; // The DWARF above is just a list of functions. Parse all of them to // extract the function types and their calling convention values. for (DWARFDIE func : cu_die.children()) { ASSERT_EQ(func.Tag(), DW_TAG_subprogram); SymbolContext sc; bool new_type = false; lldb::TypeSP type = ast_parser.ParseTypeFromDWARF(sc, func, &new_type); found_function_types.push_back( type->GetForwardCompilerType().GetTypeName().AsCString()); } // Compare the parsed function types against the expected list of types. const std::vector<std::string> expected_function_types = { "void () __attribute__((regcall))", "void () __attribute__((fastcall))", "void () __attribute__((stdcall))", "void () __attribute__((vectorcall))", "void () __attribute__((pascal))", "void () __attribute__((ms_abi))", "void () __attribute__((sysv_abi))", "void ()", // invalid calling convention. "void ()", // DW_CC_normal -> no attribute }; ASSERT_EQ(found_function_types, expected_function_types); }
34.365942
80
0.539273
[ "vector" ]
ed48e0376a0f5ee24fa3105a64745b42212981d2
22,658
hpp
C++
OGDF/include/coin/CoinParam.hpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
13
2017-12-21T03:35:41.000Z
2022-01-31T13:45:25.000Z
OGDF/include/coin/CoinParam.hpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
7
2017-09-13T01:31:24.000Z
2021-12-14T00:31:50.000Z
OGDF/include/coin/CoinParam.hpp
shahnidhi/MetaCarvel
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
[ "MIT" ]
15
2017-09-07T18:28:55.000Z
2022-01-18T14:17:43.000Z
/* $Id: CoinParam.hpp 1494 2011-11-01 16:58:47Z tkr $ */ #ifndef CoinParam_H #define CoinParam_H /* Copyright (C) 2002, International Business Machines Corporation and others. All Rights Reserved. This code is licensed under the terms of the Eclipse Public License (EPL). */ /*! \file CoinParam.hpp \brief Declaration of a class for command line parameters. */ #include <vector> #include <string> #include <cstdio> /*! \class CoinParam \brief A base class for `keyword value' command line parameters. The underlying paradigm is that a parameter specifies an action to be performed on a target object. The base class provides two function pointers, a `push' function and a `pull' function. By convention, a push function will set some value in the target object or perform some action using the target object. A `pull' function will retrieve some value from the target object. This is only a convention, however; CoinParam and associated utilities make no use of these functions and have no hardcoded notion of how they should be used. The action to be performed, and the target object, will be specific to a particular application. It is expected that users will derive application-specific parameter classes from this base class. A derived class will typically add fields and methods to set/get a code for the action to be performed (often, an enum class) and the target object (often, a pointer or reference). Facilities provided by the base class and associated utility routines include: <ul> <li> Support for common parameter types with numeric, string, or keyword values. <li> Support for short and long help messages. <li> Pointers to `push' and `pull' functions as described above. <li> Command line parsing and keyword matching. </ul> All utility routines are declared in the #CoinParamUtils namespace. The base class recognises five types of parameters: actions (which require no value); numeric parameters with integer or real (double) values; keyword parameters, where the value is one of a defined set of value-keywords; and string parameters (where the value is a string). The base class supports the definition of a valid range, a default value, and short and long help messages for a parameter. As defined by the #CoinParamFunc typedef, push and pull functions should take a single parameter, a pointer to a CoinParam. Typically this object will actually be a derived class as described above, and the implementation function will have access to all capabilities of CoinParam and of the derived class. When specified as command line parameters, the expected syntax is `-keyword value' or `-keyword=value'. You can also use the Gnu double-dash style, `--keyword'. Spaces around the `=' will \e not work. The keyword (name) for a parameter can be defined with an `!' to mark the minimal match point. For example, allow!ableGap will be considered matched by the strings `allow', `allowa', `allowab', \e etc. Similarly, the value-keyword strings for keyword parameters can be defined with `!' to mark the minimal match point. Matching of keywords and value-keywords is \e not case sensitive. */ class CoinParam { public: /*! \name Subtypes */ //@{ /*! \brief Enumeration for the types of parameters supported by CoinParam CoinParam provides support for several types of parameters: <ul> <li> Action parameters, which require no value. <li> Integer and double numeric parameters, with upper and lower bounds. <li> String parameters that take an arbitrary string value. <li> Keyword parameters that take a defined set of string (value-keyword) values. Value-keywords are associated with integers in the order in which they are added, starting from zero. </ul> */ typedef enum { coinParamInvalid = 0, coinParamAct, coinParamInt, coinParamDbl, coinParamStr, coinParamKwd } CoinParamType ; /*! \brief Type declaration for push and pull functions. By convention, a return code of 0 indicates execution without error, >0 indicates nonfatal error, and <0 indicates fatal error. This is only convention, however; the base class makes no use of the push and pull functions and has no hardcoded interpretation of the return code. */ typedef int (*CoinParamFunc)(CoinParam *param) ; //@} /*! \name Constructors and Destructors Be careful how you specify parameters for the constructors! Some compilers are entirely too willing to convert almost anything to bool. */ //@{ /*! \brief Default constructor */ CoinParam() ; /*! \brief Constructor for a parameter with a double value The default value is 0.0. Be careful to clearly indicate that \p lower and \p upper are real (double) values to distinguish this constructor from the constructor for an integer parameter. */ CoinParam(std::string name, std::string help, double lower, double upper, double dflt = 0.0, bool display = true) ; /*! \brief Constructor for a parameter with an integer value The default value is 0. */ CoinParam(std::string name, std::string help, int lower, int upper, int dflt = 0, bool display = true) ; /*! \brief Constructor for a parameter with keyword values The string supplied as \p firstValue becomes the first value-keyword. Additional value-keywords can be added using appendKwd(). It's necessary to specify both the first value-keyword (\p firstValue) and the default value-keyword index (\p dflt) in order to distinguish this constructor from the constructors for string and action parameters. Value-keywords are associated with an integer, starting with zero and increasing as each keyword is added. The value-keyword given as \p firstValue will be associated with the integer zero. The integer supplied for \p dflt can be any value, as long as it will be valid once all value-keywords have been added. */ CoinParam(std::string name, std::string help, std::string firstValue, int dflt, bool display = true) ; /*! \brief Constructor for a string parameter For some compilers, the default value (\p dflt) must be specified explicitly with type std::string to distinguish the constructor for a string parameter from the constructor for an action parameter. For example, use std::string("default") instead of simply "default", or use a variable of type std::string. */ CoinParam(std::string name, std::string help, std::string dflt, bool display = true) ; /*! \brief Constructor for an action parameter */ CoinParam(std::string name, std::string help, bool display = true) ; /*! \brief Copy constructor */ CoinParam(const CoinParam &orig) ; /*! \brief Clone */ virtual CoinParam *clone() ; /*! \brief Assignment */ CoinParam &operator=(const CoinParam &rhs) ; /*! \brief Destructor */ virtual ~CoinParam() ; //@} /*! \name Methods to query and manipulate the value(s) of a parameter */ //@{ /*! \brief Add an additional value-keyword to a keyword parameter */ void appendKwd(std::string kwd) ; /*! \brief Return the integer associated with the specified value-keyword Returns -1 if no value-keywords match the specified string. */ int kwdIndex(std::string kwd) const ; /*! \brief Return the value-keyword that is the current value of the keyword parameter */ std::string kwdVal() const ; /*! \brief Set the value of the keyword parameter using the integer associated with a value-keyword. If \p printIt is true, the corresponding value-keyword string will be echoed to std::cout. */ void setKwdVal(int value, bool printIt = false) ; /*! \brief Set the value of the keyword parameter using a value-keyword string. The given string will be tested against the set of value-keywords for the parameter using the shortest match rules. */ void setKwdVal(const std::string value ) ; /*! \brief Prints the set of value-keywords defined for this keyword parameter */ void printKwds() const ; /*! \brief Set the value of a string parameter */ void setStrVal(std::string value) ; /*! \brief Get the value of a string parameter */ std::string strVal() const ; /*! \brief Set the value of a double parameter */ void setDblVal(double value) ; /*! \brief Get the value of a double parameter */ double dblVal() const ; /*! \brief Set the value of a integer parameter */ void setIntVal(int value) ; /*! \brief Get the value of a integer parameter */ int intVal() const ; /*! \brief Add a short help string to a parameter */ inline void setShortHelp(const std::string help) { shortHelp_ = help ; } /*! \brief Retrieve the short help string */ inline std::string shortHelp() const { return (shortHelp_) ; } /*! \brief Add a long help message to a parameter See printLongHelp() for a description of how messages are broken into lines. */ inline void setLongHelp(const std::string help) { longHelp_ = help ; } /*! \brief Retrieve the long help message */ inline std::string longHelp() const { return (longHelp_) ; } /*! \brief Print long help Prints the long help string, plus the valid range and/or keywords if appropriate. The routine makes a best effort to break the message into lines appropriate for an 80-character line. Explicit line breaks in the message will be observed. The short help string will be used if long help is not available. */ void printLongHelp() const ; //@} /*! \name Methods to query and manipulate a parameter object */ //@{ /*! \brief Return the type of the parameter */ inline CoinParamType type() const { return (type_) ; } /*! \brief Set the type of the parameter */ inline void setType(CoinParamType type) { type_ = type ; } /*! \brief Return the parameter keyword (name) string */ inline std::string name() const { return (name_) ; } /*! \brief Set the parameter keyword (name) string */ inline void setName(std::string name) { name_ = name ; processName() ; } /*! \brief Check if the specified string matches the parameter keyword (name) string Returns 1 if the string matches and meets the minimum match length, 2 if the string matches but doesn't meet the minimum match length, and 0 if the string doesn't match. Matches are \e not case-sensitive. */ int matches (std::string input) const ; /*! \brief Return the parameter keyword (name) string formatted to show the minimum match length For example, if the parameter name was defined as allow!ableGap, the string returned by matchName would be allow(ableGap). */ std::string matchName() const ; /*! \brief Set visibility of parameter Intended to control whether the parameter is shown when a list of parameters is processed. Used by CoinParamUtils::printHelp when printing help messages for a list of parameters. */ inline void setDisplay(bool display) { display_ = display ; } /*! \brief Get visibility of parameter */ inline bool display() const { return (display_) ; } /*! \brief Get push function */ inline CoinParamFunc pushFunc() { return (pushFunc_) ; } /*! \brief Set push function */ inline void setPushFunc(CoinParamFunc func) { pushFunc_ = func ; } /*! \brief Get pull function */ inline CoinParamFunc pullFunc() { return (pullFunc_) ; } /*! \brief Set pull function */ inline void setPullFunc(CoinParamFunc func) { pullFunc_ = func ; } //@} private: /*! \name Private methods */ //@{ /*! Process a name for efficient matching */ void processName() ; //@} /*! \name Private parameter data */ //@{ /// Parameter type (see #CoinParamType) CoinParamType type_ ; /// Parameter name std::string name_ ; /// Length of parameter name size_t lengthName_ ; /*! \brief Minimum length required to declare a match for the parameter name. */ size_t lengthMatch_ ; /// Lower bound on value for a double parameter double lowerDblValue_ ; /// Upper bound on value for a double parameter double upperDblValue_ ; /// Double parameter - current value double dblValue_ ; /// Lower bound on value for an integer parameter int lowerIntValue_ ; /// Upper bound on value for an integer parameter int upperIntValue_ ; /// Integer parameter - current value int intValue_ ; /// String parameter - current value std::string strValue_ ; /// Set of valid value-keywords for a keyword parameter std::vector<std::string> definedKwds_ ; /*! \brief Current value for a keyword parameter (index into #definedKwds_) */ int currentKwd_ ; /// Push function CoinParamFunc pushFunc_ ; /// Pull function CoinParamFunc pullFunc_ ; /// Short help std::string shortHelp_ ; /// Long help std::string longHelp_ ; /// Display when processing lists of parameters? bool display_ ; //@} } ; /*! \relatesalso CoinParam \brief A type for a parameter vector. */ typedef std::vector<CoinParam*> CoinParamVec ; /*! \relatesalso CoinParam \brief A stream output function for a CoinParam object. */ std::ostream &operator<< (std::ostream &s, const CoinParam &param) ; /* Bring in the utility functions for parameter handling (CbcParamUtils). */ /*! \brief Utility functions for processing CoinParam parameters. The functions in CoinParamUtils support command line or interactive parameter processing and a help facility. Consult the `Related Functions' section of the CoinParam class documentation for individual function documentation. */ namespace CoinParamUtils { /*! \relatesalso CoinParam \brief Take command input from the file specified by src. Use stdin for \p src to specify interactive prompting for commands. */ void setInputSrc(FILE *src) ; /*! \relatesalso CoinParam \brief Returns true if command line parameters are being processed. */ bool isCommandLine() ; /*! \relatesalso CoinParam \brief Returns true if parameters are being obtained from stdin. */ bool isInteractive() ; /*! \relatesalso CoinParam \brief Attempt to read a string from the input. \p argc and \p argv are used only if isCommandLine() would return true. If \p valid is supplied, it will be set to 0 if a string is parsed without error, 2 if no field is present. */ std::string getStringField(int argc, const char *argv[], int *valid) ; /*! \relatesalso CoinParam \brief Attempt to read an integer from the input. \p argc and \p argv are used only if isCommandLine() would return true. If \p valid is supplied, it will be set to 0 if an integer is parsed without error, 1 if there's a parse error, and 2 if no field is present. */ int getIntField(int argc, const char *argv[], int *valid) ; /*! \relatesalso CoinParam \brief Attempt to read a real (double) from the input. \p argc and \p argv are used only if isCommandLine() would return true. If \p valid is supplied, it will be set to 0 if a real number is parsed without error, 1 if there's a parse error, and 2 if no field is present. */ double getDoubleField(int argc, const char *argv[], int *valid) ; /*! \relatesalso CoinParam \brief Scan a parameter vector for parameters whose keyword (name) string matches \p name using minimal match rules. \p matchNdx is set to the index of the last parameter that meets the minimal match criteria (but note there should be at most one matching parameter if the parameter vector is properly configured). \p shortCnt is set to the number of short matches (should be zero for a properly configured parameter vector if a minimal match is found). The return value is the number of matches satisfying the minimal match requirement (should be 0 or 1 in a properly configured vector). */ int matchParam(const CoinParamVec &paramVec, std::string name, int &matchNdx, int &shortCnt) ; /*! \relatesalso CoinParam \brief Get the next command keyword (name) To be precise, return the next field from the current command input source, after a bit of processing. In command line mode (isCommandLine() returns true) the next field will normally be of the form `-keyword' or `--keyword' (\e i.e., a parameter keyword), and the string returned would be `keyword'. In interactive mode (isInteractive() returns true), the user will be prompted if necessary. It is assumed that the user knows not to use the `-' or `--' prefixes unless specifying parameters on the command line. There are a number of special cases if we're in command line mode. The order of processing of the raw string goes like this: <ul> <li> A stand-alone `-' is forced to `stdin'. <li> A stand-alone '--' is returned as a word; interpretation is up to the client. <li> A prefix of '-' or '--' is stripped from the string. </ul> If the result is the string `stdin', command processing shifts to interactive mode and the user is immediately prompted for a new command. Whatever results from the above sequence is returned to the user as the return value of the function. An empty string indicates end of input. \p prompt will be used only if it's necessary to prompt the user in interactive mode. */ std::string getCommand(int argc, const char *argv[], const std::string prompt, std::string *pfx = nullptr) ; /*! \relatesalso CoinParam \brief Look up the command keyword (name) in the parameter vector. Print help if requested. In the most straightforward use, \p name is a string without `?', and the value returned is the index in \p paramVec of the single parameter that matched \p name. One or more '?' characters at the end of \p name is a query for information. The routine prints short (one '?') or long (more than one '?') help messages for a query. Help is also printed in the case where the name is ambiguous (some of the matches did not meet the minimal match length requirement). Note that multiple matches meeting the minimal match requirement is a configuration error. The mimimal match length for the parameters involved is too short. If provided as parameters, on return <ul> <li> \p matchCnt will be set to the number of matches meeting the minimal match requirement <li> \p shortCnt will be set to the number of matches that did not meet the miminal match requirement <li> \p queryCnt will be set to the number of '?' characters at the end of the name </ul> The return values are: <ul> <li> >0: index in \p paramVec of the single unique match for \p name <li> -1: a query was detected (one or more '?' characters at the end of \p name <li> -2: one or more short matches, not a query <li> -3: no matches, not a query <li> -4: multiple matches meeting the minimal match requirement (configuration error) </ul> */ int lookupParam(std::string name, CoinParamVec &paramVec, int *matchCnt = nullptr, int *shortCnt = nullptr, int *queryCnt = nullptr) ; /*! \relatesalso CoinParam \brief Utility to print a long message as filled lines of text The routine makes a best effort to break lines without exceeding the standard 80 character line length. Explicit newlines in \p msg will be obeyed. */ void printIt(const char *msg) ; /*! \relatesalso CoinParam \brief Utility routine to print help given a short match or explicit request for help. The two really are related, in that a query (a string that ends with one or more `?' characters) will often result in a short match. The routine expects that \p name matches a single parameter, and does not look for multiple matches. If called with \p matchNdx < 0, the routine will look up \p name in \p paramVec and print the full name from the parameter. If called with \p matchNdx > 0, it just prints the name from the specified parameter. If the name is a query, short (one '?') or long (more than one '?') help is printed. */ void shortOrHelpOne(CoinParamVec &paramVec,int matchNdx, std::string name, int numQuery) ; /*! \relatesalso CoinParam \brief Utility routine to print help given multiple matches. If the name is not a query, or asks for short help (\e i.e., contains zero or one '?' characters), the list of matching names is printed. If the name asks for long help (contains two or more '?' characters), short help is printed for each matching name. */ void shortOrHelpMany(CoinParamVec &paramVec, std::string name, int numQuery) ; /*! \relatesalso CoinParam \brief Print a generic `how to use the command interface' help message. The message is hard coded to match the behaviour of the parsing utilities. */ void printGenericHelp() ; /*! \relatesalso CoinParam \brief Utility routine to print help messages for one or more parameters. Intended as a utility to implement explicit `help' commands. Help will be printed for all parameters in \p paramVec from \p firstParam to \p lastParam, inclusive. If \p shortHelp is true, short help messages will be printed. If \p longHelp is true, long help messages are printed. \p shortHelp overrules \p longHelp. If neither is true, only command keywords are printed. \p prefix is printed before each line; it's an imperfect attempt at indentation. */ void printHelp(CoinParamVec &paramVec, int firstParam, int lastParam, std::string prefix, bool shortHelp, bool longHelp, bool hidden) ; } #endif /* CoinParam_H */
35.128682
80
0.68104
[ "object", "vector" ]
ed493cb12ff6e7b54e3b2638eeb55623b78d5182
23,359
hpp
C++
include/gl/image.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/image.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/image.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_GL_IMAGE_RAW_HPP #define PIC_GL_IMAGE_RAW_HPP #include "../base.hpp" #include "../image.hpp" #include "../gl.hpp" #include "../util/gl/fbo.hpp" #include "../util/gl/formats.hpp" #include "../util/gl/timings.hpp" #include "../util/gl/buffer_ops.hpp" #include "../util/gl/buffer_allocation.hpp" #include "../util/gl/mask.hpp" #include "../util/gl/redux.hpp" #include "../util/gl/redux_ops.hpp" namespace pic { enum IMAGESTORE {IMG_GPU_CPU, IMG_CPU_GPU, IMG_CPU, IMG_GPU, IMG_NULL}; /** * @brief The ImageGL class */ class ImageGL: public Image { protected: GLuint texture; GLenum target; IMAGESTORE mode; //TODO: check if the mode is always correctly updated bool notOwnedGL; //do we own the OpenGL texture?? Fbo *tmpFbo; //stack for statistics std::vector<GLuint> stack; /** * @brief releaseGL */ void releaseGL(); /** * @brief assignGL assigns an (r, g, b, a) value to an image using glClearColor. * @param r is the value for the red channel. * @param g is the value for the green channel. * @param b is the value for the blue channel. * @param a is the value for the alpha channel. */ void assignGL(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f) { if(tmpFbo == NULL) { tmpFbo = new Fbo(); tmpFbo->create(width, height, 1, false, texture); } glClearColor(r, g, b, a); //Rendering tmpFbo->bind(); glViewport(0, 0, (GLsizei)width, (GLsizei)height); glClear(GL_COLOR_BUFFER_BIT); //Fbo tmpFbo->unbind(); } /** * @brief thisOperatorConst * @param a * @param op */ inline void thisOperatorConst(const float &a, BOGL op) { BufferOpsGL *ops = BufferOpsGL::getInstance(); ops->list[op]->update(a); ops->list[op]->Process(getTexture(), 0, getTexture(), width, height); } /** * @brief thisOperatorConstColor * @param a * @param op */ inline void thisOperatorConstColor(const Arrayf &a, BOGL op) { BufferOpsGL *ops = BufferOpsGL::getInstance(); float c0[4]; Arrayf::assign(a.data, MIN(a.nData, 4), c0); ops->list[op]->update(c0); ops->list[op]->Process(getTexture(), 0, getTexture(), width, height); } /** * @brief thisOperatorImage * @param a * @param op */ inline void thisOperatorImage(const ImageGL &a, BOGL op) { BufferOpsGL *ops = BufferOpsGL::getInstance(); if(channels == a.channels && width == a.width && height == a.height) { ops->list[op]->Process(getTexture(), a.getTexture(), getTexture(), width, height); } else { if((nPixels() == a.nPixels()) && (a.channels == 1)) { ops->list[op + 8]->Process(getTexture(), a.getTexture(), getTexture(), width, height); } } } /** * @brief newOperatorConstColor * @param a * @param op * @return */ inline ImageGL newOperatorConstColor(const Arrayf &a, BOGL op) { ImageGL ret(frames, width, height, channels, IMG_GPU, target); BufferOpsGL *ops = BufferOpsGL::getInstance(); float c0[4]; Arrayf::assign(a.data, MIN(a.nData, 4), c0); ops->list[op]->update(c0); ops->list[op]->Process(getTexture(), 0, ret.getTexture(), width, height); return ret; } /** * @brief newOperatorConst * @param a * @param op * @return */ inline ImageGL newOperatorConst(const float &a, BOGL op) { ImageGL ret(frames, width, height, channels, IMG_GPU, target); BufferOpsGL *ops = BufferOpsGL::getInstance(); ops->list[op]->update(a); ops->list[op]->Process(getTexture(), 0, ret.getTexture(), width, height); return ret; } /** * @brief newOperatorImage * @param a * @param op */ inline ImageGL newOperatorImage(const ImageGL &a, BOGL op) { ImageGL ret(frames, width, height, channels, IMG_GPU, target); BufferOpsGL *ops = BufferOpsGL::getInstance(); if(channels == a.channels && width == a.width && height == a.height) { ops->list[op]->Process(getTexture(), a.getTexture(), ret.getTexture(), width, height); } else { if((nPixels() == a.nPixels()) && ((a.channels == 1) || (channels == 1))) { if(a.channels == 1) { ops->list[op + 8]->Process(getTexture(), a.getTexture(), ret.getTexture(), width, height); } else { ops->list[op + 8]->Process(a.getTexture(), getTexture(), ret.getTexture(), width, height); } } } return ret; } public: /** * @brief ImageGL */ ImageGL(); ~ImageGL(); /** * @brief ImageGL * @param texture * @param target */ ImageGL(GLuint texture, GLenum target); /** * @brief ImageGL * @param img * @param transferOwnership */ ImageGL(Image *img, bool transferOwnership); /** * @brief ImageGL * @param img * @param target * @param mipmap * @param transferOwnership */ ImageGL(Image *img, GLenum target, bool mipmap, bool transferOwnership); /** * @brief ImageGL * @param nameFile */ ImageGL(std::string nameFile): Image(nameFile) { notOwnedGL = false; mode = IMG_CPU; texture = 0; target = 0; tmpFbo = NULL; } /** * @brief Image * @param frames * @param width * @param height * @param channels * @param data */ ImageGL(int frames, int width, int height, int channels, float *data) : Image (frames, width, height, channels, data) { notOwnedGL = false; mode = IMG_CPU; texture = 0; target = 0; tmpFbo = NULL; } /** * @brief ImageGL * @param frames * @param width * @param height * @param channels * @param mode */ ImageGL(int frames, int width, int height, int channels, IMAGESTORE mode, GLenum target); /** * @brief allocateSimilarOneGL * @return */ ImageGL *allocateSimilarOneGL(); /** * @brief cloneGL * @return */ ImageGL *cloneGL(); /** * @brief generateTextureGL * @param target * @param format_type * @param mipmap * @return */ GLuint generateTextureGL(GLenum target, GLenum format_type, bool mipmap); /** * @brief loadSliceIntoTexture * @param i */ void loadSliceIntoTexture(int i); /** * @brief loadAllSlicesIntoTexture */ void loadAllSlicesIntoTexture(); /** * @brief loadFromMemory */ void loadFromMemory(); /** * @brief loadToMemory */ void loadToMemory(); /** * @brief readFromBindedFBO */ void readFromBindedFBO(); /** * @brief readFromFBO * @param fbo */ void readFromFBO(Fbo *fbo); /** * @brief readFromFBO * @param fbo * @param format */ void readFromFBO(Fbo *fbo, GLenum format); /** * @brief bindTexture */ void bindTexture(); /** * @brief unBindTexture */ void unBindTexture(); /** * @brief updateModeGPU */ void updateModeGPU() { if(mode == IMG_NULL) { mode = IMG_GPU; } if(mode == IMG_CPU) { mode = IMG_CPU_GPU; } } /** * @brief updateModeCPU */ void updateModeCPU() { if(mode == IMG_NULL) { mode = IMG_CPU; } if(mode == IMG_GPU) { mode = IMG_CPU_GPU; } } /** * @brief getTexture * @return */ GLuint getTexture() const { return texture; } /** * @brief setTexture * @param texture */ void setTexture(GLuint texture) { //TODO: UNSAFE! this->texture = texture; } /** * @brief getTarget * @return */ GLenum getTarget() { return target; } /** * @brief getVal * @param ret * @param flt * @return */ float *getVal(float *ret, ReduxGL *flt) { if(texture == 0) { return ret; } if(ret == NULL) { ret = new float [channels]; } if(stack.empty()) { ReduxGL::allocateReduxData(width, height, channels, stack, 1); } GLuint output = flt->Redux(texture, width, height, channels, stack); //copy data from GPU to main memory int mode, modeInternalFormat; getModesGL(channels, mode, modeInternalFormat); glBindTexture(GL_TEXTURE_2D, output); glGetTexImage(GL_TEXTURE_2D, 0, mode, GL_FLOAT, ret); glBindTexture(GL_TEXTURE_2D, 0); return ret; } /** * @brief getMinVal * @param imgIn * @return */ float *getMinVal(float *ret = NULL) { ReduxOpsGL *ops = ReduxOpsGL::getInstance(); return getVal(ret, ops->list[REDGL_MIN]); } /** * @brief getMaxVal * @param imgIn * @param ret * @return */ float *getMaxVal(float *ret = NULL) { ReduxOpsGL *ops = ReduxOpsGL::getInstance(); return getVal(ret, ops->list[REDGL_MAX]); } /** * @brief getSumVal * @param imgIn * @param ret * @return */ float *getSumVal(float *ret = NULL) { ReduxOpsGL *ops = ReduxOpsGL::getInstance(); return getVal(ret, ops->list[REDGL_SUM]); } /** * @brief getMeanVal * @param imgIn * @return */ float *getMeanVal(float *ret = NULL) { ReduxOpsGL *ops = ReduxOpsGL::getInstance(); return getVal(ret, ops->list[REDGL_MEAN]); } /** * @brief getLogMeanVal * @param imgIn * @return */ float *getLogMeanVal(float *ret = NULL) { ReduxOpsGL *ops = ReduxOpsGL::getInstance(); ret = getVal(ret, ops->list[REDGL_LOG_MEAN]); for(int i = 0; i < channels; i++) { ret[i] = expf(ret[i]); } return ret; } /** * @brief clamp * @param a * @param b */ void clamp(float a, float b); /** * @brief operator = * @param a */ void operator =(const ImageGL &a); /** * @brief operator = * @param a */ void operator =(const float &a); /** * @brief operator += * @param a */ void operator +=(const ImageGL &a); /** * @brief operator += * @param a */ void operator +=(const float &a); /** * @brief operator + * @param a * @return */ ImageGL operator +(const ImageGL &a); /** * @brief operator + * @param a * @return */ ImageGL operator +(const float &a); /** * @brief operator -= * @param a */ void operator -=(const ImageGL &a); /** * @brief operator -= * @param a */ void operator -=(const float &a); /** * @brief operator - * @param a * @return */ ImageGL operator -(const ImageGL &a); /** * @brief operator - * @param a * @return */ ImageGL operator -(const float &a); /** * @brief operator *= * @param a */ void operator *=(const ImageGL &a); /** * @brief operator *= * @param a */ void operator *=(const float &a); /** * @brief operator * * @param a * @return */ ImageGL operator *(const ImageGL &a); /** * @brief operator * * @param a * @return */ ImageGL operator *(const float &a); /** * @brief operator /= * @param a */ void operator /=(const ImageGL &a); /** * @brief operator /= * @param a */ void operator /=(const float &a); /** * @brief operator /= * @param a */ void operator /=(const Arrayf &a); /** * @brief operator / * @param a * @return */ ImageGL operator /(const ImageGL &a); /** * @brief operator / * @param a * @return */ ImageGL operator /(const float &a); }; PIC_INLINE ImageGL::ImageGL() : Image() { notOwnedGL = false; texture = 0; target = 0; mode = IMG_NULL; tmpFbo = NULL; } PIC_INLINE ImageGL::ImageGL(GLuint texture, GLuint target) : Image() { notOwnedGL = true; tmpFbo = NULL; mode = IMG_GPU; this->texture = texture; this->target = target; getTextureInformationGL(texture, target, width, height, frames, channels); allocateAux(); } PIC_INLINE ImageGL::ImageGL(Image *img, GLenum target, bool mipmap, bool transferOwnership = false): Image() { if(transferOwnership) { notOwned = false; img->changeOwnership(true); } else { notOwned = true; } notOwnedGL = false; tmpFbo = NULL; width = img->width; height = img->height; frames = img->frames; channels = img->channels; data = img->data; allocateAux(); texture = 0; generateTextureGL(target, GL_FLOAT, mipmap); mode = IMG_CPU_GPU; } PIC_INLINE ImageGL::ImageGL(Image *img, bool transferOwnership = false) : Image() { if(transferOwnership) { notOwned = false; img->changeOwnership(true); } else { notOwned = true; } notOwnedGL = false; tmpFbo = NULL; width = img->width; height = img->height; frames = img->frames; channels = img->channels; data = img->data; allocateAux(); texture = 0; mode = IMG_CPU; } PIC_INLINE ImageGL::ImageGL(int frames, int width, int height, int channels, IMAGESTORE mode, GLenum target) : Image() { notOwnedGL = false; tmpFbo = NULL; this->mode = mode; if(this->mode == IMG_GPU_CPU) { this->mode = IMG_CPU_GPU; } switch(this->mode) { case IMG_CPU_GPU: { allocate(width, height, channels, frames); generateTextureGL(target, GL_FLOAT, false); } break; case IMG_CPU: { allocate(width, height, channels, frames); } break; case IMG_GPU: { this->width = width; this->height = height; this->frames = frames; this->depth = frames; this->channels = channels; allocateAux(); generateTextureGL(target, GL_FLOAT, false); } break; default: { }break; } } PIC_INLINE ImageGL::~ImageGL() { releaseGL(); release(); } /** * @brief ImageGL::generateTextureGL * @param target * @param format_type * @param mipmap * @return */ PIC_INLINE GLuint ImageGL::generateTextureGL(GLenum target = GL_TEXTURE_2D, GLenum format_type = GL_FLOAT, bool mipmap = false) { this->texture = 0; this->target = target; updateModeGPU(); if(format_type == GL_INT) { int *buffer = new int[width * height * channels]; for(int i = 0; i < (width * height * channels); i++) { buffer[i] = int(lround(data[i])); } texture = generateTexture2DU32GL(width, height, channels, buffer); delete[] buffer; return texture; } switch(target) { case GL_TEXTURE_2D: { texture = generateTexture2DGL(width, height, channels, data, mipmap); } break; case GL_TEXTURE_3D: { if(frames > 1) { texture = generateTexture3DGL(width, height, channels, frames, data); } else { texture = generateTexture2DGL(width, height, channels, data, mipmap); this->target = GL_TEXTURE_2D; } } break; case GL_TEXTURE_2D_ARRAY: { texture = generateTexture2DArrayGL(width, height, channels, frames, data); } break; case GL_TEXTURE_CUBE_MAP: { if(frames > 5) { texture = generateTextureCubeMapGL(width, height, channels, frames, data); } else { if(frames > 1) { texture = generateTexture2DArrayGL(width, height, channels, frames, data); this->target = GL_TEXTURE_2D_ARRAY; } else { texture = generateTexture2DGL(width, height, channels, data, mipmap); this->target = GL_TEXTURE_2D; } } } break; } return texture; } PIC_INLINE ImageGL *ImageGL::cloneGL() { //call Image clone function Image *tmp = this->clone(); //wrap tmp into an ImageGL return new ImageGL(tmp, target, false, true); } PIC_INLINE void ImageGL::releaseGL() { if(notOwnedGL) { return; } if(texture != 0) { glDeleteTextures(1, &texture); texture = 0; target = 0; } auto n = stack.size(); for(auto i = 0; i < n; i++) { if(stack[i] != 0) { glDeleteTextures(1, &stack[i]); stack[i] = 0; } } } PIC_INLINE ImageGL *ImageGL::allocateSimilarOneGL() { #ifdef PIC_DEBUG printf("ImageGL::allocateSimilarOneGL -- %d %d %d %d %d\n", frames, width, height, channels, mode); #endif ImageGL *ret = new ImageGL(frames, width, height, channels, mode, target); return ret; } PIC_INLINE void ImageGL::loadFromMemory() { int mode, modeInternalFormat; getModesGL(channels, mode, modeInternalFormat); glBindTexture(target, texture); switch(target) { case GL_TEXTURE_2D: { glTexImage2D(target, 0, modeInternalFormat, width, height, 0, mode, GL_FLOAT, data); } break; case GL_TEXTURE_3D: { glTexImage3D(GL_TEXTURE_3D, 0, modeInternalFormat, width, height, frames, 0, mode, GL_FLOAT, data); } break; } glBindTexture(target, 0); } PIC_INLINE void ImageGL::loadToMemory() { if(texture == 0) { #ifdef PIC_DEBUG printf("This texture can not be trasferred from GPU memory\n"); #endif return; } if(data == NULL) { #ifdef PIC_DEBUG printf("RAM memory allocated: %d %d %d %d\n", width, height, channels, frames); #endif allocate(width, height, channels, frames); this->mode = IMG_CPU_GPU; } int mode, modeInternalFormat; getModesGL(channels, mode, modeInternalFormat); bindTexture(); glGetTexImage(target, 0, mode, GL_FLOAT, data); unBindTexture(); } PIC_INLINE void ImageGL::loadSliceIntoTexture(int i) { int mode, modeInternalFormat; getModesGL(channels, mode, modeInternalFormat); glBindTexture(target, texture); i = i % frames; glTexSubImage3D(target, 0, 0, 0, i, width, height, 1, mode, GL_FLOAT, &data[i * tstride]); glBindTexture(target, 0); } PIC_INLINE void ImageGL::loadAllSlicesIntoTexture() { if(target != GL_TEXTURE_3D && target != GL_TEXTURE_2D_ARRAY) { return; } for(int i = 0; i < frames; i++) { loadSliceIntoTexture(i); } } PIC_INLINE void ImageGL::readFromFBO(Fbo *fbo, GLenum format) { //TO DO: check data bool bCheck = (fbo->width != width) || (fbo->height != height); if(data == NULL || bCheck) { allocate(fbo->width, fbo->height, 4, 1); } //ReadPixels from the FBO fbo->bind(); glReadPixels(0, 0, width, height, format, GL_FLOAT, data); fbo->unbind(); /* glBindTexture(GL_TEXTURE_2D, fbo->tex); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, data); glBindTexture(GL_TEXTURE_2D, 0);*/ } PIC_INLINE void ImageGL::readFromFBO(Fbo *fbo) { if(mode == IMG_NULL) { mode = IMG_CPU; } readFromFBO(fbo, GL_RGBA); } PIC_INLINE void ImageGL::readFromBindedFBO() { int mode, modeInternalFormat; getModesGL(channels, mode, modeInternalFormat); if(mode == 0x0) { #ifdef PIC_DEBUG printf("void ImageGL::readFromBindedFBO(): error unknown format!"); #endif return; } //TODO: check width height and data (mode and modeInternalFormat) glReadPixels(0, 0, width, height, mode, GL_FLOAT, data); flipV(); } PIC_INLINE void ImageGL::bindTexture() { glBindTexture(target, texture); } PIC_INLINE void ImageGL::unBindTexture() { glBindTexture(target, 0); } PIC_INLINE void ImageGL::clamp(float a = 0.0f, float b = 1.0f) { BufferOpsGL *ops = BufferOpsGL::getInstance(); ops->list[BOGL_CLAMP]->update(a, b); ops->list[BOGL_CLAMP]->Process(getTexture(), 0, getTexture(), width, height); } PIC_INLINE void ImageGL::operator =(const ImageGL &a) { thisOperatorImage(a, BOGL_ID); } PIC_INLINE void ImageGL::operator =(const float &a) { thisOperatorConst(a, BOGL_ID_CONST); } PIC_INLINE void ImageGL::operator +=(const ImageGL &a) { thisOperatorImage(a, BOGL_ADD); } PIC_INLINE void ImageGL::operator +=(const float &a) { thisOperatorConst(a, BOGL_ADD_CONST); } PIC_INLINE ImageGL ImageGL::operator +(const ImageGL &a) { return newOperatorImage(a, BOGL_ADD); } PIC_INLINE ImageGL ImageGL::operator +(const float &a) { return newOperatorConst(a, BOGL_ADD_CONST); } PIC_INLINE void ImageGL::operator -=(const ImageGL &a) { thisOperatorImage(a, BOGL_SUB); } PIC_INLINE void ImageGL::operator -=(const float &a) { thisOperatorConst(a, BOGL_SUB_CONST); } PIC_INLINE ImageGL ImageGL::operator -(const ImageGL &a) { return newOperatorImage(a, BOGL_SUB); } PIC_INLINE ImageGL ImageGL::operator -(const float &a) { return newOperatorConst(a, BOGL_SUB_CONST); } PIC_INLINE void ImageGL::operator *=(const ImageGL &a) { thisOperatorImage(a, BOGL_MUL); } PIC_INLINE void ImageGL::operator *=(const float &a) { thisOperatorConst(a, BOGL_MUL_CONST); } PIC_INLINE ImageGL ImageGL::operator *(const ImageGL &a) { return newOperatorImage(a, BOGL_MUL); } PIC_INLINE ImageGL ImageGL::operator *(const float &a) { return newOperatorConst(a, BOGL_MUL_CONST); } PIC_INLINE void ImageGL::operator /=(const ImageGL &a) { thisOperatorImage(a, BOGL_DIV); } PIC_INLINE void ImageGL::operator /=(const float &a) { thisOperatorConst(a, BOGL_DIV_CONST); } PIC_INLINE void ImageGL::operator /=(const Arrayf &a) { thisOperatorConstColor(a, BOGL_DIV_CONST); } PIC_INLINE ImageGL ImageGL::operator /(const ImageGL &a) { return newOperatorImage(a, BOGL_DIV); } PIC_INLINE ImageGL ImageGL::operator /(const float &a) { return newOperatorConst(a, BOGL_DIV_CONST); } } // end namespace pic #endif /* PIC_GL_IMAGE_RAW_HPP */
21.293528
127
0.563937
[ "vector" ]
ed4e56cb8682bf53b76c3daab09a04ef8efdc02f
606
cpp
C++
destructor.cpp
PRASAD-DANGARE/CPP
bf5ba5f87a229d88152fef80cb6a4d73bf578815
[ "MIT" ]
null
null
null
destructor.cpp
PRASAD-DANGARE/CPP
bf5ba5f87a229d88152fef80cb6a4d73bf578815
[ "MIT" ]
null
null
null
destructor.cpp
PRASAD-DANGARE/CPP
bf5ba5f87a229d88152fef80cb6a4d73bf578815
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int count = 0; class alpha { public: alpha() { count++; cout << "\n No Of Object Created " << count; } ~alpha() { cout << "\n No Of Object Destroyed " << count; count--; } }; int main() { cout << "\n\n Enter Main \n"; alpha A1, A2, A3, A4; { cout << "\n\n Enter Block1 \n"; alpha A5; } { cout << "\n\n Enter Block2 \n"; alpha A6; } cout << "\n\n Re-Enter Main \n"; return 0; }
15.947368
57
0.40264
[ "object" ]
ed56007ace89371eaaed970c38a224268b72f587
9,154
cpp
C++
plugins/multiarc/ace.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
1,256
2015-07-07T12:19:17.000Z
2022-03-31T18:41:41.000Z
plugins/multiarc/ace.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
305
2017-11-01T18:58:50.000Z
2022-03-22T11:07:23.000Z
plugins/multiarc/ace.cpp
MKadaner/FarManager
c99a14c12e3481dd25ce71451ecd264656f631bb
[ "BSD-3-Clause" ]
183
2017-10-28T11:31:14.000Z
2022-03-30T16:46:24.000Z
/* ACE.CPP Second-level plugin module for FAR Manager and MultiArc plugin Copyright (c) 1996 Eugene Roshal Copyrigth (c) 2000 FAR group */ #include <windows.h> #include <string.h> #include <dos.h> #include <malloc.h> #include <stddef.h> #include <memory.h> #include <plugin.hpp> #include "fmt.hpp" //#define CALC_CRC static const struct OSIDType { BYTE Type; char Name[15]; } OSID[]= { {0,"MS-DOS"}, {1,"OS/2"}, {2,"Win32"}, {3,"Unix"}, {4,"MAC-OS"}, {5,"Win NT"}, {6,"Primos"}, {7,"APPLE GS"}, {8,"ATARI"}, {9,"VAX VMS"}, {10,"AMIGA"}, {11,"NEXT"}, }; PACK_PUSH(1) struct ACEHEADER { WORD CRC16; // CRC16 over block WORD HeaderSize; // size of the block(from HeaderType) BYTE HeaderType; // archive header type is 0 WORD HeaderFlags; BYTE Signature[7]; // '**ACE**' BYTE VerExtract; // version needed to extract archive BYTE VerCreate; // version used to create the archive BYTE Host; // HOST-OS for ACE used to create the archive BYTE VolumeNum; // which volume of a multi-volume-archive is it? DWORD AcrTime; // date and time in MS-DOS format BYTE Reserved[8]; // 8 bytes reserved for the future }; PACK_POP() PACK_CHECK(ACEHEADER, 1); static HANDLE ArcHandle; static DWORD NextPosition,FileSize,SFXSize; static ACEHEADER MainHeader; int HostOS=0, UnpVer=0; #if defined(CALC_CRC) #define CRCPOLY 0xEDB88320 #define CRC_MASK 0xFFFFFFFF static unsigned crctable[256]; static BOOL CRCTableCreated=FALSE; static void make_crctable(void) { unsigned r,i,j; for (i=0;i<=255;i++) { for (r=i,j=8;j;j--) r=(r&1)?(r>>1)^CRCPOLY:(r>>1); crctable[i] = r; } CRCTableCreated=TRUE; } static DWORD getcrc(DWORD crc,BYTE *addr,int len) { if(!CRCTableCreated) make_crctable(); while (len--) crc=crctable[(BYTE)crc^(*addr++)]^(crc>>8); return(crc); } #endif BOOL WINAPI _export IsArchive(const char *Name,const unsigned char *Data,int DataSize) { for (int I=0;I<(int)(DataSize-sizeof(ACEHEADER));I++) { const unsigned char *D=Data+I; if (D[0]=='*' && D[1]=='*' && D[2]=='A' && D[3]=='C' && D[4]=='E' && D[5]=='*' && D[6]=='*' ) { ACEHEADER *Header=(ACEHEADER *)(Data+I-7); #if defined(CALC_CRC) DWORD crc=CRC_MASK; crc=getcrc(crc,&Header->HeaderType,Header->HeaderSize); #endif if (Header->HeaderType == 0 && Header->HeaderSize >= (sizeof(ACEHEADER)-offsetof(ACEHEADER,HeaderFlags)) #if defined(CALC_CRC) && LOWORD(crc) == LOWORD(Header->CRC16) #endif ) { SFXSize=I-7; return(TRUE); } } } return(FALSE); } BOOL WINAPI _export OpenArchive(const char *Name,int *Type) { DWORD ReadSize; ArcHandle=CreateFile(Name,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL); if (ArcHandle==INVALID_HANDLE_VALUE) return(FALSE); *Type=0; FileSize=GetFileSize(ArcHandle,NULL); NextPosition=SFXSize; SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN); if (!ReadFile(ArcHandle,&MainHeader,sizeof(MainHeader),&ReadSize,NULL) || ReadSize!=sizeof(MainHeader)) { CloseHandle(ArcHandle); return(FALSE); } NextPosition=SFXSize+MainHeader.HeaderSize+sizeof(WORD)*2; SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN); for(int I=0; I < (int)(ARRAYSIZE(OSID)); ++I) if(OSID[I].Type == MainHeader.Host) { HostOS=I; break; } UnpVer=(MainHeader.VerExtract/10)*256+(MainHeader.VerExtract%10); return(TRUE); } int WINAPI _export GetArcItem(PluginPanelItem *Item, ArcItemInfo *Info) { PACK_PUSH(1) struct ACEHEADERBLOCK { WORD CRC16; WORD HeaderSize; } Block; PACK_POP() PACK_CHECK(ACEHEADERBLOCK, 1); HANDLE hHeap=GetProcessHeap(); DWORD ReadSize; BYTE *TempBuf; while(1) { NextPosition=SetFilePointer(ArcHandle,NextPosition,NULL,FILE_BEGIN); if (NextPosition==0xFFFFFFFF) return(GETARC_READERROR); if (NextPosition>FileSize) return(GETARC_UNEXPEOF); if (!ReadFile(ArcHandle,&Block,sizeof(Block),&ReadSize,NULL)) return(GETARC_READERROR); if (!ReadSize || !Block.HeaderSize) //??? return(GETARC_EOF); TempBuf=(BYTE*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, Block.HeaderSize); if(!TempBuf) return(GETARC_READERROR); if (!ReadFile(ArcHandle,TempBuf,Block.HeaderSize,&ReadSize,NULL)) { HeapFree(hHeap,0,TempBuf); return(GETARC_READERROR); } if (ReadSize==0 || Block.HeaderSize != ReadSize) { HeapFree(hHeap,0,TempBuf); return(GETARC_EOF); } #if defined(CALC_CRC) DWORD crc=CRC_MASK; crc=getcrc(crc,TempBuf,Block.HeaderSize); if (LOWORD(crc) != LOWORD(Block.CRC16)) { HeapFree(hHeap,0,TempBuf); return(GETARC_BROKEN); } #endif NextPosition+=sizeof(Block)+Block.HeaderSize; if(*TempBuf == 1) // File block { PACK_PUSH(1) struct ACEHEADERFILE { BYTE HeaderType; WORD HeaderFlags; DWORD PackSize; DWORD UnpSize; WORD FTime; // File Time an Date Stamp WORD FDate; // File Time an Date Stamp DWORD FileAttr; DWORD CRC32; WORD TechInfo; WORD DictSize; //???? WORD Reserved; WORD FileNameSize; char FileName[1]; } *FileHeader; PACK_POP() PACK_CHECK(ACEHEADERFILE, 1); FileHeader=(ACEHEADERFILE*)TempBuf; if(FileHeader->HeaderFlags&1) { Item->FindData.dwFileAttributes=FileHeader->FileAttr; if(FileHeader->FileNameSize) { if(FileHeader->FileNameSize >= (WORD)sizeof(Item->FindData.cFileName)) return(GETARC_BROKEN); memcpy(Item->FindData.cFileName,FileHeader->FileName,FileHeader->FileNameSize); } Item->FindData.cFileName[FileHeader->FileNameSize]=0; Item->FindData.nFileSizeLow=FileHeader->UnpSize; Item->FindData.nFileSizeHigh=0; Item->PackSize=FileHeader->PackSize; FILETIME lft; DosDateTimeToFileTime(FileHeader->FDate,FileHeader->FTime,&lft); LocalFileTimeToFileTime(&lft,&Item->FindData.ftLastWriteTime); Info->Solid=FileHeader->HeaderFlags&(1<<15)?1:0; Info->Encrypted=FileHeader->HeaderFlags&(1<<14)?1:0; Info->Comment=FileHeader->HeaderFlags&2?1:0; Info->UnpVer=UnpVer; //????? Info->DictSize=1<<FileHeader->DictSize; //????? lstrcpy(Info->HostOS,OSID[HostOS].Name); Item->CRC32=FileHeader->CRC32; NextPosition+=FileHeader->PackSize; break; } } PACK_PUSH(1) struct ACERECORDS { BYTE HeaderType; // header type of recovery records is 2 WORD HeaderFlags; // Bit 0 1 (RecSize field present) DWORD RecSize; } *RecHeader; PACK_POP() PACK_CHECK(ACERECORDS, 1); RecHeader=(ACERECORDS*)TempBuf; if(RecHeader->HeaderFlags&1) NextPosition+=RecHeader->RecSize; HeapFree(hHeap,0,TempBuf); } HeapFree(hHeap,0,TempBuf); return(GETARC_SUCCESS); } BOOL WINAPI _export CloseArchive(ArcInfo *Info) { if(Info) { Info->SFXSize=SFXSize; Info->Volume=MainHeader.HeaderFlags&(1<<11)?1:0; Info->Comment=MainHeader.HeaderFlags&2?1:0; Info->Recovery=MainHeader.HeaderFlags&(1<<13)?1:0; Info->Lock=MainHeader.HeaderFlags&(1<<14)?1:0; Info->Flags|=MainHeader.HeaderFlags&(1<<12)?AF_AVPRESENT:0; } return(CloseHandle(ArcHandle)); } DWORD WINAPI _export GetSFXPos(void) { return SFXSize; } BOOL WINAPI _export GetFormatName(int Type,char *FormatName,char *DefaultExt) { if (Type==0) { lstrcpy(FormatName,"ACE"); lstrcpy(DefaultExt,"ace"); return(TRUE); } return(FALSE); } BOOL WINAPI _export GetDefaultCommands(int Type,int Command,char *Dest) { if (Type==0) { static const char *Commands[]={ /*Extract */"ace32 x {-p%%P} -y -c- -std {%%S} %%A @%%LN", /*Extract without paths */"ace32 e -av- {-p%%P} -y -c- -std {%%S} %%A @%%LN", /*Test */"ace32 t -y {-p%%P} -c- -std {%%S} %%A", /*Delete */"ace32 d -y -std {-t%%W} {%%S} %%A @%%LN", /*Comment archive */"ace32 cm -y -std {-t%%W} {%%S} %%A", /*Comment files */"ace32 cf -y -std {-t%%W} {%%S} %%A {@%%LN}", /*Convert to SFX */"ace32 s -y -std {%%S} %%A", /*Lock archive */"ace32 k -y -std {%%S} %%A", /*Protect archive */"ace32 rr -y -std {%%S} %%A", /*Recover archive */"ace32 r -y -std {%%S} %%A", /*Add files */"ace32 a -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", /*Move files */"ace32 m -c2 -y -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", /*Add files and folders */"ace32 a -y -c2 -r -f -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", /*Move files and folders*/"ace32 m -y -c2 -r -f -std {-p%%P} {-t%%W} {%%S} %%A @%%LN", /*"All files" mask */"*.*" }; if (Command<(int)(ARRAYSIZE(Commands))) { lstrcpy(Dest,Commands[Command]); return(TRUE); } } return(FALSE); }
26.304598
97
0.610116
[ "solid" ]
ed56565d7e26afd9ba38d4bcf45d16f72df20a68
35,438
cpp
C++
src/demo/fly_sorter/image_grabber.cpp
hhhHanqing/bias
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
[ "Apache-2.0" ]
5
2020-07-23T18:59:08.000Z
2021-12-14T02:56:12.000Z
src/demo/fly_sorter/image_grabber.cpp
hhhHanqing/bias
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
[ "Apache-2.0" ]
4
2020-08-30T13:55:22.000Z
2022-03-24T21:14:15.000Z
src/demo/fly_sorter/image_grabber.cpp
hhhHanqing/bias
ac409978ac0bfc6bc4cf8570bf7ce7509e81a219
[ "Apache-2.0" ]
3
2020-10-04T17:53:15.000Z
2022-02-24T05:55:53.000Z
#include "image_grabber.hpp" #include "camera_facade.hpp" #include "exception.hpp" #include <QPointer> #include <QMap> #include <QFile> #include <QFileInfo> #include <QDir> #include <QString> #include <QStringList> #include <QTextStream> #include <iostream> #include <fstream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // Constants // ---------------------------------------------------------------------------- const QString DEBUG_DUMP_CAMERA_PROPS_FILE_NAME("fly_sorter_camera_props_dump.txt"); const int CAPTURE_FROM_DIR_FRAME_NUMBER_MUL = 1000; // Function prototypes // ---------------------------------------------------------------------------- bool getFrameNumberToFileInfoMap( QFileInfoList imageFileInfoList, QMap<int,QFileInfo> &frameNumberToFileInfoMap, QString errorMsg ); bool getFrameNumberFilterMap( QDir captureInputDir, QMap<int,bool> &frameNumberFilterMap, QString errorMsg ); // CameraInfo // ---------------------------------------------------------------------------- CameraInfo::CameraInfo() { vendor = QString(""); model = QString(""); guid = QString(""); } // ImageData // ---------------------------------------------------------------------------- ImageData::ImageData() { frameCount = 0; dateTime = 0.0; } void ImageData::copy(ImageData imageData) { frameCount = imageData.frameCount; dateTime = imageData.dateTime; imageData.mat.copyTo(mat); } // ImageGrabber // ---------------------------------------------------------------------------- ImageGrabber::ImageGrabber(ImageGrabberParam param, QObject *parent) : QObject(parent) { param_ = param; stopped_ = false; dumpCamPropsFlag_ = false; } void ImageGrabber::stopCapture() { stopped_ = true; } void ImageGrabber::dumpCameraProperties() { dumpCamPropsFlag_ = true; }; void ImageGrabber::run() { if (param_.captureMode == QString("camera")) { runCaptureFromCamera(); } else if (param_.captureMode == QString("file")) { runCaptureFromFile(); } else if (param_.captureMode == QString("directory")) { runCaptureFromDir(); } else { QString errorMsg = QString("Unable to start capture: unknown capture mode "); errorMsg += param_.captureMode; emit cameraSetupError(errorMsg); } CameraInfo emptyInfo; emit newCameraInfo(emptyInfo); emit stopped(); } void ImageGrabber::runCaptureFromCamera() { // Setup camera and start capture if (!setupCamera()) { return; } try { cameraPtr_ -> startCapture(); } catch (RuntimeError &runtimeError) { unsigned int errorId = runtimeError.id(); QString errorMsg = QString("Unable to start capture: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return; } // Grab images ImageData imageData; while (!stopped_) { try { imageData.mat = cameraPtr_ -> grabImage(); } catch (RuntimeError &runtimeError) { continue; } imageData.frameCount++; QDateTime currentDateTime = QDateTime::currentDateTime(); imageData.dateTime = double(currentDateTime.toMSecsSinceEpoch())*(1.0e-3); emit newImage(imageData); // dump camera properties if (dumpCamPropsFlag_) { dumpCamPropsFlag_ = false; std::cout << "DEBUG: dumping camera properties" << std::endl; std::ofstream camPropsStream; camPropsStream.open(DEBUG_DUMP_CAMERA_PROPS_FILE_NAME.toStdString()); camPropsStream << (cameraPtr_ -> getAllPropertiesString()); camPropsStream.close(); } } // Clean up try { cameraPtr_ -> stopCapture(); } catch (RuntimeError &runtimeError) { unsigned int errorId = runtimeError.id(); QString errorMsg = QString("Unable to start capture: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); } try { cameraPtr_ -> disconnect(); } catch (RuntimeError &runtimeError) { unsigned int errorId = runtimeError.id(); QString errorMsg = QString("Unable to disconnect from camera: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); } } void ImageGrabber::runCaptureFromFile() { cv::VideoCapture fileCapture; // Open the capture input file try { fileCapture.open(param_.captureInputFile.toStdString()); } catch(cv::Exception& exception) { QString errorMsg = QString("Error opening captureInputFile, "); errorMsg += param_.captureInputFile + QString(", - "); errorMsg += QString::fromStdString(exception.what()); emit fileReadError(errorMsg); return; } if (!fileCapture.isOpened()) { QString errorMsg = QString("Unable to open captureInputFile, "); errorMsg += param_.captureInputFile; emit fileReadError(errorMsg); return; } // Get number of frames and fourcc unsigned int numFrames; int fourcc; try { numFrames = (unsigned int)(fileCapture.get(CV_CAP_PROP_FRAME_COUNT)); fourcc = int(fileCapture.get(CV_CAP_PROP_FOURCC)); } catch(cv::Exception& exception) { QString errorMsg = QString("Unable to get properties from captureInputFile, "); errorMsg += param_.captureInputFile + QString(", "); errorMsg += QString::fromStdString(exception.what()); emit fileReadError(errorMsg); return; } //std::cout << "fourcc: " << fourcc << std::endl; //std::cout << "numFrames: " << numFrames << std::endl; if ((fourcc == 0) || (fourcc == 808466521)) { // -------------------------------------------------------------------- // TEMPORARY - currently having problems with DIB/raw formats need to // fix this // -------------------------------------------------------------------- QString errorMsg = QString("Fourcc code is equal to 0 - this is currently not supported"); emit fileReadError(errorMsg); return; } // Read frame from input file at frameRate. unsigned long frameCount = 0; //float sleepDt = 1.0e3/param_.frameRate; //float sleepDt = 0.5*1.0e3/param_.frameRate; float sleepDt = 0.2*1.0e3/param_.frameRate; std::cout << param_.captureInputFile.toStdString() << std::endl; std::cout << "begin play back" << std::endl; ImageData imageData; while ((!stopped_) && (frameCount < numFrames)) { std::cout << (frameCount+1) << "/" << numFrames << std::endl; cv::Mat mat; try { fileCapture >> mat; } catch (cv::Exception &exception) { QString errorMsg = QString("Unable to read frame %1: ").arg(frameCount); errorMsg += QString::fromStdString(exception.what()); emit fileReadError(errorMsg); stopped_ = true; continue; } catch (...) { QString errorMsg = QString("Unable to read frame %1: ").arg(frameCount); errorMsg += QString("an uknown exception occured"); emit fileReadError(errorMsg); stopped_ = true; continue; } if (mat.empty()) { // This shouldn't happen, but just in case // skip any frames that come back empty. frameCount++; //std::cout << "empty frame" << std::endl; continue; } else { //std::cout << std::endl; } imageData.mat = mat.clone(); // Get deep copy of image mat (required) imageData.frameCount = frameCount; QDateTime currentDateTime = QDateTime::currentDateTime(); imageData.dateTime = double(currentDateTime.toMSecsSinceEpoch())*(1.0e-3); emit newImage(imageData); frameCount++; ThreadHelper::msleep(sleepDt); // DEBUG - slow down // ------------------------------------------------------------------------ //if (frameCount > 100) //{ // ThreadHelper::msleep(1000); //} //------------------------------------------------------------------------- } std::cout << "play back done" << std::endl; // Release file try { fileCapture.release(); } catch(cv::Exception& exception) { QString errorMsg = QString("Error releasing captureInputFile, "); errorMsg += param_.captureInputFile + QString(", - "); errorMsg += QString::fromStdString(exception.what()); emit fileReadError(errorMsg); return; } //std::cout << "end" << std::endl; return; } void ImageGrabber::runCaptureFromDir() { float sleepDt = 1.0e3/param_.frameRate; unsigned long fileCount = 0; // Check that capture directory exists QDir captureInputDir = QDir(param_.captureInputDir); if (!captureInputDir.exists()) { QString dirStr = captureInputDir.absolutePath(); QString errorMsg = QString("Error: captureInputDir %1 does not exist.").arg(dirStr); emit fileReadError(errorMsg); return; } // Check that debug images sub-directory exists QDir debugImagesDir = QDir(captureInputDir.absolutePath() + "/debug_images"); if (!debugImagesDir.exists()) { QString dirStr = debugImagesDir.absolutePath(); QString errorMsg = QString("Error: debug_images dir %1 does not exist.").arg(dirStr); emit fileReadError(errorMsg); return; } // Get names of image files in capture directory QStringList bmpFilter("*.bmp"); debugImagesDir.setSorting(QDir::Name); QFileInfoList imageFileInfoList = debugImagesDir.entryInfoList(bmpFilter); // Create map from frame number in filename and sort images files by frame number QMap<int, QFileInfo> frameNumberToFileInfoMap; QString mapErrorMsg; bool mapOk = getFrameNumberToFileInfoMap(imageFileInfoList,frameNumberToFileInfoMap,mapErrorMsg); if (!mapOk) { emit fileReadError(mapErrorMsg); return; } QList<int> frameNumberList = frameNumberToFileInfoMap.keys(); qSort(frameNumberList.begin(), frameNumberList.end()); QListIterator<int> frameNumberIt(frameNumberList); // Read debug data log and create filter map QMap<int, bool> frameNumberFilterMap; mapOk = getFrameNumberFilterMap(captureInputDir,frameNumberFilterMap, mapErrorMsg); if (!mapOk) { emit fileReadError(mapErrorMsg); return; } while ((!stopped_) && frameNumberIt.hasNext()) { ImageData imageData; int frameNumber = frameNumberIt.next(); QFileInfo fileInfo = frameNumberToFileInfoMap[frameNumber]; QString fileName = fileInfo.absoluteFilePath(); //std::cout << "count: " << fileCount << ", fileName " << fileName.toStdString(); // Filter out undesired values if (!frameNumberFilterMap.contains(frameNumber)) { QString errorMsg = QString("frame number not found in filter map for dir %1").arg( captureInputDir.absolutePath() ); emit fileReadError(errorMsg); return; } bool filterValue = frameNumberFilterMap[frameNumber]; if (!filterValue) { //std::cout << " - skipped (filtered)" << std::endl; continue; } // Make sure file exists if (!fileInfo.exists()) { //std::cout <<" - skipped (doesn't exist)" << std::endl; continue; } //std::cout << std::endl; // Read image from file cv::Mat subImageMat; try { subImageMat = cv::imread(fileName.toStdString()); } catch (cv::Exception &exception) { QString errorMsg = QString("Unable to read image %1: ").arg(fileName); errorMsg += QString::fromStdString(exception.what()); emit fileReadError(errorMsg); stopped_ = true; continue; } // Place mat in larger padded image unsigned int pad = 500; cv::Scalar padColor = cv::Scalar(255,255,255); cv::Size subImageSize = subImageMat.size(); cv::Size fullImageSize = cv::Size(subImageSize.width+2*pad,subImageSize.height+2*pad); cv::Mat fullImageMat = cv::Mat(fullImageSize, CV_8UC3, padColor); cv::copyMakeBorder(subImageMat,fullImageMat, pad, pad, pad, pad, cv::BORDER_CONSTANT, padColor); imageData.mat = fullImageMat.clone(); // Get deep copy of image mat (required) imageData.frameCount = frameNumber; QDateTime currentDateTime = QDateTime::currentDateTime(); imageData.dateTime = double(currentDateTime.toMSecsSinceEpoch())*(1.0e-3); emit newImage(imageData); ThreadHelper::msleep(sleepDt); fileCount++; } return; } bool ImageGrabber::setupCamera() { CameraFinder cameraFinder; CameraPtrList cameraPtrList; // Get list guids for all cameras found try { cameraPtrList = cameraFinder.createCameraPtrList(); } catch (bias::RuntimeError &runtimeError) { QString errorMsg = QString("Unable to enumerate cameras: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // If no cameras found - error if (cameraPtrList.empty()) { QString errorMsg = QString("No cameras found"); emit cameraSetupError(errorMsg); return false; } // Connect to first camera cameraPtr_ = cameraPtrList.front(); if (cameraPtr_ -> isConnected()) { QString errorMsg = QString("Camera is already connected"); emit cameraSetupError(errorMsg); return false; } try { cameraPtr_ -> connect(); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to connect to camera: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } CameraInfo cameraInfo; cameraInfo.vendor = QString::fromStdString(cameraPtr_ -> getVendorName()); cameraInfo.model = QString::fromStdString(cameraPtr_ -> getModelName()); cameraInfo.guid = QString::fromStdString((cameraPtr_ -> getGuid()).toString()); emit newCameraInfo(cameraInfo); // Set video mode try { cameraPtr_ -> setVideoMode(VIDEOMODE_FORMAT7); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set Video Mode: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set trigger try { cameraPtr_ -> setTriggerInternal(); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set trigger: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set frame rate PropertyInfo frameRateInfo; Property frameRateProp; try { frameRateInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_FRAME_RATE); frameRateProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_FRAME_RATE); } catch (RuntimeError &runtimeError) { QString errorMsg = QString( "Unable to get framerate property: " ); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if (param_.frameRate < frameRateInfo.minAbsoluteValue) { QString errorMsg = QString( "framerate less than minimum allowed %1" ).arg(frameRateInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } if (param_.frameRate > frameRateInfo.maxAbsoluteValue) { QString errorMsg = QString( "framerate greater than maximum allowed %1" ).arg(frameRateInfo.maxAbsoluteValue); emit cameraSetupError(errorMsg); return false; } frameRateProp.absoluteControl = true; frameRateProp.absoluteValue = param_.frameRate; frameRateProp.autoActive = false; try { cameraPtr_ -> setProperty(frameRateProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set framerate property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set gain PropertyInfo gainInfo; Property gainProp; try { gainInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_GAIN); gainProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_GAIN); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get gain property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if (param_.gain < gainInfo.minAbsoluteValue) { QString errorMsg = QString( "gain less than minimum allowed %1" ).arg(gainInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } if (param_.gain > gainInfo.maxAbsoluteValue) { QString errorMsg = QString( "gain greater than maximum allowed %1" ).arg(gainInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } gainProp.absoluteControl = true; gainProp.absoluteValue = param_.gain; gainProp.autoActive = false; try { cameraPtr_ -> setProperty(gainProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set gain property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set shutter PropertyInfo shutterInfo; Property shutterProp; try { shutterInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_SHUTTER); shutterProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_SHUTTER); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get shutter property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if (param_.shutter < shutterInfo.minAbsoluteValue) { QString errorMsg = QString( "shutter less than minimum allowed %1" ).arg(shutterInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } if (param_.shutter > shutterInfo.maxAbsoluteValue) { QString errorMsg = QString( "shutter greater than maximum allowed %1" ).arg(shutterInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } shutterProp.absoluteControl = true; shutterProp.absoluteValue = param_.shutter; shutterProp.autoActive = false; try { cameraPtr_ -> setProperty(shutterProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set shutter property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set brightness PropertyInfo brightnessInfo; Property brightnessProp; try { brightnessInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_BRIGHTNESS); brightnessProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_BRIGHTNESS); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get brightness property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if (param_.brightness < brightnessInfo.minValue) { QString errorMsg = QString( "brightness less than minimum allowed %1" ).arg(brightnessInfo.minValue); emit cameraSetupError(errorMsg); return false; } if (param_.brightness > brightnessInfo.maxValue) { QString errorMsg = QString( "brightness greater than maximum allowed %1" ).arg(brightnessInfo.minValue); emit cameraSetupError(errorMsg); return false; } brightnessProp.absoluteControl = false; brightnessProp.value = param_.brightness; brightnessProp.autoActive = false; try { cameraPtr_ -> setProperty(brightnessProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set brightness property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Set Gamma - if present PropertyInfo gammaInfo; Property gammaProp; try { gammaInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_GAMMA); gammaProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_GAMMA); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get gamma property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } // Color camera specific - for development dont' set if can't if ((gammaInfo.present) && (gammaInfo.manualCapable) && (gammaInfo.absoluteCapable)) { //std::cout << "setting gamma" << std::endl; if (param_.gamma < gammaInfo.minAbsoluteValue) { QString errorMsg = QString( "gamma less than minimum allowed %1" ).arg(gammaInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } if (param_.gamma > gammaInfo.maxAbsoluteValue) { QString errorMsg = QString( "gamma greater than maximum allowed %1" ).arg(gammaInfo.maxAbsoluteValue); emit cameraSetupError(errorMsg); return false; } gammaProp.absoluteControl = true; gammaProp.absoluteValue = param_.gamma; gammaProp.autoActive = false; try { cameraPtr_ -> setProperty(gammaProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set gamma property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } } else { //std::cout << "not setting gamma" << std::endl; // ------------------------------------------- // TO DO ... emit warning if not present?? // ------------------------------------------- } // Set Saturation - if present PropertyInfo saturationInfo; Property saturationProp; try { saturationInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_SATURATION); saturationProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_SATURATION); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get saturation property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if ((saturationInfo.present) && (saturationInfo.manualCapable) && (saturationInfo.absoluteCapable)) { //std::cout << "setting saturation" << std::endl; if (param_.saturation < saturationInfo.minAbsoluteValue) { QString errorMsg = QString( "saturation less than minimum allowed %1" ).arg(saturationInfo.minAbsoluteValue); emit cameraSetupError(errorMsg); return false; } if (param_.saturation > saturationInfo.maxAbsoluteValue) { QString errorMsg = QString( "saturation greater than maximum allowed %1" ).arg(saturationInfo.maxAbsoluteValue); emit cameraSetupError(errorMsg); return false; } saturationProp.absoluteControl = true; saturationProp.absoluteValue = param_.saturation; saturationProp.autoActive = false; try { cameraPtr_ -> setProperty(saturationProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set saturation property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } } else { //std::cout << "not setting saturation" << std::endl; // ------------------------------------------------ // TO DO ... emit waring if not present?? // ------------------------------------------------ } // Set whiteBalance (Red and Blue) - if present PropertyInfo whiteBalanceInfo; Property whiteBalanceProp; try { whiteBalanceInfo = cameraPtr_ -> getPropertyInfo(PROPERTY_TYPE_SATURATION); whiteBalanceProp = cameraPtr_ -> getProperty(PROPERTY_TYPE_SATURATION); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to get whiteBalance property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } if ((whiteBalanceInfo.present) && (whiteBalanceInfo.manualCapable)) { //std::cout << "setting whiteBalance" << std::endl; if (param_.whiteBalanceRed < whiteBalanceInfo.minValue) { QString errorMsg = QString( "whiteBalanceRed less than minimum allowed %1" ).arg(whiteBalanceInfo.minValue); emit cameraSetupError(errorMsg); return false; } if (param_.whiteBalanceRed > whiteBalanceInfo.maxValue) { QString errorMsg = QString( "whiteBalanceRed greater than maximum allowed %1" ).arg(whiteBalanceInfo.maxValue); emit cameraSetupError(errorMsg); return false; } if (param_.whiteBalanceBlue < whiteBalanceInfo.minValue) { QString errorMsg = QString( "whiteBalanceBlue less than minimum allowed %1" ).arg(whiteBalanceInfo.minValue); emit cameraSetupError(errorMsg); return false; } if (param_.whiteBalanceBlue > whiteBalanceInfo.maxValue) { QString errorMsg = QString( "whiteBalanceBlue greater than maximum allowed %1" ).arg(whiteBalanceInfo.maxValue); emit cameraSetupError(errorMsg); return false; } whiteBalanceProp.absoluteControl = false; whiteBalanceProp.valueA = param_.whiteBalanceRed; whiteBalanceProp.valueB = param_.whiteBalanceBlue; whiteBalanceProp.autoActive = false; try { cameraPtr_ -> setProperty(whiteBalanceProp); } catch (RuntimeError &runtimeError) { QString errorMsg = QString("Unable to set whiteBalance property: "); errorMsg += QString::fromStdString(runtimeError.what()); emit cameraSetupError(errorMsg); return false; } } else { //std::cout << "not setting whiteBalance" << std::endl; // ------------------------------------------------ // TO DO ... emit waring if not present?? // ------------------------------------------------ } return true; } // Utility functions // ---------------------------------------------------------------------------- bool getFrameNumberToFileInfoMap( QFileInfoList imageFileInfoList, QMap<int,QFileInfo> &frameNumberToFileInfoMap, QString errorMsg ) { for (int i=0; i<imageFileInfoList.size(); i++) { bool intOk; QFileInfo fileInfo = imageFileInfoList[i]; QString fileName = fileInfo.fileName(); int frmInd = fileName.indexOf(QString("frm")); if (frmInd == -1) { errorMsg = QString("Error: unable to find frm in %1").arg(fileName); return false; } int frmScoreInd0 = fileName.indexOf(QString("_"),frmInd); if (frmScoreInd0 == -1) { errorMsg = QString("Error: unable to parse frame number in %1").arg(fileName); return false; } int frmScoreInd1 = fileName.indexOf(QString("_"),frmScoreInd0+1); if (frmScoreInd1 == -1) { errorMsg = QString("Error: unable to parse frame number in %1").arg(fileName); return false; } intOk = true; int frameNumber = fileName.mid(frmScoreInd0+1, frmScoreInd1-frmScoreInd0-1).toInt(&intOk); if (!intOk) { errorMsg = QString("Error: unable to convert frameNumber to int in file %1").arg(fileName); return false; } int cntInd = fileName.indexOf(QString("cnt")); if (cntInd == -1) { errorMsg = QString("Error: unable to find cnt in %1").arg(fileName); return false; } int cntScoreInd0 = fileName.indexOf(QString("_"), cntInd); if (cntScoreInd0 == -1) { errorMsg = QString("Error: unable to parse object count in %1").arg(fileName); return false; } int cntScoreInd1 = fileName.indexOf(QString("."), cntScoreInd0+1); if (cntScoreInd1 == -1) { errorMsg = QString("Error: unable to parse object count in %1").arg(fileName); return false; } intOk = true; int objectCount = fileName.mid(cntScoreInd0+1,cntScoreInd1-cntScoreInd0-1).toInt(&intOk); if (!intOk) { errorMsg = QString("Error: unable to convert count to int in file %1").arg(fileName); return false; } int frameNumberWithCount = frameNumber*CAPTURE_FROM_DIR_FRAME_NUMBER_MUL + objectCount; if (!frameNumberToFileInfoMap.contains(frameNumberWithCount)) { frameNumberToFileInfoMap.insert(frameNumberWithCount, fileInfo); } } return true; } bool getFrameNumberFilterMap( QDir captureInputDir, QMap<int,bool> &frameNumberFilterMap, QString errorMsg ) { // Check that file exists QString logFileName("debug_data_log.txt"); if (!captureInputDir.exists(logFileName)) { errorMsg = QString("Error: %1 not found in capture directory").arg(logFileName); return false; } // Open file QFile logFile(captureInputDir.absoluteFilePath(logFileName)); if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { errorMsg = QString("Error: unable to open debug data log %1").arg(logFileName); return false; } // Read contents and create map QTextStream logStream(&logFile); bool inFrameCount = false; bool filterFlag = true; int frameNumberWithCount = -1; while (!logStream.atEnd()) { QString line = logStream.readLine(); QStringList lineList = line.split(" ",QString::SkipEmptyParts); lineList = lineList.replaceInStrings(QString(","),QString("")); if (lineList.isEmpty()) { // Skip empty lines continue; } if (lineList.contains("Frame:") && lineList.contains("count:")) { inFrameCount = true; bool intOk = true; int frameNumber = lineList[1].toInt(&intOk); if (frameNumber == -1) { errorMsg = QString("Error: unable to parse frame number in %1").arg( captureInputDir.absoluteFilePath(logFileName) ); return false; } int objectCount = lineList[3].toInt(&intOk); if (objectCount == -1) { errorMsg = QString("Error: unable to parse object count in %1").arg( captureInputDir.absoluteFilePath(logFileName) ); return false; } frameNumberWithCount = frameNumber*CAPTURE_FROM_DIR_FRAME_NUMBER_MUL + objectCount; } else if (lineList.contains("onBorderX:") || lineList.contains("onBorderY:")) { bool intOk = true; int onBorderVal = lineList[1].toInt(&intOk); if ( (!intOk) || (onBorderVal < 0) || (onBorderVal > 1)) { errorMsg = QString("Error: unable to parse onBorder value in %1").arg( captureInputDir.absoluteFilePath(logFileName) ); return false; } if (onBorderVal == 1) { filterFlag = false; } } else if (lineList.contains("contourVector:")) { if (inFrameCount) { frameNumberFilterMap.insert(frameNumberWithCount,filterFlag); } inFrameCount = false; filterFlag = true; } } logFile.close(); return true; }
31.75448
105
0.560556
[ "object", "model" ]
ed5f66134c4e5a7b857c6835b3727ab8f261c16c
14,046
cc
C++
poseutils-uses-autodiff.cc
dkogan/mrcal
ca4678e1171841fd9cd158b87ee460163647b495
[ "Apache-2.0" ]
80
2021-02-23T19:50:49.000Z
2022-03-29T08:05:56.000Z
poseutils-uses-autodiff.cc
dkogan/mrcal
ca4678e1171841fd9cd158b87ee460163647b495
[ "Apache-2.0" ]
2
2021-03-26T10:44:09.000Z
2021-06-23T21:14:10.000Z
poseutils-uses-autodiff.cc
dkogan/mrcal
ca4678e1171841fd9cd158b87ee460163647b495
[ "Apache-2.0" ]
8
2021-02-23T13:34:18.000Z
2021-11-09T13:33:28.000Z
#include "autodiff.hh" #include "strides.h" extern "C" { #include "poseutils.h" } template<int N> static void rotate_point_r_core(// output val_withgrad_t<N>* x_outg, // inputs const val_withgrad_t<N>* rg, const val_withgrad_t<N>* x_ing, bool inverted) { // Rodrigues rotation formula: // xrot = x cos(th) + cross(axis, x) sin(th) + axis axist x (1 - cos(th)) // // I have r = axis*th -> th = norm(r) -> // xrot = x cos(th) + cross(r, x) sin(th)/th + r rt x (1 - cos(th)) / (th*th) // an inversion would flip the sign on: // - rg // - cross // - inner // But inner is always multiplied by rg, making the sign irrelevant. So an // inversion only flips the sign on the cross double sign = inverted ? -1.0 : 1.0; const val_withgrad_t<N> th2 = rg[0]*rg[0] + rg[1]*rg[1] + rg[2]*rg[2]; const val_withgrad_t<N> cross[3] = { (rg[1]*x_ing[2] - rg[2]*x_ing[1])*sign, (rg[2]*x_ing[0] - rg[0]*x_ing[2])*sign, (rg[0]*x_ing[1] - rg[1]*x_ing[0])*sign }; const val_withgrad_t<N> inner = rg[0]*x_ing[0] + rg[1]*x_ing[1] + rg[2]*x_ing[2]; if(th2.x < 1e-10) { // Small rotation. I don't want to divide by 0, so I take the limit // lim(th->0, xrot) = // = x + cross(r, x) + r rt x lim(th->0, (1 - cos(th)) / (th*th)) // = x + cross(r, x) + r rt x lim(th->0, sin(th) / (2*th)) // = x + cross(r, x) + r rt x/2 for(int i=0; i<3; i++) x_outg[i] = x_ing[i] + cross[i] + rg[i]*inner / 2.; } else { // Non-small rotation. This is the normal path const val_withgrad_t<N> th = th2.sqrt(); const vec_withgrad_t<N, 2> sc = th.sincos(); for(int i=0; i<3; i++) x_outg[i] = x_ing[i]*sc.v[1] + cross[i] * sc.v[0]/th + rg[i] * inner * (val_withgrad_t<N>(1.) - sc.v[1]) / th2; } } template<int N> static void r_from_R_core(// output val_withgrad_t<N>* rg, // inputs const val_withgrad_t<N>* Rg) { val_withgrad_t<N> tr = Rg[0] + Rg[4] + Rg[8]; val_withgrad_t<N> axis[3] = { Rg[2*3 + 1] - Rg[1*3 + 2], Rg[0*3 + 2] - Rg[2*3 + 0], Rg[1*3 + 0] - Rg[0*3 + 1] }; val_withgrad_t<N> costh = (tr - 1.) / 2.; if( (fabs(axis[0].x) > 1e-10 || fabs(axis[1].x) > 1e-10 || fabs(axis[2].x) > 1e-10) && fabs(costh.x) < (1. - 1e-10) ) { // normal path val_withgrad_t<N> th = costh.acos(); val_withgrad_t<N> mag_axis_recip = val_withgrad_t<N>(1.) / ((axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2]).sqrt()); for(int i=0; i<3; i++) rg[i] = axis[i] * mag_axis_recip * th; } else { // small th. Can't divide by it. But I can look at the limit. // // axis / (2 sinth)*th = axis/2 *th/sinth ~ axis/2 for(int i=0; i<3; i++) rg[i] = axis[i] / 2.; } } extern "C" void mrcal_rotate_point_r_full( // output double* x_out, // (3,) array int x_out_stride0, // in bytes. <= 0 means "contiguous" double* J_r, // (3,3) array. May be NULL int J_r_stride0, // in bytes. <= 0 means "contiguous" int J_r_stride1, // in bytes. <= 0 means "contiguous" double* J_x, // (3,3) array. May be NULL int J_x_stride0, // in bytes. <= 0 means "contiguous" int J_x_stride1, // in bytes. <= 0 means "contiguous" // input const double* r, // (3,) array. May be NULL int r_stride0, // in bytes. <= 0 means "contiguous" const double* x_in, // (3,) array. May be NULL int x_in_stride0, // in bytes. <= 0 means "contiguous" bool inverted // if true, I apply a // rotation in the opposite // direction. J_r corresponds // to the input r ) { init_stride_1D(x_out, 3); init_stride_2D(J_r, 3,3); init_stride_2D(J_x, 3,3); init_stride_1D(r, 3); init_stride_1D(x_in, 3); if(J_r == NULL && J_x == NULL) { vec_withgrad_t<0, 3> rg (r, -1, r_stride0); vec_withgrad_t<0, 3> x_ing(x_in, -1, x_in_stride0); vec_withgrad_t<0, 3> x_outg; rotate_point_r_core<0>(x_outg.v, rg.v, x_ing.v, inverted); x_outg.extract_value(x_out, x_out_stride0); } else if(J_r != NULL && J_x == NULL) { vec_withgrad_t<3, 3> rg (r, 0, r_stride0); vec_withgrad_t<3, 3> x_ing(x_in, -1, x_in_stride0); vec_withgrad_t<3, 3> x_outg; rotate_point_r_core<3>(x_outg.v, rg.v, x_ing.v, inverted); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_r, 0, 3, 0, J_r_stride0, J_r_stride1); } else if(J_r == NULL && J_x != NULL) { vec_withgrad_t<3, 3> rg (r, -1, r_stride0); vec_withgrad_t<3, 3> x_ing(x_in, 0, x_in_stride0); vec_withgrad_t<3, 3> x_outg; rotate_point_r_core<3>(x_outg.v, rg.v, x_ing.v, inverted); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_x, 0, 3, 0, J_x_stride0,J_x_stride1); } else { vec_withgrad_t<6, 3> rg (r, 0, r_stride0); vec_withgrad_t<6, 3> x_ing(x_in, 3, x_in_stride0); vec_withgrad_t<6, 3> x_outg; rotate_point_r_core<6>(x_outg.v, rg.v, x_ing.v, inverted); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_r, 0, 3, 0, J_r_stride0, J_r_stride1); x_outg.extract_grad (J_x, 3, 3, 0, J_x_stride0, J_x_stride1); } } extern "C" void mrcal_transform_point_rt_full( // output double* x_out, // (3,) array int x_out_stride0, // in bytes. <= 0 means "contiguous" double* J_rt, // (3,6) array. May be NULL int J_rt_stride0, // in bytes. <= 0 means "contiguous" int J_rt_stride1, // in bytes. <= 0 means "contiguous" double* J_x, // (3,3) array. May be NULL int J_x_stride0, // in bytes. <= 0 means "contiguous" int J_x_stride1, // in bytes. <= 0 means "contiguous" // input const double* rt, // (6,) array. May be NULL int rt_stride0, // in bytes. <= 0 means "contiguous" const double* x_in, // (3,) array. May be NULL int x_in_stride0, // in bytes. <= 0 means "contiguous" bool inverted // if true, I apply the // transformation in the // opposite direction. // J_rt corresponds to // the input rt ) { if(!inverted) { init_stride_1D(x_out, 3); init_stride_2D(J_rt, 3,6); // init_stride_2D(J_x, 3,3 ); init_stride_1D(rt, 6 ); // init_stride_1D(x_in, 3 ); // to make in-place operations work double t[3] = { P1(rt, 3), P1(rt, 4), P1(rt, 5) }; // I want rotate(x) + t // First rotate(x) mrcal_rotate_point_r_full(x_out, x_out_stride0, J_rt, J_rt_stride0, J_rt_stride1, J_x, J_x_stride0, J_x_stride1, rt, rt_stride0, x_in, x_in_stride0, false); // And now +t. The J_r, J_x gradients are unaffected. J_t is identity for(int i=0; i<3; i++) P1(x_out,i) += t[i]; if(J_rt) mrcal_identity_R_full(&P2(J_rt,0,3), J_rt_stride0, J_rt_stride1); } else { // I use the special-case rx_minus_rt() to efficiently rotate both x and // t by the same r init_stride_1D(x_out, 3); init_stride_2D(J_rt, 3,6); init_stride_2D(J_x, 3,3 ); init_stride_1D(rt, 6 ); init_stride_1D(x_in, 3 ); if(J_rt == NULL && J_x == NULL) { vec_withgrad_t<0, 3> x_minus_t(x_in, -1, x_in_stride0); x_minus_t -= vec_withgrad_t<0, 3>(&P1(rt,3), -1, rt_stride0); vec_withgrad_t<0, 3> rg (&rt[0], -1, rt_stride0); vec_withgrad_t<0, 3> x_outg; rotate_point_r_core<0>(x_outg.v, rg.v, x_minus_t.v, true); x_outg.extract_value(x_out, x_out_stride0); } else if(J_rt != NULL && J_x == NULL) { vec_withgrad_t<6, 3> x_minus_t(x_in, -1, x_in_stride0); x_minus_t -= vec_withgrad_t<6, 3>(&P1(rt,3), 3, rt_stride0); vec_withgrad_t<6, 3> rg (&rt[0], 0, rt_stride0); vec_withgrad_t<6, 3> x_outg; rotate_point_r_core<6>(x_outg.v, rg.v, x_minus_t.v, true); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_rt, 0, 3, 0, J_rt_stride0, J_rt_stride1); x_outg.extract_grad (&P2(J_rt,0,3), 3, 3, 0, J_rt_stride0, J_rt_stride1); } else if(J_rt == NULL && J_x != NULL) { vec_withgrad_t<3, 3> x_minus_t(x_in, 0, x_in_stride0); x_minus_t -= vec_withgrad_t<3, 3>(&P1(rt,3),-1, rt_stride0); vec_withgrad_t<3, 3> rg (&rt[0], -1, rt_stride0); vec_withgrad_t<3, 3> x_outg; rotate_point_r_core<3>(x_outg.v, rg.v, x_minus_t.v, true); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_x, 0, 3, 0, J_x_stride0, J_x_stride1); } else { vec_withgrad_t<9, 3> x_minus_t(x_in, 3, x_in_stride0); x_minus_t -= vec_withgrad_t<9, 3>(&P1(rt,3), 6, rt_stride0); vec_withgrad_t<9, 3> rg (&rt[0], 0, rt_stride0); vec_withgrad_t<9, 3> x_outg; rotate_point_r_core<9>(x_outg.v, rg.v, x_minus_t.v, true); x_outg.extract_value(x_out, x_out_stride0); x_outg.extract_grad (J_rt, 0, 3, 0, J_rt_stride0, J_rt_stride1); x_outg.extract_grad (&P2(J_rt,0,3), 6, 3, 0, J_rt_stride0, J_rt_stride1); x_outg.extract_grad (J_x, 3, 3, 0, J_x_stride0, J_x_stride1); } } } extern "C" void mrcal_r_from_R_full( // output double* r, // (3,) vector int r_stride0, // in bytes. <= 0 means "contiguous" double* J, // (3,3,3) array. Gradient. May be NULL int J_stride0, // in bytes. <= 0 means "contiguous" int J_stride1, // in bytes. <= 0 means "contiguous" int J_stride2, // in bytes. <= 0 means "contiguous" // input const double* R, // (3,3) array int R_stride0, // in bytes. <= 0 means "contiguous" int R_stride1 // in bytes. <= 0 means "contiguous" ) { init_stride_1D(r, 3); init_stride_3D(J, 3,3,3); init_stride_2D(R, 3,3); if(J == NULL) { vec_withgrad_t<0, 3> rg; vec_withgrad_t<0, 9> Rg; Rg.init_vars(&P2(R,0,0), 0,3, -1, R_stride1); Rg.init_vars(&P2(R,1,0), 3,3, -1, R_stride1); Rg.init_vars(&P2(R,2,0), 6,3, -1, R_stride1); r_from_R_core<0>(rg.v, Rg.v); rg.extract_value(r, r_stride0); } else { vec_withgrad_t<9, 3> rg; vec_withgrad_t<9, 9> Rg; Rg.init_vars(&P2(R,0,0), 0,3, 0, R_stride1); Rg.init_vars(&P2(R,1,0), 3,3, 3, R_stride1); Rg.init_vars(&P2(R,2,0), 6,3, 6, R_stride1); r_from_R_core<9>(rg.v, Rg.v); rg.extract_value(r, r_stride0); // J is dr/dR of shape (3,3,3). autodiff.h has a gradient of shape // (3,9): the /dR part is flattened. I pull it out in 3 chunks that scan // the middle dimension. So I fill in J[:,0,:] then J[:,1,:] then J[:,2,:] rg.extract_grad(&P3(J,0,0,0), 0,3, 0,J_stride0,J_stride2,3); rg.extract_grad(&P3(J,0,1,0), 3,3, 0,J_stride0,J_stride2,3); rg.extract_grad(&P3(J,0,2,0), 6,3, 0,J_stride0,J_stride2,3); } }
38.694215
91
0.452015
[ "shape", "vector" ]
ed601774e517efe903a05d74b0e1bc3e5efbfea8
40,799
cpp
C++
src/third_party/angle/src/tests/test_utils/VulkanExternalHelper.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/angle/src/tests/test_utils/VulkanExternalHelper.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/angle/src/tests/test_utils/VulkanExternalHelper.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // VulkanExternalHelper.cpp : Helper for allocating & managing vulkan external objects. #include "test_utils/VulkanExternalHelper.h" #include <vector> #include "common/bitset_utils.h" #include "common/debug.h" #include "common/system_utils.h" #include "common/vulkan/vulkan_icd.h" namespace angle { namespace { std::vector<VkExtensionProperties> EnumerateInstanceExtensionProperties(const char *layerName) { uint32_t instanceExtensionCount; VkResult result = vkEnumerateInstanceExtensionProperties(layerName, &instanceExtensionCount, nullptr); ASSERT(result == VK_SUCCESS); std::vector<VkExtensionProperties> instanceExtensionProperties(instanceExtensionCount); result = vkEnumerateInstanceExtensionProperties(layerName, &instanceExtensionCount, instanceExtensionProperties.data()); ASSERT(result == VK_SUCCESS); return instanceExtensionProperties; } std::vector<VkPhysicalDevice> EnumeratePhysicalDevices(VkInstance instance) { uint32_t physicalDeviceCount; VkResult result = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr); ASSERT(result == VK_SUCCESS); std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount); result = vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices.data()); return physicalDevices; } std::vector<VkExtensionProperties> EnumerateDeviceExtensionProperties( VkPhysicalDevice physicalDevice, const char *layerName) { uint32_t deviceExtensionCount; VkResult result = vkEnumerateDeviceExtensionProperties(physicalDevice, layerName, &deviceExtensionCount, nullptr); ASSERT(result == VK_SUCCESS); std::vector<VkExtensionProperties> deviceExtensionProperties(deviceExtensionCount); result = vkEnumerateDeviceExtensionProperties(physicalDevice, layerName, &deviceExtensionCount, deviceExtensionProperties.data()); ASSERT(result == VK_SUCCESS); return deviceExtensionProperties; } std::vector<VkQueueFamilyProperties> GetPhysicalDeviceQueueFamilyProperties( VkPhysicalDevice physicalDevice) { uint32_t queueFamilyPropertyCount; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertyCount, nullptr); std::vector<VkQueueFamilyProperties> physicalDeviceQueueFamilyProperties( queueFamilyPropertyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertyCount, physicalDeviceQueueFamilyProperties.data()); return physicalDeviceQueueFamilyProperties; } bool HasExtension(const std::vector<VkExtensionProperties> instanceExtensions, const char *extensionName) { for (const auto &extensionProperties : instanceExtensions) { if (!strcmp(extensionProperties.extensionName, extensionName)) return true; } return false; } bool HasExtension(const std::vector<const char *> enabledExtensions, const char *extensionName) { for (const char *enabledExtension : enabledExtensions) { if (!strcmp(enabledExtension, extensionName)) return true; } return false; } uint32_t FindMemoryType(const VkPhysicalDeviceMemoryProperties &memoryProperties, uint32_t memoryTypeBits, VkMemoryPropertyFlags requiredMemoryPropertyFlags) { for (size_t memoryIndex : angle::BitSet32<32>(memoryTypeBits)) { ASSERT(memoryIndex < memoryProperties.memoryTypeCount); if ((memoryProperties.memoryTypes[memoryIndex].propertyFlags & requiredMemoryPropertyFlags) == requiredMemoryPropertyFlags) { return static_cast<uint32_t>(memoryIndex); } } return UINT32_MAX; } void ImageMemoryBarrier(VkCommandBuffer commandBuffer, VkImage image, uint32_t srcQueueFamilyIndex, uint32_t dstQueueFamilyIndex, VkImageLayout oldLayout, VkImageLayout newLayout) { const VkImageMemoryBarrier imageMemoryBarriers[] = { /* [0] = */ {/* .sType = */ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, /* .pNext = */ nullptr, /* .srcAccessMask = */ VK_ACCESS_MEMORY_WRITE_BIT, /* .dstAccessMask = */ VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, /* .oldLayout = */ oldLayout, /* .newLayout = */ newLayout, /* .srcQueueFamilyIndex = */ srcQueueFamilyIndex, /* .dstQueueFamilyIndex = */ dstQueueFamilyIndex, /* .image = */ image, /* .subresourceRange = */ { /* .aspectMask = */ VK_IMAGE_ASPECT_COLOR_BIT, /* .basicMiplevel = */ 0, /* .levelCount = */ 1, /* .baseArrayLayer = */ 0, /* .layerCount = */ 1, }}}; const uint32_t imageMemoryBarrierCount = std::extent<decltype(imageMemoryBarriers)>(); constexpr VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; constexpr VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; const VkDependencyFlags dependencyFlags = 0; vkCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, 0, nullptr, 0, nullptr, imageMemoryBarrierCount, imageMemoryBarriers); } } // namespace VulkanExternalHelper::VulkanExternalHelper() {} VulkanExternalHelper::~VulkanExternalHelper() { if (mDevice != VK_NULL_HANDLE) { vkDeviceWaitIdle(mDevice); } if (mCommandPool != VK_NULL_HANDLE) { vkDestroyCommandPool(mDevice, mCommandPool, nullptr); } if (mDevice != VK_NULL_HANDLE) { vkDestroyDevice(mDevice, nullptr); mDevice = VK_NULL_HANDLE; mGraphicsQueue = VK_NULL_HANDLE; } if (mInstance != VK_NULL_HANDLE) { vkDestroyInstance(mInstance, nullptr); mInstance = VK_NULL_HANDLE; } } void VulkanExternalHelper::initialize(bool useSwiftshader, bool enableValidationLayers) { bool enableValidationLayersOverride = enableValidationLayers; #if !defined(ANGLE_ENABLE_VULKAN_VALIDATION_LAYERS) enableValidationLayersOverride = false; #endif vk::ICD icd = useSwiftshader ? vk::ICD::SwiftShader : vk::ICD::Default; vk::ScopedVkLoaderEnvironment scopedEnvironment(enableValidationLayersOverride, icd); ASSERT(mInstance == VK_NULL_HANDLE); VkResult result = VK_SUCCESS; #if ANGLE_SHARED_LIBVULKAN result = volkInitialize(); ASSERT(result == VK_SUCCESS); #endif // ANGLE_SHARED_LIBVULKAN std::vector<VkExtensionProperties> instanceExtensionProperties = EnumerateInstanceExtensionProperties(nullptr); std::vector<const char *> requestedInstanceExtensions = { VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME}; std::vector<const char *> enabledInstanceExtensions; for (const char *extensionName : requestedInstanceExtensions) { if (HasExtension(instanceExtensionProperties, extensionName)) { enabledInstanceExtensions.push_back(extensionName); } } VkApplicationInfo applicationInfo = { /* .sType = */ VK_STRUCTURE_TYPE_APPLICATION_INFO, /* .pNext = */ nullptr, /* .pApplicationName = */ "ANGLE Tests", /* .applicationVersion = */ 1, /* .pEngineName = */ nullptr, /* .engineVersion = */ 0, /* .apiVersion = */ VK_API_VERSION_1_0, }; uint32_t enabledInstanceExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size()); std::vector<const char *> enabledLayerNames; if (enableValidationLayersOverride) { enabledLayerNames.push_back("VK_LAYER_KHRONOS_validation"); } VkInstanceCreateInfo instanceCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, /* .pNext = */ nullptr, /* .flags = */ 0, /* .pApplicationInfo = */ &applicationInfo, /* .enabledLayerCount = */ static_cast<uint32_t>(enabledLayerNames.size()), /* .ppEnabledLayerNames = */ enabledLayerNames.data(), /* .enabledExtensionCount = */ enabledInstanceExtensionCount, /* .ppEnabledExtensionName = */ enabledInstanceExtensions.data(), }; result = vkCreateInstance(&instanceCreateInfo, nullptr, &mInstance); ASSERT(result == VK_SUCCESS); ASSERT(mInstance != VK_NULL_HANDLE); #if ANGLE_SHARED_LIBVULKAN volkLoadInstance(mInstance); #endif // ANGLE_SHARED_LIBVULKAN std::vector<VkPhysicalDevice> physicalDevices = EnumeratePhysicalDevices(mInstance); ASSERT(physicalDevices.size() > 0); VkPhysicalDeviceProperties physicalDeviceProperties; ChoosePhysicalDevice(physicalDevices, icd, &mPhysicalDevice, &physicalDeviceProperties); vkGetPhysicalDeviceMemoryProperties(mPhysicalDevice, &mMemoryProperties); std::vector<VkExtensionProperties> deviceExtensionProperties = EnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr); std::vector<const char *> requestedDeviceExtensions = { VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME, VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME, VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME, }; std::vector<const char *> enabledDeviceExtensions; for (const char *extensionName : requestedDeviceExtensions) { if (HasExtension(deviceExtensionProperties, extensionName)) { enabledDeviceExtensions.push_back(extensionName); } } std::vector<VkQueueFamilyProperties> queueFamilyProperties = GetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice); for (uint32_t i = 0; i < queueFamilyProperties.size(); ++i) { if (queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { mGraphicsQueueFamilyIndex = i; } } ASSERT(mGraphicsQueueFamilyIndex != UINT32_MAX); constexpr uint32_t kQueueCreateInfoCount = 1; constexpr uint32_t kGraphicsQueueCount = 1; float graphicsQueuePriorities[kGraphicsQueueCount] = {0.f}; VkDeviceQueueCreateInfo queueCreateInfos[kQueueCreateInfoCount] = { /* [0] = */ { /* .sType = */ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, /* .pNext = */ nullptr, /* .flags = */ 0, /* .queueFamilyIndex = */ mGraphicsQueueFamilyIndex, /* .queueCount = */ 1, /* .pQueuePriorities = */ graphicsQueuePriorities, }, }; uint32_t enabledDeviceExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size()); VkDeviceCreateInfo deviceCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, /* .pNext = */ nullptr, /* .flags = */ 0, /* .queueCreateInfoCount = */ kQueueCreateInfoCount, /* .pQueueCreateInfos = */ queueCreateInfos, /* .enabledLayerCount = */ 0, /* .ppEnabledLayerNames = */ nullptr, /* .enabledExtensionCount = */ enabledDeviceExtensionCount, /* .ppEnabledExtensionName = */ enabledDeviceExtensions.data(), /* .pEnabledFeatures = */ nullptr, }; result = vkCreateDevice(mPhysicalDevice, &deviceCreateInfo, nullptr, &mDevice); ASSERT(result == VK_SUCCESS); ASSERT(mDevice != VK_NULL_HANDLE); #if ANGLE_SHARED_LIBVULKAN volkLoadDevice(mDevice); #endif // ANGLE_SHARED_LIBVULKAN constexpr uint32_t kGraphicsQueueIndex = 0; static_assert(kGraphicsQueueIndex < kGraphicsQueueCount, "must be in range"); vkGetDeviceQueue(mDevice, mGraphicsQueueFamilyIndex, kGraphicsQueueIndex, &mGraphicsQueue); ASSERT(mGraphicsQueue != VK_NULL_HANDLE); VkCommandPoolCreateInfo commandPoolCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, /* .pNext = */ nullptr, /* .flags = */ 0, /* .queueFamilyIndex = */ mGraphicsQueueFamilyIndex, }; result = vkCreateCommandPool(mDevice, &commandPoolCreateInfo, nullptr, &mCommandPool); ASSERT(result == VK_SUCCESS); mHasExternalMemoryFd = HasExtension(enabledDeviceExtensions, VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME); mHasExternalSemaphoreFd = HasExtension(enabledDeviceExtensions, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME); mHasExternalMemoryFuchsia = HasExtension(enabledDeviceExtensions, VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME); mHasExternalSemaphoreFuchsia = HasExtension(enabledDeviceExtensions, VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME); vkGetPhysicalDeviceImageFormatProperties2 = reinterpret_cast<PFN_vkGetPhysicalDeviceImageFormatProperties2>( vkGetInstanceProcAddr(mInstance, "vkGetPhysicalDeviceImageFormatProperties2")); vkGetMemoryFdKHR = reinterpret_cast<PFN_vkGetMemoryFdKHR>( vkGetInstanceProcAddr(mInstance, "vkGetMemoryFdKHR")); ASSERT(!mHasExternalMemoryFd || vkGetMemoryFdKHR); vkGetSemaphoreFdKHR = reinterpret_cast<PFN_vkGetSemaphoreFdKHR>( vkGetInstanceProcAddr(mInstance, "vkGetSemaphoreFdKHR")); ASSERT(!mHasExternalSemaphoreFd || vkGetSemaphoreFdKHR); vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = reinterpret_cast<PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR>( vkGetInstanceProcAddr(mInstance, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR")); vkGetMemoryZirconHandleFUCHSIA = reinterpret_cast<PFN_vkGetMemoryZirconHandleFUCHSIA>( vkGetInstanceProcAddr(mInstance, "vkGetMemoryZirconHandleFUCHSIA")); ASSERT(!mHasExternalMemoryFuchsia || vkGetMemoryZirconHandleFUCHSIA); vkGetSemaphoreZirconHandleFUCHSIA = reinterpret_cast<PFN_vkGetSemaphoreZirconHandleFUCHSIA>( vkGetInstanceProcAddr(mInstance, "vkGetSemaphoreZirconHandleFUCHSIA")); ASSERT(!mHasExternalSemaphoreFuchsia || vkGetSemaphoreZirconHandleFUCHSIA); } bool VulkanExternalHelper::canCreateImageExternal( VkFormat format, VkImageType type, VkImageTiling tiling, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags, VkExternalMemoryHandleTypeFlagBits handleType) const { VkPhysicalDeviceExternalImageFormatInfo externalImageFormatInfo = { /* .sType = */ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO, /* .pNext = */ nullptr, /* .handleType = */ handleType, }; VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = { /* .sType = */ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, /* .pNext = */ &externalImageFormatInfo, /* .format = */ format, /* .type = */ type, /* .tiling = */ tiling, /* .usage = */ usageFlags, /* .flags = */ createFlags, }; VkExternalImageFormatProperties externalImageFormatProperties = { /* .sType = */ VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES, /* .pNext = */ nullptr, }; VkImageFormatProperties2 imageFormatProperties = { /* .sType = */ VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, /* .pNext = */ &externalImageFormatProperties}; VkResult result = vkGetPhysicalDeviceImageFormatProperties2(mPhysicalDevice, &imageFormatInfo, &imageFormatProperties); if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) { return false; } ASSERT(result == VK_SUCCESS); constexpr VkExternalMemoryFeatureFlags kRequiredFeatures = VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT | VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT; if ((externalImageFormatProperties.externalMemoryProperties.externalMemoryFeatures & kRequiredFeatures) != kRequiredFeatures) { return false; } return true; } VkResult VulkanExternalHelper::createImage2DExternal(VkFormat format, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags, VkExtent3D extent, VkExternalMemoryHandleTypeFlags handleTypes, VkImage *imageOut, VkDeviceMemory *deviceMemoryOut, VkDeviceSize *deviceMemorySizeOut) { VkExternalMemoryImageCreateInfoKHR externalMemoryImageCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, /* .pNext = */ nullptr, /* .handleTypes = */ handleTypes, }; VkImageCreateInfo imageCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* .pNext = */ &externalMemoryImageCreateInfo, /* .flags = */ createFlags, /* .imageType = */ VK_IMAGE_TYPE_2D, /* .format = */ format, /* .extent = */ extent, /* .mipLevels = */ 1, /* .arrayLayers = */ 1, /* .samples = */ VK_SAMPLE_COUNT_1_BIT, /* .tiling = */ VK_IMAGE_TILING_OPTIMAL, /* .usage = */ usageFlags, /* .sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* .queueFamilyIndexCount = */ 0, /* .pQueueFamilyIndices = */ nullptr, /* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED, }; VkImage image = VK_NULL_HANDLE; VkResult result = vkCreateImage(mDevice, &imageCreateInfo, nullptr, &image); if (result != VK_SUCCESS) { return result; } VkMemoryPropertyFlags requestedMemoryPropertyFlags = 0; VkMemoryRequirements memoryRequirements; vkGetImageMemoryRequirements(mDevice, image, &memoryRequirements); uint32_t memoryTypeIndex = FindMemoryType(mMemoryProperties, memoryRequirements.memoryTypeBits, requestedMemoryPropertyFlags); ASSERT(memoryTypeIndex != UINT32_MAX); VkDeviceSize deviceMemorySize = memoryRequirements.size; VkExportMemoryAllocateInfo exportMemoryAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO, /* .pNext = */ nullptr, /* .handleTypes = */ handleTypes, }; VkMemoryDedicatedAllocateInfoKHR memoryDedicatedAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, /* .pNext = */ &exportMemoryAllocateInfo, /* .image = */ image, }; VkMemoryAllocateInfo memoryAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, /* .pNext = */ &memoryDedicatedAllocateInfo, /* .allocationSize = */ deviceMemorySize, /* .memoryTypeIndex = */ memoryTypeIndex, }; VkDeviceMemory deviceMemory = VK_NULL_HANDLE; result = vkAllocateMemory(mDevice, &memoryAllocateInfo, nullptr, &deviceMemory); if (result != VK_SUCCESS) { vkDestroyImage(mDevice, image, nullptr); return result; } VkDeviceSize memoryOffset = 0; result = vkBindImageMemory(mDevice, image, deviceMemory, memoryOffset); if (result != VK_SUCCESS) { vkFreeMemory(mDevice, deviceMemory, nullptr); vkDestroyImage(mDevice, image, nullptr); return result; } *imageOut = image; *deviceMemoryOut = deviceMemory; *deviceMemorySizeOut = deviceMemorySize; return VK_SUCCESS; } bool VulkanExternalHelper::canCreateImageOpaqueFd(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags) const { if (!mHasExternalMemoryFd) { return false; } return canCreateImageExternal(format, type, tiling, createFlags, usageFlags, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT); } VkResult VulkanExternalHelper::createImage2DOpaqueFd(VkFormat format, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags, VkExtent3D extent, VkImage *imageOut, VkDeviceMemory *deviceMemoryOut, VkDeviceSize *deviceMemorySizeOut) { return createImage2DExternal(format, createFlags, usageFlags, extent, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, imageOut, deviceMemoryOut, deviceMemorySizeOut); } VkResult VulkanExternalHelper::exportMemoryOpaqueFd(VkDeviceMemory deviceMemory, int *fd) { VkMemoryGetFdInfoKHR memoryGetFdInfo = { /* .sType = */ VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, /* .pNext = */ nullptr, /* .memory = */ deviceMemory, /* .handleType = */ VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, }; return vkGetMemoryFdKHR(mDevice, &memoryGetFdInfo, fd); } bool VulkanExternalHelper::canCreateImageZirconVmo(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags) const { if (!mHasExternalMemoryFuchsia) { return false; } return canCreateImageExternal(format, type, tiling, createFlags, usageFlags, VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA); } VkResult VulkanExternalHelper::createImage2DZirconVmo(VkFormat format, VkImageCreateFlags createFlags, VkImageUsageFlags usageFlags, VkExtent3D extent, VkImage *imageOut, VkDeviceMemory *deviceMemoryOut, VkDeviceSize *deviceMemorySizeOut) { return createImage2DExternal(format, createFlags, usageFlags, extent, VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA, imageOut, deviceMemoryOut, deviceMemorySizeOut); } VkResult VulkanExternalHelper::exportMemoryZirconVmo(VkDeviceMemory deviceMemory, zx_handle_t *vmo) { VkMemoryGetZirconHandleInfoFUCHSIA memoryGetZirconHandleInfo = { /* .sType = */ VK_STRUCTURE_TYPE_TEMP_MEMORY_GET_ZIRCON_HANDLE_INFO_FUCHSIA, /* .pNext = */ nullptr, /* .memory = */ deviceMemory, /* .handleType = */ VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA, }; return vkGetMemoryZirconHandleFUCHSIA(mDevice, &memoryGetZirconHandleInfo, vmo); } bool VulkanExternalHelper::canCreateSemaphoreOpaqueFd() const { if (!mHasExternalSemaphoreFd || !vkGetPhysicalDeviceExternalSemaphorePropertiesKHR) { return false; } VkPhysicalDeviceExternalSemaphoreInfo externalSemaphoreInfo = { /* .sType = */ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, /* .pNext = */ nullptr, /* .handleType = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, }; VkExternalSemaphoreProperties externalSemaphoreProperties = { /* .sType = */ VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, }; vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(mPhysicalDevice, &externalSemaphoreInfo, &externalSemaphoreProperties); constexpr VkExternalSemaphoreFeatureFlags kRequiredFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT | VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT; if ((externalSemaphoreProperties.externalSemaphoreFeatures & kRequiredFeatures) != kRequiredFeatures) { return false; } return true; } VkResult VulkanExternalHelper::createSemaphoreOpaqueFd(VkSemaphore *semaphore) { VkExportSemaphoreCreateInfo exportSemaphoreCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, /* .pNext = */ nullptr, /* .handleTypes = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, }; VkSemaphoreCreateInfo semaphoreCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, /* .pNext = */ &exportSemaphoreCreateInfo, /* .flags = */ 0, }; return vkCreateSemaphore(mDevice, &semaphoreCreateInfo, nullptr, semaphore); } VkResult VulkanExternalHelper::exportSemaphoreOpaqueFd(VkSemaphore semaphore, int *fd) { VkSemaphoreGetFdInfoKHR semaphoreGetFdInfo = { /* .sType = */ VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, /* .pNext = */ nullptr, /* .semaphore = */ semaphore, /* .handleType = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, }; return vkGetSemaphoreFdKHR(mDevice, &semaphoreGetFdInfo, fd); } bool VulkanExternalHelper::canCreateSemaphoreZirconEvent() const { if (!mHasExternalSemaphoreFuchsia || !vkGetPhysicalDeviceExternalSemaphorePropertiesKHR) { return false; } VkPhysicalDeviceExternalSemaphoreInfo externalSemaphoreInfo = { /* .sType = */ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, /* .pNext = */ nullptr, /* .handleType = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA, }; VkExternalSemaphoreProperties externalSemaphoreProperties = { /* .sType = */ VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, }; vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(mPhysicalDevice, &externalSemaphoreInfo, &externalSemaphoreProperties); constexpr VkExternalSemaphoreFeatureFlags kRequiredFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT | VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT; if ((externalSemaphoreProperties.externalSemaphoreFeatures & kRequiredFeatures) != kRequiredFeatures) { return false; } return true; } VkResult VulkanExternalHelper::createSemaphoreZirconEvent(VkSemaphore *semaphore) { VkExportSemaphoreCreateInfo exportSemaphoreCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, /* .pNext = */ nullptr, /* .handleTypes = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA, }; VkSemaphoreCreateInfo semaphoreCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, /* .pNext = */ &exportSemaphoreCreateInfo, /* .flags = */ 0, }; return vkCreateSemaphore(mDevice, &semaphoreCreateInfo, nullptr, semaphore); } VkResult VulkanExternalHelper::exportSemaphoreZirconEvent(VkSemaphore semaphore, zx_handle_t *event) { VkSemaphoreGetZirconHandleInfoFUCHSIA semaphoreGetZirconHandleInfo = { /* .sType = */ VK_STRUCTURE_TYPE_TEMP_SEMAPHORE_GET_ZIRCON_HANDLE_INFO_FUCHSIA, /* .pNext = */ nullptr, /* .semaphore = */ semaphore, /* .handleType = */ VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TEMP_ZIRCON_EVENT_BIT_FUCHSIA, }; return vkGetSemaphoreZirconHandleFUCHSIA(mDevice, &semaphoreGetZirconHandleInfo, event); } void VulkanExternalHelper::releaseImageAndSignalSemaphore(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkSemaphore semaphore) { VkResult result; VkCommandBuffer commandBuffers[] = {VK_NULL_HANDLE}; constexpr uint32_t commandBufferCount = std::extent<decltype(commandBuffers)>(); VkCommandBufferAllocateInfo commandBufferAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, /* .pNext = */ nullptr, /* .commandPool = */ mCommandPool, /* .level = */ VK_COMMAND_BUFFER_LEVEL_PRIMARY, /* .commandBufferCount = */ commandBufferCount, }; result = vkAllocateCommandBuffers(mDevice, &commandBufferAllocateInfo, commandBuffers); ASSERT(result == VK_SUCCESS); VkCommandBufferBeginInfo commandBufferBeginInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, /* .pNext = */ nullptr, /* .flags = */ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, /* .pInheritanceInfo = */ nullptr, }; result = vkBeginCommandBuffer(commandBuffers[0], &commandBufferBeginInfo); ASSERT(result == VK_SUCCESS); ImageMemoryBarrier(commandBuffers[0], image, mGraphicsQueueFamilyIndex, VK_QUEUE_FAMILY_EXTERNAL, oldLayout, newLayout); result = vkEndCommandBuffer(commandBuffers[0]); ASSERT(result == VK_SUCCESS); const VkSemaphore signalSemaphores[] = { semaphore, }; constexpr uint32_t signalSemaphoreCount = std::extent<decltype(signalSemaphores)>(); const VkSubmitInfo submits[] = { /* [0] = */ { /* .sType */ VK_STRUCTURE_TYPE_SUBMIT_INFO, /* .pNext = */ nullptr, /* .waitSemaphoreCount = */ 0, /* .pWaitSemaphores = */ nullptr, /* .pWaitDstStageMask = */ nullptr, /* .commandBufferCount = */ commandBufferCount, /* .pCommandBuffers = */ commandBuffers, /* .signalSemaphoreCount = */ signalSemaphoreCount, /* .pSignalSemaphores = */ signalSemaphores, }, }; constexpr uint32_t submitCount = std::extent<decltype(submits)>(); const VkFence fence = VK_NULL_HANDLE; result = vkQueueSubmit(mGraphicsQueue, submitCount, submits, fence); ASSERT(result == VK_SUCCESS); } void VulkanExternalHelper::waitSemaphoreAndAcquireImage(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkSemaphore semaphore) { VkResult result; VkCommandBuffer commandBuffers[] = {VK_NULL_HANDLE}; constexpr uint32_t commandBufferCount = std::extent<decltype(commandBuffers)>(); VkCommandBufferAllocateInfo commandBufferAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, /* .pNext = */ nullptr, /* .commandPool = */ mCommandPool, /* .level = */ VK_COMMAND_BUFFER_LEVEL_PRIMARY, /* .commandBufferCount = */ commandBufferCount, }; result = vkAllocateCommandBuffers(mDevice, &commandBufferAllocateInfo, commandBuffers); ASSERT(result == VK_SUCCESS); VkCommandBufferBeginInfo commandBufferBeginInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, /* .pNext = */ nullptr, /* .flags = */ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, /* .pInheritanceInfo = */ nullptr, }; result = vkBeginCommandBuffer(commandBuffers[0], &commandBufferBeginInfo); ASSERT(result == VK_SUCCESS); ImageMemoryBarrier(commandBuffers[0], image, VK_QUEUE_FAMILY_EXTERNAL, mGraphicsQueueFamilyIndex, oldLayout, newLayout); result = vkEndCommandBuffer(commandBuffers[0]); ASSERT(result == VK_SUCCESS); const VkSemaphore waitSemaphores[] = { semaphore, }; const VkPipelineStageFlags waitDstStageMasks[] = { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, }; constexpr uint32_t waitSemaphoreCount = std::extent<decltype(waitSemaphores)>(); constexpr uint32_t waitDstStageMaskCount = std::extent<decltype(waitDstStageMasks)>(); static_assert(waitSemaphoreCount == waitDstStageMaskCount, "waitSemaphores and waitDstStageMasks must be the same length"); const VkSubmitInfo submits[] = { /* [0] = */ { /* .sType */ VK_STRUCTURE_TYPE_SUBMIT_INFO, /* .pNext = */ nullptr, /* .waitSemaphoreCount = */ waitSemaphoreCount, /* .pWaitSemaphores = */ waitSemaphores, /* .pWaitDstStageMask = */ waitDstStageMasks, /* .commandBufferCount = */ commandBufferCount, /* .pCommandBuffers = */ commandBuffers, /* .signalSemaphoreCount = */ 0, /* .pSignalSemaphores = */ nullptr, }, }; constexpr uint32_t submitCount = std::extent<decltype(submits)>(); const VkFence fence = VK_NULL_HANDLE; result = vkQueueSubmit(mGraphicsQueue, submitCount, submits, fence); ASSERT(result == VK_SUCCESS); } void VulkanExternalHelper::readPixels(VkImage srcImage, VkImageLayout srcImageLayout, VkFormat srcImageFormat, VkOffset3D imageOffset, VkExtent3D imageExtent, void *pixels, size_t pixelsSize) { ASSERT(srcImageFormat == VK_FORMAT_B8G8R8A8_UNORM || srcImageFormat == VK_FORMAT_R8G8B8A8_UNORM); ASSERT(imageExtent.depth == 1); ASSERT(pixelsSize == 4 * imageExtent.width * imageExtent.height); VkBufferCreateInfo bufferCreateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, /* .pNext = */ nullptr, /* .flags = */ 0, /* .size = */ pixelsSize, /* .usage = */ VK_BUFFER_USAGE_TRANSFER_DST_BIT, /* .sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* .queueFamilyIndexCount = */ 0, /* .pQueueFamilyIndices = */ nullptr, }; VkBuffer stagingBuffer = VK_NULL_HANDLE; VkResult result = vkCreateBuffer(mDevice, &bufferCreateInfo, nullptr, &stagingBuffer); ASSERT(result == VK_SUCCESS); VkMemoryPropertyFlags requestedMemoryPropertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(mDevice, stagingBuffer, &memoryRequirements); uint32_t memoryTypeIndex = FindMemoryType(mMemoryProperties, memoryRequirements.memoryTypeBits, requestedMemoryPropertyFlags); ASSERT(memoryTypeIndex != UINT32_MAX); VkDeviceSize deviceMemorySize = memoryRequirements.size; VkMemoryDedicatedAllocateInfoKHR memoryDedicatedAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, /* .pNext = */ nullptr, /* .image = */ VK_NULL_HANDLE, /* .buffer = */ stagingBuffer, }; VkMemoryAllocateInfo memoryAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, /* .pNext = */ &memoryDedicatedAllocateInfo, /* .allocationSize = */ deviceMemorySize, /* .memoryTypeIndex = */ memoryTypeIndex, }; VkDeviceMemory deviceMemory = VK_NULL_HANDLE; result = vkAllocateMemory(mDevice, &memoryAllocateInfo, nullptr, &deviceMemory); ASSERT(result == VK_SUCCESS); result = vkBindBufferMemory(mDevice, stagingBuffer, deviceMemory, 0 /* memoryOffset */); ASSERT(result == VK_SUCCESS); VkCommandBuffer commandBuffers[] = {VK_NULL_HANDLE}; constexpr uint32_t commandBufferCount = std::extent<decltype(commandBuffers)>(); VkCommandBufferAllocateInfo commandBufferAllocateInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, /* .pNext = */ nullptr, /* .commandPool = */ mCommandPool, /* .level = */ VK_COMMAND_BUFFER_LEVEL_PRIMARY, /* .commandBufferCount = */ commandBufferCount, }; result = vkAllocateCommandBuffers(mDevice, &commandBufferAllocateInfo, commandBuffers); ASSERT(result == VK_SUCCESS); VkCommandBufferBeginInfo commandBufferBeginInfo = { /* .sType = */ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, /* .pNext = */ nullptr, /* .flags = */ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, /* .pInheritanceInfo = */ nullptr, }; result = vkBeginCommandBuffer(commandBuffers[0], &commandBufferBeginInfo); ASSERT(result == VK_SUCCESS); VkBufferImageCopy bufferImageCopies[] = { /* [0] = */ { /* .bufferOffset = */ 0, /* .bufferRowLength = */ 0, /* .bufferImageHeight = */ 0, /* .imageSubresources = */ { /* .aspectMask = */ VK_IMAGE_ASPECT_COLOR_BIT, /* .mipLevel = */ 0, /* .baseArrayLayer = */ 0, /* .layerCount = */ 1, }, /* .imageOffset = */ imageOffset, /* .imageExtent = */ imageExtent, }, }; constexpr uint32_t bufferImageCopyCount = std::extent<decltype(bufferImageCopies)>(); vkCmdCopyImageToBuffer(commandBuffers[0], srcImage, srcImageLayout, stagingBuffer, bufferImageCopyCount, bufferImageCopies); VkMemoryBarrier memoryBarriers[] = { /* [0] = */ {/* .sType = */ VK_STRUCTURE_TYPE_MEMORY_BARRIER, /* .pNext = */ nullptr, /* .srcAccessMask = */ VK_ACCESS_MEMORY_WRITE_BIT, /* .dstAccessMask = */ VK_ACCESS_HOST_READ_BIT}, }; constexpr uint32_t memoryBarrierCount = std::extent<decltype(memoryBarriers)>(); vkCmdPipelineBarrier(commandBuffers[0], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0 /* dependencyFlags */, memoryBarrierCount, memoryBarriers, 0, nullptr, 0, nullptr); result = vkEndCommandBuffer(commandBuffers[0]); ASSERT(result == VK_SUCCESS); const VkSubmitInfo submits[] = { /* [0] = */ { /* .sType */ VK_STRUCTURE_TYPE_SUBMIT_INFO, /* .pNext = */ nullptr, /* .waitSemaphoreCount = */ 0, /* .pWaitSemaphores = */ nullptr, /* .pWaitDstStageMask = */ nullptr, /* .commandBufferCount = */ commandBufferCount, /* .pCommandBuffers = */ commandBuffers, /* .signalSemaphoreCount = */ 0, /* .pSignalSemaphores = */ nullptr, }, }; constexpr uint32_t submitCount = std::extent<decltype(submits)>(); const VkFence fence = VK_NULL_HANDLE; result = vkQueueSubmit(mGraphicsQueue, submitCount, submits, fence); ASSERT(result == VK_SUCCESS); result = vkQueueWaitIdle(mGraphicsQueue); ASSERT(result == VK_SUCCESS); vkFreeCommandBuffers(mDevice, mCommandPool, commandBufferCount, commandBuffers); void *stagingMemory = nullptr; result = vkMapMemory(mDevice, deviceMemory, 0 /* offset */, pixelsSize, 0 /* flags */, &stagingMemory); ASSERT(result == VK_SUCCESS); VkMappedMemoryRange memoryRanges[] = { /* [0] = */ { /* .sType = */ VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, /* .pNext = */ nullptr, /* .memory = */ deviceMemory, /* .offset = */ 0, /* .size = */ pixelsSize, }, }; constexpr uint32_t memoryRangeCount = std::extent<decltype(memoryRanges)>(); result = vkInvalidateMappedMemoryRanges(mDevice, memoryRangeCount, memoryRanges); ASSERT(result == VK_SUCCESS); memcpy(pixels, stagingMemory, pixelsSize); vkUnmapMemory(mDevice, deviceMemory); vkFreeMemory(mDevice, deviceMemory, nullptr); vkDestroyBuffer(mDevice, stagingBuffer, nullptr); } } // namespace angle
40.59602
100
0.647835
[ "vector" ]
ed61030dac7f11250e408e0c5db1ddf620075362
2,679
cpp
C++
Base/Resources/CliffMesh.cpp
JARVIS-AI/HiveWE
c0a2a2e863d3fb901497e8038d689e30b411df40
[ "MIT" ]
null
null
null
Base/Resources/CliffMesh.cpp
JARVIS-AI/HiveWE
c0a2a2e863d3fb901497e8038d689e30b411df40
[ "MIT" ]
null
null
null
Base/Resources/CliffMesh.cpp
JARVIS-AI/HiveWE
c0a2a2e863d3fb901497e8038d689e30b411df40
[ "MIT" ]
null
null
null
#include "CliffMesh.h" #include <QOpenGLFunctions_4_5_Core> #include "Utilities.h" #include "BinaryReader.h" #include "MDX.h" #include "Hierarchy.h" CliffMesh::CliffMesh(const fs::path& path) { if (path.extension() == ".mdx" || path.extension() == ".MDX") { auto reader = BinaryReader(hierarchy.open_file(path)); mdx::MDX model = mdx::MDX(reader); auto set = model.geosets.front(); gl->glCreateBuffers(1, &vertex_buffer); gl->glNamedBufferData(vertex_buffer, set.vertices.size() * sizeof(glm::vec3), set.vertices.data(), GL_STATIC_DRAW); gl->glCreateBuffers(1, &uv_buffer); gl->glNamedBufferData(uv_buffer, set.texture_coordinate_sets.front().size() * sizeof(glm::vec2), set.texture_coordinate_sets.front().data(), GL_STATIC_DRAW); gl->glCreateBuffers(1, &normal_buffer); gl->glNamedBufferData(normal_buffer, set.normals.size() * sizeof(glm::vec3), set.normals.data(), GL_STATIC_DRAW); gl->glCreateBuffers(1, &instance_buffer); indices = set.faces.size(); gl->glCreateBuffers(1, &index_buffer); gl->glNamedBufferData(index_buffer, set.faces.size() * sizeof(uint16_t), set.faces.data(), GL_STATIC_DRAW); } } CliffMesh::~CliffMesh() { gl->glDeleteBuffers(1, &vertex_buffer); gl->glDeleteBuffers(1, &uv_buffer); gl->glDeleteBuffers(1, &normal_buffer); gl->glDeleteBuffers(1, &instance_buffer); gl->glDeleteBuffers(1, &index_buffer); } void CliffMesh::render_queue(const glm::vec4 position) { render_jobs.push_back(position); } void CliffMesh::render() { if (render_jobs.empty()) { return; } gl->glNamedBufferData(instance_buffer, render_jobs.size() * sizeof(glm::vec4), render_jobs.data(), GL_STATIC_DRAW); gl->glEnableVertexAttribArray(0); gl->glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); gl->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); gl->glEnableVertexAttribArray(1); gl->glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); gl->glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); gl->glEnableVertexAttribArray(2); gl->glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); gl->glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); gl->glEnableVertexAttribArray(3); gl->glBindBuffer(GL_ARRAY_BUFFER, instance_buffer); gl->glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 0, nullptr); gl->glVertexAttribDivisor(3, 1); gl->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); gl->glDrawElementsInstanced(GL_TRIANGLES, indices, GL_UNSIGNED_SHORT, nullptr, render_jobs.size()); gl->glVertexAttribDivisor(3, 0); // ToDo use vao gl->glDisableVertexAttribArray(0); gl->glDisableVertexAttribArray(1); gl->glDisableVertexAttribArray(2); gl->glDisableVertexAttribArray(3); render_jobs.clear(); }
33.4875
159
0.747294
[ "render", "model" ]
ed6273b9c17928fc3aab0a831b1bc6000880e29d
6,956
cpp
C++
src/RageUtil_BackgroundLoader.cpp
lunixbochs/stepmania-3.9
fe330c1b1857a9747f53571588ed3b2d4374c148
[ "Info-ZIP" ]
null
null
null
src/RageUtil_BackgroundLoader.cpp
lunixbochs/stepmania-3.9
fe330c1b1857a9747f53571588ed3b2d4374c148
[ "Info-ZIP" ]
null
null
null
src/RageUtil_BackgroundLoader.cpp
lunixbochs/stepmania-3.9
fe330c1b1857a9747f53571588ed3b2d4374c148
[ "Info-ZIP" ]
null
null
null
#include "global.h" #include "RageUtil_BackgroundLoader.h" #include "RageFile.h" #include "RageFileManager.h" #include "RageUtil.h" #include "RageLog.h" #include "RageThreads.h" /* If we're on an OS with a good caching system, writing to our own cache will only * waste memory. In that case, just read the file, to force it into system cache. * If we're on a system with an unreliable cache, read it into our own cache. This * helps in Windows, where even reading directory entries off of a CD--even if they've * just been read--can cause long delays if the disk is in use. */ static const bool g_bWriteToCache = true; static const bool g_bEnableBackgroundLoading = false; BackgroundLoader::BackgroundLoader(): m_StartSem( "BackgroundLoaderSem" ), m_Mutex( "BackgroundLoaderMutex" ) { if( !g_bEnableBackgroundLoading ) return; m_sCachePathPrefix = ssprintf( "@mem/%p", this ); m_bShutdownThread = false; m_sThreadIsActive = m_sThreadShouldAbort = false; m_LoadThread.SetName( "BackgroundLoader" ); m_LoadThread.Create( LoadThread_Start, this ); } static void DeleteEmptyDirectories( CString sDir ) { vector<CString> asNewDirs; GetDirListing( sDir + "/*", asNewDirs, false, true ); for( unsigned i = 0; i < asNewDirs.size(); ++i ) { ASSERT_M( IsADirectory(asNewDirs[i]), asNewDirs[i] ); DeleteEmptyDirectories( asNewDirs[i] ); } FILEMAN->Remove( sDir ); } BackgroundLoader::~BackgroundLoader() { if( !g_bEnableBackgroundLoading ) return; Abort(); m_bShutdownThread = true; m_StartSem.Post(); m_LoadThread.Wait(); /* Delete all leftover cached files. */ map<CString,int>::iterator it; for( it = m_FinishedRequests.begin(); it != m_FinishedRequests.end(); ++it ) FILEMAN->Remove( GetCachePath( it->first ) ); /* m_sCachePathPrefix should be filled with several empty directories. Delete * them and m_sCachePathPrefix, so we don't leak them. */ DeleteEmptyDirectories( m_sCachePathPrefix ); } /* Pull a request out of m_CacheRequests. */ CString BackgroundLoader::GetRequest() { if( !g_bEnableBackgroundLoading ) return ""; LockMut( m_Mutex ); if( !m_CacheRequests.size() ) return ""; CString ret; ret = m_CacheRequests.front(); m_CacheRequests.erase( m_CacheRequests.begin(), m_CacheRequests.begin()+1 ); return ret; } CString BackgroundLoader::GetCachePath( CString sPath ) const { return m_sCachePathPrefix + "/" + sPath; } void BackgroundLoader::LoadThread() { while( !m_bShutdownThread ) { /* Wait for a request. It's normal for this to wait for a long time; don't * fail on timeout. */ m_StartSem.Wait( false ); CString sFile = GetRequest(); if( sFile.empty() ) continue; { /* If the file already exists, short circuit. */ LockMut( m_Mutex ); map<CString,int>::iterator it; it = m_FinishedRequests.find( sFile ); if( it != m_FinishedRequests.end() ) { ++it->second; LOG->Trace("XXX: request %s done loading (already done), cnt now %i", sFile.c_str(), m_FinishedRequests[sFile] ); continue; } } m_sThreadIsActive = true; LOG->Trace("XXX: reading %s", sFile.c_str()); CString sCachePath = GetCachePath( sFile ); /* Open the file and read it. */ RageFile src; if( src.Open(sFile) ) { /* If we're writing to a file cache ... */ RageFile dst; bool bWriteToCache = g_bWriteToCache; if( bWriteToCache ) bWriteToCache = dst.Open( sCachePath, RageFile::WRITE ); LOG->Trace("XXX: go on '%s' to '%s'", sFile.c_str(), sCachePath.c_str()); char buf[1024*4]; while( !m_sThreadShouldAbort && !src.AtEOF() ) { int got = src.Read( buf, sizeof(buf) ); if( got > 0 && bWriteToCache ) dst.Write( buf, got ); } if( bWriteToCache ) dst.Close(); LOG->Trace("XXX: done"); } src.Close(); LockMut( m_Mutex ); if( !m_sThreadShouldAbort ) { ++m_FinishedRequests[sFile]; LOG->Trace("XXX: request %s done loading, cnt now %i", sFile.c_str(), m_FinishedRequests[sFile] ); } else { FILEMAN->Remove( sCachePath ); LOG->Trace("XXX: request %s aborted", sFile.c_str() ); } m_sThreadShouldAbort = false; m_sThreadIsActive = false; } } void BackgroundLoader::CacheFile( const CString &sFile ) { if( !g_bEnableBackgroundLoading ) return; LockMut( m_Mutex ); if( sFile == "" ) ++m_FinishedRequests[sFile]; else { m_CacheRequests.push_back( sFile ); m_StartSem.Post(); } } bool BackgroundLoader::IsCacheFileFinished( const CString &sFile, CString &sActualPath ) { if( !g_bEnableBackgroundLoading ) { sActualPath = sFile; return true; } LockMut( m_Mutex ); if( sFile == "" ) { sActualPath = ""; return true; } map<CString,int>::iterator it; it = m_FinishedRequests.find( sFile ); if( it == m_FinishedRequests.end() ) return false; LOG->Trace("XXX: %s finished (%i)", sFile.c_str(), it->second); sActualPath = GetCachePath( sFile ); return true; } void BackgroundLoader::FinishedWithCachedFile( const CString &sFile ) { if( !g_bEnableBackgroundLoading ) return; if( sFile == "" ) return; map<CString,int>::iterator it; it = m_FinishedRequests.find( sFile ); ASSERT_M( it != m_FinishedRequests.end(), sFile ); --it->second; ASSERT_M( it->second >= 0, ssprintf("%i", it->second) ); if( !it->second ) { m_FinishedRequests.erase( it ); FILEMAN->Remove( GetCachePath( sFile ) ); } } void BackgroundLoader::Abort() { if( !g_bEnableBackgroundLoading ) return; LockMut( m_Mutex ); /* Clear any pending requests. */ while( !GetRequest().empty() ) ; /* Tell the thread to abort any request it's handling now. */ if( m_sThreadIsActive ) m_sThreadShouldAbort = true; } /* * (c) 2004 Glenn Maynard * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
26.052434
117
0.69724
[ "vector" ]
ed65210b4bc844de067826da3bb3677c61e63a33
6,607
cpp
C++
IrrlichtExtensions/ChooseFromListDialog.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
null
null
null
IrrlichtExtensions/ChooseFromListDialog.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
1
2020-07-31T13:20:54.000Z
2020-08-06T15:45:39.000Z
IrrlichtExtensions/ChooseFromListDialog.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
null
null
null
#include <ChooseFromListDialog.h> #include <AggregateGUIElement.h> #include <AggregatableGUIElementAdapter.h> #include <timing.h> #include <IrrlichtDevice.h> #include <IVideoDriver.h> #include <IGUIEnvironment.h> #include <IGUIFont.h> #include <IGUIWindow.h> #include <IGUIStaticText.h> #include <IGUIButton.h> using namespace irr; using namespace video; using namespace gui; using namespace core; OutsideCancelWindow::OutsideCancelWindow(irr::gui::IGUIEnvironment* environment, irr::gui::IGUIWindow* win, irr::s32 id): IGUIWindow(environment, environment->getRootGUIElement(), id, rect<s32>(0,0,environment->getVideoDriver()->getScreenSize().Width,environment->getVideoDriver()->getScreenSize().Height)){ this->win = win; addChild(win); } irr::gui::IGUIButton* OutsideCancelWindow::getCloseButton() const{return win->getCloseButton();} irr::gui::IGUIButton* OutsideCancelWindow::getMinimizeButton() const{return win->getMinimizeButton();} irr::gui::IGUIButton* OutsideCancelWindow::getMaximizeButton() const{return win->getMaximizeButton();} bool OutsideCancelWindow::isDraggable() const{return win->isDraggable();} void OutsideCancelWindow::setDraggable(bool draggable){return win->setDraggable(draggable);} void OutsideCancelWindow::setDrawBackground(bool draw){return win->setDrawBackground(draw);} bool OutsideCancelWindow::getDrawBackground() const{return win->getDrawBackground();} void OutsideCancelWindow::setDrawTitlebar(bool draw){return win->setDrawTitlebar(draw);} bool OutsideCancelWindow::getDrawTitlebar() const{return win->getDrawTitlebar();} irr::core::rect<s32> OutsideCancelWindow::getClientRect() const{return win->getClientRect();} bool OutsideCancelWindow::OnEvent(const SEvent& event){ if(event.EventType==EET_MOUSE_INPUT_EVENT){ const SEvent::SMouseInput& m = event.MouseInput; if(m.Event==EMIE_LMOUSE_LEFT_UP){ vector2d<s32> mPos(m.X, m.Y); if(!win->getAbsolutePosition().isPointInside(mPos)){ SEvent toPost; toPost.EventType = EET_GUI_EVENT; toPost.GUIEvent.Caller = this; toPost.GUIEvent.Element = NULL; toPost.GUIEvent.EventType = EGET_MESSAGEBOX_NO; Parent->OnEvent(toPost); remove(); drop(); return true; } } } return IGUIWindow::OnEvent(event); } irr::gui::IGUIWindow* createChooseFromListDialog(irr::IrrlichtDevice* device, std::vector<irr::gui::IGUIButton*>& buttonsOut, const std::vector<int32_t>& buttonIds, const std::vector<std::wstring>& buttonLabels, const std::wstring& headline, int32_t aggregationId, int32_t aggregatableId, bool modal, bool cancelByClickOutside){ IVideoDriver* driver = device->getVideoDriver(); IGUIEnvironment* env = device->getGUIEnvironment(); dimension2d<u32> dim = driver->getScreenSize(); u32 w = dim.Width, h = dim.Height; double sqrtArea = sqrt(w*h); int32_t buttonHeight = (int32_t)(0.0625*0.79057*sqrtArea+.5); s32 padding = (s32)(.01*sqrtArea+.5); IGUIFont* font = env->getSkin()->getFont(); u32 sizeW = 4*padding+font->getDimension(headline.c_str()).Width; for(uint32_t i=0; i<buttonLabels.size(); i++){ u32 reqSizeW = 4*padding+font->getDimension(buttonLabels[i].c_str()).Width; if(reqSizeW>sizeW){sizeW = reqSizeW;} } u32 sizeH = 3*padding+1.2*buttonHeight+(buttonLabels.size()*1.2*buttonHeight); IGUIWindow* win = env->addWindow(rect<s32>(w/2-sizeW/2, h/2-sizeH/2, w/2+sizeW/2, h/2+sizeH/2), modal); win->getCloseButton()->setVisible(false); win->setDraggable(false); win->setDrawTitlebar(false); IGUIStaticText* headlineEle = env->addStaticText(headline.c_str(), rect<s32>(padding,padding,sizeW-padding,padding+buttonHeight), false, false, win); headlineEle->setTextAlignment(EGUIA_CENTER, EGUIA_CENTER); rect<s32> content(padding, 2*padding+buttonHeight, sizeW-padding, sizeH-padding); f32 lineYPart = ((f32)buttonHeight)/(f32)content.getHeight(); AggregateGUIElement* buttonList = new AggregateGUIElement(env, 1.f, 1.f, 1.f, 1.f, false, false, true, {}, {}, false, aggregationId, NULL, win, content); buttonList->addSubElement(new EmptyGUIElement(env, .2f*lineYPart, 1.f/1.f, false, false, aggregatableId)); buttonsOut.resize(buttonLabels.size()); for(uint32_t i=0; i<buttonLabels.size(); i++){ buttonsOut[i] = env->addButton(rect<s32>(0,0,0,0), NULL, buttonIds[i], buttonLabels[i].c_str()); buttonList->addSubElement(new AggregatableGUIElementAdapter(env, lineYPart, 4.f/1.f, false, buttonsOut[i], false, aggregatableId)); buttonList->addSubElement(new EmptyGUIElement(env, .2f*lineYPart, 1.f/1.f, false, false, aggregatableId)); } if(cancelByClickOutside){ win = new OutsideCancelWindow(env, win); } return win; } class ChooseFromListEventReceiver : public irr::IEventReceiver{ public: uint32_t res; bool running; std::vector<irr::gui::IGUIButton*> buttons; ChooseFromListEventReceiver():res(0),running(true){} bool OnEvent(const SEvent& event){ if(event.EventType==EET_GUI_EVENT){ const SEvent::SGUIEvent& g = event.GUIEvent; if(g.EventType==EGET_BUTTON_CLICKED){ for(uint32_t i=0; i<buttons.size(); i++){ if(g.Caller==buttons[i]){ res = i; running = false; break; } } } } return false; } }; uint32_t startChooseFromListDialog(irr::IrrlichtDevice* device, const std::vector<int32_t>& buttonIds, const std::vector<std::wstring>& buttonLabels, const std::wstring& headline, int32_t aggregationId, int32_t aggregatableId, irr::video::SColor bgColor, bool modal){ IVideoDriver* driver = device->getVideoDriver(); IGUIEnvironment* env = device->getGUIEnvironment(); IEventReceiver* oldrcv = device->getEventReceiver(); ChooseFromListEventReceiver rcv; device->setEventReceiver(&rcv); irr::core::dimension2d<irr::u32> screenSize = driver->getScreenSize(); double screenChangeTime = getSecs(); bool screenChanged = false; irr::gui::IGUIWindow* win = createChooseFromListDialog(device, rcv.buttons, buttonIds, buttonLabels, headline, aggregationId, aggregatableId, modal); win->getParent()->sendToBack(win); while(device->run() && rcv.running){ driver->beginScene(true, true, bgColor); env->drawAll(); driver->endScene(); device->yield(); if(screenChanged && getSecs()-screenChangeTime>.33){ win->remove(); win = createChooseFromListDialog(device, rcv.buttons, buttonIds, buttonLabels, headline, aggregationId, aggregatableId, modal); win->getParent()->sendToBack(win); screenChanged = false; } if(driver->getScreenSize()!=screenSize){ screenSize = driver->getScreenSize(); screenChanged = true; screenChangeTime = getSecs(); } } win->remove(); device->setEventReceiver(oldrcv); return rcv.res; }
40.286585
328
0.742243
[ "vector" ]
ed68f2584e0274febbcab75e7829528bd6650695
1,578
cc
C++
api/audio_codecs/opus_audio_decoder_factory.cc
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
344
2016-07-03T11:45:20.000Z
2022-03-19T16:54:10.000Z
api/audio_codecs/opus_audio_decoder_factory.cc
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
59
2020-08-24T09:17:42.000Z
2022-02-27T23:33:37.000Z
api/audio_codecs/opus_audio_decoder_factory.cc
gaoxiaoyang/webrtc
21021f022be36f5d04f8a3a309e345f65c8603a9
[ "BSD-3-Clause" ]
278
2016-04-26T07:37:12.000Z
2022-01-24T10:09:44.000Z
/* * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "api/audio_codecs/opus_audio_decoder_factory.h" #include <memory> #include <vector> #include "api/audio_codecs/audio_decoder_factory_template.h" #include "api/audio_codecs/opus/audio_decoder_multi_channel_opus.h" #include "api/audio_codecs/opus/audio_decoder_opus.h" namespace webrtc { namespace { // Modify an audio decoder to not advertise support for anything. template <typename T> struct NotAdvertised { using Config = typename T::Config; static absl::optional<Config> SdpToConfig( const SdpAudioFormat& audio_format) { return T::SdpToConfig(audio_format); } static void AppendSupportedDecoders(std::vector<AudioCodecSpec>* specs) { // Don't advertise support for anything. } static std::unique_ptr<AudioDecoder> MakeAudioDecoder( const Config& config, absl::optional<AudioCodecPairId> codec_pair_id = absl::nullopt) { return T::MakeAudioDecoder(config, codec_pair_id); } }; } // namespace rtc::scoped_refptr<AudioDecoderFactory> CreateOpusAudioDecoderFactory() { return CreateAudioDecoderFactory< AudioDecoderOpus, NotAdvertised<AudioDecoderMultiChannelOpus>>(); } } // namespace webrtc
31.56
75
0.757288
[ "vector" ]
ed6a888eaffdd18cbd9bad69ff0b5758e77b5cc4
5,271
hh
C++
c/testsrc/test_typestest/bakery.hh
orangeturtle739/tako
d14fb9827f8a09c0847989b64a4d60914d10db40
[ "Apache-2.0" ]
null
null
null
c/testsrc/test_typestest/bakery.hh
orangeturtle739/tako
d14fb9827f8a09c0847989b64a4d60914d10db40
[ "Apache-2.0" ]
null
null
null
c/testsrc/test_typestest/bakery.hh
orangeturtle739/tako
d14fb9827f8a09c0847989b64a4d60914d10db40
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Jacob Glueck // // 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 "test_types/bakery.hh" #include "test_types/bakery/v1.hh" #include "test_types/bakery/v2.hh" #include "test_types/bakery/v3.hh" #include "test_types/bakery/v4.hh" using namespace test_types::bakery; namespace v1 = test_types::bakery::v1; namespace v2 = test_types::bakery::v2; namespace v3 = test_types::bakery::v3; namespace v4 = test_types::bakery::v4; namespace latest = v4; using namespace std; // ===================================================== // BAKERY // Operates on only the latest version uint8_t flavor_id(const latest::Flavor& flavor) { if (flavor == latest::Flavor::VANILLA) { return 0; } if (flavor == latest::Flavor::CHOCOLATE) { return 63; } if (flavor == latest::Flavor::CARMEL) { return 94; } throw std::domain_error("input had illegal value"); } latest::Message process_latest(const latest::MessageView& msg) { return latest::Message { .msg = msg.msg().match( [&](const latest::ErrorResponseView&) -> latest::MessageVariant { return latest::ErrorResponse{}; }, [&](const latest::NewOrderRequestView& new_order_request) -> latest::MessageVariant { uint64_t order_id = new_order_request.order().match( [&](const latest::CupcakeOrderView& order) -> uint64_t { // Very clever order ID system -- it works as long as you don't get // the same order twice uint64_t temp = static_cast<uint32_t>(order.quantity()); temp |= static_cast<uint64_t>(flavor_id(order.flavor())) << 32; temp |= static_cast<uint64_t>(flavor_id(order.frosting_flavor())) << 40; return temp; }, [&](const latest::CakeOrderView&) -> uint64_t { return 42; } ); return latest::NewOrderResponse{.order_id = order_id}; }, [&](const latest::NewOrderResponseView&) -> latest::MessageVariant { return latest::ErrorResponse{}; }, [&](const latest::CancelOrderRequestView&) -> latest::MessageVariant { return latest::CancelOrderResponse{}; }, [&](const latest::CancelOrderResponseView&) -> latest::MessageVariant { return latest::ErrorResponse{}; } )}; } // ===================================================== // VERSION HANDLING // Reads packets, converts them to the latest version, and then downgrades the output class PacketVariantVisitor { public: v1::Message operator()(const v1::MessageView& msg) const { // Added a field so this is a bit tricky, we have to copy it and build a new view auto next_bytes = v2::convert(msg.build(), tako::Type<v2::Message>{}).serialize(); auto next_view = v2::MessageView::parse(next_bytes).value().rendered; return v2::convert((*this)(next_view), tako::Type<v1::Message>{}); } v2::Message operator()(const v2::MessageView& msg) const { // Direct view-to-view conversion since we made a backwards compatible change // (adding Flavor::CARMEL) auto next_view = v3::convert(msg, tako::Type<v3::MessageView>{}); return v3::convert((*this)(next_view), tako::Type<v2::Message>{}); } v3::Message operator()(const v3::MessageView& msg) const { // Direct view-to-view conversion since we made a backwards compatible change // (adding messages types: CancelOrderRequest and CancelOrderResponse) auto next_view = v4::convert(msg, tako::Type<v4::MessageView>{}); // Note that when we down-convert, there is a .value() -- the convert returns // an optional, because we added cancel order messages, and those can't // be represented in the prior version. return v4::convert((*this)(next_view), tako::Type<v3::Message>{}).value(); } v4::Message operator()(const v4::MessageView& msg) const { return process_latest(msg); } }; // ===================================================== // ENTRYPOINT // Handles a new cupcake order and generates the response! static std::vector<gsl::byte> handle_order(gsl::span<const gsl::byte> data) { tako::ParseResult<PacketView> parse_result = PacketView::parse(data); if (!parse_result) { return Packet {.payload = latest::Message {.msg = latest::ErrorResponse{}}}.serialize(); } // Now we have a valid message, so we can process the order! PacketVariantView packet_variant = parse_result->rendered.payload(); return Packet { .payload = packet_variant.accept(tako::unify<PacketVariant>(PacketVariantVisitor{})), }.serialize(); }
43.925
96
0.628723
[ "vector" ]
ed6b549f30340c4bc639edec2b59b5862ac0bc17
55,512
hpp
C++
addons/equipment/configs/uniforms/vehicles/pcu.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/equipment/configs/uniforms/vehicles/pcu.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/equipment/configs/uniforms/vehicles/pcu.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
class USP_PCU_G3C; class USP_PCU_G3C_MX; class USP_PCU_G3C_OR; class USP_PCU_G3C_KP; class USP_PCU_G3C_KP_MX; class USP_PCU_G3C_KP_OR; class USP_PCU_G3C_MC_SOCOMD: USP_PCU_G3C{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU (MC-ADF)"; uniformClass = "USP_PCU_G3C_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX2_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX2 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX2_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX3_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX3 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX3_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX4_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX4 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX4_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX5_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX5 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX5_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX6_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX6 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX6_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX7_MC_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX7 (MC-ADF)"; uniformClass = "USP_PCU_G3C_MX7_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR2_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR2 (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR2_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR3_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR3 (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR3_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR4_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR4 (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR4_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR5_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR5 (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR5_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR6_MC_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR6 (MC-ADF)"; uniformClass = "USP_PCU_G3C_OR6_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MC_SOCOMD: USP_PCU_G3C_KP{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX2_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX2 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX2_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX3_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX3 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX3_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX4_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX4 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX4_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX5_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX5 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX5_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX6_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX6 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX6_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX7_MC_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX7 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX7_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR2_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR2 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR2_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR3_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR3 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR3_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR4_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR4 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR4_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR5_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR5 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR5_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR6_MC_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR6 (MC-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR6_MC_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; // Grey class USP_PCU_G3C_MC_GRY_SOCOMD: USP_PCU_G3C{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX2_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX2 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX2_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX3_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX3 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX3_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX4_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX4 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX4_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX5_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX5 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX5_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX6_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX6 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX6_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX7_MC_GRY_SOCOMD: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX7 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_MX7_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR2_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR2 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR2_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR3_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR3 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR3_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR4_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR4 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR4_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR5_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR5 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR5_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR6_MC_GRY_SOCOMD: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR6 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_OR6_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MC_GRY_SOCOMD: USP_PCU_G3C_KP{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX2_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX2 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX2_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX3_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX3 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX3_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX4_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX4 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX4_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX5_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX5 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX5_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX6_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX6 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX6_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX7_MC_GRY_SOCOMD: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX7 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_MX7_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR2_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR2 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR2_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR3_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR3 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR3_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR4_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR4 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR4_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR5_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR5 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR5_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR6_MC_GRY_SOCOMD: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR6 (MC/GRY-ADF)"; uniformClass = "USP_PCU_G3C_KP_OR6_MC_GRY_SOCOMD"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MC_RECON: USP_PCU_G3C{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU (MC-Recon)"; uniformClass = "USP_PCU_G3C_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX2_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX2 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX2_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX3_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX3 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX3_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX4_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX4 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX4_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX5_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX5 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX5_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX6_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX6 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX6_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX7_MC_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX7 (MC-Recon)"; uniformClass = "USP_PCU_G3C_MX7_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR2_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR2 (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR2_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR3_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR3 (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR3_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR4_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR4 (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR4_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR5_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR5 (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR5_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR6_MC_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR6 (MC-Recon)"; uniformClass = "USP_PCU_G3C_OR6_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MC_RECON: USP_PCU_G3C_KP{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX2_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX2 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX2_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX3_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX3 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX3_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX4_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX4 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX4_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX5_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX5 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX5_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX6_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX6 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX6_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX7_MC_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX7 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX7_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR2_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR2 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR2_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR3_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR3 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR3_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR4_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR4 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR4_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR5_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR5 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR5_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR6_MC_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR6 (MC-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR6_MC_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_mc_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MC_GRY_RECON: USP_PCU_G3C{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX2_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX2 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX2_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX3_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX3 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX3_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX4_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX4 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX4_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX5_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX5 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX5_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX6_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX6 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX6_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_MX7_MC_GRY_RECON: USP_PCU_G3C_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/MX7 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_MX7_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR2_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR2 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR2_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR3_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR3 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR3_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR4_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR4 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR4_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR5_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR5 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR5_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_OR6_MC_GRY_RECON: USP_PCU_G3C_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/OR6 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_OR6_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MC_GRY_RECON: USP_PCU_G3C_KP{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX2_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX2 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX2_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_blk2_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX3_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX3 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX3_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX4_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX4 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX4_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_wdl_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX5_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX5 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX5_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX6_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX6 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX6_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_mcb_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_MX7_MC_GRY_RECON: USP_PCU_G3C_KP_MX{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/MX7 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_MX7_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_mechanix_gry_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_blk_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR2_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR2 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR2_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_cbr_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR3_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR3 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR3_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_grn_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR4_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR4 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR4_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mc_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR5_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR5 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR5_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_mix_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; }; class USP_PCU_G3C_KP_OR6_MC_GRY_RECON: USP_PCU_G3C_KP_OR{ author = "UnderSiege Productions"; displayName = "[SOCOMD] Crye PCU/G3C PCU/KP/OR6 (MC/GRY-Recon)"; uniformClass = "USP_PCU_G3C_KP_OR6_MC_GRY_RECON"; picture = "\usp_gear_body\data\ui\usp_icon_g3c_mc_ca.paa"; hiddenSelectionsTextures[] = {"\usp_gear_body\model\tx\usp_pcu_gry_co.paa","\usp_gear_body\model\tx\usp_g3c_pants_mc_co.paa","\usp_gear_body\model\tx\usp_overlord_tan_co.paa","\usp_gear_body\model\tx\usp_salomon_co.paa"}; };
70.002522
226
0.770878
[ "model" ]
ed6cac861915117be380c35106a9f4b5a907778e
3,011
cpp
C++
test/aot/AOTCacheTest.cpp
chenhengqi/WasmEdge
80eb92e5989433b65d0e1670abe0b13670c0bc2d
[ "Apache-2.0" ]
null
null
null
test/aot/AOTCacheTest.cpp
chenhengqi/WasmEdge
80eb92e5989433b65d0e1670abe0b13670c0bc2d
[ "Apache-2.0" ]
null
null
null
test/aot/AOTCacheTest.cpp
chenhengqi/WasmEdge
80eb92e5989433b65d0e1670abe0b13670c0bc2d
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 //===-- wasmedge/test/aot/AOTCacheTest.cpp - aot cache unit tests ---------===// // // Part of the WasmEdge Project. // //===----------------------------------------------------------------------===// /// /// \file /// This file contents unit tests of caching compiled WASM. /// //===----------------------------------------------------------------------===// #include "aot/cache.h" #include "common/config.h" #include "common/span.h" #include "gtest/gtest.h" #include <vector> namespace { using namespace std::literals::string_literals; using namespace std::literals::string_view_literals; TEST(CacheTest, GlobalEmpty) { const auto Path = WasmEdge::AOT::Cache::getPath( {}, WasmEdge::AOT::Cache::StorageScope::Global); EXPECT_TRUE(Path); auto Root = *Path; while (Root.filename().u8string() != "wasmedge"sv) { ASSERT_TRUE(Root.has_parent_path()); Root = Root.parent_path(); } std::error_code ErrCode; const auto Part = std::filesystem::proximate(*Path, Root, ErrCode); EXPECT_FALSE(ErrCode); EXPECT_EQ( Part.u8string(), "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"s); } TEST(CacheTest, LocalEmpty) { const auto Path = WasmEdge::AOT::Cache::getPath( {}, WasmEdge::AOT::Cache::StorageScope::Local); EXPECT_TRUE(Path); auto Root = *Path; while (Root.filename().u8string() != ".wasmedge"sv) { ASSERT_TRUE(Root.has_parent_path()); Root = Root.parent_path(); } Root /= "cache"sv; std::error_code ErrCode; const auto Part = std::filesystem::proximate(*Path, Root, ErrCode); EXPECT_FALSE(ErrCode); EXPECT_EQ( Part.u8string(), "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"s); } TEST(CacheTest, GlobalKey) { const auto Path = WasmEdge::AOT::Cache::getPath( {}, WasmEdge::AOT::Cache::StorageScope::Global, "key"s); EXPECT_TRUE(Path); auto Root = *Path; while (Root.filename().u8string() != "wasmedge"sv) { ASSERT_TRUE(Root.has_parent_path()); Root = Root.parent_path(); } std::error_code ErrCode; const auto Part = std::filesystem::proximate(*Path, Root, ErrCode); EXPECT_FALSE(ErrCode); EXPECT_EQ( Part.u8string(), "key/af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"s); } TEST(CacheTest, LocalKey) { const auto Path = WasmEdge::AOT::Cache::getPath( {}, WasmEdge::AOT::Cache::StorageScope::Local, "key"s); EXPECT_TRUE(Path); auto Root = *Path; while (Root.filename().u8string() != ".wasmedge"sv) { ASSERT_TRUE(Root.has_parent_path()); Root = Root.parent_path(); } Root /= "cache"sv; std::error_code ErrCode; const auto Part = std::filesystem::proximate(*Path, Root, ErrCode); EXPECT_FALSE(ErrCode); EXPECT_EQ( Part.u8string(), "key/af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"s); } } // namespace GTEST_API_ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.11
80
0.652939
[ "vector" ]
ed70dabb9da076481f7126d23d962857d2fd1e31
290
hpp
C++
trunk/+simLib/src/C-mexed/rankProb.hpp
andreatassi/SparseRLNC
7b98409409762e381c2da4633e0fb584909393e6
[ "Apache-2.0" ]
null
null
null
trunk/+simLib/src/C-mexed/rankProb.hpp
andreatassi/SparseRLNC
7b98409409762e381c2da4633e0fb584909393e6
[ "Apache-2.0" ]
null
null
null
trunk/+simLib/src/C-mexed/rankProb.hpp
andreatassi/SparseRLNC
7b98409409762e381c2da4633e0fb584909393e6
[ "Apache-2.0" ]
null
null
null
#include <boost/math/special_functions/binomial.hpp> #include <iostream> #include <ctime> #include <cassert> #include <vector> #include <algorithm> #include <math.h> double condRankP(unsigned int r, unsigned int c, double p, unsigned int q); double nCkF(unsigned int n, unsigned int k);
24.166667
75
0.751724
[ "vector" ]
ed718b97b9e3d276984808c2e53ce47309a650f6
5,107
cpp
C++
toolbox/mex/meshing_mex/GetListOfConnTri2Tri_mex.cpp
CoMind-Technologies/NIRFASTer
afa40cea97502aa83430c81b69a077acca98ca78
[ "BSD-3-Clause" ]
1
2020-11-19T02:51:48.000Z
2020-11-19T02:51:48.000Z
toolbox/mex/meshing_mex/GetListOfConnTri2Tri_mex.cpp
CoMind-Technologies/NIRFASTer
afa40cea97502aa83430c81b69a077acca98ca78
[ "BSD-3-Clause" ]
2
2020-07-14T12:08:00.000Z
2021-06-11T16:29:16.000Z
toolbox/mex/meshing_mex/GetListOfConnTri2Tri_mex.cpp
CoMind-Technologies/NIRFASTer
afa40cea97502aa83430c81b69a077acca98ca78
[ "BSD-3-Clause" ]
3
2021-05-19T09:26:23.000Z
2021-11-08T17:41:52.000Z
/* * GetListOfConnTri2Tri_mex.cpp * * * Created by Hamid Ghadyani on 1/7/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #include "GetListOfConnTri2Tri_mex.h" // #define p(i,j) p[(i)+np*(j)] #define ele(i,j) ele[(i)+nele*(j)] //#define list(i,j) list[(i)+nele*(j)]; /* To compile this file use: * For Windows: * mex -v -DWIN32 -I./meshlib GetListOfConnTri2Tri_mex.cpp meshlib/vector.cpp * *For Mac/Linux * mex -v -I./meshlib GetListOfConnTri2Tri_mex.cpp meshlib/vector.cpp */ // [list,vertex_tri_hash]=GetListOfConnTri2Tri_mex(ele,p) // list(i): list of 3 connected triangles to triangle i // vertex_tri_hash(i): list of all triangles sharing node i void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs!=2 || nlhs<1) { mexPrintf("[list,vertex_tri_hash]=GetListOfConnTri2Tri_mex(ele,p)\n"); mexErrMsgTxt("GetListOfConnTri2Tri_mex: Needs 2 input argument"); } nele = mxGetM(prhs[0]); std::vector< std::set<ulong> > Graph(nele); if (!mxIsDouble(prhs[1])) mexErrMsgTxt("GetListOfConnTri2Tri_mex: input argument 2 should be of 'double' type"); np = mxGetM(prhs[1]); std::vector< std::set<ulong> > vertex_tri_hash(np); if (mxIsDouble(prhs[0])) ele = (double *) mxGetData(prhs[0]); else mexErrMsgTxt("GetListOfConnTri2Tri_mex: t needs to be 'double'!"); mxArray *cell_pointer; // Returned variable which holds connectivity list of triangles. mxArray *cell_pointer2; // The list that holds which triangles are connected to a given vertex // Populate the return value of 'list' PopulateGraph(Graph, vertex_tri_hash); cell_pointer=mxCreateCellMatrix(nele,1); for (ulong i=0; i<nele; ++i) { SetCell(cell_pointer, Graph[i], i); } plhs[0] = cell_pointer; if (nlhs>=2) { cell_pointer2 = mxCreateCellMatrix(np,1); for (ulong i=0; i<np; ++i) { SetCell(cell_pointer2, vertex_tri_hash[i], i); } plhs[1] = cell_pointer2; } } void PopulateGraph(std::vector< std::set<ulong> > &Graph, std::vector< std::set<ulong> > &vertex_tri_hash) { std::set<ulong> myneighbors; // Populate the hash table which tells us which triangles are sharing a specific node. for (ulong i=0; i<nele; ++i) { for (int j=0; j<3; ++j) vertex_tri_hash[(ulong) (ele(i,j)-1)].insert(i+1); } std::set<ulong> tmpSet; std::queue<ulong> q; std::vector<long> edge_check (nele, White); bool endflag=false; ulong starte=1; while (!endflag) { q.push(starte); ulong dummyc=0; while (!q.empty()) { ulong u = q.front(); myneighbors = FindNeighboringTriangles(u, vertex_tri_hash); for (std::set<ulong>::iterator it=myneighbors.begin(); it!=myneighbors.end(); ++it) { if (edge_check[(*it)-1]==Black) continue; if (u != *it) { ulong tempak = *it; tmpSet.clear(); tmpSet = Graph[u-1]; tmpSet.insert(*it); Graph[u-1] = tmpSet; tmpSet.clear(); tmpSet = Graph[(*it)-1]; tmpSet.insert(u); Graph[(*it)-1] = tmpSet; if (edge_check[(*it)-1] == White) q.push(*it); edge_check[(*it)-1] = edge_check[(*it)-1] + 1; // if (edge_check[(*it)-1]>=3) // edge_check[(*it)-1] = Black; } } edge_check[u-1] = Black; q.pop(); dummyc++; } endflag=true; for (ulong i=0; i<nele; ++i) { if (edge_check[i]!=Black) { starte = i+1; endflag=false; break; } } } } // Searches all the triangles sharing a node with 'tri' in order to figure out // the ones that share an edge. It then returns those triangles' IDs std::set<ulong> FindNeighboringTriangles(ulong tri, std::vector< std::set<ulong> > &vertex_tri_hash ) { std::set<ulong> neighbours, ret; std::set<ulong>::iterator it; for (int i=0; i<3; ++i) { for (it=vertex_tri_hash[(ulong)(ele(tri-1,i))-1].begin(); it!=vertex_tri_hash[(ulong)(ele(tri-1,i))-1].end(); ++it) { if (*it != tri) neighbours.insert(*it); } } for (it=neighbours.begin(); it!=neighbours.end(); ++it) { if (ShareEdge(tri,*it)) { ret.insert(*it); } } return ret; } // If triangle u and v share an edge, it will return true, otherwise false bool ShareEdge(ulong u, ulong v) { bool flag = false; ulong NV[3]={(ulong)(ele(v-1,0)), (ulong)(ele(v-1,1)), (ulong)(ele(v-1,2))}; ulong NU[3]={(ulong)(ele(u-1,0)), (ulong)(ele(u-1,1)), (ulong)(ele(u-1,2))}; ulong eu1, eu2, ev1, ev2; for (int i=0; i<3; ++i) { eu1 = NU[edge[i][0]]; eu2 = NU[edge[i][1]]; for (int j=0; j<3; ++j) { ev1 = NV[edge[j][0]]; ev2 = NV[edge[j][1]]; if ((eu1==ev1 && eu2==ev2) || (eu1==ev2 && eu2==ev1)) { return true; } } } return flag; } void SetCell(mxArray* cell_pointer, std::set<ulong> conn_elems, ulong i) { mwSize dims[2] = {1, static_cast<mwSize>(conn_elems.size())}; mxArray *tmpArray2=mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); double *temp2 = (double *) mxGetData(tmpArray2); ulong counter=0; for (std::set<ulong>::iterator j=conn_elems.begin(); j!=conn_elems.end(); temp2[counter]=*j, ++counter, ++j); mxSetCell(cell_pointer, i, mxDuplicateArray(tmpArray2)); mxDestroyArray(tmpArray2); }
29.017045
119
0.63599
[ "vector" ]
ed78d2a517d9a28b60d1e6bacc120b610eb36120
19,732
cpp
C++
llvm_analysis/AnalysisHelpers/EntryPointIdentifier/src/main.cpp
deadly-platypus/dr_checker
103a732c92f5eb525ff797c4c88be9b73fb0f38a
[ "BSD-2-Clause" ]
295
2017-08-17T00:30:56.000Z
2022-03-24T08:13:57.000Z
llvm_analysis/AnalysisHelpers/EntryPointIdentifier/src/main.cpp
deadly-platypus/dr_checker
103a732c92f5eb525ff797c4c88be9b73fb0f38a
[ "BSD-2-Clause" ]
26
2017-08-21T02:03:44.000Z
2021-08-29T17:41:35.000Z
llvm_analysis/AnalysisHelpers/EntryPointIdentifier/src/main.cpp
deadly-platypus/dr_checker
103a732c92f5eb525ff797c4c88be9b73fb0f38a
[ "BSD-2-Clause" ]
77
2017-08-17T03:36:21.000Z
2022-03-28T11:40:20.000Z
// // Created by machiry on 1/30/17. // #include <iostream> #include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/ValueSymbolTable.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Debug.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Analysis/CFGPrinter.h" #include "llvm/Support/FileSystem.h" #include "llvm/IR/Module.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <fstream> using namespace std; using namespace llvm; #define NETDEV_IOCTL "NETDEVIOCTL" #define READ_HDR "FileRead" #define WRITE_HDR "FileWrite" #define IOCTL_HDR "IOCTL" #define DEVATTR_SHOW "DEVSHOW" #define DEVATTR_STORE "DEVSTORE" #define V4L2_IOCTL_FUNC "V4IOCTL" #define END_HDR "ENDEND" typedef struct { std::string st_name; long mem_id; std::string method_lab; } INT_STS; INT_STS kernel_sts[] { {"struct.watchdog_ops", 9, IOCTL_HDR}, {"struct.bin_attribute", 3, READ_HDR}, {"struct.bin_attribute", 4, WRITE_HDR}, {"struct.atmdev_ops", 3, IOCTL_HDR}, {"struct.atmphy_ops", 1, IOCTL_HDR}, {"struct.atm_ioctl", 1, IOCTL_HDR}, {"struct.kernfs_ops", 4, READ_HDR}, {"struct.kernfs_ops", 6, WRITE_HDR}, {"struct.ppp_channel_ops", 1, IOCTL_HDR}, {"struct.hdlcdrv_ops", 4, IOCTL_HDR}, {"struct.vfio_device_ops", 3, READ_HDR}, {"struct.vfio_device_ops", 4, WRITE_HDR}, {"struct.vfio_device_ops", 5, IOCTL_HDR}, {"struct.vfio_iommu_driver_ops", 4, READ_HDR}, {"struct.vfio_iommu_driver_ops", 5, WRITE_HDR}, {"struct.vfio_iommu_driver_ops", 6, IOCTL_HDR}, {"struct.rtc_class_ops", 2, IOCTL_HDR}, {"struct.net_device_ops", 10, IOCTL_HDR}, {"struct.kvm_device_ops", 6, IOCTL_HDR}, {"struct.ide_disk_ops", 8, IOCTL_HDR}, {"struct.ide_ioctl_devset", 0, IOCTL_HDR}, {"struct.ide_ioctl_devset", 1, IOCTL_HDR}, {"struct.pci_ops", 0, READ_HDR}, {"struct.pci_ops", 1, WRITE_HDR}, {"struct.cdrom_device_info", 10, IOCTL_HDR}, {"struct.cdrom_device_ops", 12, IOCTL_HDR}, {"struct.iio_chan_spec_ext_info", 2, READ_HDR}, {"struct.iio_chan_spec_ext_info", 3, WRITE_HDR}, {"struct.proto_ops", 9, IOCTL_HDR}, {"struct.usb_phy_io_ops", 0, READ_HDR}, {"struct.usb_phy_io_ops", 1, WRITE_HDR}, {"struct.usb_gadget_ops", 6, IOCTL_HDR}, {"struct.uart_ops", 23, IOCTL_HDR}, {"struct.tty_ldisc_ops", 8, READ_HDR}, {"struct.tty_ldisc_ops", 9, WRITE_HDR}, {"struct.tty_ldisc_ops", 10, IOCTL_HDR}, {"struct.fb_ops", 17, IOCTL_HDR}, {"struct.v4l2_subdev_core_ops", 13, IOCTL_HDR}, {"struct.m2m1shot_devops", 8, IOCTL_HDR}, {"struct.nfc_phy_ops", 0, WRITE_HDR}, {"struct.snd_ac97_bus_ops", 2, WRITE_HDR}, {"struct.snd_ac97_bus_ops", 3, READ_HDR}, {"struct.snd_hwdep_ops", 1, READ_HDR}, {"struct.snd_hwdep_ops", 2, WRITE_HDR}, {"struct.snd_hwdep_ops", 6, IOCTL_HDR}, {"struct.snd_hwdep_ops", 7, IOCTL_HDR}, {"struct.snd_soc_component", 14, READ_HDR}, {"struct.snd_soc_component", 15, WRITE_HDR}, {"struct.snd_soc_codec_driver", 14, READ_HDR}, {"struct.snd_soc_codec_driver", 15, WRITE_HDR}, {"struct.snd_pcm_ops", 2, IOCTL_HDR}, {"struct.snd_ak4xxx_ops", 2, WRITE_HDR}, {"struct.snd_info_entry_text", 0, READ_HDR}, {"struct.snd_info_entry_text", 1, WRITE_HDR}, {"struct.snd_info_entry_ops", 2, READ_HDR}, {"struct.snd_info_entry_ops", 3, WRITE_HDR}, {"struct.snd_info_entry_ops", 6, IOCTL_HDR}, {"struct.tty_buffer", 4, READ_HDR}, {"struct.tty_operations", 7, WRITE_HDR}, {"struct.tty_operations", 12, IOCTL_HDR}, {"struct.posix_clock_operations", 10, IOCTL_HDR}, {"struct.posix_clock_operations", 15, READ_HDR}, {"struct.block_device_operations", 3, IOCTL_HDR}, {"struct.security_operations", 64, IOCTL_HDR}, {"struct.file_operations", 2, READ_HDR}, {"struct.file_operations", 3, WRITE_HDR}, {"struct.file_operations", 10, IOCTL_HDR}, {"struct.efi_pci_io_protocol_access_32_t", 0, READ_HDR}, {"struct.efi_pci_io_protocol_access_32_t", 1, WRITE_HDR}, {"struct.efi_pci_io_protocol_access_64_t", 0, READ_HDR}, {"struct.efi_pci_io_protocol_access_64_t", 1, WRITE_HDR}, {"struct.efi_pci_io_protocol_access_t", 0, READ_HDR}, {"struct.efi_pci_io_protocol_access_t", 1, WRITE_HDR}, {"struct.efi_file_handle_32_t", 4, READ_HDR}, {"struct.efi_file_handle_32_t", 5, WRITE_HDR}, {"struct.efi_file_handle_64_t", 4, READ_HDR}, {"struct.efi_file_handle_64_t", 5, WRITE_HDR}, {"struct._efi_file_handle", 4, READ_HDR}, {"struct._efi_file_handle", 5, WRITE_HDR}, {"struct.video_device", 21, IOCTL_HDR}, {"struct.video_device", 22, IOCTL_HDR}, {"struct.v4l2_file_operations", 1, READ_HDR}, {"struct.v4l2_file_operations", 2, WRITE_HDR}, {"struct.v4l2_file_operations", 4, IOCTL_HDR}, {"struct.v4l2_file_operations", 5, IOCTL_HDR}, {"struct.media_file_operations", 1, READ_HDR}, {"struct.media_file_operations", 2, WRITE_HDR}, {"struct.media_file_operations", 4, IOCTL_HDR}, {"END", 0, END_HDR} }; void print_err(char *prog_name) { std::cerr << "[!] This program identifies all the entry points from the provided bitcode file.\n"; std::cerr << "[!] saves these entry points into provided output file, which could be used to run analysis on.\n"; std::cerr << "[?] " << prog_name << " <llvm_linked_bit_code_file> <output_txt_file>\n"; exit(-1); } void process_netdev_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // net device ioctl: 10 Value *currFieldVal = actualStType->getOperand(10); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", NETDEV_IOCTL, targetFunction->getName().str().c_str()); } } } void process_device_attribute_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // dev show: 1 Value *currFieldVal = actualStType->getOperand(1); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", DEVATTR_SHOW, targetFunction->getName().str().c_str()); } // dev store : 2 currFieldVal = actualStType->getOperand(2); targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", DEVATTR_STORE, targetFunction->getName().str().c_str()); } } } void process_file_operations_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // read: 2 Value *currFieldVal = actualStType->getOperand(2); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", READ_HDR, targetFunction->getName().str().c_str()); } // write: 3 currFieldVal = actualStType->getOperand(3); targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", WRITE_HDR, targetFunction->getName().str().c_str()); } // ioctl : 10 currFieldVal = actualStType->getOperand(10); targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", IOCTL_HDR, targetFunction->getName().str().c_str()); } // ioctl : 10 currFieldVal = actualStType->getOperand(8); targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", IOCTL_HDR, targetFunction->getName().str().c_str()); } } } void process_snd_pcm_ops_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // ioctl: 2 Value *currFieldVal = actualStType->getOperand(2); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", IOCTL_HDR, targetFunction->getName().str().c_str()); } } } void process_v4l2_ioctl_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // all fields are function pointers for(unsigned int i=0; i<actualStType->getNumOperands(); i++) { Value *currFieldVal = actualStType->getOperand(i); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", V4L2_IOCTL_FUNC, targetFunction->getName().str().c_str()); } } } } void process_v4l2_file_ops_st(GlobalVariable *currGlobal, FILE *outputFile) { if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); // read: 1 Value *currFieldVal = actualStType->getOperand(1); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", READ_HDR, targetFunction->getName().str().c_str()); } // write: 2 currFieldVal = actualStType->getOperand(2); targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", WRITE_HDR, targetFunction->getName().str().c_str()); } } } char** str_split(char* a_str, const char a_delim) { char** result = 0; size_t count = 0; char* tmp = a_str; char* last_comma = 0; char delim[2]; delim[0] = a_delim; delim[1] = 0; /* Count how many elements will be extracted. */ while (*tmp) { if (a_delim == *tmp) { count++; last_comma = tmp; } tmp++; } /* Add space for trailing token. */ count += last_comma < (a_str + strlen(a_str) - 1); /* Add space for terminating null string so caller knows where the list of returned strings ends. */ count++; result = (char**)malloc(sizeof(char*) * count); if (result) { size_t idx = 0; char* token = strtok(a_str, delim); while (token) { assert(idx < count); *(result + idx++) = strdup(token); token = strtok(0, delim); } assert(idx == count - 1); *(result + idx) = 0; } return result; } bool process_struct_in_custom_entry_files(GlobalVariable *currGlobal, FILE *outputFile, std::vector<string> &allentries) { bool retVal = false; if(currGlobal->hasInitializer()) { // get the initializer. Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); Type *targetType = currGlobal->getType(); assert(targetType->isPointerTy()); Type *containedType = targetType->getContainedType(0); std::string curr_st_name = containedType->getStructName(); char hello_str[1024]; for(auto curre:allentries) { if(curre.find(curr_st_name) != std::string::npos) { strcpy(hello_str, curre.c_str()); // structure found char** tokens = str_split(hello_str, ','); assert(!strcmp(curr_st_name.c_str(), tokens[0])); long ele_ind = strtol(tokens[1], NULL, 10); Value *currFieldVal = actualStType->getOperand(ele_ind); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", tokens[2], targetFunction->getName().str().c_str()); } if (tokens) { int i; for (i = 0; *(tokens + i); i++) { free(*(tokens + i)); } free(tokens); } retVal = true; } } } return retVal; } void process_global(GlobalVariable *currGlobal, FILE *outputFile, std::vector<string> &allentries) { std::string file_op_st("struct.file_operations"); std::string dev_attr_st("struct.device_attribute"); std::string dri_attr_st("struct.driver_attribute"); std::string bus_attr_st("struct.bus_attribute"); std::string net_dev_st("struct.net_device_ops"); std::string snd_pcm_st("struct.snd_pcm_ops"); std::string v4l2_ioctl_st("struct.v4l2_ioctl_ops"); std::string v4l2_file_ops_st("struct.v4l2_file_operations"); Type *targetType = currGlobal->getType(); assert(targetType->isPointerTy()); Type *containedType = targetType->getContainedType(0); if (containedType->isStructTy()) { StructType *targetSt = dyn_cast<StructType>(containedType); if(targetSt->isLiteral()) { return; } if(process_struct_in_custom_entry_files(currGlobal, outputFile, allentries)) { return; } if (containedType->getStructName() == file_op_st) { process_file_operations_st(currGlobal, outputFile); } else if(containedType->getStructName() == dev_attr_st || containedType->getStructName() == dri_attr_st) { process_device_attribute_st(currGlobal, outputFile); } else if(containedType->getStructName() == net_dev_st) { process_netdev_st(currGlobal, outputFile); } else if(containedType->getStructName() == snd_pcm_st) { process_snd_pcm_ops_st(currGlobal, outputFile); } else if(containedType->getStructName() == v4l2_file_ops_st) { process_v4l2_file_ops_st(currGlobal, outputFile); } else if(containedType->getStructName() == v4l2_ioctl_st) { process_v4l2_ioctl_st(currGlobal, outputFile); } else { unsigned long i=0; while(kernel_sts[i].method_lab != END_HDR) { if(kernel_sts[i].st_name == containedType->getStructName()) { if(currGlobal->hasInitializer()) { Constant *targetConstant = currGlobal->getInitializer(); ConstantStruct *actualStType = dyn_cast<ConstantStruct>(targetConstant); Value *currFieldVal = actualStType->getOperand(kernel_sts[i].mem_id); Function *targetFunction = dyn_cast<Function>(currFieldVal); if(targetFunction != nullptr && !targetFunction->isDeclaration()) { fprintf(outputFile, "%s:%s\n", kernel_sts[i].method_lab.c_str(), targetFunction->getName().str().c_str()); } } } i++; } } } } // some debug function /*void check_my_guy(Module *m, CallInst *currInst) { errs() << "Called for:" << *currInst << ":" << *(currInst->getFunctionType()) << "\n"; for(auto a = m->begin(), b = m->end(); a != b; a++) { Function *my_func = &(*a); if (my_func != nullptr && !my_func->isDeclaration() && my_func->getFunctionType() == currInst->getFunctionType()) { errs() << my_func->getName() << ":" << my_func->getNumUses() << "\n"; for (Value::user_iterator i = my_func->user_begin(), e = my_func->user_end(); i != e; ++i) { CallInst *currC = dyn_cast<CallInst>(*i); if (currC == nullptr) { errs() << "F is used in a non call instruction:\n"; errs() << **i << "\n"; } } } } }*/ int main(int argc, char *argv[]) { //check args if(argc < 3) { print_err(argv[0]); } char *src_llvm_file = argv[1]; char *output_txt_file = argv[2]; char *entry_point_file = NULL; std::vector<string> entryPointStrings; entryPointStrings.clear(); if(argc > 3) { entry_point_file = argv[3]; std::ifstream infile(entry_point_file); std::string line; while (std::getline(infile, line)) { entryPointStrings.push_back(line); } } FILE *outputFile = fopen(output_txt_file, "w"); assert(outputFile != nullptr); LLVMContext context; ErrorOr<std::unique_ptr<MemoryBuffer>> fileOrErr = MemoryBuffer::getFileOrSTDIN(src_llvm_file); ErrorOr<std::unique_ptr<llvm::Module>> moduleOrErr = parseBitcodeFile(fileOrErr.get()->getMemBufferRef(), context); Module *m = moduleOrErr.get().get(); Module::GlobalListType &currGlobalList = m->getGlobalList(); for(Module::global_iterator gstart = currGlobalList.begin(), gend = currGlobalList.end(); gstart != gend; gstart++) { GlobalVariable *currGlobal = &(*gstart); process_global(currGlobal, outputFile, entryPointStrings); } /*for(auto a = m->begin(), b = m->end(); a != b; a++) { //check_my_guy(&(*a)); for(auto fi = (*a).begin(), fe = (*a).end(); fi != fe; fi++) { for(auto bs=(*fi).begin(), be=(*fi).end(); bs!=be; bs++) { Instruction *currI = &(*bs); assert(currI != nullptr); CallInst *currC = dyn_cast<CallInst>(currI); if(currC != nullptr && currC->getCalledFunction() == nullptr) { check_my_guy(m, currC); } } } }*/ fclose(outputFile); }
39.228628
134
0.61048
[ "vector" ]
1434dd5fbd7b0e82a639f2a71c1869e51346bc07
5,168
cpp
C++
MVC6SH/Examples/Learnvcn/Chap18/MyDraw8/Shape.cpp
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
MVC6SH/Examples/Learnvcn/Chap18/MyDraw8/Shape.cpp
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
MVC6SH/Examples/Learnvcn/Chap18/MyDraw8/Shape.cpp
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
// Shape.cpp: implementation of the CShape class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyDraw.h" #include "Shape.h" #include "Resource.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //////////////////////////////////// // Class CShape implementation IMPLEMENT_SERIAL(CShape, CObject, 1) CShape::CShape() { m_boxShape.SetRect(0, 0, 0, 0); m_bTransparent = true; m_nColorShape = ID_COLOR_BLACK; m_bSelected = false; } CShape::~CShape() { } //////////////////////////////////// // Class CShpRectangle implementation IMPLEMENT_SERIAL(CShpRectangle, CShape, 1) void CShpRectangle::Draw(CDC* pDC, bool bSelectionModeOn) // Virtual override { pDC->Rectangle(m_boxShape); if(m_bSelected && bSelectionModeOn) DrawHandles(pDC); } //////////////////////////////////// // Class CShpEllipse implementation IMPLEMENT_SERIAL(CShpEllipse, CShape, 1) void CShpEllipse::Draw(CDC* pDC, bool bSelectionModeOn) // Virtual override { pDC->Ellipse(m_boxShape); if(m_bSelected && bSelectionModeOn) DrawHandles(pDC); } void CShape::Serialize(CArchive& ar) { BYTE byTransparent; CObject::Serialize(ar); if (ar.IsStoring()) { // TODO: add storing code here. byTransparent = (m_bTransparent ? 1 : 0); ar << m_boxShape << byTransparent << m_nColorShape; } else { // TODO: add loading code here. ar >> m_boxShape >> byTransparent >> m_nColorShape; m_bTransparent = (byTransparent != 0); m_bSelected = false; // We don't store selection state } } void CShape::CreateHandleRects() { // Calculate the rectangles for a set of selection // handles and store them in array of handle rects. int nHandSize = GetSystemMetrics(SM_CXBORDER) * 7; // Create an inflated rect around the shape's bounding // rect, m_boxShape. CRect ri = m_boxShape; ri.InflateRect(nHandSize, -nHandSize); // Calculate rects for corner handles. // Left top corner selection handle CRect rectLeftTop(ri.left, ri.top, m_boxShape.left, m_boxShape.top); rectLeftTop.OffsetRect(4, -4); arHandles[0] = rectLeftTop; // Right top corner selection handle CRect rectRightTop(m_boxShape.right, ri.top, ri.right, m_boxShape.top); rectRightTop.OffsetRect(-4, -4); arHandles[1] = rectRightTop; // Right bottom corner selection handle CRect rectRightBottom(m_boxShape.right, m_boxShape.bottom, ri.right, ri.bottom); rectRightBottom.OffsetRect(-4, 4); arHandles[2] = rectRightBottom; // Left bottom corner selection handle CRect rectLeftBottom(ri.left, m_boxShape.bottom, m_boxShape.left, ri.bottom); rectLeftBottom.OffsetRect(4, 4); arHandles[3] = rectLeftBottom; // Calculate rects for handles in centers of sides. // Calculate x values for top and bottom center // selection handles. int centerVert = ri.left + (ri.right - ri.left) / 2; int leftVert = centerVert - (nHandSize / 2); int rightVert = centerVert + (nHandSize / 2); // Bottom center selection handle CRect rectBottomCenter(leftVert, ri.top, rightVert, m_boxShape.top); rectBottomCenter.OffsetRect(0, -4); arHandles[4] = rectBottomCenter; // Top center selection handle CRect rectTopCenter(leftVert, m_boxShape.bottom, rightVert, ri.bottom); rectTopCenter.OffsetRect(0, 4); arHandles[6] = rectTopCenter; // Calculate y values for left and right center // selection handles. int centerHorz = ri.top + (ri.bottom - ri.top) / 2; int topHorz = centerHorz - (nHandSize / 2); int bottomHorz = centerHorz + (nHandSize / 2); // Right center selection handle CRect rectRightCenter(m_boxShape.right, topHorz, ri.right, bottomHorz); rectRightCenter.OffsetRect(-4, 0); arHandles[5] = rectRightCenter; // Left center selection handle CRect rectLeftCenter(ri.left, topHorz, m_boxShape.left, bottomHorz); rectLeftCenter.OffsetRect(4, 0); arHandles[7] = rectLeftCenter; } void CShape::DrawHandles(CDC *pDC) { // Put selection handles on a selected shape. // Set up brush for painting selection handles. CBrush* pBrush = new CBrush(COLOR_HIGHLIGHT); CBrush* pBrushOld = (CBrush*)pDC->SelectObject(pBrush); // Calculate areas to paint for handles. CreateHandleRects(); // Draw the handle rects with black interior brush. for(int i = 0; i < 8; i++) { pDC->Rectangle(arHandles[i]); } pDC->SelectObject(pBrushOld); // We created this brush, so we must dispose of it. // We only borrowed pBrushOld, so Windows disposes of it. delete pBrush; }
28.240437
78
0.610681
[ "shape" ]
1437c5aaa1dc143f5d24ca94b5cd0b140ade7c0d
3,158
cpp
C++
lib/test/async/test_transform.cpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
lib/test/async/test_transform.cpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
lib/test/async/test_transform.cpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
#include "../catch.hpp" #include "async/transform.hpp" #include "async/just.hpp" #include "async/receive.hpp" #include "tmp/type_list.hpp" TEST_CASE("Transform") { SECTION("Value type should not change for an identity transform") { auto transformed = async::transform( async::justValue(int(5)), [](int i) { return i; } ); using ValueTypes = async::SenderValueTypes<decltype(transformed), tmp::TypeList, tmp::TypeList>; STATIC_REQUIRE(std::is_same_v<ValueTypes, tmp::TypeList<tmp::TypeList<int>>>); } SECTION("Transform should be able to transform no arguments") { double receivedValue = 0; auto sender = async::transform( async::justValue(), []() -> double { return 10.0; }); using ValueTypeList = async::SenderValueTypes<decltype(sender), tmp::TypeList, tmp::TypeList>; STATIC_REQUIRE(std::is_same_v<ValueTypeList, tmp::TypeList<tmp::TypeList<double>>>); auto op = async::connect( std::move(sender), async::receiveValue([&receivedValue](auto v) { receivedValue = v; })); async::start(op); REQUIRE(receivedValue == 10.0); } SECTION("Transform should be able to transform multiple arguments") { double receivedValue = 0; auto sender = async::transform( async::justValue(int(5), true, 'a'), [](auto i, auto, auto) -> double { return i*5; }); using ValueTypes = async::SenderValueTypes<decltype(sender), tmp::TypeList, tmp::TypeList>; STATIC_REQUIRE(std::is_same<ValueTypes, tmp::TypeList<tmp::TypeList<double>>>::value); STATIC_REQUIRE(async::Sender<decltype(sender)>); auto op = async::connect(std::move(sender), async::receiveValue([&receivedValue](auto v) { receivedValue = v; })); async::start(op); REQUIRE(receivedValue == 25); } SECTION("Should pass errors through un-transformed") { const int errorCode = 10; int receivedError = 0; auto op = async::connect( async::transform( async::justError(errorCode), []() { }), async::receiveError([&receivedError](auto e) { receivedError = e; })); async::start(op); REQUIRE(receivedError == errorCode); } SECTION("The factory should support piping") { int receivedValue = -1; auto sender = async::justValue(int(5)) | async::transform([&](int i) { return i*2; }) | async::transform([&](int i) { return i; }); STATIC_REQUIRE(async::Sender<decltype(sender)>); auto op = async::connect(std::move(sender), async::receiveValue([&receivedValue](auto v) { receivedValue = v; })); async::start(op); REQUIRE(receivedValue == 10); } }
32.22449
104
0.538315
[ "transform" ]
144606487bc6f1619898f37f41196e4bd1396b7d
6,582
cpp
C++
Jimmy_Core/Locker.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
1
2021-05-17T23:03:14.000Z
2021-05-17T23:03:14.000Z
Jimmy_Core/Locker.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
null
null
null
Jimmy_Core/Locker.cpp
nozsavsev/jimmy
0be7a153e9c1a2f14710d072fd172ee1b3402742
[ "Apache-2.0" ]
null
null
null
/*Copyright 2020 Nozdrachev Ilia 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 <SFML/Graphics.hpp> #include "Jimmy_Core.h" struct display_deskriptor { int sx, sy, px, py; }; std::vector <display_deskriptor> ddesk; BOOL ENudi(HMONITOR p1, HDC hdc, LPRECT lpr, LPARAM p3) { if (lpr) ddesk.push_back({ lpr->right - lpr->left,lpr->bottom - lpr->top,lpr->left,lpr->top }); return true; } ///* class color_change_t { public: sf::Color from; sf::Color to; sf::Color getVal(float coff) { return { (unsigned char)(((float)to.r - (float)from.r) * coff + (float)from.r) , (unsigned char)(((float)to.g - (float)from.g) * coff + (float)from.g) , (unsigned char)(((float)to.b - (float)from.b) * coff + (float)from.b) , (unsigned char)(((float)to.a - (float)from.a) * coff + (float)from.a) , }; } }; //*/ #define ANIM_TIME 250.f #define ANIM_TIME_ALL 300.f void pcolor(sf::Color c, float coff) { printf("(%d:%d:%d:%d) -> %f\n", c.r, c.g, c.b, c.a, coff); } void pcolor(float c, float coff) { printf("%f -> %f\n", c, coff); } void Locker_immproc() { static bool first = true; static color_change_t gradi_unlock; static color_change_t gradi_lock; static sf::Clock unlockAnim; static sf::Clock lockAnim; static bool justLocked = true; static std::vector <sf::RenderWindow*>winvec; static sf::Event evt; static sf::Font ft; static sf::Text tx; if (first) { ft.loadFromFile("C:\\WINDOWS\\Fonts\\Arial.ttf"); tx.setFont(ft); tx.setCharacterSize(20); first = false; HKPP::Hotkey_Manager::Get_Instance()->Add_Callback([&](int nCode, WPARAM w, LPARAM l, VectorEx<key_deskriptor> keydesk, bool repeated_input) -> bool { if (keydesk.Contains(Jimmy_Global_properties.Locker_ActivateKey.load()) && !repeated_input && w == WM_KEYDOWN) Jimmy_Global_properties.Locker_IsLocked = true; if (keydesk.Contains(Jimmy_Global_properties.Locker_ExitKey.load()) && !repeated_input && w == WM_KEYDOWN) Jimmy_Global_properties.Locker_IsLocked = false; if (Jimmy_Global_properties.Locker_IsLocked && (((KBDLLHOOKSTRUCT*)l)->vkCode == VK_LWIN || ((KBDLLHOOKSTRUCT*)l)->vkCode == VK_RWIN)) return true; return false; }); EnumDisplayMonitors(GetDC(0), NULL, &ENudi, (LPARAM)NULL); std::for_each(ddesk.begin(), ddesk.end(), [&](display_deskriptor dd) -> void { sf::RenderWindow* wpt = new sf::RenderWindow(sf::VideoMode(dd.sx + 1, dd.sy + 1), "", sf::Style::None); if (wpt) { while (wpt->pollEvent(evt)); wpt->clear(sf::Color(50, 180, 50)); wpt->display(); wpt->setVerticalSyncEnabled(true); SetWindowPos(wpt->getSystemHandle(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); wpt->setPosition(sf::Vector2i(dd.px - 1, dd.py)); winvec.push_back(wpt); } }); gradi_unlock.from = sf::Color(0, 0, 0); gradi_unlock.to = sf::Color(200, 200, 200); gradi_lock.from = sf::Color(200, 200, 200); gradi_lock.to = sf::Color(0, 0, 0); } if (Jimmy_Global_properties.Locker_IsLocked || unlockAnim.getElapsedTime().asMilliseconds() < ANIM_TIME_ALL || lockAnim.getElapsedTime().asMilliseconds() < ANIM_TIME_ALL) { if (justLocked == false) { std::for_each(winvec.begin(), winvec.end(), [&](sf::RenderWindow* wpt) -> void { ShowWindow(wpt->getSystemHandle(), SW_SHOW); }); justLocked = true; lockAnim.restart(); } if (!Jimmy_Global_properties.Locker_IsLocked == false) { unlockAnim.restart(); } { HWND hw = winvec[0]->getSystemHandle(); SetForegroundWindow(hw); SetActiveWindow(hw); } std::for_each(winvec.begin(), winvec.end(), [&](sf::RenderWindow* wpt) -> void { ShowWindow(wpt->getSystemHandle(), SW_NORMAL); while (wpt->pollEvent(evt)); if (Jimmy_Global_properties.Locker_IsLocked) { int cval = lockAnim.getElapsedTime().asMilliseconds(); if (cval > ANIM_TIME) cval = ANIM_TIME; wpt->clear(gradi_lock.getVal(cval / ANIM_TIME)); } else { int cval = unlockAnim.getElapsedTime().asMilliseconds(); if (cval > ANIM_TIME) cval = ANIM_TIME; wpt->clear(gradi_unlock.getVal(cval / ANIM_TIME)); } tx.setCharacterSize(25); tx.setFillColor(sf::Color::White); tx.setString( "MouseBlocking --> " + std::string(Jimmy_Global_properties.Block_Injected_Mouse ? "True\n" : "False\n") + "KeyboardBlocking --> " + std::string(Jimmy_Global_properties.Block_Injected_Keyboard ? "True\n" : "False\n") + "OverlayService --> " + std::string(Jimmy_Global_properties.Media_Overlay_Service ? "True\n" : "False\n") ); tx.setPosition(0, 0); tx.setOrigin(sf::Vector2f(0, 0)); tx.setPosition({ 10,10 }); wpt->draw(tx); wpt->display(); }); } else { if (justLocked) { std::for_each(winvec.begin(), winvec.end(), [&](sf::RenderWindow* wpt) -> void { ShowWindow(wpt->getSystemHandle(), SW_HIDE); }); justLocked = false; } std::for_each(winvec.begin(), winvec.end(), [&](sf::RenderWindow* wpt) -> void { while (wpt->pollEvent(evt)); }); Sleep(10); } }
33.581633
174
0.558341
[ "vector" ]
144974b53251d064eadaa8cb5290175a457d3e05
24,182
cc
C++
L1Trigger/TrackFindingTracklet/plugins/L1FPGATrackProducer.cc
vegajustin26/cmssw
96c978e46803b32e86ec46085f2876fae476258f
[ "Apache-2.0" ]
1
2022-03-07T17:42:33.000Z
2022-03-07T17:42:33.000Z
L1Trigger/TrackFindingTracklet/plugins/L1FPGATrackProducer.cc
varsill/cmssw
18c56dbcab98dfc5d415deca0daf2395121bf5ae
[ "Apache-2.0" ]
null
null
null
L1Trigger/TrackFindingTracklet/plugins/L1FPGATrackProducer.cc
varsill/cmssw
18c56dbcab98dfc5d415deca0daf2395121bf5ae
[ "Apache-2.0" ]
1
2022-01-17T12:32:41.000Z
2022-01-17T12:32:41.000Z
////////////////////////// // Producer by Anders // // and Emmanuele // // july 2012 @ CU // ////////////////////////// //////////////////// // FRAMEWORK HEADERS #include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" // #include "FWCore/Framework/interface/one/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/FileInPath.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" // #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" /////////////////////// // DATA FORMATS HEADERS #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" // #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/SiPixelDetId/interface/PXBDetId.h" #include "DataFormats/SiPixelDetId/interface/PXFDetId.h" #include "DataFormats/Common/interface/DetSetVector.h" // #include "L1Trigger/TrackFindingTracklet/interface/SLHCEvent.h" #include "L1Trigger/TrackFindingTracklet/interface/L1TStub.h" #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "SimDataFormats/TrackingHit/interface/PSimHit.h" #include "SimDataFormats/Track/interface/SimTrack.h" #include "SimDataFormats/Track/interface/SimTrackContainer.h" #include "SimDataFormats/Vertex/interface/SimVertex.h" #include "SimDataFormats/Vertex/interface/SimVertexContainer.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h" #include "SimTracker/TrackTriggerAssociation/interface/TTStubAssociationMap.h" #include "SimTracker/TrackTriggerAssociation/interface/TTClusterAssociationMap.h" // #include "DataFormats/Math/interface/LorentzVector.h" #include "DataFormats/Math/interface/Vector3D.h" // #include "DataFormats/L1TrackTrigger/interface/TTCluster.h" #include "DataFormats/L1TrackTrigger/interface/TTStub.h" #include "DataFormats/L1TrackTrigger/interface/TTTrack.h" #include "DataFormats/L1TrackTrigger/interface/TTTrack_TrackWord.h" #include "DataFormats/L1TrackTrigger/interface/TTTypes.h" #include "DataFormats/L1TrackTrigger/interface/TTDTC.h" #include "L1Trigger/TrackerDTC/interface/Setup.h" // #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/Candidate/interface/Candidate.h" // #include "DataFormats/GeometryCommonDetAlgo/interface/MeasurementPoint.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "DataFormats/SiPixelDetId/interface/PixelChannelIdentifier.h" #include "TrackingTools/GeomPropagators/interface/HelixArbitraryPlaneCrossing.h" //////////////////////////// // DETECTOR GEOMETRY HEADERS #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/CommonTopologies/interface/PixelGeomDetUnit.h" #include "Geometry/CommonTopologies/interface/PixelGeomDetType.h" #include "Geometry/TrackerGeometryBuilder/interface/PixelTopologyBuilder.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/RectangularPixelTopology.h" #include "Geometry/CommonDetUnit/interface/GeomDetType.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" // #include "Geometry/Records/interface/StackedTrackerGeometryRecord.h" /////////////// // Tracklet emulation #include "L1Trigger/TrackFindingTracklet/interface/Settings.h" #include "L1Trigger/TrackFindingTracklet/interface/Sector.h" #include "L1Trigger/TrackFindingTracklet/interface/Track.h" #include "L1Trigger/TrackFindingTracklet/interface/TrackletEventProcessor.h" //////////////// // PHYSICS TOOLS #include "RecoTracker/TkSeedGenerator/interface/FastHelix.h" #include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h" #include "DataFormats/GeometryCommonDetAlgo/interface/MeasurementVector.h" #include "DataFormats/GeometrySurface/interface/BoundPlane.h" #include "L1Trigger/TrackTrigger/interface/StubPtConsistency.h" #include "L1Trigger/TrackTrigger/interface/TrackQuality.h" ////////////// // STD HEADERS #include <memory> #include <string> #include <iostream> #include <fstream> ////////////// // NAMESPACES using namespace edm; using namespace std; ////////////////////////////// // // // CLASS DEFINITION // // // ////////////////////////////// ///////////////////////////////////// // this class is needed to make a map // between different types of stubs struct L1TStubCompare { public: bool operator()(const trklet::L1TStub& a, const trklet::L1TStub& b) const { if (a.x() != b.x()) return (b.x() > a.x()); else { if (a.y() != b.y()) return (b.y() > a.y()); else return (a.z() > b.z()); } } }; class L1FPGATrackProducer : public edm::one::EDProducer<edm::one::WatchRuns> { public: /// Constructor/destructor explicit L1FPGATrackProducer(const edm::ParameterSet& iConfig); ~L1FPGATrackProducer() override; private: int eventnum; /// Containers of parameters passed by python configuration file edm::ParameterSet config; bool readMoreMcTruth_; /// File path for configuration files edm::FileInPath fitPatternFile; edm::FileInPath memoryModulesFile; edm::FileInPath processingModulesFile; edm::FileInPath wiresFile; edm::FileInPath tableTEDFile; edm::FileInPath tableTREFile; string asciiEventOutName_; std::ofstream asciiEventOut_; // settings containing various constants for the tracklet processing trklet::Settings settings; // event processor for the tracklet track finding trklet::TrackletEventProcessor eventProcessor; unsigned int nHelixPar_; bool extended_; bool trackQuality_; std::unique_ptr<TrackQuality> trackQualityModel_; std::map<string, vector<int>> dtclayerdisk; edm::ESHandle<TrackerTopology> tTopoHandle; edm::ESHandle<TrackerGeometry> tGeomHandle; edm::InputTag MCTruthClusterInputTag; edm::InputTag MCTruthStubInputTag; edm::InputTag TrackingParticleInputTag; const edm::EDGetTokenT<reco::BeamSpot> bsToken_; edm::EDGetTokenT<TTClusterAssociationMap<Ref_Phase2TrackerDigi_>> ttClusterMCTruthToken_; edm::EDGetTokenT<std::vector<TrackingParticle>> TrackingParticleToken_; edm::EDGetTokenT<TTDTC> tokenDTC_; // helper class to store DTC configuration trackerDTC::Setup setup_; // Setup token edm::ESGetToken<trackerDTC::Setup, trackerDTC::SetupRcd> esGetToken_; /// ///////////////// /// /// MANDATORY METHODS /// void beginRun(const edm::Run& run, const edm::EventSetup& iSetup) override; void endRun(edm::Run const&, edm::EventSetup const&) override; void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override; }; ////////////// // CONSTRUCTOR L1FPGATrackProducer::L1FPGATrackProducer(edm::ParameterSet const& iConfig) : config(iConfig), readMoreMcTruth_(iConfig.getParameter<bool>("readMoreMcTruth")), MCTruthClusterInputTag(readMoreMcTruth_ ? config.getParameter<edm::InputTag>("MCTruthClusterInputTag") : edm::InputTag()), MCTruthStubInputTag(readMoreMcTruth_ ? config.getParameter<edm::InputTag>("MCTruthStubInputTag") : edm::InputTag()), TrackingParticleInputTag(readMoreMcTruth_ ? iConfig.getParameter<edm::InputTag>("TrackingParticleInputTag") : edm::InputTag()), bsToken_(consumes<reco::BeamSpot>(config.getParameter<edm::InputTag>("BeamSpotSource"))), tokenDTC_(consumes<TTDTC>(edm::InputTag(iConfig.getParameter<edm::InputTag>("InputTagTTDTC")))) { if (readMoreMcTruth_) { ttClusterMCTruthToken_ = consumes<TTClusterAssociationMap<Ref_Phase2TrackerDigi_>>(MCTruthClusterInputTag); TrackingParticleToken_ = consumes<std::vector<TrackingParticle>>(TrackingParticleInputTag); } produces<std::vector<TTTrack<Ref_Phase2TrackerDigi_>>>("Level1TTTracks").setBranchAlias("Level1TTTracks"); asciiEventOutName_ = iConfig.getUntrackedParameter<string>("asciiFileName", ""); fitPatternFile = iConfig.getParameter<edm::FileInPath>("fitPatternFile"); processingModulesFile = iConfig.getParameter<edm::FileInPath>("processingModulesFile"); memoryModulesFile = iConfig.getParameter<edm::FileInPath>("memoryModulesFile"); wiresFile = iConfig.getParameter<edm::FileInPath>("wiresFile"); extended_ = iConfig.getParameter<bool>("Extended"); nHelixPar_ = iConfig.getParameter<unsigned int>("Hnpar"); if (extended_) { tableTEDFile = iConfig.getParameter<edm::FileInPath>("tableTEDFile"); tableTREFile = iConfig.getParameter<edm::FileInPath>("tableTREFile"); } // book ES product esGetToken_ = esConsumes<trackerDTC::Setup, trackerDTC::SetupRcd, edm::Transition::BeginRun>(); // -------------------------------------------------------------------------------- // set options in Settings based on inputs from configuration files // -------------------------------------------------------------------------------- settings.setExtended(extended_); settings.setNHelixPar(nHelixPar_); settings.setFitPatternFile(fitPatternFile.fullPath()); settings.setProcessingModulesFile(processingModulesFile.fullPath()); settings.setMemoryModulesFile(memoryModulesFile.fullPath()); settings.setWiresFile(wiresFile.fullPath()); if (extended_) { settings.setTableTEDFile(tableTEDFile.fullPath()); settings.setTableTREFile(tableTREFile.fullPath()); //FIXME: The TED and TRE tables are currently disabled by default, so we //need to allow for the additional tracklets that will eventually be //removed by these tables, once they are finalized settings.setNbitstrackletindex(10); } eventnum = 0; if (not asciiEventOutName_.empty()) { asciiEventOut_.open(asciiEventOutName_.c_str()); } if (settings.debugTracklet()) { edm::LogVerbatim("Tracklet") << "fit pattern : " << fitPatternFile.fullPath() << "\n process modules : " << processingModulesFile.fullPath() << "\n memory modules : " << memoryModulesFile.fullPath() << "\n wires : " << wiresFile.fullPath(); if (extended_) { edm::LogVerbatim("Tracklet") << "table_TED : " << tableTEDFile.fullPath() << "\n table_TRE : " << tableTREFile.fullPath(); } } trackQuality_ = iConfig.getParameter<bool>("TrackQuality"); if (trackQuality_) { trackQualityModel_ = std::make_unique<TrackQuality>(iConfig.getParameter<edm::ParameterSet>("TrackQualityPSet")); } } ///////////// // DESTRUCTOR L1FPGATrackProducer::~L1FPGATrackProducer() { if (asciiEventOut_.is_open()) { asciiEventOut_.close(); } } ///////END RUN // void L1FPGATrackProducer::endRun(const edm::Run& run, const edm::EventSetup& iSetup) {} //////////// // BEGIN JOB void L1FPGATrackProducer::beginRun(const edm::Run& run, const edm::EventSetup& iSetup) { //////////////////////// // GET MAGNETIC FIELD // edm::ESHandle<MagneticField> magneticFieldHandle; iSetup.get<IdealMagneticFieldRecord>().get(magneticFieldHandle); const MagneticField* theMagneticField = magneticFieldHandle.product(); double mMagneticFieldStrength = theMagneticField->inTesla(GlobalPoint(0, 0, 0)).z(); settings.setBfield(mMagneticFieldStrength); setup_ = iSetup.getData(esGetToken_); // initialize the tracklet event processing (this sets all the processing & memory modules, wiring, etc) eventProcessor.init(settings); } ////////// // PRODUCE void L1FPGATrackProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { typedef std::map<trklet::L1TStub, edm::Ref<edmNew::DetSetVector<TTStub<Ref_Phase2TrackerDigi_>>, TTStub<Ref_Phase2TrackerDigi_>>, L1TStubCompare> stubMapType; typedef edm::Ref<edmNew::DetSetVector<TTCluster<Ref_Phase2TrackerDigi_>>, TTCluster<Ref_Phase2TrackerDigi_>> TTClusterRef; /// Prepare output auto L1TkTracksForOutput = std::make_unique<std::vector<TTTrack<Ref_Phase2TrackerDigi_>>>(); stubMapType stubMap; /// Geometry handles etc edm::ESHandle<TrackerGeometry> geometryHandle; /// Set pointers to Stacked Modules iSetup.get<TrackerDigiGeometryRecord>().get(geometryHandle); //////////// // GET BS // edm::Handle<reco::BeamSpot> beamSpotHandle; iEvent.getByToken(bsToken_, beamSpotHandle); math::XYZPoint bsPosition = beamSpotHandle->position(); iSetup.get<TrackerTopologyRcd>().get(tTopoHandle); iSetup.get<TrackerDigiGeometryRecord>().get(tGeomHandle); eventnum++; trklet::SLHCEvent ev; ev.setEventNum(eventnum); ev.setIP(bsPosition.x(), bsPosition.y()); // tracking particles edm::Handle<std::vector<TrackingParticle>> TrackingParticleHandle; if (readMoreMcTruth_) iEvent.getByToken(TrackingParticleToken_, TrackingParticleHandle); // tracker topology const TrackerTopology* const tTopo = tTopoHandle.product(); const TrackerGeometry* const theTrackerGeom = tGeomHandle.product(); //////////////////////// // GET THE PRIMITIVES // edm::Handle<TTDTC> handleDTC; iEvent.getByToken<TTDTC>(tokenDTC_, handleDTC); // must be defined for code to compile, even if it's not used unless readMoreMcTruth_ is true map<edm::Ptr<TrackingParticle>, int> translateTP; // MC truth association maps edm::Handle<TTClusterAssociationMap<Ref_Phase2TrackerDigi_>> MCTruthTTClusterHandle; if (readMoreMcTruth_) { iEvent.getByToken(ttClusterMCTruthToken_, MCTruthTTClusterHandle); //////////////////////////////////////////////// /// LOOP OVER TRACKING PARTICLES & GET SIMTRACKS int ntps = 1; //count from 1 ; 0 will mean invalid int this_tp = 0; for (const auto& iterTP : *TrackingParticleHandle) { edm::Ptr<TrackingParticle> tp_ptr(TrackingParticleHandle, this_tp); this_tp++; // only keep TPs producing a cluster if (MCTruthTTClusterHandle->findTTClusterRefs(tp_ptr).empty()) continue; if (iterTP.g4Tracks().empty()) { continue; } int sim_eventid = iterTP.g4Tracks().at(0).eventId().event(); int sim_type = iterTP.pdgId(); float sim_pt = iterTP.pt(); float sim_eta = iterTP.eta(); float sim_phi = iterTP.phi(); float vx = iterTP.vertex().x(); float vy = iterTP.vertex().y(); float vz = iterTP.vertex().z(); if (sim_pt < 1.0 || std::abs(vz) > 100.0 || hypot(vx, vy) > 50.0) continue; ev.addL1SimTrack(sim_eventid, ntps, sim_type, sim_pt, sim_eta, sim_phi, vx, vy, vz); translateTP[tp_ptr] = ntps; ntps++; } //end loop over TPs } // end if (readMoreMcTruth_) ///////////////////////////////// /// READ DTC STUB INFORMATION /// ///////////////////////////////// // Process stubs in each region and channel within that region for (const int& region : handleDTC->tfpRegions()) { for (const int& channel : handleDTC->tfpChannels()) { // Get the DTC name form the channel static string dtcbasenames[12] = { "PS10G_1", "PS10G_2", "PS10G_3", "PS10G_4", "PS_1", "PS_2", "2S_1", "2S_2", "2S_3", "2S_4", "2S_5", "2S_6"}; string dtcname = dtcbasenames[channel % 12]; if (channel % 24 >= 12) dtcname = "neg" + dtcname; dtcname += (channel < 24) ? "_A" : "_B"; // Get the stubs from the DTC const TTDTC::Stream& streamFromDTC{handleDTC->stream(region, channel)}; // Prepare the DTC stubs for the IR for (size_t stubIndex = 0; stubIndex < streamFromDTC.size(); ++stubIndex) { const TTDTC::Frame& stub{streamFromDTC[stubIndex]}; if (stub.first.isNull()) { continue; } const GlobalPoint& ttPos = setup_.stubPos(stub.first); //Get the 2 bits for the layercode string layerword = stub.second.to_string().substr(61, 2); unsigned int layercode = 2 * (layerword[0] - '0') + layerword[1] - '0'; assert(layercode < 4); //translation from the two bit layercode to the layer/disk number of each of the //12 channels (dtcs) static int layerdisktab[12][4] = {{0, 6, 8, 10}, {0, 7, 9, -1}, {1, 7, -1, -1}, {6, 8, 10, -1}, {2, 7, -1, -1}, {2, 9, -1, -1}, {3, 4, -1, -1}, {4, -1, -1, -1}, {5, -1, -1, -1}, {5, 8, -1, -1}, {6, 9, -1, -1}, {7, 10, -1, -1}}; int layerdisk = layerdisktab[channel % 12][layercode]; assert(layerdisk != -1); //Get the 36 bit word - skip the lowest 3 buts (status and layer code) constexpr int DTCLinkWordSize = 64; constexpr int StubWordSize = 36; constexpr int LayerandStatusCodeSize = 3; string stubword = stub.second.to_string().substr(DTCLinkWordSize - StubWordSize - LayerandStatusCodeSize, StubWordSize); string stubwordhex = ""; //Loop over the 9 words in the 36 bit stub word for (unsigned int i = 0; i < 9; i++) { bitset<4> bits(stubword.substr(i * 4, 4)); ulong val = bits.to_ulong(); stubwordhex += ((val < 10) ? ('0' + val) : ('A' + val - 10)); } /// Get the Inner and Outer TTCluster edm::Ref<edmNew::DetSetVector<TTCluster<Ref_Phase2TrackerDigi_>>, TTCluster<Ref_Phase2TrackerDigi_>> innerCluster = stub.first->clusterRef(0); edm::Ref<edmNew::DetSetVector<TTCluster<Ref_Phase2TrackerDigi_>>, TTCluster<Ref_Phase2TrackerDigi_>> outerCluster = stub.first->clusterRef(1); // ----------------------------------------------------- // check module orientation, if flipped, need to store that information for track fit // ----------------------------------------------------- const DetId innerDetId = innerCluster->getDetId(); const GeomDetUnit* det_inner = theTrackerGeom->idToDetUnit(innerDetId); const auto* theGeomDet_inner = dynamic_cast<const PixelGeomDetUnit*>(det_inner); const PixelTopology* topol_inner = dynamic_cast<const PixelTopology*>(&(theGeomDet_inner->specificTopology())); MeasurementPoint coords_inner = innerCluster->findAverageLocalCoordinatesCentered(); LocalPoint clustlp_inner = topol_inner->localPosition(coords_inner); GlobalPoint posStub_inner = theGeomDet_inner->surface().toGlobal(clustlp_inner); const DetId outerDetId = outerCluster->getDetId(); const GeomDetUnit* det_outer = theTrackerGeom->idToDetUnit(outerDetId); const auto* theGeomDet_outer = dynamic_cast<const PixelGeomDetUnit*>(det_outer); const PixelTopology* topol_outer = dynamic_cast<const PixelTopology*>(&(theGeomDet_outer->specificTopology())); MeasurementPoint coords_outer = outerCluster->findAverageLocalCoordinatesCentered(); LocalPoint clustlp_outer = topol_outer->localPosition(coords_outer); GlobalPoint posStub_outer = theGeomDet_outer->surface().toGlobal(clustlp_outer); bool isFlipped = (posStub_outer.mag() < posStub_inner.mag()); vector<int> assocTPs; for (unsigned int iClus = 0; iClus <= 1; iClus++) { // Loop over both clusters that make up stub. const TTClusterRef& ttClusterRef = stub.first->clusterRef(iClus); // Now identify all TP's contributing to either cluster in stub. vector<edm::Ptr<TrackingParticle>> vecTpPtr = MCTruthTTClusterHandle->findTrackingParticlePtrs(ttClusterRef); for (const edm::Ptr<TrackingParticle>& tpPtr : vecTpPtr) { if (translateTP.find(tpPtr) != translateTP.end()) { if (iClus == 0) { assocTPs.push_back(translateTP.at(tpPtr)); } else { assocTPs.push_back(-translateTP.at(tpPtr)); } // N.B. Since not all tracking particles are stored in InputData::vTPs_, sometimes no match will be found. } else { assocTPs.push_back(0); } } } double stubbend = stub.first->bendFE(); //stub.first->rawBend() if (ttPos.z() < -120) { stubbend = -stubbend; } ev.addStub(dtcname, region, layerdisk, stubwordhex, setup_.psModule(setup_.dtcId(region, channel)), isFlipped, ttPos.x(), ttPos.y(), ttPos.z(), stubbend, stub.first->innerClusterPosition(), assocTPs); const trklet::L1TStub& lastStub = ev.lastStub(); stubMap[lastStub] = stub.first; } } } ////////////////////////// // NOW RUN THE L1 tracking if (!asciiEventOutName_.empty()) { ev.write(asciiEventOut_); } const std::vector<trklet::Track>& tracks = eventProcessor.tracks(); // this performs the actual tracklet event processing eventProcessor.event(ev); int ntracks = 0; for (const auto& track : tracks) { if (track.duplicate()) continue; ntracks++; // this is where we create the TTTrack object double tmp_rinv = track.rinv(settings); double tmp_phi = track.phi0(settings); double tmp_tanL = track.tanL(settings); double tmp_z0 = track.z0(settings); double tmp_d0 = track.d0(settings); double tmp_chi2rphi = track.chisqrphi(); double tmp_chi2rz = track.chisqrz(); unsigned int tmp_hit = track.hitpattern(); TTTrack<Ref_Phase2TrackerDigi_> aTrack(tmp_rinv, tmp_phi, tmp_tanL, tmp_z0, tmp_d0, tmp_chi2rphi, tmp_chi2rz, 0, 0, 0, tmp_hit, settings.nHelixPar(), settings.bfield()); unsigned int trksector = track.sector(); unsigned int trkseed = (unsigned int)abs(track.seed()); aTrack.setPhiSector(trksector); aTrack.setTrackSeedType(trkseed); const vector<trklet::L1TStub>& stubptrs = track.stubs(); vector<trklet::L1TStub> stubs; stubs.reserve(stubptrs.size()); for (const auto& stubptr : stubptrs) { stubs.push_back(stubptr); } stubMapType::const_iterator it; for (const auto& itstubs : stubs) { it = stubMap.find(itstubs); if (it != stubMap.end()) { aTrack.addStubRef(it->second); } else { // could not find stub in stub map } } // pt consistency aTrack.setStubPtConsistency( StubPtConsistency::getConsistency(aTrack, theTrackerGeom, tTopo, settings.bfield(), settings.nHelixPar())); // set TTTrack word aTrack.setTrackWordBits(); if (trackQuality_) { trackQualityModel_->setTrackQuality(aTrack); } // test track word //aTrack.testTrackWordBits(); L1TkTracksForOutput->push_back(aTrack); } iEvent.put(std::move(L1TkTracksForOutput), "Level1TTTracks"); } /// End of produce() // /////////////////////////// // // DEFINE THIS AS A PLUG-IN DEFINE_FWK_MODULE(L1FPGATrackProducer);
37.433437
120
0.642668
[ "geometry", "object", "vector" ]
1450f8ee020c1bf6a729e213661f6bff23e7fc3b
3,740
hpp
C++
src/Rendering/Material.hpp
LuisEduardoR/SCC0250---CG
e115c0d63d7f55e4fe9eb43dcf1ab6c754ed9f17
[ "MIT" ]
1
2021-06-10T17:23:24.000Z
2021-06-10T17:23:24.000Z
src/Rendering/Material.hpp
LuisEduardoR/SCC0250-CG
e115c0d63d7f55e4fe9eb43dcf1ab6c754ed9f17
[ "MIT" ]
null
null
null
src/Rendering/Material.hpp
LuisEduardoR/SCC0250-CG
e115c0d63d7f55e4fe9eb43dcf1ab6c754ed9f17
[ "MIT" ]
null
null
null
// Abner Eduardo Silveira Santos - NUSP 10692012 // Amanda de Moura Peres - NUSP 10734522 // Luís Eduardo Rozante de Freitas Pereira - NUSP 10734794 // Desenvolvido para a disciplina: // SCC0250 - Computação Gráfica (2021) // Prof. Ricardo M. Marcacini /* This file contains the base classes to represent 2D material */ # ifndef MATERIAL_HPP # define MATERIAL_HPP # define CONST_PI 3.14159265358979323846f # include "../Assets/WavefrontMaterial.hpp" # include "../Math/Vector.hpp" # include <GL/glew.h> # include <cmath> # include <vector> # include <memory> union Matrix4x4; class TextureObject; class Shader; // Base material class Material { public: explicit Material(std::shared_ptr<Shader> shader); // CONSTRUCTORS Material(const Material& other) = default; Material(Material&& other) = default; // OPERATORS auto operator=(const Material& other) -> Material& = default; auto operator=(Material&& other) -> Material& = default; // DESTRUCTOR virtual ~Material() = default; public: // Sets this material for rendering. virtual auto Bind() -> void; private: std::shared_ptr<Shader> shader; }; // Default material for most 3D objects class DefaultMaterial : public Material { public: static constexpr std::size_t MAX_LIGHTS{ 10 }; // Transformation static constexpr GLint LOCATION_MODEL{ 0 }; static constexpr GLint LOCATION_VIEW{ 1 }; static constexpr GLint LOCATION_PROJECTION{ 2 }; // Base color /* static constexpr GLint LOCATION_COLOR{ 3 }; */ static constexpr GLint LOCATION_TEXTURE{ 4 }; // Ambient Light static constexpr GLint LOCATION_AMBIENT_LIGHT_COLOR{ 5 }; // Material Properties static constexpr GLint LOCATION_AMBIENT_REFLECTIVITY{ 6 }; static constexpr GLint LOCATION_DIFFUSE_REFLECTIVITY{ 7 }; static constexpr GLint LOCATION_SPECULAR_REFLECTIVITY{ 8 }; static constexpr GLint LOCATION_SPECULAR_EXPONENT{ 9 }; // Point Lights static constexpr GLint LOCATION_LIGHTS{ 10 }; public: // CONSTRUCTORS DefaultMaterial( std::shared_ptr<Shader> shader, const WavefrontMaterial& material, std::shared_ptr<TextureObject> texture); DefaultMaterial(const DefaultMaterial& other) = default; DefaultMaterial(DefaultMaterial&& other) = default; // OPERATORS auto operator=(const DefaultMaterial& other) -> DefaultMaterial& = default; auto operator=(DefaultMaterial&& other) -> DefaultMaterial& = default; // DESTRUCTOR ~DefaultMaterial() override = default; public: // Sets this material for rendering. auto Bind() -> void override; private: /* Color color; */ std::shared_ptr<TextureObject> texture; Vector3 ambientReflectivity; Vector3 diffuseReflectivity; Vector3 specularReflectivity; float specularExponent; }; // Special material for the skybox class SkyboxMaterial : public Material { public: // Transformation static constexpr GLint LOCATION_VIEW{ 1 }; // Base color static constexpr GLint LOCATION_TEXTURE{ 4 }; public: // CONSTRUCTORS SkyboxMaterial(std::shared_ptr<Shader> shader, std::shared_ptr<TextureObject> texture); SkyboxMaterial(const SkyboxMaterial& other) = default; SkyboxMaterial(SkyboxMaterial&& other) = default; // OPERATORS auto operator=(const SkyboxMaterial& other) -> SkyboxMaterial& = default; auto operator=(SkyboxMaterial&& other) -> SkyboxMaterial& = default; // DESTRUCTOR ~SkyboxMaterial() override = default; public: // Sets this material for rendering. auto Bind() -> void override; private: std::shared_ptr<TextureObject> texture; }; # endif /* end of include guard: MATERIAL_HPP */
26.714286
91
0.708289
[ "vector", "3d" ]
145523e58f886c21f1b0cd965dea1143652c1e48
522
cpp
C++
IfcPlusPlus/src/ifcpp/model/AttributeObject.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
IfcPlusPlus/src/ifcpp/model/AttributeObject.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
IfcPlusPlus/src/ifcpp/model/AttributeObject.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
//#include "AttributeObject.h" //AttributeObject::AttributeObject() {} //AttributeObject::AttributeObject(std::vector<shared_ptr<BuildingObject> >& vec) { m_vec = vec; } //AttributeObject::~AttributeObject() {} ////virtual const char* className() const { return "AttributeObject"; } //shared_ptr<BuildingObject> AttributeObject::getDeepCopy() const { return shared_ptr<BuildingObject>(new AttributeObject()); } // //void AttributeObject::getStepParameter(std::stringstream& stream, bool is_select_type) const {}
52.2
128
0.747126
[ "vector" ]
145ed9a2f8b7ae3bf6b42c0bfaf0731e22a1b6b3
12,670
cpp
C++
scratchpad/cpp_connections/vanilia/nparray/tcontract.cpp
Argonne-QIS/QTensor
db0d5199ab4d127d4b05ae472bc130a9fdc48485
[ "MIT" ]
null
null
null
scratchpad/cpp_connections/vanilia/nparray/tcontract.cpp
Argonne-QIS/QTensor
db0d5199ab4d127d4b05ae472bc130a9fdc48485
[ "MIT" ]
null
null
null
scratchpad/cpp_connections/vanilia/nparray/tcontract.cpp
Argonne-QIS/QTensor
db0d5199ab4d127d4b05ae472bc130a9fdc48485
[ "MIT" ]
null
null
null
#include "Python.h" #include <iostream> #include "numpy/arrayobject.h" #include <math.h> #include <chrono> #include <complex> #include "mkl.h" using namespace std::chrono; using namespace std; static PyObject * mkl_contract_complex(PyObject *dummy, PyObject *args) { PyObject *argA=NULL, *argB, *argC; PyObject *A=NULL, *B, *C; std::complex<double> *Aptr, *Bptr, *Cptr; std::complex<double> alpha(1, 0); std::complex<double> beta(0, 0); auto epoch = high_resolution_clock::now(); int nd; npy_intp * dimC; if (!PyArg_ParseTuple(args, "OOO!", &argA, &argB, &PyArray_Type, &argC)) return NULL; A = PyArray_FROM_OTF(argA, NPY_COMPLEX128, NPY_ARRAY_IN_ARRAY); if (A == NULL) return NULL; B = PyArray_FROM_OTF(argB, NPY_COMPLEX128, NPY_ARRAY_IN_ARRAY); if (B == NULL) goto fail; #if NPY_API_VERSION >= 0x0000000c C = PyArray_FROM_OTF(argC, NPY_COMPLEX128, NPY_ARRAY_INOUT_ARRAY2); #else C = PyArray_FROM_OTF(argC, NPY_COMPLEX128, NPY_ARRAY_INOUT_ARRAY); #endif if (C == NULL) goto fail; //auto now = high_resolution_clock::now(); //auto millis = duration_cast<milliseconds>(now - epoch).count(); //std::cout << "after convert. duration (μs) = " << millis << std::endl; nd = PyArray_NDIM(C); if (nd!=3) goto fail; dimC = PyArray_DIMS(C); Aptr = (std::complex<double> *)PyArray_DATA(A); Bptr = (std::complex<double> *)PyArray_DATA(B); Cptr = (std::complex<double> *)PyArray_DATA(C); for (int i=0; i<dimC[0]; i++){ // for (int j=0; j<dimC[1]; j++){ // for (int k=0; k<dimC[2]; k++){ // Cptr[i*dimC[1]*dimC[2] + j*dimC[2] + k] = // Aptr[i*dimC[1] + j]*Bptr[i*dimC[2] + k]; // } // } cblas_zgemm(CblasColMajor, CblasNoTrans, CblasTrans, dimC[2], dimC[1], 1, &alpha, Bptr + i*dimC[2], dimC[2], Aptr + i*dimC[1], dimC[1], &beta, Cptr + i*dimC[2]*dimC[1], dimC[2]); } /* code that makes use of arguments */ /* You will probably need at least nd = PyArray_NDIM(<..>) -- number of dimensions dims = PyArray_DIMS(<..>) -- npy_intp array of length nd showing length in each dim. dptr = (double *)PyArray_DATA(<..>) -- pointer to data. If an error occurs goto fail. */ Py_DECREF(A); Py_DECREF(B); Py_DECREF(C); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(A); Py_XDECREF(B); Py_XDECREF(C); return NULL; } static PyObject * mkl_contract(PyObject *dummy, PyObject *args) { PyObject *argA=NULL, *argB, *argC; PyObject *A=NULL, *B, *C; double *Aptr, *Bptr, *Cptr; auto epoch = high_resolution_clock::now(); int nd; npy_intp * dimC; if (!PyArg_ParseTuple(args, "OOO!", &argA, &argB, &PyArray_Type, &argC)) return NULL; A = PyArray_FROM_OTF(argA, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (A == NULL) return NULL; B = PyArray_FROM_OTF(argB, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (B == NULL) goto fail; #if NPY_API_VERSION >= 0x0000000c C = PyArray_FROM_OTF(argC, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY2); #else C = PyArray_FROM_OTF(argC, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY); #endif if (C == NULL) goto fail; //auto now = high_resolution_clock::now(); //auto millis = duration_cast<milliseconds>(now - epoch).count(); //std::cout << "after convert. duration (μs) = " << millis << std::endl; nd = PyArray_NDIM(C); if (nd!=3) goto fail; dimC = PyArray_DIMS(C); Aptr = (double *)PyArray_DATA(A); Bptr = (double *)PyArray_DATA(B); Cptr = (double *)PyArray_DATA(C); for (int i=0; i<dimC[0]; i++){ // for (int j=0; j<dimC[1]; j++){ // for (int k=0; k<dimC[2]; k++){ // Cptr[i*dimC[1]*dimC[2] + j*dimC[2] + k] = // Aptr[i*dimC[1] + j]*Bptr[i*dimC[2] + k]; // } // } cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, dimC[2], dimC[1], 1, 1.0, Bptr + i*dimC[2], dimC[2], Aptr + i*dimC[1], dimC[1], 0.0, Cptr + i*dimC[2]*dimC[1], dimC[2]); } /* code that makes use of arguments */ /* You will probably need at least nd = PyArray_NDIM(<..>) -- number of dimensions dims = PyArray_DIMS(<..>) -- npy_intp array of length nd showing length in each dim. dptr = (double *)PyArray_DATA(<..>) -- pointer to data. If an error occurs goto fail. */ Py_DECREF(A); Py_DECREF(B); Py_DECREF(C); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(A); Py_XDECREF(B); Py_XDECREF(C); return NULL; } static PyObject * triple_loop_contract(PyObject *dummy, PyObject *args) { PyObject *argA=NULL, *argB, *argC; PyObject *A=NULL, *B, *C; double *Aptr, *Bptr, *Cptr; auto epoch = high_resolution_clock::now(); int nd; npy_intp * dimC; if (!PyArg_ParseTuple(args, "OOO!", &argA, &argB, &PyArray_Type, &argC)) return NULL; A = PyArray_FROM_OTF(argA, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (A == NULL) return NULL; B = PyArray_FROM_OTF(argB, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (B == NULL) goto fail; #if NPY_API_VERSION >= 0x0000000c C = PyArray_FROM_OTF(argC, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY2); #else C = PyArray_FROM_OTF(argC, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY); #endif if (C == NULL) goto fail; //auto now = high_resolution_clock::now(); //auto millis = duration_cast<milliseconds>(now - epoch).count(); //std::cout << "after convert. duration (μs) = " << millis << std::endl; nd = PyArray_NDIM(C); if (nd!=3) goto fail; dimC = PyArray_DIMS(C); Aptr = (double *)PyArray_DATA(A); Bptr = (double *)PyArray_DATA(B); Cptr = (double *)PyArray_DATA(C); for (int i=0; i<dimC[0]; i++){ for (int j=0; j<dimC[1]; j++){ for (int k=0; k<dimC[2]; k++){ Cptr[i*dimC[1]*dimC[2] + j*dimC[2] + k] = Aptr[i*dimC[1] + j]*Bptr[i*dimC[2] + k]; } } } Py_DECREF(A); Py_DECREF(B); Py_DECREF(C); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(A); Py_XDECREF(B); Py_XDECREF(C); return NULL; } static PyObject * print_4(PyObject *dummy, PyObject *args) { PyObject *arg=NULL; PyObject *arr=NULL; double *dptr; if (!PyArg_ParseTuple(args, "O", &arg)) return NULL; auto epoch = high_resolution_clock::now(); arr = PyArray_FROM_OTF(arg, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (arr == NULL) return NULL; auto now = high_resolution_clock::now(); auto millis = duration_cast<milliseconds>(now - epoch).count(); std::cout << "after convert. duration (μs) = " << millis << std::endl; dptr = (double *)PyArray_DATA(arr); std::cout << "arr[0] = " << *dptr << std::endl; std::cout << "arr[1] = " << *(dptr+1) << std::endl; std::cout << "arr[2] = " << *(dptr+2) << std::endl; std::cout << "arr[3] = " << *(dptr+3) << std::endl; Py_DECREF(arr); Py_INCREF(Py_None); return Py_None; } // -- Examples static PyObject * integrate3(PyObject * module, PyObject * args) { PyObject * argy=NULL; // Regular Python/C API PyArrayObject * yarr=NULL; // Extended Numpy/C API double dx,dy,dz; std::cout << "in func" <<std::endl; // "O" format -> read argument as a PyObject type into argy (Python/C API) if (!PyArg_ParseTuple(args, "Oddd", &argy,&dx,&dy,&dz)) { PyErr_SetString(PyExc_ValueError, "Error parsing arguments."); return NULL; } std::cout << "parsed" << std::endl; // Determine if it's a complex number array (Numpy/C API) int DTYPE = PyArray_ObjectType(argy, NPY_FLOAT); int iscomplex = PyTypeNum_ISCOMPLEX(DTYPE); std::cout << "Is complex" << iscomplex << std::endl; // parse python object into numpy array (Numpy/C API) yarr = (PyArrayObject *)PyArray_FROM_OTF(argy, DTYPE, NPY_ARRAY_IN_ARRAY); if (yarr==NULL) { Py_INCREF(Py_None); return Py_None; } //just assume this for 3 dimensional array...you can generalize to N dims if (PyArray_NDIM(yarr) != 3) { Py_CLEAR(yarr); PyErr_SetString(PyExc_ValueError, "Expected 3 dimensional integrand"); return NULL; } npy_intp * dims = PyArray_DIMS(yarr); npy_intp i,j,k,m; double * p; //initialize variable to hold result Py_complex result = {.real = 0, .imag = 0}; std::cout << "Is complex" << iscomplex << std::endl; if (iscomplex) { for (i=0;i<dims[0];i++) for (j=0;j<dims[1];j++) for (k=0;k<dims[1];k++) { p = (double*)PyArray_GETPTR3(yarr, i,j,k); result.real += *p; result.imag += *(p+1); } } else { for (i=0;i<dims[0];i++) for (j=0;j<dims[1];j++) for (k=0;k<dims[1];k++) { p = (double*)PyArray_GETPTR3(yarr, i,j,k); result.real += *p; } } //multiply by step size result.real *= (dx*dy*dz); result.imag *= (dx*dy*dz); Py_CLEAR(yarr); //copy result into returnable type with new reference if (iscomplex) { return Py_BuildValue("D", &result); } else { return Py_BuildValue("d", result.real); } }; static PyObject * example_wrapper(PyObject *dummy, PyObject *args) { PyObject *arg1=NULL, *arg2=NULL, *out=NULL; PyObject *arr1=NULL, *arr2=NULL, *oarr=NULL; double *dptr; if (!PyArg_ParseTuple(args, "OOO!", &arg1, &arg2, &PyArray_Type, &out)) return NULL; arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (arr1 == NULL) return NULL; arr2 = PyArray_FROM_OTF(arg2, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (arr2 == NULL) goto fail; #if NPY_API_VERSION >= 0x0000000c oarr = PyArray_FROM_OTF(out, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY2); #else oarr = PyArray_FROM_OTF(out, NPY_DOUBLE, NPY_ARRAY_INOUT_ARRAY); #endif if (oarr == NULL) goto fail; std::cout << "arr1" << std::endl; dptr = (double *)PyArray_DATA(arr1); std::cout << "arrval = " << *dptr << std::endl; std::cout << "arrval = " << *(dptr+1) << std::endl; std::cout << "arrval = " << *(dptr+2) << std::endl; std::cout << "arrval = " << *dptr+3 << std::endl; std::cout << "arrval = " << *dptr+4 << std::endl; /* code that makes use of arguments */ /* You will probably need at least nd = PyArray_NDIM(<..>) -- number of dimensions dims = PyArray_DIMS(<..>) -- npy_intp array of length nd showing length in each dim. dptr = (double *)PyArray_DATA(<..>) -- pointer to data. If an error occurs goto fail. */ Py_DECREF(arr1); Py_DECREF(arr2); Py_DECREF(oarr); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); Py_XDECREF(oarr); return NULL; } // -- static PyMethodDef tcontract_Methods[] = { {"integrate3", integrate3, METH_VARARGS, "Pass 3D numpy array (double or complex) and dx,dy,dz step size. Returns Reimman integral"}, {"example", example_wrapper, METH_VARARGS, "Example from https://numpy.org/doc/stable/user/c-info.how-to-extend.html"}, {"print_4", print_4, METH_VARARGS, "Prints first 4 values of numpy array"}, {"triple_loop_contract", triple_loop_contract, METH_VARARGS, "Contracts two arrays with first common index"}, {"mkl_contract", mkl_contract, METH_VARARGS, "Contracts two arrays with first common index using MKL"}, {"mkl_contract_complex", mkl_contract_complex, METH_VARARGS, "Contracts two arrays with first common index using MKL"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; static struct PyModuleDef module = { PyModuleDef_HEAD_INIT, "tcontract", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ tcontract_Methods }; PyMODINIT_FUNC PyInit_tcontract(void) { // Called on import // Returns a pointer to module, which is insected into `sys.modules` import_array(); // needed for numpy to work return PyModule_Create(&module); }
29.26097
97
0.582557
[ "object", "3d" ]
14615d044487baff1699a051ff4ab56f2546e074
465
cpp
C++
cpp/main.cpp
davemarr621/Social_spider_opt_1
93188ecbe63f1fc0254300a15b63dbc49e766a5b
[ "MIT" ]
22
2015-03-02T13:18:41.000Z
2021-12-04T10:06:11.000Z
cpp/main.cpp
davemarr621/Social_spider_opt_1
93188ecbe63f1fc0254300a15b63dbc49e766a5b
[ "MIT" ]
null
null
null
cpp/main.cpp
davemarr621/Social_spider_opt_1
93188ecbe63f1fc0254300a15b63dbc49e766a5b
[ "MIT" ]
10
2015-12-20T13:23:52.000Z
2021-08-23T02:56:10.000Z
#include "SSA.h" using namespace std; class MyProblem : public Problem { public: MyProblem(unsigned int dimension) : Problem(dimension) { } double eval(const std::vector<double>& solution) { double sum = 0.0; for (int i = 0; i < solution.size(); ++i) { sum += solution[i] * solution[i]; } return sum; } }; int main() { SSA ssa(new MyProblem(30), 30); ssa.run(10000, 1.0, 0.7, 0.1); return 0; }
21.136364
62
0.55914
[ "vector" ]
146338dcebe129c2c56134f885076ff4cc06c215
30,562
cpp
C++
ds/security/cryptoapi/pkitrust/wintrust/winvtrst.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/cryptoapi/pkitrust/wintrust/winvtrst.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/cryptoapi/pkitrust/wintrust/winvtrst.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1996 - 1999 // // File: winvtrst.cpp // // Contents: Microsoft Internet Security Trust Provider // // Functions: WinVerifyTrustEx // WinVerifyTrust // WTHelperGetFileHash // // *** local functions *** // _VerifyTrust // _FillProviderData // _CleanupProviderData // _CleanupProviderNonStateData // _WVTSipFreeSubjectInfo // _WVTSipFreeSubjectInfoKeepState // _WVTSetupProviderData // // History: 31-May-1997 pberkman created // //-------------------------------------------------------------------------- #include "global.hxx" #include "wvtver1.h" #include "softpub.h" #include "imagehlp.h" LONG _VerifyTrust( IN HWND hWnd, IN GUID *pgActionID, IN OUT PWINTRUST_DATA pWinTrustData, OUT OPTIONAL BYTE *pbSubjectHash, IN OPTIONAL OUT DWORD *pcbSubjectHash, OUT OPTIONAL ALG_ID *pHashAlgid ); BOOL _FillProviderData(CRYPT_PROVIDER_DATA *pProvData, HWND hWnd, WINTRUST_DATA *pWinTrustData); void _CleanupProviderData(CRYPT_PROVIDER_DATA *pProvData); void _CleanupProviderNonStateData(CRYPT_PROVIDER_DATA *ProvData); BOOL _WVTSipFreeSubjectInfo(SIP_SUBJECTINFO *pSubj); BOOL _WVTSetupProviderData(CRYPT_PROVIDER_DATA *psProvData, CRYPT_PROVIDER_DATA *psStateProvData); BOOL _WVTSipFreeSubjectInfoKeepState(SIP_SUBJECTINFO *pSubj); VOID FreeWintrustStateData (WINTRUST_DATA* pWintrustData); extern CCatalogCache g_CatalogCache; ////////////////////////////////////////////////////////////////////////////////////// // // WinVerifyTrustEx // // extern "C" HRESULT WINAPI WinVerifyTrustEx(HWND hWnd, GUID *pgActionID, WINTRUST_DATA *pWinTrustData) { return((HRESULT)WinVerifyTrust(hWnd, pgActionID, pWinTrustData)); } #define PE_EXE_HEADER_TAG "MZ" #define PE_EXE_HEADER_TAG_LEN 2 BOOL _IsUnsignedPEFile( PWINTRUST_FILE_INFO pFileInfo ) { BOOL fIsUnsignedPEFile = FALSE; HANDLE hFile = NULL; BOOL fCloseFile = FALSE; BYTE rgbHeader[PE_EXE_HEADER_TAG_LEN]; DWORD dwBytesRead; DWORD dwCertCnt; hFile = pFileInfo->hFile; if (NULL == hFile || INVALID_HANDLE_VALUE == hFile) { hFile = CreateFileU( pFileInfo->pcwszFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, // lpsa OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL // hTemplateFile ); if (INVALID_HANDLE_VALUE == hFile) goto CreateFileError; fCloseFile = TRUE; } if (0 != SetFilePointer( hFile, 0, // lDistanceToMove NULL, // lpDistanceToMoveHigh FILE_BEGIN )) goto SetFilePointerError; dwBytesRead = 0; if (!ReadFile( hFile, rgbHeader, PE_EXE_HEADER_TAG_LEN, &dwBytesRead, NULL // lpOverlapped ) || PE_EXE_HEADER_TAG_LEN != dwBytesRead) goto ReadFileError; if (0 != memcmp(rgbHeader, PE_EXE_HEADER_TAG, PE_EXE_HEADER_TAG_LEN)) goto NotPEFile; // Now see if the PE file is signed dwCertCnt = 0; if (!ImageEnumerateCertificates( hFile, CERT_SECTION_TYPE_ANY, &dwCertCnt, NULL, // Indices 0 // IndexCount ) || 0 == dwCertCnt) fIsUnsignedPEFile = TRUE; CommonReturn: if (fCloseFile) CloseHandle(hFile); return fIsUnsignedPEFile; ErrorReturn: goto CommonReturn; TRACE_ERROR(CreateFileError) TRACE_ERROR(SetFilePointerError) TRACE_ERROR(ReadFileError) TRACE_ERROR(NotPEFile) } extern "C" LONG WINAPI WinVerifyTrust(HWND hWnd, GUID *pgActionID, LPVOID pOld) { PWINTRUST_DATA pWinTrustData = (PWINTRUST_DATA) pOld; // For SAFER, see if this is a unsigned PE file if (_ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, dwProvFlags) && (pWinTrustData->dwProvFlags & WTD_SAFER_FLAG) && (WTD_STATEACTION_IGNORE == pWinTrustData->dwStateAction) && (WTD_CHOICE_FILE == pWinTrustData->dwUnionChoice)) { if (_IsUnsignedPEFile(pWinTrustData->pFile)) { SetLastError((DWORD) TRUST_E_NOSIGNATURE); return (LONG) TRUST_E_NOSIGNATURE; } } return _VerifyTrust( hWnd, pgActionID, pWinTrustData, NULL, // pbSubjectHash NULL, // pcbSubjectHash NULL // pHashAlgid ); } // Returns S_OK and the hash if the file was signed and contains a valid // hash extern "C" LONG WINAPI WTHelperGetFileHash( IN LPCWSTR pwszFilename, IN DWORD dwFlags, IN OUT OPTIONAL PVOID *pvReserved, OUT OPTIONAL BYTE *pbFileHash, IN OUT OPTIONAL DWORD *pcbFileHash, OUT OPTIONAL ALG_ID *pHashAlgid ) { GUID wvtFileActionID = WINTRUST_ACTION_GENERIC_VERIFY_V2; WINTRUST_FILE_INFO wvtFileInfo; WINTRUST_DATA wvtData; // // Initialize the _VerifyTrust input data structure // memset(&wvtData, 0, sizeof(wvtData)); // default all fields to 0 wvtData.cbStruct = sizeof(wvtData); // wvtData.pPolicyCallbackData = // use default code signing EKU // wvtData.pSIPClientData = // no data to pass to SIP wvtData.dwUIChoice = WTD_UI_NONE; // wvtData.fdwRevocationChecks = // do revocation checking if // enabled by admin policy or // IE advanced user options wvtData.dwUnionChoice = WTD_CHOICE_FILE; wvtData.pFile = &wvtFileInfo; // wvtData.dwStateAction = // default verification // wvtData.hWVTStateData = // not applicable for default // wvtData.pwszURLReference = // not used // Only want to get the hash wvtData.dwProvFlags = WTD_HASH_ONLY_FLAG; // // Initialize the WinVerifyTrust file info data structure // memset(&wvtFileInfo, 0, sizeof(wvtFileInfo)); // default all fields to 0 wvtFileInfo.cbStruct = sizeof(wvtFileInfo); wvtFileInfo.pcwszFilePath = pwszFilename; // wvtFileInfo.hFile = // allow WVT to open // wvtFileInfo.pgKnownSubject // allow WVT to determine // // Call _VerifyTrust // return _VerifyTrust( NULL, // hWnd &wvtFileActionID, &wvtData, pbFileHash, pcbFileHash, pHashAlgid ); } LONG _VerifyTrust( IN HWND hWnd, IN GUID *pgActionID, IN OUT PWINTRUST_DATA pWinTrustData, OUT OPTIONAL BYTE *pbSubjectHash, IN OPTIONAL OUT DWORD *pcbSubjectHash, OUT OPTIONAL ALG_ID *pHashAlgid ) { CRYPT_PROVIDER_DATA sProvData; CRYPT_PROVIDER_DATA *pStateProvData; HRESULT hr; BOOL fVersion1; BOOL fCacheableCall; PCATALOG_CACHED_STATE pCachedState = NULL; BOOL fVersion1WVTCalled = FALSE; DWORD cbInSubjectHash; DWORD dwLastError = 0; hr = TRUST_E_PROVIDER_UNKNOWN; pStateProvData = NULL; if (pcbSubjectHash) { cbInSubjectHash = *pcbSubjectHash; *pcbSubjectHash = 0; } else { cbInSubjectHash = 0; } if (pHashAlgid) *pHashAlgid = 0; fCacheableCall = g_CatalogCache.IsCacheableWintrustCall( pWinTrustData ); if ( fCacheableCall == TRUE ) { g_CatalogCache.LockCache(); if ( pWinTrustData->dwStateAction == WTD_STATEACTION_AUTO_CACHE_FLUSH ) { g_CatalogCache.FlushCache(); g_CatalogCache.UnlockCache(); return( ERROR_SUCCESS ); } pCachedState = g_CatalogCache.FindCachedState( pWinTrustData ); g_CatalogCache.AdjustWintrustDataToCachedState( pWinTrustData, pCachedState, FALSE ); } if (WintrustIsVersion1ActionID(pgActionID)) { fVersion1 = TRUE; } else { fVersion1 = FALSE; if (_ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, hWVTStateData)) { if ((pWinTrustData->dwStateAction == WTD_STATEACTION_VERIFY) || (pWinTrustData->dwStateAction == WTD_STATEACTION_CLOSE)) { pStateProvData = WTHelperProvDataFromStateData(pWinTrustData->hWVTStateData); if (pWinTrustData->dwStateAction == WTD_STATEACTION_CLOSE) { if (pWinTrustData->hWVTStateData) { _CleanupProviderData(pStateProvData); DELETE_OBJECT(pWinTrustData->hWVTStateData); } assert( fCacheableCall == FALSE ); return(ERROR_SUCCESS); } } } } if (_WVTSetupProviderData(&sProvData, pStateProvData)) { sProvData.pgActionID = pgActionID; if (!(pStateProvData)) { if (!(WintrustLoadFunctionPointers(pgActionID, sProvData.psPfns))) { // // it may be that we are looking for a version 1 trust provider. // hr = Version1_WinVerifyTrust(hWnd, pgActionID, pWinTrustData); fVersion1WVTCalled = TRUE; } if ( fVersion1WVTCalled == FALSE ) { if (fVersion1) { // // backwards compatibility with IE3.x and previous // WINTRUST_DATA sWinTrustData; WINTRUST_FILE_INFO sWinTrustFileInfo; pWinTrustData = ConvertDataFromVersion1(hWnd, pgActionID, &sWinTrustData, &sWinTrustFileInfo, pWinTrustData); } if (!_FillProviderData(&sProvData, hWnd, pWinTrustData)) { hr = ERROR_NOT_ENOUGH_MEMORY; goto ErrorCase; } } } // On July 27, 2000 removed support for the IE4 way of chain building. sProvData.dwProvFlags |= CPD_USE_NT5_CHAIN_FLAG; if ( fVersion1WVTCalled == FALSE ) { if (sProvData.psPfns->pfnInitialize) { (*sProvData.psPfns->pfnInitialize)(&sProvData); } if (sProvData.psPfns->pfnObjectTrust) { (*sProvData.psPfns->pfnObjectTrust)(&sProvData); } if (sProvData.psPfns->pfnSignatureTrust) { (*sProvData.psPfns->pfnSignatureTrust)(&sProvData); } if (sProvData.psPfns->pfnCertificateTrust) { (*sProvData.psPfns->pfnCertificateTrust)(&sProvData); } if (sProvData.psPfns->pfnFinalPolicy) { hr = (*sProvData.psPfns->pfnFinalPolicy)(&sProvData); } if (sProvData.psPfns->pfnTestFinalPolicy) { (*sProvData.psPfns->pfnTestFinalPolicy)(&sProvData); } if (sProvData.psPfns->pfnCleanupPolicy) { (*sProvData.psPfns->pfnCleanupPolicy)(&sProvData); } dwLastError = sProvData.dwFinalError; if (0 == dwLastError) { dwLastError = (DWORD) hr; } if (pcbSubjectHash && hr != TRUST_E_NOSIGNATURE) { // Return the subject's hash DWORD cbHash; if (sProvData.pPDSip && sProvData.pPDSip->psIndirectData) { cbHash = sProvData.pPDSip->psIndirectData->Digest.cbData; } else { cbHash = 0; } if (cbHash > 0) { *pcbSubjectHash = cbHash; if (pbSubjectHash) { if (cbInSubjectHash >= cbHash) { memcpy(pbSubjectHash, sProvData.pPDSip->psIndirectData->Digest.pbData, cbHash); } else if (S_OK == hr) { hr = ERROR_MORE_DATA; } } if (pHashAlgid) { *pHashAlgid = CertOIDToAlgId( sProvData.pPDSip->psIndirectData->DigestAlgorithm.pszObjId); } } } if (!(pStateProvData)) { // // no previous state saved // if ((_ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, hWVTStateData)) && (pWinTrustData->dwStateAction == WTD_STATEACTION_VERIFY)) { // // first time call and asking to maintain state... // if (!(pWinTrustData->hWVTStateData = (HANDLE)WVTNew(sizeof(CRYPT_PROVIDER_DATA)))) { _CleanupProviderData(&sProvData); hr = ERROR_NOT_ENOUGH_MEMORY; } else { _CleanupProviderNonStateData(&sProvData); memcpy(pWinTrustData->hWVTStateData, &sProvData, sizeof(CRYPT_PROVIDER_DATA)); } } else { _CleanupProviderData(&sProvData); } } else { // // only free up memory specific to this object/member // _CleanupProviderNonStateData(&sProvData); memcpy(pWinTrustData->hWVTStateData, &sProvData, sizeof(CRYPT_PROVIDER_DATA)); } // // in version 1, when called by IE3.x and earlier, if security level is HIGH, // then the no bad UI is set. If we had an error, we want to // set the error to TRUST_E_FAIL. If we do not trust the object, every other // case sets it to TRUST_E_SUBJECT_NOT_TRUSTED and IE throws NO UI.... // if (fVersion1) { if (hr != ERROR_SUCCESS) { if ((pWinTrustData) && (_ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, dwUIChoice))) { if (pWinTrustData->dwUIChoice == WTD_UI_NOBAD) { hr = TRUST_E_FAIL; // ie throws UI. } else { hr = TRUST_E_SUBJECT_NOT_TRUSTED; // ie throws no UI. } } else { hr = TRUST_E_SUBJECT_NOT_TRUSTED; // ie throws no UI. } } } } } else { hr = TRUST_E_SYSTEM_ERROR; } ErrorCase: if ( fCacheableCall == TRUE ) { if ( pCachedState == NULL ) { if ( g_CatalogCache.CreateCachedStateFromWintrustData( pWinTrustData, &pCachedState ) == TRUE ) { g_CatalogCache.AddCachedState( pCachedState ); } } if ( pCachedState == NULL ) { FreeWintrustStateData( pWinTrustData ); } g_CatalogCache.AdjustWintrustDataToCachedState( pWinTrustData, pCachedState, TRUE ); g_CatalogCache.ReleaseCachedState( pCachedState ); g_CatalogCache.UnlockCache(); } SetLastError(dwLastError); return (LONG) hr; } ////////////////////////////////////////////////////////////////////////////////////// // // local utility functions // // BOOL _FillProviderData(CRYPT_PROVIDER_DATA *pProvData, HWND hWnd, WINTRUST_DATA *pWinTrustData) { BOOL fHasTrustPubFlags; // // remember: we do NOT want to return FALSE unless it is an absolutely // catastrophic error! Let the Trust provider handle (eg: none!) // if (pWinTrustData && _ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, dwProvFlags)) pProvData->dwProvFlags = pWinTrustData->dwProvFlags & WTD_PROV_FLAGS_MASK; if ((hWnd == INVALID_HANDLE_VALUE) || !(hWnd)) { if (pWinTrustData->dwUIChoice != WTD_UI_NONE) { hWnd = GetDesktopWindow(); } } pProvData->hWndParent = hWnd; pProvData->hProv = I_CryptGetDefaultCryptProv(0); // get the default and DONT RELEASE IT!!!! pProvData->dwEncoding = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING; pProvData->pWintrustData = pWinTrustData; pProvData->dwError = ERROR_SUCCESS; // allocate errors if (!(pProvData->padwTrustStepErrors)) { if (!(pProvData->padwTrustStepErrors = (DWORD *)WVTNew(TRUSTERROR_MAX_STEPS * sizeof(DWORD)))) { pProvData->dwError = GetLastError(); // // NOTE!! this is currently the only FALSE return, so the caller will // assume ERROR_NOT_ENOUGH_MEMORY if FALSE is returned from this function // return(FALSE); } pProvData->cdwTrustStepErrors = TRUSTERROR_MAX_STEPS; } memset(pProvData->padwTrustStepErrors, 0x00, sizeof(DWORD) * TRUSTERROR_MAX_STEPS); WintrustGetRegPolicyFlags(&pProvData->dwRegPolicySettings); // // do NOT allow test certs EVER! // // Bug 581160: changed April 4, 2001 // pProvData->dwRegPolicySettings &= ~(WTPF_TRUSTTEST | WTPF_TESTCANBEVALID); GetRegSecuritySettings(&pProvData->dwRegSecuritySettings); fHasTrustPubFlags = I_CryptReadTrustedPublisherDWORDValueFromRegistry( CERT_TRUST_PUB_AUTHENTICODE_FLAGS_VALUE_NAME, &pProvData->dwTrustPubSettings ); if (fHasTrustPubFlags) { if (pProvData->dwTrustPubSettings & (CERT_TRUST_PUB_ALLOW_MACHINE_ADMIN_TRUST | CERT_TRUST_PUB_ALLOW_ENTERPRISE_ADMIN_TRUST)) { // End User trust not allowed pProvData->dwRegPolicySettings = WTPF_IGNOREREVOKATION | WTPF_IGNOREREVOCATIONONTS | WTPF_OFFLINEOK_IND | WTPF_OFFLINEOK_COM | WTPF_OFFLINEOKNBU_IND | WTPF_OFFLINEOKNBU_COM | WTPF_ALLOWONLYPERTRUST; } // Allow the safer UI to enable revocation checking if (pProvData->dwTrustPubSettings & CERT_TRUST_PUB_CHECK_PUBLISHER_REV_FLAG) { pProvData->dwRegPolicySettings &= ~WTPF_IGNOREREVOKATION; pProvData->dwRegPolicySettings |= WTPF_OFFLINEOK_IND | WTPF_OFFLINEOK_COM | WTPF_OFFLINEOKNBU_IND | WTPF_OFFLINEOKNBU_COM; } if (pProvData->dwTrustPubSettings & CERT_TRUST_PUB_CHECK_TIMESTAMP_REV_FLAG) { pProvData->dwRegPolicySettings &= ~WTPF_IGNOREREVOCATIONONTS; pProvData->dwRegPolicySettings |= WTPF_OFFLINEOK_IND | WTPF_OFFLINEOK_COM | WTPF_OFFLINEOKNBU_IND | WTPF_OFFLINEOKNBU_COM; } } if (!(pWinTrustData) || !(_ISINSTRUCT(WINTRUST_DATA, pWinTrustData->cbStruct, dwUIChoice))) { pProvData->padwTrustStepErrors[TRUSTERROR_STEP_FINAL_WVTINIT] = (DWORD)ERROR_INVALID_PARAMETER; } return(TRUE); } void _CleanupProviderData(CRYPT_PROVIDER_DATA *pProvData) { // pProvData->hProv: we're using crypt32's default // pProvData->pWintrustData->xxx->hFile if ((pProvData->fOpenedFile) && (pProvData->pWintrustData != NULL)) { HANDLE *phFile; phFile = NULL; switch (pProvData->pWintrustData->dwUnionChoice) { case WTD_CHOICE_FILE: phFile = &pProvData->pWintrustData->pFile->hFile; break; case WTD_CHOICE_CATALOG: phFile = &pProvData->pWintrustData->pCatalog->hMemberFile; break; } if ((phFile) && (*phFile) && (*phFile != INVALID_HANDLE_VALUE)) { CloseHandle(*phFile); *phFile = INVALID_HANDLE_VALUE; pProvData->fOpenedFile = FALSE; } } if (pProvData->dwSubjectChoice == CPD_CHOICE_SIP) { DELETE_OBJECT(pProvData->pPDSip->pSip); DELETE_OBJECT(pProvData->pPDSip->pCATSip); _WVTSipFreeSubjectInfo(pProvData->pPDSip->psSipSubjectInfo); DELETE_OBJECT(pProvData->pPDSip->psSipSubjectInfo); _WVTSipFreeSubjectInfo(pProvData->pPDSip->psSipCATSubjectInfo); DELETE_OBJECT(pProvData->pPDSip->psSipCATSubjectInfo); TrustFreeDecode(WVT_MODID_WINTRUST, (BYTE **)&pProvData->pPDSip->psIndirectData); DELETE_OBJECT(pProvData->pPDSip); } if (pProvData->hMsg) { CryptMsgClose(pProvData->hMsg); pProvData->hMsg = NULL; } // signer structure for (int i = 0; i < (int)pProvData->csSigners; i++) { TrustFreeDecode(WVT_MODID_WINTRUST, (BYTE **)&pProvData->pasSigners[i].psSigner); DeallocateCertChain(pProvData->pasSigners[i].csCertChain, &pProvData->pasSigners[i].pasCertChain); DELETE_OBJECT(pProvData->pasSigners[i].pasCertChain); if (_ISINSTRUCT(CRYPT_PROVIDER_SGNR, pProvData->pasSigners[i].cbStruct, pChainContext) && pProvData->pasSigners[i].pChainContext) CertFreeCertificateChain(pProvData->pasSigners[i].pChainContext); // counter signers for (int i2 = 0; i2 < (int)pProvData->pasSigners[i].csCounterSigners; i2++) { TrustFreeDecode(WVT_MODID_WINTRUST, (BYTE **)&pProvData->pasSigners[i].pasCounterSigners[i2].psSigner); DeallocateCertChain(pProvData->pasSigners[i].pasCounterSigners[i2].csCertChain, &pProvData->pasSigners[i].pasCounterSigners[i2].pasCertChain); DELETE_OBJECT(pProvData->pasSigners[i].pasCounterSigners[i2].pasCertChain); if (_ISINSTRUCT(CRYPT_PROVIDER_SGNR, pProvData->pasSigners[i].pasCounterSigners[i2].cbStruct, pChainContext) && pProvData->pasSigners[i].pasCounterSigners[i2].pChainContext) CertFreeCertificateChain( pProvData->pasSigners[i].pasCounterSigners[i2].pChainContext); } DELETE_OBJECT(pProvData->pasSigners[i].pasCounterSigners); } DELETE_OBJECT(pProvData->pasSigners); // MUST BE DONE LAST!!! Using the force flag!!! if (pProvData->pahStores) { DeallocateStoreChain(pProvData->chStores, pProvData->pahStores); DELETE_OBJECT(pProvData->pahStores); } pProvData->chStores = 0; // pProvData->padwTrustStepErrors DELETE_OBJECT(pProvData->padwTrustStepErrors); // pProvData->pasProvPrivData DELETE_OBJECT(pProvData->pasProvPrivData); pProvData->csProvPrivData = 0; // pProvData->psPfns if (pProvData->psPfns) { if (pProvData->psPfns->psUIpfns) { DELETE_OBJECT(pProvData->psPfns->psUIpfns->psUIData); DELETE_OBJECT(pProvData->psPfns->psUIpfns); } DELETE_OBJECT(pProvData->psPfns); } } void _CleanupProviderNonStateData(CRYPT_PROVIDER_DATA *pProvData) { // pProvData->hProv: we're using default! // pProvData->pWintrustData->xxx->hFile: close! if ((pProvData->fOpenedFile) && (pProvData->pWintrustData != NULL)) { HANDLE *phFile; phFile = NULL; switch (pProvData->pWintrustData->dwUnionChoice) { case WTD_CHOICE_FILE: phFile = &pProvData->pWintrustData->pFile->hFile; break; case WTD_CHOICE_CATALOG: phFile = &pProvData->pWintrustData->pCatalog->hMemberFile; break; } if ((phFile) && (*phFile) && (*phFile != INVALID_HANDLE_VALUE)) { CloseHandle(*phFile); *phFile = INVALID_HANDLE_VALUE; pProvData->fOpenedFile = FALSE; } } if (pProvData->dwSubjectChoice == CPD_CHOICE_SIP) { DELETE_OBJECT(pProvData->pPDSip->pSip); _WVTSipFreeSubjectInfoKeepState(pProvData->pPDSip->psSipSubjectInfo); // pProvData->pPDSip->psSipSubjectInfo: keep // pProvData->pPDSip->pCATSip: keep // pProvData->pPDSip->psSipCATSubjectInfo: keep TrustFreeDecode(WVT_MODID_WINTRUST, (BYTE **)&pProvData->pPDSip->psIndirectData); // pProvData->pPDSip: keep } // pProvData->hMsg: keep // signer structure: keep // pProvData->pahStores: keep // pProvData->padwTrustStepErrors: keep // pProvData->pasProvPrivData: keep // pProvData->psPfns: keep } BOOL _WVTSipFreeSubjectInfo(SIP_SUBJECTINFO *pSubj) { if (!(pSubj)) { return(FALSE); } DELETE_OBJECT(pSubj->pgSubjectType); switch(pSubj->dwUnionChoice) { case MSSIP_ADDINFO_BLOB: DELETE_OBJECT(pSubj->psBlob); break; case MSSIP_ADDINFO_CATMEMBER: if (pSubj->psCatMember) { // The following APIs are in DELAYLOAD'ed mscat32.dll. If the // DELAYLOAD fails an exception is raised. __try { CryptCATClose( CryptCATHandleFromStore(pSubj->psCatMember->pStore)); } __except(EXCEPTION_EXECUTE_HANDLER) { DWORD dwExceptionCode = GetExceptionCode(); } DELETE_OBJECT(pSubj->psCatMember); } break; } return(TRUE); } BOOL _WVTSipFreeSubjectInfoKeepState(SIP_SUBJECTINFO *pSubj) { if (!(pSubj)) { return(FALSE); } DELETE_OBJECT(pSubj->pgSubjectType); switch(pSubj->dwUnionChoice) { case MSSIP_ADDINFO_BLOB: DELETE_OBJECT(pSubj->psBlob); break; case MSSIP_ADDINFO_CATMEMBER: break; } return(TRUE); } BOOL _WVTSetupProviderData(CRYPT_PROVIDER_DATA *psProvData, CRYPT_PROVIDER_DATA *psState) { if (psState) { memcpy(psProvData, psState, sizeof(CRYPT_PROVIDER_DATA)); if (_ISINSTRUCT(CRYPT_PROVIDER_DATA, psProvData->cbStruct, fRecallWithState)) { psProvData->fRecallWithState = TRUE; } return(TRUE); } memset(psProvData, 0x00, sizeof(CRYPT_PROVIDER_DATA)); psProvData->cbStruct = sizeof(CRYPT_PROVIDER_DATA); if (!(psProvData->psPfns = (CRYPT_PROVIDER_FUNCTIONS *)WVTNew(sizeof(CRYPT_PROVIDER_FUNCTIONS)))) { return(FALSE); } memset(psProvData->psPfns, 0x00, sizeof(CRYPT_PROVIDER_FUNCTIONS)); psProvData->psPfns->cbStruct = sizeof(CRYPT_PROVIDER_FUNCTIONS); if (!(psProvData->psPfns->psUIpfns = (CRYPT_PROVUI_FUNCS *)WVTNew(sizeof(CRYPT_PROVUI_FUNCS)))) { return(FALSE); } memset(psProvData->psPfns->psUIpfns, 0x00, sizeof(CRYPT_PROVUI_FUNCS)); psProvData->psPfns->psUIpfns->cbStruct = sizeof(CRYPT_PROVUI_FUNCS); if (!(psProvData->psPfns->psUIpfns->psUIData = (CRYPT_PROVUI_DATA *)WVTNew(sizeof(CRYPT_PROVUI_DATA)))) { return(FALSE); } memset(psProvData->psPfns->psUIpfns->psUIData, 0x00, sizeof(CRYPT_PROVUI_DATA)); psProvData->psPfns->psUIpfns->psUIData->cbStruct = sizeof(CRYPT_PROVUI_DATA); GetSystemTimeAsFileTime(&psProvData->sftSystemTime); return(TRUE); } VOID FreeWintrustStateData (WINTRUST_DATA* pWintrustData) { PCRYPT_PROVIDER_DATA pStateProvData; pStateProvData = WTHelperProvDataFromStateData( pWintrustData->hWVTStateData ); if ( pStateProvData != NULL ) { _CleanupProviderData( pStateProvData ); DELETE_OBJECT( pWintrustData->hWVTStateData ); } }
31.637681
116
0.533571
[ "object" ]
14743a6cc8c73dc344f4e744027456bf7492d729
2,799
cpp
C++
SceneInstance.cpp
aoustry/Odewine
d288b7170b25b23827eb2530e06d0135ad069679
[ "MIT" ]
null
null
null
SceneInstance.cpp
aoustry/Odewine
d288b7170b25b23827eb2530e06d0135ad069679
[ "MIT" ]
null
null
null
SceneInstance.cpp
aoustry/Odewine
d288b7170b25b23827eb2530e06d0135ad069679
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <cfloat> // for DBL_MAX #include <cmath> // for fabs() #include <iostream> #include <vector> #include <fstream> #include "SceneInstance.h" #include <assert.h> bool is_element(vector<int> vec, int el){ for (Iter it = vec.begin() ; it<vec.end();it++){ if (*it==el){ return true; } } return false; } SceneInstance::SceneInstance(const char* filename){ std::ifstream ifs (filename, std::ifstream::in); char buffer [25]; //Lecture de n ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; n = atoi (buffer); //std::cout << n << "\n"; //Lecture de n ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; m = atoi(buffer); //std::cout << m << "\n"; //Lecture de lambda ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; lambda = atoi(buffer); //std::cout << lambda << "\n"; //Lecture de gamma ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; gamma = atoi(buffer); //std::cout << gamma << "\n"; //Lecture de gamma ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; sigma = stod(buffer); //std::cout << sigma << "\n"; //Lecture de c for (int i = 0 ; i<m ;i++){ ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; c.push_back(atoi(buffer)); //std::cout << c[i] << "\n"; } //Lecture de d for (int i = 0 ; i<n ;i++){ ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; d.push_back(stod(buffer)); //std::cout << d[i] << "\n"; } //Lecture de u for (int i = 0 ; i<n ;i++){ ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; u.push_back(stod(buffer)); //std::cout << u[i] << "\n"; } //Lecture de p for (int i = 0 ; i<n+m ;i++){ vector<double> aux ; for (int j =0; j <n+m; j++){ ifs.getline(buffer,25); //std::cout<<buffer<< "\n"; aux.push_back(stold(buffer)); //std::cout << aux[j] << "\n"; } p.push_back(aux); } } SceneInstance::SceneInstance(SceneInstance SI,vector<int> clients_delete, vector<int> ap_delete){ n = SI.n - clients_delete.size() ; m = SI.m - ap_delete.size(); lambda = SI.lambda; gamma = SI.gamma ; sigma = SI.sigma; vector <int> list_indices = {}; u = {}; d= {}; for (int k = 0 ; k<SI.n;k++){ if (is_element(clients_delete,k)==false){ list_indices.push_back(k); u.push_back(SI.u[k]); d.push_back(SI.d[k]); } } c = {}; for (int k = 0 ; k<SI.m;k++){ if (is_element(ap_delete,k)==false){ c.push_back(SI.c[k]); list_indices.push_back(k+SI.n); } } assert(list_indices.size()==n+m); p = {}; for (int ind1 = 0 ; ind1<list_indices.size();ind1++ ){ vector <double> line = {}; for (int ind2 = 0 ; ind2<list_indices.size();ind2++ ){ line.push_back(SI.p[list_indices[ind1]][list_indices[ind2]]); } p.push_back(line); } }
21.204545
97
0.559128
[ "vector" ]
1478d1be30e0a8c5d96a4c40571d25979bc8184c
4,280
cpp
C++
tools/bvh_extractor/extract_bvh2.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
1
2021-08-19T15:21:32.000Z
2021-08-19T15:21:32.000Z
tools/bvh_extractor/extract_bvh2.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
null
null
null
tools/bvh_extractor/extract_bvh2.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
null
null
null
#include <fstream> #include "traversal.h" #include "driver/bvh.h" #include "driver/obj.h" class Bvh2Builder { public: Bvh2Builder(std::vector<Node2>& nodes, std::vector<Tri1>& tris) : nodes_(nodes), tris_(tris) {} void build(const std::vector<Tri>& tris) { builder_.build(tris, NodeWriter(this), LeafWriter(this, tris), 2); } #ifdef STATISTICS void print_stats() const { builder_.print_stats(); } #endif private: struct CostFn { static float leaf_cost(int count, float area) { return count * area; } static float traversal_cost(float area) { return area * 1.0f; } }; struct NodeWriter { Bvh2Builder* builder; NodeWriter(Bvh2Builder* builder) : builder(builder) {} template <typename BBoxFn> int operator() (int parent, int child, const BBox& parent_bb, int count, BBoxFn bboxes) { auto& nodes = builder->nodes_; int i = nodes.size(); nodes.emplace_back(); if (parent >= 0 && child >= 0) nodes[parent].child.e[child] = i + 1; assert(count == 2); const BBox& bbox1 = bboxes(0); nodes[i].bounds.e[0] = bbox1.min.x; nodes[i].bounds.e[2] = bbox1.min.y; nodes[i].bounds.e[4] = bbox1.min.z; nodes[i].bounds.e[1] = bbox1.max.x; nodes[i].bounds.e[3] = bbox1.max.y; nodes[i].bounds.e[5] = bbox1.max.z; const BBox& bbox2 = bboxes(1); nodes[i].bounds.e[ 6] = bbox2.min.x; nodes[i].bounds.e[ 8] = bbox2.min.y; nodes[i].bounds.e[10] = bbox2.min.z; nodes[i].bounds.e[ 7] = bbox2.max.x; nodes[i].bounds.e[ 9] = bbox2.max.y; nodes[i].bounds.e[11] = bbox2.max.z; return i; } }; struct LeafWriter { Bvh2Builder* builder; const std::vector<Tri>& ref_tris; LeafWriter(Bvh2Builder* builder, const std::vector<Tri>& ref_tris) : builder(builder), ref_tris(ref_tris) {} template <typename RefFn> void operator() (int parent, int child, const BBox& leaf_bb, int ref_count, RefFn refs) { auto& nodes = builder->nodes_; auto& tris = builder->tris_; nodes[parent].child.e[child] = ~tris.size(); for (int i = 0; i < ref_count; i++) { const int ref = refs(i); const Tri& tri = ref_tris[ref]; auto e1 = tri.v0 - tri.v1; auto e2 = tri.v2 - tri.v0; auto n = cross(e1, e2); tris.emplace_back(Tri1 { { { tri.v0.x, tri.v0.y, tri.v0.z } }, 0, { { e1.x, e1.y, e1.z } }, 0, { { e2.x, e2.y, e2.z } }, ref }); } // Add sentinel tris.back().prim_id |= 0x80000000; } }; SplitBvhBuilder<2, CostFn> builder_; std::vector<Node2>& nodes_; std::vector<Tri1>& tris_; }; size_t build_bvh2(std::ofstream& out, const obj::TriMesh& tri_mesh) { std::vector<Tri> tris; for (size_t i = 0; i < tri_mesh.indices.size(); i += 4) { auto& v0 = tri_mesh.vertices[tri_mesh.indices[i + 0]]; auto& v1 = tri_mesh.vertices[tri_mesh.indices[i + 1]]; auto& v2 = tri_mesh.vertices[tri_mesh.indices[i + 2]]; tris.emplace_back(v0, v1, v2); } std::vector<Node2> new_nodes; std::vector<Tri1> new_tris; Bvh2Builder builder(new_nodes, new_tris); builder.build(tris); uint64_t offset = sizeof(uint32_t) * 3 + sizeof(Node2) * new_nodes.size() + sizeof(Tri1) * new_tris.size(); uint32_t block_type = 1; uint32_t num_nodes = new_nodes.size(); uint32_t num_tris = new_tris.size(); out.write((char*)&offset, sizeof(uint64_t)); out.write((char*)&block_type, sizeof(uint32_t)); out.write((char*)&num_nodes, sizeof(uint32_t)); out.write((char*)&num_tris, sizeof(uint32_t)); out.write((char*)new_nodes.data(), sizeof(Node2) * new_nodes.size()); out.write((char*)new_tris.data(), sizeof(Tri1) * new_tris.size()); return new_nodes.size(); }
30.791367
97
0.540421
[ "vector" ]
1483d27436211727bc5070ff359155c988f4ec92
9,548
cpp
C++
src/geom_region_proposal.cpp
simonernst/geom_rcnn
4ee6255cd919a8247c45863d3aa4b68a099ecc7c
[ "MIT" ]
null
null
null
src/geom_region_proposal.cpp
simonernst/geom_rcnn
4ee6255cd919a8247c45863d3aa4b68a099ecc7c
[ "MIT" ]
null
null
null
src/geom_region_proposal.cpp
simonernst/geom_rcnn
4ee6255cd919a8247c45863d3aa4b68a099ecc7c
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/PolygonStamped.h> #include <geometry_msgs/Point32.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <pcl/ModelCoefficients.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/common/common.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/voxel_grid.h> #include <pcl/features/normal_3d.h> #include <pcl/kdtree/kdtree.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> ros::Publisher pub0, pub1, pub2, pub3, pub4, pub5; float xmin, xmax, ymin, ymax, zmin, zmax; bool verbose; void passthrough_z(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered) { // Create the filtering object pcl::PassThrough<pcl::PointXYZ> pass; pass.setInputCloud (boost::make_shared<pcl::PointCloud<pcl::PointXYZ> >(*cloud_filtered)); pass.setFilterFieldName ("z"); pass.setFilterLimits (zmin, zmax); pass.filter (*cloud_filtered); } void passthrough_x(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered) { // Create the filtering object pcl::PassThrough<pcl::PointXYZ> pass; pass.setInputCloud (boost::make_shared<pcl::PointCloud<pcl::PointXYZ> >(*cloud_filtered)); pass.setFilterFieldName ("x"); pass.setFilterLimits (xmin, xmax); pass.filter (*cloud_filtered); } void passthrough_y(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered) { // Create the filtering object pcl::PassThrough<pcl::PointXYZ> pass; pass.setInputCloud (boost::make_shared<pcl::PointCloud<pcl::PointXYZ> >(*cloud_filtered)); pass.setFilterFieldName ("y"); pass.setFilterLimits (ymin, ymax); pass.filter (*cloud_filtered); } void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& input) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>), cloud_f (new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*input, *cloud); if (verbose == true) { std::cout << "PointCloud before filtering has: " << cloud->points.size () << " data points." << std::endl; //* } // Get Min & Max pcl::PointXYZ min_full; pcl::PointXYZ max_full; pcl::getMinMax3D (*cloud, min_full, max_full); // Create the filtering object: downsample the dataset using a leaf size of 1cm pcl::VoxelGrid<pcl::PointXYZ> vg; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>); vg.setInputCloud (cloud); vg.setLeafSize (0.01f, 0.01f, 0.01f); vg.filter (*cloud_filtered); if (verbose == true) { std::cout << "PointCloud after filtering has: " << cloud_filtered->points.size () << " data points." << std::endl; //* } // Create the passthrough filter object: downsample the dataset using a leaf size of 1cm passthrough_z(cloud_filtered); passthrough_x(cloud_filtered); passthrough_y(cloud_filtered); sensor_msgs::PointCloud2::Ptr cloud_filtered_ros (new sensor_msgs::PointCloud2 ()); pcl::toROSMsg(*cloud_filtered, *cloud_filtered_ros); cloud_filtered_ros->header.frame_id = input->header.frame_id; pub3.publish(*cloud_filtered_ros); // Create the segmentation object for the planar model and set all the parameters pcl::SACSegmentation<pcl::PointXYZ> seg; pcl::PointIndices::Ptr inliers (new pcl::PointIndices); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZ> ()); seg.setOptimizeCoefficients (true); seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setMaxIterations (100); seg.setDistanceThreshold (0.02); // Segment the largest planar component from the remaining cloud seg.setInputCloud (cloud_filtered); seg.segment (*inliers, *coefficients); // Extract the planar inliers from the input cloud pcl::ExtractIndices<pcl::PointXYZ> extract; extract.setInputCloud (cloud_filtered); extract.setIndices (inliers); extract.setNegative (false); // Get the points associated with the planar surface extract.filter (*cloud_plane); if (verbose == true) { std::cout << "PointCloud representing the planar component: " << cloud_plane->points.size () << " data points." << std::endl; } // Publish plane points sensor_msgs::PointCloud2::Ptr cloud_plane_ros (new sensor_msgs::PointCloud2 ()); pcl::toROSMsg(*cloud_plane, *cloud_plane_ros); cloud_plane_ros->header.frame_id = input->header.frame_id; pub0.publish(*cloud_plane_ros); // Remove the planar inliers, extract the rest extract.setNegative (true); extract.filter (*cloud_f); // Publish outlier points sensor_msgs::PointCloud2::Ptr cloud_outlier_ros (new sensor_msgs::PointCloud2 ()); pcl::toROSMsg(*cloud_f, *cloud_outlier_ros); cloud_outlier_ros->header.frame_id = input->header.frame_id; pub1.publish(*cloud_outlier_ros); // Creating the KdTree object for the search method of the extraction pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud (cloud_f); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; ec.setClusterTolerance (0.02); // 2cm ec.setMinClusterSize (25); ec.setMaxClusterSize (800); ec.setSearchMethod (tree); ec.setInputCloud (cloud_f); ec.extract (cluster_indices); if (verbose == true) { std::cout << "Number of clusters : " << cluster_indices.size() << '\n'; } // seed rng for cloud colors srand (100); pcl::PointCloud<pcl::PointXYZRGB>::Ptr full_cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGB>); for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZ>); int r = rand() % 256; int b = rand() % 256; int g = rand() % 256; for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit) { cloud_cluster->points.push_back (cloud_f->points[*pit]); //* pcl::PointXYZRGB color_point = pcl::PointXYZRGB(r, g, b); color_point.x = cloud_f->points[*pit].x; color_point.y = cloud_f->points[*pit].y; color_point.z = cloud_f->points[*pit].z; full_cloud_cluster->points.push_back(color_point); } cloud_cluster->width = cloud_cluster->points.size (); cloud_cluster->height = 1; cloud_cluster->is_dense = true; full_cloud_cluster->width = full_cloud_cluster->width + cloud_cluster->points.size (); full_cloud_cluster-> height = 1; full_cloud_cluster->is_dense = true; // Get centroid Eigen::Vector4f centroid; pcl::compute3DCentroid (*cloud_cluster, centroid); // Get Min & Max pcl::PointXYZ min; pcl::PointXYZ max; pcl::getMinMax3D (*cloud_cluster, min, max); geometry_msgs::PolygonStamped poly; geometry_msgs::PolygonStamped poly_depth; geometry_msgs::Point32 ul, ll, lr, ur, cen; ul.x = min.x; ul.y = max.y; ul.z = centroid[2]; // max.z; ll.x = min.x; ll.y = min.y; ll.z = centroid[2]; // max.z; lr.x = max.x; lr.y = min.y; lr.z = centroid[2]; // max.z; ur.x = max.x; ur.y = max.y; ur.z = centroid[2]; // max.z; cen.x = centroid[0]; cen.y = centroid[1]; cen.z = centroid[2]; poly.polygon.points.push_back(ul); poly.polygon.points.push_back(ll); poly.polygon.points.push_back(lr); poly.polygon.points.push_back(ur); poly.header.frame_id = input->header.frame_id; pub4.publish(poly); poly_depth.polygon.points.push_back(ul); poly_depth.polygon.points.push_back(lr); poly_depth.polygon.points.push_back(cen); poly_depth.header.frame_id = input->header.frame_id; pub5.publish(poly_depth); if (verbose == true) { std::cout << "PointCloud representing the Cluster: " << cloud_cluster->points.size () << " data points." << std::endl; } } sensor_msgs::PointCloud2::Ptr cloud_cluster_ros (new sensor_msgs::PointCloud2 ()); pcl::toROSMsg(*full_cloud_cluster, *cloud_cluster_ros); cloud_cluster_ros->header.frame_id = input->header.frame_id; pub2.publish(*cloud_cluster_ros); } int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "geom_region_proposal_node"); ros::NodeHandle nh; // Load parameters nh.getParam("/geom_region_proposal/xmin", xmin); nh.getParam("/geom_region_proposal/xmax", xmax); nh.getParam("/geom_region_proposal/ymin", ymin); nh.getParam("/geom_region_proposal/ymax", ymax); nh.getParam("/geom_region_proposal/zmin", zmin); nh.getParam("/geom_region_proposal/zmax", zmax); nh.getParam("/geom_region_proposal/verbose", verbose); // Create a ROS subscriber for the input point cloud ros::Subscriber sub = nh.subscribe ("camera/depth_registered/points", 1, cloud_cb); // Create a ROS publisher for the output point cloud pub0 = nh.advertise<sensor_msgs::PointCloud2> ("plane_inliers", 1); pub1 = nh.advertise<sensor_msgs::PointCloud2> ("plane_outliers", 1); pub2 = nh.advertise<sensor_msgs::PointCloud2> ("object_clusters", 1); pub3 = nh.advertise<sensor_msgs::PointCloud2> ("cloud_filtered", 1); pub4 = nh.advertise<geometry_msgs::PolygonStamped> ("candidate_regions", 1); pub5 = nh.advertise<geometry_msgs::PolygonStamped> ("candidate_regions_depth", 1); // Spin ros::spin (); }
36.723077
129
0.709573
[ "object", "vector", "model" ]
148605ddd0af0035dfca9b1d085f0874d3137792
4,293
cpp
C++
hw1/main.cpp
rumen-cholakov/Data-Mining
fb0850b14e4a51783cf4ff930a1945b92198662d
[ "MIT" ]
null
null
null
hw1/main.cpp
rumen-cholakov/Data-Mining
fb0850b14e4a51783cf4ff930a1945b92198662d
[ "MIT" ]
null
null
null
hw1/main.cpp
rumen-cholakov/Data-Mining
fb0850b14e4a51783cf4ff930a1945b92198662d
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; class States { private: string start; string goal; vector<string> result; public: States(int); ~States(); string& getStart(); string& getGoal(); vector<string>& getResult(); void addToResult(string&); void removeFromResult(); bool solution(string&); static string newMove(int, int, string&); static bool canMove(int, int, string&); static bool isNewMoveViable(int, int, string&); static int emptyPosition(string&); static void allMoves(string&, vector<string>&); }; States::States(int size):result(0) { result.reserve((size + 1) * (size + 1)); string left(size,'>'); string right(size,'<'); start = left; start.append("_").append(right); goal = right; goal.append("_").append(left); } States::~States() { } string& States::getStart() { return start; } string& States::getGoal() { return goal; } vector<string>& States::getResult() { return result; } void States::addToResult(string& state) { result.push_back(state); } void States::removeFromResult() { result.pop_back(); } bool States::solution(string& state) { return state == this->goal; } string States::newMove(int index, int zeroPosition, string& state) { string newState = state; swap(newState[index], newState[zeroPosition]); return newState; } bool States::canMove(int index, int zeroPosition, string& state) { return (state[index] == '>' && (zeroPosition == index + 1 || zeroPosition == index + 2)) || (state[index] == '<' && (zeroPosition == index - 1 || zeroPosition == index - 2)); } bool States::isNewMoveViable(int index, int zeroPosition, string& state) { swap(state[index], state[zeroPosition]); switch (zeroPosition) { case 0: return !((state[1] == state[2]) && (state[1] == '>')); break; case 1: return !((state[2] == state[3]) && (state[2] == '>')); break; default: if (zeroPosition == state.length() - 1) { return !((state[state.length() - 2] == state[state.length() - 3]) && (state[state.length() - 2] == '<')); } else if(zeroPosition == state.length() - 2) { return !((state[state.length() - 3] == state[state.length() - 4]) && (state[state.length() - 3] == '<')); } break; } bool stuckInSameDirection = state[index - 2] == state[index - 1] && state[index + 2] == state[index + 1] && state[index - 2] == state[index + 2]; bool stuckInBadJump = state[index + 2] == state[index - 1] && state[index - 2] == state[index + 1]; return !(stuckInBadJump || stuckInSameDirection); } int States::emptyPosition(string& state) { return state.find('_'); } void States::allMoves(string& state, vector<string>& result) { int len = state.length(); int zeroPos = States::emptyPosition(state); int start = zeroPos - 2; int end = zeroPos + 2; string tmpState;; start = start >= 0 ? start : 0; end = end < len ? end : len - 1; for(size_t i = start; i <= end; i++) { tmpState = state; if (!(i == zeroPos) && States::canMove(i, zeroPos, tmpState)) { if (States::isNewMoveViable(i, zeroPos, tmpState)) { result.push_back(tmpState); } } } } void printResult(vector<string>& states) { for(auto &state : states) { cout << state << endl; } } bool dfs(States& states, string& newState) { states.addToResult(newState); if (states.solution(newState)) { printResult(states.getResult()); return true; } vector<string> newMoves; newMoves.reserve(4); States::allMoves(newState, newMoves); for(auto &move : newMoves) { if(dfs(states, move)) { return true; } } states.removeFromResult(); return false; } int main(int argc, char const *argv[]) { States states(atoi(argv[1])); dfs(states, states.getStart()); return 0; }
22.015385
121
0.553925
[ "vector" ]
148ee6d45a37bd15c1aaa363b5ca4ee634fda9b1
2,671
cpp
C++
src/shared_state.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
1
2022-03-09T07:21:48.000Z
2022-03-09T07:21:48.000Z
src/shared_state.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
1
2020-06-04T08:12:36.000Z
2020-06-08T06:20:06.000Z
src/shared_state.cpp
jvo203/FITSWebQL
59a98bc1916ce5b5d88ec1ee1986009f47a76e8b
[ "MIT" ]
null
null
null
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot 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/vinniefalco/CppCon2018 // #include "shared_state.hpp" #include "websocket_session.hpp" shared_state:: shared_state(std::string doc_root, std::string home_dir) : doc_root_(std::move(doc_root)), home_dir_(std::move(home_dir)) { int rc = sqlite3_open_v2("splatalogue_v3.db", &splat_db_, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, NULL); if (rc) { fprintf(stderr, "Can't open local splatalogue database: %s\n", sqlite3_errmsg(splat_db_)); sqlite3_close(splat_db_); splat_db_ = NULL; } } shared_state::~shared_state() { if (splat_db_ != NULL) sqlite3_close(splat_db_); } void shared_state:: join(websocket_session* session) { std::lock_guard<std::mutex> lock(mutex_); sessions_.insert(session); } void shared_state:: leave(websocket_session* session) { std::lock_guard<std::mutex> lock(mutex_); sessions_.erase(session); } // Broadcast a message to all websocket client sessions void shared_state:: send_progress(std::string message, std::string id, bool forced) { // Put the message in a shared pointer so we can re-use it for each client auto const ss = boost::make_shared<std::string const>(std::move(message)); auto const sid = boost::make_shared<std::string const>(std::move(id)); // Make a local list of all the weak pointers representing // the sessions, so we can do the actual sending without // holding the mutex: std::vector<boost::weak_ptr<websocket_session>> v; { std::lock_guard<std::mutex> lock(mutex_); v.reserve(sessions_.size()); for(auto p : sessions_) v.emplace_back(p->weak_from_this()); } // For each session in our local list, try to acquire a strong // pointer. If successful, then send the message on that session. for(auto const& wp : v) if(auto sp = wp.lock()) sp->send_progress(ss, sid, forced); } std::shared_ptr<FITS> shared_state::get_dataset(std::string id) { std::shared_lock<std::shared_mutex> lock(fits_mutex); auto item = DATASETS.find(id); if (item == DATASETS.end()) return nullptr; else return item->second; } void shared_state::insert_dataset(std::string id, std::shared_ptr<FITS> fits) { std::lock_guard<std::shared_mutex> guard(fits_mutex); DATASETS.insert(std::pair(id, fits)); }
28.414894
79
0.673905
[ "vector" ]
1493f560d742c1fb13bc81c41d085f95bf57fdcf
18,754
hh
C++
include/click/glue.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
1
2020-11-24T08:45:13.000Z
2020-11-24T08:45:13.000Z
include/click/glue.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
null
null
null
include/click/glue.hh
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
4
2021-11-11T21:47:10.000Z
2021-12-03T00:05:15.000Z
// -*- c-basic-offset: 4; related-file-name: "../../lib/glue.cc" -*- #ifndef CLICK_GLUE_HH #define CLICK_GLUE_HH // Removes many common #include <header>s and abstracts differences between // kernel and user space, and between operating systems. // HEADERS #if CLICK_LINUXMODULE # define _LOOSE_KERNEL_NAMES 1 /* define ino_t, off_t, etc. */ # undef __KERNEL_STRICT_NAMES # ifndef __OPTIMIZE__ # define __OPTIMIZE__ 1 /* get ntohl() macros. otherwise undefined. */ # endif # include <click/cxxprotect.h> CLICK_CXX_PROTECT # ifdef WANT_MOD_USE_COUNT # define __NO_VERSION__ # include <linux/module.h> # define HAVE_MOD_USE_COUNT 1 # endif # include <linux/kernel.h> # include <linux/string.h> # include <linux/skbuff.h> # if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 0) # include <linux/malloc.h> # include <linux/vmalloc.h> # include <linux/interrupt.h> # else # include <linux/hardirq.h> # endif # include <linux/ctype.h> # include <linux/time.h> # include <linux/errno.h> CLICK_CXX_UNPROTECT # include <click/cxxunprotect.h> #elif CLICK_BSDMODULE # include <click/cxxprotect.h> CLICK_CXX_PROTECT # include <sys/ctype.h> # include <sys/systm.h> # include <sys/time.h> # include <sys/param.h> # include <sys/kernel.h> # include <sys/mbuf.h> # include <sys/malloc.h> # include <sys/libkern.h> # include <sys/proc.h> # include <sys/sysproto.h> # include <sys/limits.h> # include <sys/module.h> /* XXX: for packages */ CLICK_CXX_UNPROTECT # include <click/cxxunprotect.h> #elif CLICK_MINIOS # include <click/cxxprotect.h> CLICK_CXX_PROTECT # include <stdio.h> # include <stdlib.h> # include <stddef.h> # include <stdint.h> # include <string.h> # include <ctype.h> # include <errno.h> # include <limits.h> # include <time.h> # include <sys/socket.h> # include <netinet/in.h> # include <sys/time.h> CLICK_CXX_UNPROTECT # include <click/cxxunprotect.h> #else /* CLICK_USERLEVEL */ # include <stdio.h> # include <stdlib.h> # include <stddef.h> # include <stdint.h> # include <string.h> # include <ctype.h> # include <errno.h> # include <limits.h> # include <time.h> # include <sys/socket.h> # include <netinet/in.h> # include <sys/time.h> # if CLICK_NS extern "C" int simclick_gettimeofday(struct timeval *); # endif # if HAVE_MULTITHREAD # include <pthread.h> # include <sched.h> # endif #endif // DEBUGGING OUTPUT extern "C" { void click_chatter(const char *fmt, ...); } // DEBUG MALLOC #if CLICK_DMALLOC && (CLICK_LINUXMODULE || CLICK_BSDMODULE || CLICK_MINIOS) extern uint32_t click_dmalloc_where; # define CLICK_DMALLOC_REG(s) do { const unsigned char *__str = reinterpret_cast<const unsigned char *>(s); click_dmalloc_where = (__str[0]<<24) | (__str[1]<<16) | (__str[2]<<8) | __str[3]; } while (0) #else # define CLICK_DMALLOC_REG(s) #endif // LALLOC #if CLICK_LINUXMODULE # define CLICK_LALLOC(size) (click_lalloc((size))) # define CLICK_LFREE(p, size) (click_lfree((p), (size))) extern "C" { void *click_lalloc(size_t size); void click_lfree(volatile void *p, size_t size); } #else # define CLICK_LALLOC(size) ((void *)(new uint8_t[(size)])) # define CLICK_LFREE(p, size) delete[] ((void) (size), (uint8_t *)(p)) #endif // RANDOMNESS CLICK_DECLS /** @brief Return a number between 0 and CLICK_RAND_MAX, inclusive. * * CLICK_RAND_MAX is guaranteed to be at least 2^31 - 1. */ uint32_t click_random(); /** @brief Return a number between @a low and @a high, inclusive. * * Returns @a low if @a low >= @a high. */ uint32_t click_random(uint32_t low, uint32_t high); /** @brief Set the click_random() seed to @a seed. */ void click_srandom(uint32_t seed); /** @brief Set the click_random() seed using a source of true randomness, * if available. */ void click_random_srandom(); #if CLICK_BSDMODULE # define CLICK_RAND_MAX 0x7FFFFFFFU #elif !CLICK_LINUXMODULE && RAND_MAX >= 0x7FFFFFFFU # define CLICK_RAND_MAX RAND_MAX #else # define CLICK_RAND_MAX 0x7FFFFFFFU extern uint32_t click_random_seed; #endif #if CLICK_NS extern uint32_t click_random(); #else inline uint32_t click_random() { # if CLICK_BSDMODULE return random(); # elif CLICK_LINUXMODULE click_random_seed = click_random_seed * 69069L + 5; return (click_random_seed ^ jiffies) & CLICK_RAND_MAX; // XXX jiffies?? #elif CLICK_MINIOS return rand(); # elif HAVE_RANDOM && CLICK_RAND_MAX == RAND_MAX // See also click_random() in ns/nsclick.cc return random(); # else return rand(); # endif } #endif inline void click_srandom(uint32_t seed) { #if CLICK_BSDMODULE srandom(seed); #elif CLICK_LINUXMODULE click_random_seed = seed; #elif CLICK_MINIOS srand(seed); #elif CLICK_NS (void) seed; /* XXX */ #elif HAVE_RANDOM && CLICK_RAND_MAX == RAND_MAX srandom(seed); #else srand(seed); #endif } CLICK_ENDDECLS // SORTING /** @brief Sort array of elements according to @a compar. * @param base pointer to array of elements * @param n number of elements in @a param * @param size size of an element * @param compar comparison function * @param user_data user data for comparison function * * Sorts an array of elements. The comparison function is called as "@a * param(@i a, @i b, @a user_data)", where @i a and @i b are pointers into the * array starting at @a base, and @a user_data is click_qsort's @a user_data * parameter. The function should return an integer less than zero, equal to * zero, or greater than zero depending on whether @i a compares less than @i * b, equal to @i b, or greater than @i b, respectively. On return the * elements in the @a param array have been reordered into strictly increasing * order. The function always returns 0. * * Click_qsort() is not a stable sort. * * @warning click_qsort() shuffles elements by swapping memory, rather than by * calling copy constructors or swap(). It is thus not safe for all types. * In particular, objects like Bitvector that maintain pointers into their own * representations are not safe to sort with click_qsort(). Conservatively, * it is safe to sort fundamental data types (like int and pointers), plain * old data types, and simple objects. It is also safe to sort String and * StringAccum objects, and to sort Vector objects that contain objects * that are safe to sort themselves. * * @note The implementation is based closely on "Engineering a Sort Function," * Jon L. Bentley and M. Douglas McIlroy, <em>Software---Practice & * Experience</em>, 23(11), 1249-1265, Nov. 1993. It has been coded * iteratively rather than recursively, and does no dynamic memory allocation, * so it will not exhaust stack space in the kernel. */ int click_qsort(void *base, size_t n, size_t size, int (*compar)(const void *a, const void *b, void *user_data), void *user_data = 0); /** @brief Sort array of elements according to @a compar. * @param base pointer to array of elements * @param n number of elements in @a param * @param size size of an element * @param compar comparison function * * @deprecated Prefer the variant where @a compar takes an extra void * *user_data argument. This variant depends on a nonstandard function * pointer cast. */ int click_qsort(void *base, size_t n, size_t size, int (*compar)(const void *a, const void *b)) CLICK_DEPRECATED; /** @brief Generic comparison function useful for click_qsort. * * Compares @a a and @a b using operator<(). */ template <typename T> int click_compare(const void *a, const void *b, void *) { const T *ta = static_cast<const T *>(a); const T *tb = static_cast<const T *>(b); return (*ta < *tb ? -1 : (*tb < *ta ? 1 : 0)); } /** @brief Sort array of elements using operator<(). */ template <typename T> int click_qsort(T *base, size_t n) { return click_qsort(base, n, sizeof(T), (int (*)(const void *, const void *, void *)) &click_compare<T>); } // OTHER #if CLICK_LINUXMODULE extern "C" { long strtol(const char *, char **, int); inline unsigned long strtoul(const char *nptr, char **endptr, int base) { return simple_strtoul(nptr, endptr, base); } # if __GNUC__ == 2 && __GNUC_MINOR__ == 96 int click_strcmp(const char *, const char *); inline int strcmp(const char *a, const char *b) { return click_strcmp(a, b); } # endif } #elif CLICK_BSDMODULE /* Char-type glue */ # define _U 0x01 /* upper */ # define _L 0x02 /* lower */ # define _D 0x04 /* digit */ # define _C 0x08 /* cntrl */ # define _P 0x10 /* punct */ # define _S 0x20 /* white space (space/lf/tab) */ # define _X 0x40 /* hex digit */ # define _SP 0x80 /* hard space (0x20) */ extern unsigned char _ctype[]; # define __ismask(x) (_ctype[(int)(unsigned char)(x)]) # define isalnum(c) ((__ismask(c)&(_U|_L|_D)) != 0) # define strchr(s, c) index(s, c) # if __FreeBSD_version >= 700000 && __FreeBSD_version < 730000 /* memmove() appeared in the FreeBSD 7.3 kernel */ extern "C" void *memmove(void *dest, const void *src, size_t len); # endif typedef struct ifnet net_device; #else /* not CLICK_LINUXMODULE || CLICK_BSDMODULE */ // provide a definition for net_device typedef struct device net_device; #endif /* CLICK_LINUXMODULE */ // COMPILE-TIME ASSERTION CHECKING #if (!defined(__cplusplus) || !HAVE_CXX_STATIC_ASSERT) && !defined(static_assert) # define static_assert(x, ...) switch ((int) (x)) case 0: case !!((int) (x)): #endif // PROCESSOR IDENTITIES #if CLICK_LINUXMODULE typedef uint32_t click_processor_t; # define CLICK_CPU_MAX NR_CPUS #elif CLICK_USERLEVEL && HAVE_MULTITHREAD typedef pthread_t click_processor_t; # define CLICK_CPU_MAX 256 #else typedef int8_t click_processor_t; # if HAVE_MULTITHREAD # define CLICK_CPU_MAX 256 # else # define CLICK_CPU_MAX 1 # endif #endif inline click_processor_t click_get_processor() { #if CLICK_LINUXMODULE # if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) return get_cpu(); # else return current->processor; # endif #elif CLICK_USERLEVEL && HAVE_MULTITHREAD return pthread_self(); #else return 0; #endif } inline void click_put_processor() { #if CLICK_LINUXMODULE # if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) # ifdef put_cpu_no_resched put_cpu_no_resched(); # else put_cpu(); # endif # endif #endif } #if CLICK_USERLEVEL && HAVE_MULTITHREAD && HAVE___THREAD_STORAGE_CLASS extern __thread int click_current_thread_id; #endif #if CLICK_USERLEVEL extern int click_nthreads; #endif inline click_processor_t click_current_processor() { #if CLICK_LINUXMODULE # if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) return smp_processor_id(); # else return current->processor; # endif #elif CLICK_USERLEVEL && HAVE_MULTITHREAD return pthread_self(); #else return 0; #endif } inline unsigned click_current_cpu_id() { #if !HAVE_MULTITHREAD return 0; #elif CLICK_USERLEVEL # if HAVE___THREAD_STORAGE_CLASS return click_current_thread_id & 0xffff; # else return sched_getcpu(); # endif #else return click_current_processor(); #endif } /** * Return an upper bound to click_current_cpu_id() */ inline unsigned click_max_cpu_ids() { #if CLICK_LINUXMODULE return NR_CPUS; #elif CLICK_USERLEVEL && HAVE___THREAD_STORAGE_CLASS return click_nthreads; #else //XXX BSDMODULE? return CLICK_CPU_MAX; #endif } inline click_processor_t click_invalid_processor() { #if CLICK_LINUXMODULE return -1; #elif CLICK_USERLEVEL && HAVE_MULTITHREAD return 0; #else return -1; #endif } // TIMEVALS AND JIFFIES // click_jiffies_t is the type of click_jiffies() and must be unsigned. // click_jiffies_difference_t is the signed version of click_jiffies_t. // CLICK_JIFFIES_MONOTONIC is true if click_jiffies() never goes backwards. #if CLICK_LINUXMODULE # define click_gettimeofday(tvp) (do_gettimeofday(tvp)) typedef unsigned long click_jiffies_t; typedef long click_jiffies_difference_t; # define click_jiffies() (jiffies) # define CLICK_JIFFIES_MONOTONIC 1 # define CLICK_HZ HZ # define click_jiffies_less(a, b) ((click_jiffies_difference_t) ((a) - (b)) < 0) # define HAS_LONG_CLICK_JIFFIES_T 1 #elif CLICK_BSDMODULE # define click_gettimeofday(tvp) (getmicrotime(tvp)) typedef unsigned click_jiffies_t; typedef int click_jiffies_difference_t; # define click_jiffies() (ticks) # define CLICK_HZ hz # define click_jiffies_less(a, b) ((click_jiffies_difference_t) ((a) - (b)) < 0) #else CLICK_DECLS void click_gettimeofday(timeval *tvp) CLICK_DEPRECATED; typedef unsigned click_jiffies_t; typedef int click_jiffies_difference_t; click_jiffies_t click_jiffies(); # define click_jiffies_less(a, b) ((click_jiffies_difference_t) ((a) - (b)) < 0) CLICK_ENDDECLS # define CLICK_HZ 1000 #endif #if SIZEOF_CLICK_JIFFIES_T != (HAS_LONG_CLICK_JIFFIES_T ? SIZEOF_LONG : SIZEOF_INT) # error "SIZEOF_CLICK_JIFFIES_T declared incorrectly" #endif // TIMEVAL OPERATIONS #ifndef timercmp // Convenience macros for operations on timevals. // NOTE: 'timercmp' does not work for >= or <=. # define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) # define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0) # define timercmp(a, b, CMP) \ (((a)->tv_sec == (b)->tv_sec) ? \ ((a)->tv_usec CMP (b)->tv_usec) : \ ((a)->tv_sec CMP (b)->tv_sec)) #endif #ifndef timeradd # define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000) \ { \ ++(result)->tv_sec; \ (result)->tv_usec -= 1000000; \ } \ } while (0) #endif #ifndef timersub # define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif #ifndef CLICK_TIMEVAL_OPERATORS inline timeval make_timeval(int sec, int usec) CLICK_DEPRECATED; inline bool operator==(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline bool operator!=(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline bool operator<(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline bool operator<=(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline bool operator>(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline bool operator>=(const timeval &a, const timeval &b) CLICK_DEPRECATED; inline timeval &operator+=(timeval &a, const timeval &b) CLICK_DEPRECATED; inline timeval &operator-=(timeval &a, const timeval &b) CLICK_DEPRECATED; inline timeval operator+(timeval a, const timeval &b) CLICK_DEPRECATED; inline timeval operator-(timeval a, const timeval &b) CLICK_DEPRECATED; inline struct timeval make_timeval(int sec, int usec) { struct timeval tv; tv.tv_sec = sec; tv.tv_usec = usec; return tv; } inline bool operator==(const struct timeval &a, const struct timeval &b) { return a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec; } inline bool operator!=(const struct timeval &a, const struct timeval &b) { return a.tv_sec != b.tv_sec || a.tv_usec != b.tv_usec; } inline bool operator<(const struct timeval &a, const struct timeval &b) { return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec < b.tv_usec); } inline bool operator<=(const struct timeval &a, const struct timeval &b) { return a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec <= b.tv_usec); } inline bool operator>=(const struct timeval &a, const struct timeval &b) { return a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec >= b.tv_usec); } inline bool operator>(const struct timeval &a, const struct timeval &b) { return a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec); } inline struct timeval & operator+=(struct timeval &a, const struct timeval &b) { timeradd(&a, &b, &a); return a; } inline struct timeval & operator-=(struct timeval &a, const struct timeval &b) { timersub(&a, &b, &a); return a; } inline struct timeval operator+(struct timeval a, const struct timeval &b) { timeradd(&a, &b, &a); return a; } inline struct timeval operator-(struct timeval a, const struct timeval &b) { timersub(&a, &b, &a); return a; } #endif CLICK_DECLS class StringAccum; StringAccum &operator<<(StringAccum &, const struct timeval &); CLICK_ENDDECLS // BYTE ORDER #ifndef le16_to_cpu # if CLICK_BYTE_ORDER == CLICK_LITTLE_ENDIAN # define le16_to_cpu(x) (x) # define cpu_to_le16(x) (x) # define le32_to_cpu(x) (x) # define cpu_to_le32(x) (x) # elif CLICK_BYTE_ORDER == CLICK_BIG_ENDIAN && defined(__APPLE__) # include <machine/byte_order.h> # define le16_to_cpu(x) NXSwapShort((x)) # define cpu_to_le16(x) NXSwapShort((x)) # define le32_to_cpu(x) NXSwapInt((x)) # define cpu_to_le32(x) NXSwapInt((x)) # elif CLICK_BYTE_ORDER == CLICK_BIG_ENDIAN && HAVE_BYTESWAP_H # include <byteswap.h> # define le16_to_cpu(x) bswap_16((x)) # define cpu_to_le16(x) bswap_16((x)) # define le32_to_cpu(x) bswap_32((x)) # define cpu_to_le32(x) bswap_32((x)) # elif CLICK_BYTE_ORDER == CLICK_BIG_ENDIAN # define le16_to_cpu(x) ((((x) & 0x00ff) << 8) | (((x) & 0xff00) >> 8)) # define cpu_to_le16(x) le16_to_cpu((x)) # define le32_to_cpu(x) (le16_to_cpu((x) >> 16) | (le16_to_cpu(x) << 16)) # define cpu_to_le32(x) le32_to_cpu((x)) # else /* leave them undefined */ # endif #endif // CYCLE COUNTS CLICK_DECLS #if HAVE_INT64_TYPES typedef uint64_t click_cycles_t; #else typedef uint32_t click_cycles_t; #endif inline click_cycles_t click_get_cycles() { #if CLICK_LINUXMODULE && HAVE_INT64_TYPES && __i386__ uint64_t x; __asm__ __volatile__ ("rdtsc" : "=A" (x)); return x; #elif CLICK_LINUXMODULE && HAVE_INT64_TYPES && __x86_64__ uint32_t xlo, xhi; __asm__ __volatile__ ("rdtsc" : "=a" (xlo), "=d" (xhi)); return xlo | (((uint64_t) xhi) << 32); #elif CLICK_LINUXMODULE && __i386__ uint32_t xlo, xhi; __asm__ __volatile__ ("rdtsc" : "=a" (xlo), "=d" (xhi)); return xlo; #elif CLICK_BSDMODULE return rdtsc(); #elif CLICK_USERLEVEL && HAVE_INT64_TYPES && __i386__ uint64_t x; __asm__ __volatile__ ("rdtsc" : "=A" (x)); return x; #elif CLICK_USERLEVEL && HAVE_INT64_TYPES && __x86_64__ uint32_t xlo, xhi; __asm__ __volatile__ ("rdtsc" : "=a" (xlo), "=d" (xhi)); return xlo | (((uint64_t) xhi) << 32); #elif CLICK_USERLEVEL && __i386__ uint32_t xlo, xhi; __asm__ __volatile__ ("rdtsc" : "=a" (xlo), "=d" (xhi)); return xlo; #elif CLICK_MINIOS /* FIXME: Implement click_get_cycles for MiniOS */ return 0; #else // add other architectures here return 0; #endif } CLICK_ENDDECLS #endif
26.677098
201
0.699904
[ "vector" ]
149bf99f9dfaabdc8d2530a7da530d00a6144d61
9,732
cpp
C++
src/mbgl/style/source_impl.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/style/source_impl.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/style/source_impl.cpp
mapzak/mapbox-gl-native-android-minimod
83f1350747be9a60eb0275bd1a8dcb8e5f027abe
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/style/source_impl.hpp> #include <mbgl/style/source_observer.hpp> #include <mbgl/map/transform.hpp> #include <mbgl/renderer/render_tile.hpp> #include <mbgl/renderer/painter.hpp> #include <mbgl/style/update_parameters.hpp> #include <mbgl/style/query_parameters.hpp> #include <mbgl/text/placement_config.hpp> #include <mbgl/util/logging.hpp> #include <mbgl/math/clamp.hpp> #include <mbgl/util/tile_cover.hpp> #include <mbgl/util/enum.hpp> #include <mbgl/algorithm/update_renderables.hpp> #include <mbgl/algorithm/generate_clip_ids.hpp> #include <mbgl/algorithm/generate_clip_ids_impl.hpp> #include <mapbox/geometry/envelope.hpp> #include <algorithm> namespace mbgl { namespace style { static SourceObserver nullObserver; Source::Impl::Impl(SourceType type_, std::string id_, Source& base_) : type(type_), id(std::move(id_)), base(base_), observer(&nullObserver) { } Source::Impl::~Impl() = default; bool Source::Impl::isLoaded() const { if (!loaded) return false; for (const auto& pair : tiles) { if (!pair.second->isComplete()) { return false; } } return true; } void Source::Impl::invalidateTiles() { tiles.clear(); renderTiles.clear(); cache.clear(); } void Source::Impl::startRender(algorithm::ClipIDGenerator& generator, const mat4& projMatrix, const TransformState& transform) { if (type == SourceType::Vector || type == SourceType::GeoJSON || type == SourceType::Annotations) { generator.update(renderTiles); } for (auto& pair : renderTiles) { auto& tile = pair.second; transform.matrixFor(tile.matrix, tile.id); matrix::multiply(tile.matrix, projMatrix, tile.matrix); } } void Source::Impl::finishRender(Painter& painter) { for (auto& pair : renderTiles) { auto& tile = pair.second; if (tile.used) { painter.renderTileDebug(tile); } } } std::map<UnwrappedTileID, RenderTile>& Source::Impl::getRenderTiles() { return renderTiles; } void Source::Impl::updateTiles(const UpdateParameters& parameters) { if (!loaded) { return; } const uint16_t tileSize = getTileSize(); const Range<uint8_t> zoomRange = getZoomRange(); // Determine the overzooming/underzooming amounts and required tiles. int32_t overscaledZoom = util::coveringZoomLevel(parameters.transformState.getZoom(), type, tileSize); int32_t tileZoom = overscaledZoom; std::vector<UnwrappedTileID> idealTiles; if (overscaledZoom >= zoomRange.min) { int32_t idealZoom = std::min<int32_t>(zoomRange.max, overscaledZoom); // Make sure we're not reparsing overzoomed raster tiles. if (type == SourceType::Raster) { tileZoom = idealZoom; } idealTiles = util::tileCover(parameters.transformState, idealZoom); } // Stores a list of all the tiles that we're definitely going to retain. There are two // kinds of tiles we need: the ideal tiles determined by the tile cover. They may not yet be in // use because they're still loading. In addition to that, we also need to retain all tiles that // we're actively using, e.g. as a replacement for tile that aren't loaded yet. std::set<OverscaledTileID> retain; auto retainTileFn = [&retain](Tile& tile, Resource::Necessity necessity) -> void { retain.emplace(tile.id); tile.setNecessity(necessity); }; auto getTileFn = [this](const OverscaledTileID& tileID) -> Tile* { auto it = tiles.find(tileID); return it == tiles.end() ? nullptr : it->second.get(); }; auto createTileFn = [this, &parameters](const OverscaledTileID& tileID) -> Tile* { std::unique_ptr<Tile> tile = cache.get(tileID); if (!tile) { tile = createTile(tileID, parameters); if (tile) { tile->setObserver(this); } } if (!tile) { return nullptr; } return tiles.emplace(tileID, std::move(tile)).first->second.get(); }; auto renderTileFn = [this](const UnwrappedTileID& tileID, Tile& tile) { renderTiles.emplace(tileID, RenderTile{ tileID, tile }); }; renderTiles.clear(); algorithm::updateRenderables(getTileFn, createTileFn, retainTileFn, renderTileFn, idealTiles, zoomRange, tileZoom); if (type != SourceType::Annotations && cache.getSize() == 0) { size_t conservativeCacheSize = std::max((float)parameters.transformState.getSize().width / util::tileSize, 1.0f) * std::max((float)parameters.transformState.getSize().height / util::tileSize, 1.0f) * (parameters.transformState.getMaxZoom() - parameters.transformState.getMinZoom() + 1) * 0.5; cache.setSize(conservativeCacheSize); } removeStaleTiles(retain); const PlacementConfig config { parameters.transformState.getAngle(), parameters.transformState.getPitch(), parameters.debugOptions & MapDebugOptions::Collision }; for (auto& pair : tiles) { pair.second->setPlacementConfig(config); } } // Moves all tiles to the cache except for those specified in the retain set. void Source::Impl::removeStaleTiles(const std::set<OverscaledTileID>& retain) { // Remove stale tiles. This goes through the (sorted!) tiles map and retain set in lockstep // and removes items from tiles that don't have the corresponding key in the retain set. auto tilesIt = tiles.begin(); auto retainIt = retain.begin(); while (tilesIt != tiles.end()) { if (retainIt == retain.end() || tilesIt->first < *retainIt) { tilesIt->second->setNecessity(Tile::Necessity::Optional); cache.add(tilesIt->first, std::move(tilesIt->second)); tiles.erase(tilesIt++); } else { if (!(*retainIt < tilesIt->first)) { ++tilesIt; } ++retainIt; } } } void Source::Impl::removeTiles() { renderTiles.clear(); if (!tiles.empty()) { removeStaleTiles({}); } } void Source::Impl::updateSymbolDependentTiles() { for (auto& pair : tiles) { pair.second->symbolDependenciesChanged(); } } void Source::Impl::reloadTiles() { cache.clear(); for (auto& pair : tiles) { pair.second->redoLayout(); } } std::unordered_map<std::string, std::vector<Feature>> Source::Impl::queryRenderedFeatures(const QueryParameters& parameters) const { std::unordered_map<std::string, std::vector<Feature>> result; if (renderTiles.empty() || parameters.geometry.empty()) { return result; } LineString<double> queryGeometry; for (const auto& p : parameters.geometry) { queryGeometry.push_back(TileCoordinate::fromScreenCoordinate( parameters.transformState, 0, { p.x, parameters.transformState.getSize().height - p.y }).p); } mapbox::geometry::box<double> box = mapbox::geometry::envelope(queryGeometry); auto sortRenderTiles = [](const RenderTile& a, const RenderTile& b) { return a.id.canonical.z != b.id.canonical.z ? a.id.canonical.z < b.id.canonical.z : a.id.canonical.y != b.id.canonical.y ? a.id.canonical.y < b.id.canonical.y : a.id.wrap != b.id.wrap ? a.id.wrap < b.id.wrap : a.id.canonical.x < b.id.canonical.x; }; std::vector<std::reference_wrapper<const RenderTile>> sortedTiles; std::transform(renderTiles.cbegin(), renderTiles.cend(), std::back_inserter(sortedTiles), [](const auto& pair) { return std::ref(pair.second); }); std::sort(sortedTiles.begin(), sortedTiles.end(), sortRenderTiles); for (const auto& renderTileRef : sortedTiles) { const RenderTile& renderTile = renderTileRef.get(); GeometryCoordinate tileSpaceBoundsMin = TileCoordinate::toGeometryCoordinate(renderTile.id, box.min); if (tileSpaceBoundsMin.x >= util::EXTENT || tileSpaceBoundsMin.y >= util::EXTENT) { continue; } GeometryCoordinate tileSpaceBoundsMax = TileCoordinate::toGeometryCoordinate(renderTile.id, box.max); if (tileSpaceBoundsMax.x < 0 || tileSpaceBoundsMax.y < 0) { continue; } GeometryCoordinates tileSpaceQueryGeometry; tileSpaceQueryGeometry.reserve(queryGeometry.size()); for (const auto& c : queryGeometry) { tileSpaceQueryGeometry.push_back(TileCoordinate::toGeometryCoordinate(renderTile.id, c)); } renderTile.tile.queryRenderedFeatures(result, tileSpaceQueryGeometry, parameters.transformState, parameters.layerIDs); } return result; } void Source::Impl::setCacheSize(size_t size) { cache.setSize(size); } void Source::Impl::onLowMemory() { cache.clear(); } void Source::Impl::setObserver(SourceObserver* observer_) { observer = observer_; } void Source::Impl::onTileChanged(Tile& tile) { observer->onTileChanged(base, tile.id); } void Source::Impl::onTileError(Tile& tile, std::exception_ptr error) { observer->onTileError(base, tile.id, error); } void Source::Impl::dumpDebugLogs() const { Log::Info(Event::General, "Source::id: %s", base.getID().c_str()); Log::Info(Event::General, "Source::loaded: %d", loaded); for (const auto& pair : tiles) { pair.second->dumpDebugLogs(); } } } // namespace style } // namespace mbgl
33.909408
132
0.636354
[ "geometry", "vector", "transform" ]
14a1a962b7908b7a9f88cfbb9a64dc12d954d26a
2,891
cpp
C++
Codeforces/34D.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
Codeforces/34D.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
Codeforces/34D.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
1
2020-05-20T18:36:31.000Z
2020-05-20T18:36:31.000Z
#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <functional> #include <bits/stdc++.h> using namespace __gnu_pbds; using namespace std; typedef long long ll; typedef pair<int,int> pt; typedef pair<long long ,long long> ptl; typedef vector<bool> vb; typedef vector<vector<bool>> vvb; typedef vector<vector<vector<bool>>> vvvb; typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef vector<vector<vector<int>>> vvvi; typedef vector<long long> vl; typedef vector<vector<long long>> vvl; typedef vector<vector<vector<long long>>> vvvl; typedef vector<pair<int, int>> vpt; typedef vector<pair<long long, long long>> vptl; typedef vector<string> vs; typedef set<int> si; typedef set<long long> sl; typedef unordered_set <int> usi; typedef unordered_set <long long> usl; typedef multiset<int> msi; typedef multiset<long long> msl; typedef map<int, int> mi; typedef map<long long, long long> ml; template <typename T> using indexed_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // order_of_key: The number of items in a set that are strictly smaller than k // find_by_order: It returns an iterator to the ith largest element //Anubhaw Bhalotia https://github.com/anubhawbhalotia #define X first #define Y second #define mp make_pair #define pb push_back #define lb lower_bound #define ub upper_bound #define beg(x) x.begin() #define en(x) x.end() #define all(x) x.begin(), x.end() #define f(i,s,n) for(int i=s;i<n;i++) #define fe(i,s,n) for(int i=s;i<=n;i++) #define fr(i,s,n) for(int i=s;i>n;i--) #define fre(i,s,n) for(int i=s;i>=n;i--) const int MOD = 998244353; typedef struct node { int a; // value at vertex pt p; // {index of parent, weight between this and parent} vpt c; // {index of child, weight between this and child} node() { a = 0; p = {-1, 0}; } }node; int buildTreeFromAdj(vector<node> &tree, vector<vpt> &adj, int root) { for(auto i : adj[root]) { if(i.X != tree[root].p.X) { tree[i.X].p = {root, i.Y}; tree[root].c.pb(i); buildTreeFromAdj(tree, adj, i.X); } } return 1; } int traverse(vector<node> &tree, vi &ans, int x) { ans[x] = tree[x].p.X; for(auto i : tree[x].c) { traverse(tree, ans, i.X); } return 1; } int solution(int tc) { int n, r1, r2, p; cin>>n>>r1>>r2; r1--; r2--; vector<vpt> adj(n); f(i, 0, n) { if(i != r1) { cin>>p; p--; adj[p].pb({i, 1}); adj[i].pb({p, 1}); } } vector<node> tree(n + 1); tree[n].a = r2; buildTreeFromAdj(tree, adj, r2); vi ans(n); traverse(tree, ans, r2); f(i, 0, n) { if(i != r2) { cout<<ans[i] + 1<<" "; } } cout<<endl; return 1; } void testCase() { int tc = 1; // cin>>tc; f(i, 0, tc) { solution(i + 1); // cout<<"Case #"<<i + 1<<": "<<solution(i + 1)<<endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); testCase(); }
21.901515
78
0.648219
[ "vector" ]
14acc03113e55dad8b9e93493ac1a23c6270c600
6,976
cpp
C++
docs/template_plugin/tests_deprecated/functional/shared_tests_instance/ie_class/ie_class.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
1
2020-06-21T09:51:42.000Z
2020-06-21T09:51:42.000Z
docs/template_plugin/tests_deprecated/functional/shared_tests_instance/ie_class/ie_class.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
docs/template_plugin/tests_deprecated/functional/shared_tests_instance/ie_class/ie_class.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <utility> #include <string> #include <vector> #include "ie_class.hpp" // // IE Class Common tests with <pluginName, deviceName params> // INSTANTIATE_TEST_CASE_P( nightly_IEClassBasicTestP, IEClassBasicTestP, ::testing::Values(std::make_pair("templatePlugin", "TEMPLATE"))); INSTANTIATE_TEST_CASE_P( nightly_IEClassNetworkTestP, IEClassNetworkTestP, ::testing::Values("TEMPLATE")); // // IE Class GetMetric // INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_SUPPORTED_CONFIG_KEYS, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_SUPPORTED_METRICS, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_AVAILABLE_DEVICES, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_FULL_DEVICE_NAME, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_OPTIMIZATION_CAPABILITIES, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_RANGE_FOR_ASYNC_INFER_REQUESTS, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetMetricTest, IEClassGetMetricTest_ThrowUnsupported, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetConfigTest, IEClassGetConfigTest_ThrowUnsupported, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassGetAvailableDevices, IEClassGetAvailableDevices, ::testing::Values("TEMPLATE")); // // IE Class SetConfig // using IEClassSetConfigTestHETERO = IEClassNetworkTest; TEST_F(IEClassSetConfigTestHETERO, nightly_SetConfigNoThrow) { { Core ie; Parameter p; ASSERT_NO_THROW(ie.SetConfig({ { HETERO_CONFIG_KEY(DUMP_GRAPH_DOT), CONFIG_VALUE(YES) } }, "HETERO")); ASSERT_NO_THROW(p = ie.GetConfig("HETERO", HETERO_CONFIG_KEY(DUMP_GRAPH_DOT))); bool dump = p.as<bool>(); ASSERT_TRUE(dump); } { Core ie; Parameter p; ASSERT_NO_THROW(ie.SetConfig({ { HETERO_CONFIG_KEY(DUMP_GRAPH_DOT), CONFIG_VALUE(NO) } }, "HETERO")); ASSERT_NO_THROW(p = ie.GetConfig("HETERO", HETERO_CONFIG_KEY(DUMP_GRAPH_DOT))); bool dump = p.as<bool>(); ASSERT_FALSE(dump); } { Core ie; Parameter p; ASSERT_NO_THROW(ie.GetMetric("HETERO", METRIC_KEY(SUPPORTED_CONFIG_KEYS))); ASSERT_NO_THROW(ie.SetConfig({ { HETERO_CONFIG_KEY(DUMP_GRAPH_DOT), CONFIG_VALUE(YES) } }, "HETERO")); ASSERT_NO_THROW(p = ie.GetConfig("HETERO", HETERO_CONFIG_KEY(DUMP_GRAPH_DOT))); bool dump = p.as<bool>(); ASSERT_TRUE(dump); } } // // IE Class GetConfig // INSTANTIATE_TEST_CASE_P( nightly_IEClassGetConfigTest, IEClassGetConfigTest, ::testing::Values("TEMPLATE")); using IEClassGetConfigTestTEMPLATE = IEClassNetworkTest; TEST_F(IEClassGetConfigTestTEMPLATE, nightly_GetConfigNoThrow) { Core ie; Parameter p; std::string deviceName = "TEMPLATE"; ASSERT_NO_THROW(p = ie.GetMetric(deviceName, METRIC_KEY(SUPPORTED_CONFIG_KEYS))); std::vector<std::string> configValues = p; for (auto && confKey : configValues) { if (CONFIG_KEY(DEVICE_ID) == confKey) { std::string defaultDeviceID = ie.GetConfig(deviceName, CONFIG_KEY(DEVICE_ID)); std::cout << CONFIG_KEY(DEVICE_ID) << " : " << defaultDeviceID << std::endl; } else if (CONFIG_KEY(PERF_COUNT) == confKey) { bool defaultPerfCount = ie.GetConfig(deviceName, CONFIG_KEY(PERF_COUNT)); std::cout << CONFIG_KEY(PERF_COUNT) << " : " << defaultPerfCount << std::endl; } else if (CONFIG_KEY(EXCLUSIVE_ASYNC_REQUESTS) == confKey) { bool defaultExclusive = ie.GetConfig(deviceName, CONFIG_KEY(EXCLUSIVE_ASYNC_REQUESTS)); std::cout << CONFIG_KEY(EXCLUSIVE_ASYNC_REQUESTS) << " : " << defaultExclusive << std::endl; } } } // // Executable Network GetMetric // INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetMetricTest, IEClassExecutableNetworkGetMetricTest_SUPPORTED_CONFIG_KEYS, ::testing::Values("TEMPLATE", "MULTI:TEMPLATE", "HETERO:TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetMetricTest, IEClassExecutableNetworkGetMetricTest_SUPPORTED_METRICS, ::testing::Values("TEMPLATE", "MULTI:TEMPLATE", "HETERO:TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetMetricTest, IEClassExecutableNetworkGetMetricTest_NETWORK_NAME, ::testing::Values("TEMPLATE", "MULTI:TEMPLATE", "HETERO:TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetMetricTest, IEClassExecutableNetworkGetMetricTest_OPTIMAL_NUMBER_OF_INFER_REQUESTS, ::testing::Values("TEMPLATE", "MULTI:TEMPLATE", "HETERO:TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetMetricTest_ThrowsUnsupported, IEClassExecutableNetworkGetMetricTest, ::testing::Values("TEMPLATE", "MULTI:TEMPLATE", "HETERO:TEMPLATE")); // // Executable Network GetConfig / SetConfig // INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkGetConfigTest, IEClassExecutableNetworkGetConfigTest, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassExecutableNetworkSetConfigTest, IEClassExecutableNetworkSetConfigTest, ::testing::Values("TEMPLATE")); // IE Class Query network INSTANTIATE_TEST_CASE_P( nightly_IEClassQueryNetworkTest, IEClassQueryNetworkTest, ::testing::Values("TEMPLATE")); // IE Class Load network INSTANTIATE_TEST_CASE_P( nightly_IEClassLoadNetworkTest, IEClassLoadNetworkTest, ::testing::Values("TEMPLATE")); // // Hetero Executable Network GetMetric // #ifdef ENABLE_MKL_DNN INSTANTIATE_TEST_CASE_P( nightly_IEClassHeteroExecutableNetworlGetMetricTest, IEClassHeteroExecutableNetworkGetMetricTest_SUPPORTED_CONFIG_KEYS, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassHeteroExecutableNetworlGetMetricTest, IEClassHeteroExecutableNetworkGetMetricTest_SUPPORTED_METRICS, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassHeteroExecutableNetworlGetMetricTest, IEClassHeteroExecutableNetworkGetMetricTest_NETWORK_NAME, ::testing::Values("TEMPLATE")); INSTANTIATE_TEST_CASE_P( nightly_IEClassHeteroExecutableNetworlGetMetricTest, IEClassHeteroExecutableNetworkGetMetricTest_TARGET_FALLBACK, ::testing::Values("TEMPLATE")); #endif // ENABLE_MKL_DNN
33.864078
127
0.731078
[ "vector" ]
14adaa4cf7c334cb8a045309661445aebd641ca8
8,980
cpp
C++
src/appleseed/renderer/modeling/shadergroup/shader.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
1
2021-04-02T10:51:57.000Z
2021-04-02T10:51:57.000Z
src/appleseed/renderer/modeling/shadergroup/shader.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
src/appleseed/renderer/modeling/shadergroup/shader.cpp
istemi-bahceci/appleseed
2db1041acb04bad4742cf7826ce019f0e623fe35
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2014-2017 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "shader.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/modeling/shadergroup/shaderparamparser.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/utility/foreach.h" #include "foundation/utility/searchpaths.h" #include "foundation/utility/string.h" #include "foundation/utility/uid.h" // Standard headers. #include <cassert> #include <string> using namespace foundation; using namespace std; namespace renderer { // // Shader class implementation. // namespace { const UniqueID g_class_uid = new_guid(); } struct Shader::Impl { Impl( const char* type, const char* shader, const char* layer, const ParamArray& params) : m_type(type) , m_shader(shader) { for (const_each<StringDictionary> i = params.strings(); i; ++i) { try { ShaderParamParser parser(i.it().value()); switch (parser.param_type()) { case OSLParamTypeColor: { float r, g, b; parser.parse_three_values<float>(r, g, b, true); m_params.insert(ShaderParam::create_color_param(i.it().key(), r, g, b)); } break; case OSLParamTypeColorArray: { vector<float> values; parser.parse_float3_array(values); m_params.insert(ShaderParam::create_color_array_param(i.it().key(), values)); } break; case OSLParamTypeFloat: { const float val = parser.parse_one_value<float>(); m_params.insert(ShaderParam::create_float_param(i.it().key(), val)); } break; case OSLParamTypeFloatArray: { vector<float> values; parser.parse_float_array(values); m_params.insert(ShaderParam::create_float_array_param(i.it().key(), values)); } break; case OSLParamTypeInt: { const int val = parser.parse_one_value<int>(); m_params.insert(ShaderParam::create_int_param(i.it().key(), val)); } break; case OSLParamTypeIntArray: { vector<int> values; parser.parse_int_array(values); m_params.insert(ShaderParam::create_int_array_param(i.it().key(), values)); } break; case OSLParamTypeMatrix: { float val[16]; parser.parse_n_values(16, val); m_params.insert(ShaderParam::create_matrix_param(i.it().key(), val)); } break; case OSLParamTypeMatrixArray: { vector<float> values; parser.parse_matrix_array(values); m_params.insert(ShaderParam::create_matrix_array_param(i.it().key(), values)); } break; case OSLParamTypeNormal: { float x, y, z; parser.parse_three_values<float>(x, y, z); m_params.insert(ShaderParam::create_normal_param(i.it().key(), x, y, z)); } break; case OSLParamTypeNormalArray: { vector<float> values; parser.parse_float3_array(values); m_params.insert(ShaderParam::create_normal_array_param(i.it().key(), values)); } break; case OSLParamTypePoint: { float x, y, z; parser.parse_three_values<float>(x, y, z); m_params.insert(ShaderParam::create_point_param(i.it().key(), x, y, z)); } break; case OSLParamTypePointArray: { vector<float> values; parser.parse_float3_array(values); m_params.insert(ShaderParam::create_point_array_param(i.it().key(), values)); } break; case OSLParamTypeString: { m_params.insert( ShaderParam::create_string_param( i.it().key(), parser.parse_string_value().c_str())); } break; case OSLParamTypeVector: { float x, y, z; parser.parse_three_values<float>(x, y, z); m_params.insert(ShaderParam::create_vector_param(i.it().key(), x, y, z)); } break; case OSLParamTypeVectorArray: { vector<float> values; parser.parse_float3_array(values); m_params.insert(ShaderParam::create_vector_array_param(i.it().key(), values)); } break; default: RENDERER_LOG_ERROR( "error adding OSL param %s, of unknown type %s; will use the default value.", i.it().key(), i.it().value()); break; } } catch (const ExceptionOSLParamParseError&) { RENDERER_LOG_ERROR( "error parsing OSL param value, param = %s, value = %s; will use the default value.", i.it().key(), i.it().value()); } } } string m_type; string m_shader; ShaderParamContainer m_params; }; Shader::Shader( const char* type, const char* shader, const char* layer, const ParamArray& params) : Entity(g_class_uid, params) , impl(new Impl(type, shader, layer, params)) { // We use the layer name as the entity name, as it's unique. set_name(layer); } Shader::~Shader() { delete impl; } void Shader::release() { delete this; } const char* Shader::get_type() const { return impl->m_type.c_str(); } const char* Shader::get_shader() const { return impl->m_shader.c_str(); } const char* Shader::get_layer() const { return get_name(); } const ShaderParamContainer& Shader::shader_params() const { return impl->m_params; } bool Shader::add(OSL::ShadingSystem& shading_system) { for (each<ShaderParamContainer> i = impl->m_params; i; ++i) { if (!i->add(shading_system)) return false; } if (!shading_system.Shader("surface", get_shader(), get_layer())) { RENDERER_LOG_ERROR("error adding shader %s, %s.", get_shader(), get_layer()); return false; } return true; } } // namespace renderer
31.843972
105
0.512138
[ "vector" ]
14af41864a4c9d26cb900a61755687a0feecca23
53,389
cpp
C++
avmplus/core/ErrorConstants.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
avmplus/core/ErrorConstants.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
avmplus/core/ErrorConstants.cpp
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * THIS FILE IS AUTO-GENERATED. DO NOT EDIT THIS FILE. * Use the script 'errorgen' to generate this file. */ #include "avmplus.h" namespace avmplus { // Error message strings only in non-stubbed DEBUGGER builds. #if defined(DEBUGGER) && !defined(VMCFG_DEBUGGER_STUB) namespace ErrorConstants { LangName languageNames[] = { #ifdef AVMPLUS_ERROR_LANG_en { "en", LANG_en }, #endif #ifdef AVMPLUS_ERROR_LANG_fr { "fr", LANG_fr }, #endif #ifdef AVMPLUS_ERROR_LANG_ja { "ja", LANG_ja }, #endif #ifdef AVMPLUS_ERROR_LANG_zh_CN { "zh-CN", LANG_zh_CN }, #endif }; MMGC_STATIC_ASSERT((sizeof languageNames/sizeof languageNames[0]) == kLanguages); int errorMappingTable[2*kNumErrorConstants] = { 1000, 0, 1001, 1, 1002, 2, 1003, 3, 1004, 4, 1005, 5, 1006, 6, 1007, 7, 1008, 8, 1009, 9, 1010, 10, 1011, 11, 1012, 12, 1013, 13, 1014, 14, 1015, 15, 1016, 16, 1017, 17, 1018, 18, 1019, 19, 1020, 20, 1021, 21, 1022, 22, 1023, 23, 1024, 24, 1025, 25, 1026, 26, 1027, 27, 1028, 28, 1029, 29, 1030, 30, 1031, 31, 1032, 32, 1033, 33, 1034, 34, 1035, 35, 1037, 36, 1038, 37, 1039, 38, 1040, 39, 1041, 40, 1042, 41, 1043, 42, 1044, 43, 1045, 44, 1046, 45, 1047, 46, 1049, 47, 1050, 48, 1051, 49, 1052, 50, 1053, 51, 1054, 52, 1056, 53, 1057, 54, 1058, 55, 1059, 56, 1060, 57, 1061, 58, 1063, 59, 1064, 60, 1065, 61, 1066, 62, 1067, 63, 1068, 64, 1069, 65, 1070, 66, 1071, 67, 1072, 68, 1073, 69, 1074, 70, 1075, 71, 1076, 72, 1077, 73, 1078, 74, 1079, 75, 1080, 76, 1081, 77, 1082, 78, 1083, 79, 1084, 80, 1085, 81, 1086, 82, 1087, 83, 1088, 84, 1089, 85, 1090, 86, 1091, 87, 1092, 88, 1093, 89, 1094, 90, 1095, 91, 1096, 92, 1097, 93, 1098, 94, 1100, 95, 1101, 96, 1102, 97, 1103, 98, 1104, 99, 1107, 100, 1108, 101, 1109, 102, 1110, 103, 1111, 104, 1112, 105, 1113, 106, 1114, 107, 1115, 108, 1116, 109, 1117, 110, 1118, 111, 1119, 112, 1120, 113, 1121, 114, 1122, 115, 1123, 116, 1124, 117, 1125, 118, 1126, 119, 1127, 120, 1128, 121, 1129, 122, 1131, 123, 1132, 124, 1500, 125, 1501, 126, 1502, 127, 1503, 128, 1504, 129, 1505, 130, 1506, 131, 1507, 132, 1508, 133, 1510, 134, 1511, 135, 1512, 136, 1513, 137, 1514, 138, 1515, 139, 1516, 140, 1517, 141, 1518, 142, 1519, 143, 1520, 144, 1521, 145, 2004, 146, 2006, 147, 2007, 148, 2008, 149, 2012, 150, 2030, 151, 2058, 152, 2085, 153, 2088, 154, 2089, 155, 2090, 156, 2091, 157, 2092, 158, 2093, 159, 2105, 160, 2106, 161, 2107, 162, 2108, 163, 2173, 164 }; const char* errorConstants[][kNumErrorConstants] = { #ifdef AVMPLUS_ERROR_LANG_en // en { /*1000,0*/ "The system is out of memory.", /*1001,1*/ "The method %1 is not implemented.", /*1002,2*/ "Number.toPrecision has a range of 1 to 21. Number.toFixed and Number.toExponential have a range of 0 to 20. Specified value is not within expected range.", /*1003,3*/ "The radix argument must be between 2 and 36; got %1.", /*1004,4*/ "Method %1 was invoked on an incompatible object.", /*1005,5*/ "Array index is not a positive integer (%1).", /*1006,6*/ "%1 is not a function.", /*1007,7*/ "Instantiation attempted on a non-constructor.", /*1008,8*/ "%1 is ambiguous; Found more than one matching binding.", /*1009,9*/ "Cannot access a property or method of a null object reference.", /*1010,10*/ "A term is undefined and has no properties.", /*1011,11*/ "Method %1 contained illegal opcode %2 at offset %3.", /*1012,12*/ "The last instruction exceeded code size.", /*1013,13*/ "Cannot call OP_findproperty when scopeDepth is 0.", /*1014,14*/ "Class %1 could not be found.", /*1015,15*/ "Method %1 cannot set default xml namespace", /*1016,16*/ "Descendants operator (..) not supported on type %1.", /*1017,17*/ "Scope stack overflow occurred.", /*1018,18*/ "Scope stack underflow occurred.", /*1019,19*/ "Getscopeobject %1 is out of bounds.", /*1020,20*/ "Code cannot fall off the end of a method.", /*1021,21*/ "At least one branch target was not on a valid instruction in the method.", /*1022,22*/ "Type void may only be used as a function return type.", /*1023,23*/ "Stack overflow occurred.", /*1024,24*/ "Stack underflow occurred.", /*1025,25*/ "An invalid register %1 was accessed.", /*1026,26*/ "Slot %1 exceeds slotCount=%2 of %3.", /*1027,27*/ "Method_info %1 exceeds method_count=%2.", /*1028,28*/ "Disp_id %1 exceeds max_disp_id=%2 of %3.", /*1029,29*/ "Disp_id %1 is undefined on %2.", /*1030,30*/ "Stack depth is unbalanced. %1 != %2.", /*1031,31*/ "Scope depth is unbalanced. %1 != %2.", /*1032,32*/ "Cpool index %1 is out of range %2.", /*1033,33*/ "Cpool entry %1 is wrong type.", /*1034,34*/ "Type Coercion failed: cannot convert %1 to %2.", /*1035,35*/ "Illegal super expression found in method %1.", /*1037,36*/ "Cannot assign to a method %1 on %2.", /*1038,37*/ "%1 is already defined.", /*1039,38*/ "Cannot verify method until it is referenced.", /*1040,39*/ "The right-hand side of instanceof must be a class or function.", /*1041,40*/ "The right-hand side of operator must be a class.", /*1042,41*/ "Not an ABC file. major_version=%1 minor_version=%2.", /*1043,42*/ "Invalid code_length=%1.", /*1044,43*/ "MethodInfo-%1 unsupported flags=%2.", /*1045,44*/ "Unsupported traits kind=%1.", /*1046,45*/ "MethodInfo-%1 referenced before definition.", /*1047,46*/ "No entry point was found.", /*1049,47*/ "Prototype objects must be vanilla Objects.", /*1050,48*/ "Cannot convert %1 to primitive.", /*1051,49*/ "Illegal early binding access to %1.", /*1052,50*/ "Invalid URI passed to %1 function.", /*1053,51*/ "Illegal override of %1 in %2.", /*1054,52*/ "Illegal range or target offsets in exception handler.", /*1056,53*/ "Cannot create property %1 on %2.", /*1057,54*/ "%1 can only contain methods.", /*1058,55*/ "Illegal operand type: %1 must be %2.", /*1059,56*/ "ClassInfo-%1 is referenced before definition.", /*1060,57*/ "ClassInfo %1 exceeds class_count=%2.", /*1061,58*/ "The value %1 cannot be converted to %2 without losing precision.", /*1063,59*/ "Argument count mismatch on %1. Expected %2, got %3.", /*1064,60*/ "Cannot call method %1 as constructor.", /*1065,61*/ "Variable %1 is not defined.", /*1066,62*/ "The form function('function body') is not supported.", /*1067,63*/ "Native method %1 has illegal method body.", /*1068,64*/ "%1 and %2 cannot be reconciled.", /*1069,65*/ "Property %1 not found on %2 and there is no default value.", /*1070,66*/ "Method %1 not found on %2", /*1071,67*/ "Function %1 has already been bound to %2.", /*1072,68*/ "Disp_id 0 is illegal.", /*1073,69*/ "Non-override method %1 replaced because of duplicate disp_id %2.", /*1074,70*/ "Illegal write to read-only property %1 on %2.", /*1075,71*/ "Math is not a function.", /*1076,72*/ "Math is not a constructor.", /*1077,73*/ "Illegal read of write-only property %1 on %2.", /*1078,74*/ "Illegal opcode/multiname combination: %1<%2>.", /*1079,75*/ "Native methods are not allowed in loaded code.", /*1080,76*/ "Illegal value for namespace.", /*1081,77*/ "Property %1 not found on %2 and there is no default value.", /*1082,78*/ "No default namespace has been set.", /*1083,79*/ "The prefix \"%1\" for element \"%2\" is not bound.", /*1084,80*/ "Element or attribute (\"%1\") does not match QName production: QName::=(NCName':')?NCName.", /*1085,81*/ "The element type \"%1\" must be terminated by the matching end-tag \"</%2>\".", /*1086,82*/ "The %1 method only works on lists containing one item.", /*1087,83*/ "Assignment to indexed XML is not allowed.", /*1088,84*/ "The markup in the document following the root element must be well-formed.", /*1089,85*/ "Assignment to lists with more than one item is not supported.", /*1090,86*/ "XML parser failure: element is malformed.", /*1091,87*/ "XML parser failure: Unterminated CDATA section.", /*1092,88*/ "XML parser failure: Unterminated XML declaration.", /*1093,89*/ "XML parser failure: Unterminated DOCTYPE declaration.", /*1094,90*/ "XML parser failure: Unterminated comment.", /*1095,91*/ "XML parser failure: Unterminated attribute.", /*1096,92*/ "XML parser failure: Unterminated element.", /*1097,93*/ "XML parser failure: Unterminated processing instruction.", /*1098,94*/ "Illegal prefix %1 for no namespace.", /*1100,95*/ "Cannot supply flags when constructing one RegExp from another.", /*1101,96*/ "Cannot verify method %1 with unknown scope.", /*1102,97*/ "Illegal default value for type %1.", /*1103,98*/ "Class %1 cannot extend final base class.", /*1104,99*/ "Attribute \"%1\" was already specified for element \"%2\".", /*1107,100*/ "The ABC data is corrupt, attempt to read out of bounds.", /*1108,101*/ "The OP_newclass opcode was used with the incorrect base class.", /*1109,102*/ "Attempt to directly call unbound function %1 from method %2.", /*1110,103*/ "%1 cannot extend %2.", /*1111,104*/ "%1 cannot implement %2.", /*1112,105*/ "Argument count mismatch on class coercion. Expected 1, got %1.", /*1113,106*/ "OP_newactivation used in method without NEED_ACTIVATION flag.", /*1114,107*/ "OP_getglobalslot or OP_setglobalslot used with no global scope.", /*1115,108*/ "%1 is not a constructor.", /*1116,109*/ "second argument to Function.prototype.apply must be an array.", /*1117,110*/ "Invalid XML name: %1.", /*1118,111*/ "Illegal cyclical loop between nodes.", /*1119,112*/ "Delete operator is not supported with operand of type %1.", /*1120,113*/ "Cannot delete property %1 on %2.", /*1121,114*/ "Method %1 has a duplicate method body.", /*1122,115*/ "Interface method %1 has illegal method body.", /*1123,116*/ "Filter operator not supported on type %1.", /*1124,117*/ "OP_hasnext2 requires object and index to be distinct registers.", /*1125,118*/ "The index %1 is out of range %2.", /*1126,119*/ "Cannot change the length of a fixed Vector.", /*1127,120*/ "Type application attempted on a non-parameterized type.", /*1128,121*/ "Incorrect number of type parameters for %1. Expected %2, got %3.", /*1129,122*/ "Cyclic structure cannot be converted to JSON string.", /*1131,123*/ "Replacer argument to JSON stringifier must be an array or a two parameter function.", /*1132,124*/ "Invalid JSON parse input.", /*1500,125*/ "Error occurred opening file %1.", /*1501,126*/ "Error occurred writing to file %1.", /*1502,127*/ "A script has executed for longer than the default timeout period of 15 seconds.", /*1503,128*/ "A script failed to exit after 30 seconds and was terminated.", /*1504,129*/ "End of file.", /*1505,130*/ "The string index %1 is out of bounds; must be in range %2 to %3.", /*1506,131*/ "The specified range is invalid.", /*1507,132*/ "Argument %1 cannot be null.", /*1508,133*/ "The value specified for argument %1 is invalid.", /*1510,134*/ "When the callback argument is a method of a class, the optional this argument must be null.", /*1511,135*/ "Worker is already started.", /*1512,136*/ "Starting a worker that already failed is not supported.", /*1513,137*/ "Worker has terminated.\"", /*1514,138*/ "unlock() with no preceding matching lock().", /*1515,139*/ "Invalid condition timeout value: %1.", /*1516,140*/ "Condition cannot notify if associated mutex is not owned.", /*1517,141*/ "Condition cannot notifyAll if associated mutex is not owned.", /*1518,142*/ "Condition cannot wait if associated mutex is not owned.", /*1519,143*/ "Condition cannot be initialized.", /*1520,144*/ "Mutex cannot be initialized.", /*1521,145*/ "Only the worker's parent may call start.", /*2004,146*/ "One of the parameters is invalid.", /*2006,147*/ "The supplied index is out of bounds.", /*2007,148*/ "Parameter %1 must be non-null.", /*2008,149*/ "Parameter %1 must be one of the accepted values.", /*2012,150*/ "%1 class cannot be instantiated.", /*2030,151*/ "End of file was encountered.", /*2058,152*/ "There was an error decompressing the data.", /*2085,153*/ "Parameter %1 must be non-empty string.", /*2088,154*/ "The Proxy class does not implement getProperty. It must be overridden by a subclass.", /*2089,155*/ "The Proxy class does not implement setProperty. It must be overridden by a subclass.", /*2090,156*/ "The Proxy class does not implement callProperty. It must be overridden by a subclass.", /*2091,157*/ "The Proxy class does not implement hasProperty. It must be overridden by a subclass.", /*2092,158*/ "The Proxy class does not implement deleteProperty. It must be overridden by a subclass.", /*2093,159*/ "The Proxy class does not implement getDescendants. It must be overridden by a subclass.", /*2105,160*/ "The Proxy class does not implement nextNameIndex. It must be overridden by a subclass.", /*2106,161*/ "The Proxy class does not implement nextName. It must be overridden by a subclass.", /*2107,162*/ "The Proxy class does not implement nextValue. It must be overridden by a subclass.", /*2108,163*/ "The value %1 is not a valid Array length.", /*2173,164*/ "Unable to read object in stream. The class %1 does not implement flash.utils.IExternalizable but is aliased to an externalizable class." }, #endif #ifdef AVMPLUS_ERROR_LANG_fr // fr { /*1000,0*/ "La mémoire du système est saturée.", /*1001,1*/ "La méthode %1 n'est pas mise en oeuvre.", /*1002,2*/ "L'argument precision doit être compris entre %2 et %3. %1 n'est pas valide.", /*1003,3*/ "L'argument radix doit être compris entre 2 et 36. %1 détecté.", /*1004,4*/ "La méthode %1 a été invoquée pour un objet non compatible.", /*1005,5*/ "L'index du tableau n'est pas un entier positif (%1).", /*1006,6*/ "%1 n'est pas une fonction.", /*1007,7*/ "Tentative d'instanciation sur un élément non constructeur.", /*1008,8*/ "%1 est ambigu. Plusieurs liaisons correspondantes détectées.", /*1009,9*/ "Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul.", /*1010,10*/ "Un terme n'est pas défini et n'a pas de propriété.", /*1011,11*/ "La méthode %1 contenait un opcode %2 non valide au décalage %3.", /*1012,12*/ "La dernière instruction dépassait la taille du code.", /*1013,13*/ "Impossible d'appeler OP_findproperty si scopeDepth correspond à 0.", /*1014,14*/ "La classe %1 est introuvable.", /*1015,15*/ "La méthode %1 ne peut pas définir l'espace de nom xml par défaut", /*1016,16*/ "L'opérateur Descendants (..) n'est pas pris en charge sur le type %1.", /*1017,17*/ "Il s'est produit un débordement de la pile de domaine.", /*1018,18*/ "Il s'est produit un débordement négatif de la pile de domaine.", /*1019,19*/ "Getscopeobject %1 sort des limites.", /*1020,20*/ "Le code ne doit pas dépasser la fin d'une méthode.", /*1021,21*/ "Au moins une cible branche ne figurait pas dans une instruction valide de la méthode.", /*1022,22*/ "Void est réservé aux types de renvoi de fonction.", /*1023,23*/ "Il s'est produit un débordement de pile.", /*1024,24*/ "Il s'est produit un débordement négatif de pile.", /*1025,25*/ "Il s'est produit un accès à un registre %1 non valide.", /*1026,26*/ "L'emplacement %1 dépasse slotCount=%2 sur %3.", /*1027,27*/ "Method_info %1 dépasse method_count=%2.", /*1028,28*/ "Disp_id %1 dépasse max_disp_id=%2 sur %3.", /*1029,29*/ "Disp_id %1 n'est pas défini sur %2.", /*1030,30*/ "La profondeur de la pile n'est pas équilibrée. %1 != %2.", /*1031,31*/ "La profondeur du domaine n'est pas équilibrée. %1 != %2.", /*1032,32*/ "L'index Cpool %1 est en dehors des limites %2.", /*1033,33*/ "Le type de l'entrée Cpool %1 est incorrect.", /*1034,34*/ "Echec de la contrainte de type : conversion de %1 en %2 impossible.", /*1035,35*/ "Super expression illégale détectée dans la méthode %1.", /*1037,36*/ "Affectation impossible à une méthode %1 sur %2.", /*1038,37*/ "%1 est déjà défini.", /*1039,38*/ "Impossible de vérifier la méthode tant qu'elle n'est pas référencée.", /*1040,39*/ "L'expression à droite de instanceof doit être une classe ou une fonction.", /*1041,40*/ "L'expression à droite de l'opérateur doit être une classe.", /*1042,41*/ "Il ne s'agit pas d'un fichier ABC. major_version=%1 minor_version=%2.", /*1043,42*/ "code_length non valide=%1.", /*1044,43*/ "Indicateurs MethodInfo-%1 non pris en charge=%2.", /*1045,44*/ "Type de trait non pris en charge=%1.", /*1046,45*/ "MethodInfo-%1 référencé avant la définition.", /*1047,46*/ "Aucun point d'entrée n'a été détecté.", /*1049,47*/ "Les objets prototype doivent être des objets vanille.", /*1050,48*/ "Impossible de convertir %1 en primitive.", /*1051,49*/ "Accès anticipé illégal de liaison à %1.", /*1052,50*/ "URI non valide transmis à la fonction %1.", /*1053,51*/ "Remplacement illégal de %1 dans %2.", /*1054,52*/ "Plage ou décalages cibles illégaux dans le gestionnaire d'exceptions.", /*1056,53*/ "Impossible de créer la propriété %1 sur %2.", /*1057,54*/ "%1 ne peut contenir que des méthodes.", /*1058,55*/ "Type d'opérande illégal : %1 doit correspondre à %2.", /*1059,56*/ "ClassInfo-%1 est référencé avant la définition.", /*1060,57*/ "ClassInfo %1 dépasse class_count=%2.", /*1061,58*/ "La valeur %1 ne peut pas être convertie en %2 sans perte de précision.", /*1063,59*/ "Non-correspondance du nombre d'arguments sur %1. %2 prévu(s), %3 détecté(s).", /*1064,60*/ "Impossible d'appeler la méthode %1 en tant que constructeur.", /*1065,61*/ "La variable %1 n'est pas définie.", /*1066,62*/ "La fonction('corps de fonction') form n'est pas prise en charge.", /*1067,63*/ "La méthode native %1 contient un corps de méthode illégal.", /*1068,64*/ "Impossible de réconcilier %1 et %2.", /*1069,65*/ "La propriété %1 est introuvable sur %2 et il n'existe pas de valeur par défaut.", /*1070,66*/ "La méthode %1 est introuvable sur %2", /*1071,67*/ "La fonction %1 a déjà été liée à %2.", /*1072,68*/ "Disp_id 0 est illégal.", /*1073,69*/ "La méthode de non-remplacement %1 a été supplantée en raison du doublon disp_id %2.", /*1074,70*/ "Ecriture illégale dans une propriété en lecture seule %1 sur %2.", /*1075,71*/ "Math n'est pas une fonction.", /*1076,72*/ "Math n'est pas un constructeur.", /*1077,73*/ "Lecture illégale d'une propriété en écriture seule %1 sur %2.", /*1078,74*/ "Combinaison opcode/multiname illégale : %1<%2>.", /*1079,75*/ "Les méthodes natives ne sont pas autorisées dans le code chargé.", /*1080,76*/ "La valeur de l'espace de nom est illégale.", /*1081,77*/ "La propriété %1 est introuvable sur %2 et il n'existe pas de valeur par défaut.", /*1082,78*/ "Aucun espace de nom par défaut n'a été défini.", /*1083,79*/ "Le préfixe \"%1\" associé à l'élément \"%2\" n'est pas lié.", /*1084,80*/ "L'élément ou l'attribut (\"%1\") ne correspond pas à la production QName : QName::=(NCName':')?NCName.", /*1085,81*/ "Le type d'élément \"%1\" doit se terminer par la balise de fin correspondante \"</%2>\".", /*1086,82*/ "La méthode %1 ne fonctionne qu'avec les listes composées d'un seul élément.", /*1087,83*/ "L'affectation à un élément XML indexé n'est pas autorisée.", /*1088,84*/ "Le marquage du document après l'élément root doit être composé correctement.", /*1089,85*/ "L'affectation à des listes composées de plus d'un élément n'est pas prise en charge.", /*1090,86*/ "Echec de l'analyse XML : le format de l'élément est incorrect.", /*1091,87*/ "Echec de l'analyse XML : Section CDATA non terminée.", /*1092,88*/ "Echec de l'analyse XML : Déclaration XML non terminée.", /*1093,89*/ "Echec de l'analyse XML : Déclaration DOCTYPE non terminée.", /*1094,90*/ "Echec de l'analyse XML : Commentaire non terminé.", /*1095,91*/ "Echec de l'analyse XML : Attribut non terminé.", /*1096,92*/ "Echec de l'analyse XML : Elément non terminé.", /*1097,93*/ "Echec de l'analyse XML : Instruction de traitement non terminée.", /*1098,94*/ "Préfixe %1 illégal sans espace de nom.", /*1100,95*/ "Impossible de fournir des indicateurs lors de la construction d'un RegExp à partir d'un autre.", /*1101,96*/ "Impossible de vérifier la méthode %1 si le domaine est inconnu.", /*1102,97*/ "Valeur par défaut illégale pour le type %1.", /*1103,98*/ "La classe %1 ne peut pas étendre la classe de base finale.", /*1104,99*/ "L'attribut \"%1\" a déjà été spécifié pour l'élément \"%2\".", /*1107,100*/ "Les données ABC sont corrompues, tentative de lecture en dehors des limites.", /*1108,101*/ "L'élément opcode OP_newclass a été utilisé avec une classe de base incorrecte.", /*1109,102*/ "Tentative d'appel direct d'une fonction non liée %1 à partir de la méthode %2.", /*1110,103*/ "%1 ne peut pas étendre %2.", /*1111,104*/ "%1 ne peut pas mettre en oeuvre %2.", /*1112,105*/ "Non-concordance du nombre d'arguments pour contrainte de classe. 1 prévu, %1 détecté(s).", /*1113,106*/ "OP_newactivation utilisé dans la méthode sans indicateur NEED_ACTIVATION.", /*1114,107*/ "OP_getglobalslot ou OP_setglobalslot utilisé sans domaine global.", /*1115,108*/ "%1 n'est pas un constructeur.", /*1116,109*/ "Le deuxième argument transmis à Function.prototype.apply doit être un tableau.", /*1117,110*/ "Nom XML non valide : %1.", /*1118,111*/ "Boucle cyclique illégale entre noeuds.", /*1119,112*/ "L'opérateur delete n'est pas pris en charge avec une opérande de type %1.", /*1120,113*/ "Impossible de supprimer la propriété %1 sur %2.", /*1121,114*/ "La méthode %1 contient un corps de méthode dupliqué.", /*1122,115*/ "La méthode d'interface %1 contient un corps de méthode illégal.", /*1123,116*/ "L'opérateur Filter n'est pas pris en charge sur le type %1.", /*1124,117*/ "OP_hasnext2 requiert que l'objet et l'index soient des registres distincts.", /*1125,118*/ "L'index %1 est en dehors des limites %2.", /*1126,119*/ "Impossible de modifier la longueur d'un vecteur fixe.", /*1127,120*/ "Application de type tentée sur un type sans paramètre.", /*1128,121*/ "Nombre incorrect de paramètres type pour %1. %2 prévu(s), %3 détecté(s).", /*1129,122*/ "Il est impossible de convertir la structure cyclique en chaîne JSON.", /*1131,123*/ "L’argument Replacer vers le transformateur de chaînes JSON doit être un tableau ou une fonction à deux paramètres.", /*1132,124*/ "Saisie d’analyse JSON non valide.", /*1500,125*/ "Une erreur s’est produite lors de l’ouverture du fichier %1.", /*1501,126*/ "Une erreur s’est produite lors de l’écriture dans le fichier %1.", /*1502,127*/ "La durée d'exécution d'un script excède le délai par défaut (15 secondes).", /*1503,128*/ "Un script ne s'est pas terminé après 30 secondes et a été arrêté.", /*1504,129*/ "Fin du fichier.", /*1505,130*/ "L'index de chaîne %1 sort des limites. Il doit être compris entre %2 et %3.", /*1506,131*/ "La plage indiquée n'est pas valide.", /*1507,132*/ "L’argument %1 ne doit pas être null.", /*1508,133*/ "La valeur indiquée pour l’argument %1 n’est pas valide.", /*1510,134*/ "Lorsque l’argument du rappel correspond à une méthode de classe, l’argument facultatif 'this' doit être null.", /*1511,135*/ "Le programme de travail a déjà démarré.", /*1512,136*/ "Le démarrage d’un programme de travail ayant déjà échoué n’est pas pris en charge.", /*1513,137*/ "Le programme de travail est terminé.\"", /*1514,138*/ "Méthode unlock() sans méthode lock() correspondante qui précède.", /*1515,139*/ "Valeur de délai d’expiration de la condition non valide : %1.", /*1516,140*/ "L’objet Condition ne peut pas utiliser la méthode notify si l’objet Mutex associé n’existe pas.", /*1517,141*/ "L’objet Condition ne peut pas utiliser la méthode notifyAll si l’objet Mutex associé n’existe pas.", /*1518,142*/ "L’objet Condition ne peut pas attendre si l’objet Mutex associé n’existe pas.", /*1519,143*/ "Impossible d'initialiser la condition.", /*1520,144*/ "Impossible d'initialiser Mutex.", /*1521,145*/ "Seul le parent de l'opérateur peut demander le démarrage.", /*2004,146*/ "L'un des paramètres n'est pas valide.", /*2006,147*/ "L'index indiqué sort des limites.", /*2007,148*/ "Le paramètre %1 ne doit pas être nul.", /*2008,149*/ "Le paramètre %1 doit être l'une des valeurs acceptées.", /*2012,150*/ "Impossible d'instancier la classe %1.", /*2030,151*/ "Fin de fichier détectée.", /*2058,152*/ "Une erreur s'est produite lors de la décompression des données.", /*2085,153*/ "Le paramètre %1 doit être une chaîne non vide.", /*2088,154*/ "La classe Proxy ne met pas en oeuvre getProperty. Elle doit être remplacée par une sous-classe.", /*2089,155*/ "La classe Proxy ne met pas en oeuvre setProperty. Elle doit être remplacée par une sous-classe.", /*2090,156*/ "La classe Proxy ne met pas en oeuvre callProperty. Elle doit être remplacée par une sous-classe.", /*2091,157*/ "La classe Proxy ne met pas en oeuvre hasProperty. Elle doit être remplacée par une sous-classe.", /*2092,158*/ "La classe Proxy ne met pas en oeuvre deleteProperty. Elle doit être remplacée par une sous-classe.", /*2093,159*/ "La classe Proxy ne met pas en oeuvre getDescendants. Elle doit être remplacée par une sous-classe.", /*2105,160*/ "La classe Proxy ne met pas en oeuvre nextNameIndex. Elle doit être remplacée par une sous-classe.", /*2106,161*/ "La classe Proxy ne met pas en oeuvre nextName. Elle doit être remplacée par une sous-classe.", /*2107,162*/ "La classe Proxy ne met pas en oeuvre nextValue. Elle doit être remplacée par une sous-classe.", /*2108,163*/ "La valeur %1 n’est pas une valeur de tableau valide.", /*2173,164*/ "Impossible de lire l'objet dans le flux. La classe %1 n'implémente pas flash.utils.IExternalizable, mais est aliasée vers une classe externalisable." }, #endif #ifdef AVMPLUS_ERROR_LANG_ja // ja { /*1000,0*/ "システムのメモリ不足です。", /*1001,1*/ "メソッド %1 は実装されていません。", /*1002,2*/ "精度の引数には %2 ~ %3 の値を指定してください。%1 は不正な値です。", /*1003,3*/ "基数の引数には 2 ~ 36 の値を指定してください。%1 は不正な値です。", /*1004,4*/ "メソッド %1 が対応していないオブジェクトで呼び出されました。", /*1005,5*/ "配列インデックスが正の整数 (%1) ではありません。", /*1006,6*/ "%1 は関数ではありません。", /*1007,7*/ "コンストラクター以外にインスタンス化が試行されました。", /*1008,8*/ "%1 があいまいです。一致するバインディングが複数見つかりました。", /*1009,9*/ "null のオブジェクト参照のプロパティまたはメソッドにアクセスすることはできません。", /*1010,10*/ "条件は未定義であり、プロパティがありません。", /*1011,11*/ "メソッド %1 に無効な opcode %2 (オフセット %3 内) が含まれています。", /*1012,12*/ "最後の命令がコードサイズを超えました。", /*1013,13*/ "scopeDepth が 0 である場合、OP_findproperty を呼び出すことはできません。", /*1014,14*/ "クラス %1 が見つかりません。", /*1015,15*/ "メソッド %1 はデフォルトの xml 名前空間を設定できません", /*1016,16*/ "Descendants 演算子 (..) は型 %1 でサポートされていません。", /*1017,17*/ "スコープのスタックオーバーフローが発生しました。", /*1018,18*/ "スコープのスタックアンダーフローが発生しました。", /*1019,19*/ "Getscopeobject %1 が境界外です。", /*1020,20*/ "コードがメソッドの末尾からはみ出すことはできません。", /*1021,21*/ "最低 1 つのブランチターゲットがメソッドの有効な命令を反映していません。", /*1022,22*/ "Void 型は、関数の戻り型としてのみ使用できます。", /*1023,23*/ "スタックオーバーフローが発生しました。", /*1024,24*/ "スタックアンダーフローが発生しました。", /*1025,25*/ "無効なレジスタ %1 がアクセスされました。", /*1026,26*/ "スロット %1 が %3 の slotCount=%2 を超えています。", /*1027,27*/ "Method_info %1 が method_count=%2 を超えています。", /*1028,28*/ "Disp_id %1 が %3 の max_disp_id=%2 を超えています。", /*1029,29*/ "Disp_id %1 が %2 に対して未定義です。", /*1030,30*/ "スタックの深さがアンバランスです。%1 != %2。", /*1031,31*/ "スコープの深さがアンバランスです。%1 != %2。", /*1032,32*/ "Cpool のインデックス %1 が %2 の範囲外です。", /*1033,33*/ "Cpool のエントリ %1 の型が正しくありません。", /*1034,34*/ "強制型変換に失敗しました。%1 を %2 に変換できません。", /*1035,35*/ "メソッド %1 で無効な super 式が見つかりました。", /*1037,36*/ "%2 のメソッド %1 に代入できません。", /*1038,37*/ "%1 は定義済みです。", /*1039,38*/ "メソッドは参照されるまで検証できません。", /*1040,39*/ "instanceof の右側はクラスまたは関数でなければなりません。", /*1041,40*/ "演算子の右側はクラスでなければなりません。", /*1042,41*/ "ABC ファイルではありません。major_version=%1 minor_version=%2 です。", /*1043,42*/ "code_length=%1 が無効です。", /*1044,43*/ "MethodInfo-%1 サポートされていないフラグ =%2。", /*1045,44*/ "サポートされていない種類の機能 =%1。", /*1046,45*/ "MethodInfo-%1 が定義の前に参照されています。", /*1047,46*/ "エントリポイントが見つかりませんでした。", /*1049,47*/ "プロトタイプオブジェクトはバニラオブジェクトでなければなりません。", /*1050,48*/ "%1 をプリミティブに変換できません。", /*1051,49*/ "%1 へのアーリーバインディングアクセスが無効です。", /*1052,50*/ "無効な URI が %1 関数に渡されました。", /*1053,51*/ "%2 の %1 のオーバーライドが無効です。", /*1054,52*/ "例外ハンドラーの範囲またはターゲットオフセットが無効です。", /*1056,53*/ "%2 のプロパティ %1 を作成できません。", /*1057,54*/ "%1 はメソッドしか含むことができません。", /*1058,55*/ "無効なオペランド型 :%1 は %2 でなければなりません。", /*1059,56*/ "ClassInfo-%1 が定義の前に参照されています。", /*1060,57*/ "ClassInfo %1 が class_count=%2 を超えています。", /*1061,58*/ "値 %1 を %2 に変換すると精度が失われます。", /*1063,59*/ "%1 の引数の数が一致していません。%2 が必要ですが、%3 が指定されました。", /*1064,60*/ "メソッド %1 をコンストラクターとして呼び出すことはできません。", /*1065,61*/ "変数 %1 は定義されていません。", /*1066,62*/ "function('function body') という書式はサポートされていません。", /*1067,63*/ "ネイティブメソッド %1 のメソッドボディが無効です。", /*1068,64*/ "%1 と %2 は共有できません。", /*1069,65*/ "%2 にプロパティ %1 が見つからず、デフォルト値もありません。", /*1070,66*/ "%2 にメソッド %1 が見つかりません。", /*1071,67*/ "関数 %1 は %2 にバインド済みです。", /*1072,68*/ "Disp_id 0 が無効です。", /*1073,69*/ "disp_id %2 が重複しているために、非オーバーライドメソッド %1 が置換されました。", /*1074,70*/ "%2 の読み取り専用プロパティ %1 へは書き込みできません。", /*1075,71*/ "Math は関数ではありません。", /*1076,72*/ "Math はコンストラクターではありません。", /*1077,73*/ "%2 の書き込み専用プロパティ %1 の読み込みは無効です。", /*1078,74*/ "オプコードとマルチネームの組み合わせが無効です :%1<%2>。", /*1079,75*/ "読み込まれたコードではネイティブメソッドを使用できません。", /*1080,76*/ "名前空間の値が無効です。", /*1081,77*/ "%2 にプロパティ %1 が見つからず、デフォルト値もありません。", /*1082,78*/ "デフォルトの名前空間が設定されていません。", /*1083,79*/ "エレメント \"%2\" の接頭辞 \"%1\" がバインドされていません。", /*1084,80*/ "エレメントまたは属性 (\"%1\") が QName プロダクションと一致しません : QName::=(NCName':')?NCName。", /*1085,81*/ "エレメント型 \"%1\" は対応する終了タグ \"</%2>\" で終了する必要があります。", /*1086,82*/ "%1 メソッドは、単一のアイテムを含むリストに対してのみ使用できます。", /*1087,83*/ "インデックス付きの XML への代入は許可されません。", /*1088,84*/ "ルートエレメントに続くドキュメントのマークアップは整形式でなければなりません。", /*1089,85*/ "複数のアイテムを含むリストへの代入はサポートされていません。", /*1090,86*/ "XML パーサエラー :エレメントの形式が正しくありません。", /*1091,87*/ "XML パーサエラー :CDATA セクションが終了していません。", /*1092,88*/ "XML パーサエラー :XML 宣言が終了していません。", /*1093,89*/ "XML パーサエラー :DOCTYPE 宣言が終了していません。", /*1094,90*/ "XML パーサエラー :コメントが終了していません。", /*1095,91*/ "XML パーサエラー :属性が終了していません。", /*1096,92*/ "XML パーサエラー :エレメントが終了していません。", /*1097,93*/ "XML パーサエラー :処理命令が終了していません。", /*1098,94*/ "no namespace の接頭辞 %1 が無効です。", /*1100,95*/ "RegExp から別の RegExp を構築する際にフラグを渡すことはできません。", /*1101,96*/ "不明なスコープを持つメソッド %1 を検証できません。", /*1102,97*/ "型 %1 のデフォルト値が無効です。", /*1103,98*/ "クラス %1 は、final 基本クラスを拡張できません。", /*1104,99*/ "属性 \"%1\" (エレメント \"%2\") は既に指定されています。", /*1107,100*/ "ABC データは破損しているため、境界外の読み取りが試行されました。", /*1108,101*/ "OP_newclass オプコードが不正な基本クラスで使用されました。", /*1109,102*/ "結合されていない関数 %1 をメソッド %2 から直接呼び出そうとしました。", /*1110,103*/ "%1 は %2 を拡張できません。", /*1111,104*/ "%1 は %2 を実装できません。", /*1112,105*/ "クラスの型変換に指定された引数の数が不正です。1 個必要ですが、%1 個指定されました。", /*1113,106*/ "OP_newactivation が NEED_ACTIVATION フラグなしでメソッドで使用されました。", /*1114,107*/ "グローバルスコープなしで OP_getglobalslot または OP_setglobalslot が使用されました。", /*1115,108*/ "%1 はコンストラクターではありません。", /*1116,109*/ "Function.prototype.apply の 2 番目の引数は配列でなければなりません。", /*1117,110*/ "無効な XML 名 : %1。", /*1118,111*/ "ノード間に不正な周期的なループがあります。", /*1119,112*/ "Delete 演算子はオペランド型 %1 でサポートされていません。", /*1120,113*/ "%2 のプロパティ %1 を削除できません。", /*1121,114*/ "メソッド %1 のメソッドボディが重複しています。", /*1122,115*/ "インターフェイスメソッド %1 のメソッドボディが無効です。", /*1123,116*/ "Filter 演算子は型 %1 でサポートされていません。", /*1124,117*/ "OP_hasnext2 を明示的に登録するには、オブジェクトとインデックスが必要です。", /*1125,118*/ "インデックス %1 は %2 の範囲外です。", /*1126,119*/ "固定ベクターの長さは変更できません。", /*1127,120*/ "非パラメーター化された型に対して型指定を実行しようとしました。", /*1128,121*/ "%1 の型パラメーター数が正しくありません。%2 である必要がありますが、%3 が指定されました。", /*1129,122*/ "周期的な構成を JSON 文字列に変換できません。", /*1131,123*/ "JSON stringifier への Replacer 引数は、1 つの配列または 2 つのパラメーターである必要があります。", /*1132,124*/ "無効な JSON パース入力です。", /*1500,125*/ "ファイル %1 を開く際にエラーが発生しました。", /*1501,126*/ "ファイル %1 に書き込む際にエラーが発生しました。", /*1502,127*/ "スクリプトがデフォルトのタイムアウト時間の 15 秒を超えて実行されました。", /*1503,128*/ "スクリプトが 30 秒後の終了に失敗したため、強制終了しました。", /*1504,129*/ "ファイルの終端です。", /*1505,130*/ "文字列インデックス %1 が境界外です。%2 ~ %3 の範囲内である必要があります。", /*1506,131*/ "指定した範囲は無効です。", /*1507,132*/ "引数 %1 は null にすることができません。", /*1508,133*/ "引数 %1 に指定した値は無効です。", /*1510,134*/ "コールバック引数がクラスのメソッドのとき、任意指定の引数 'this' は null でなければなりません。", /*1511,135*/ "ワーカーは既に起動されています。", /*1512,136*/ "既に失敗しているワーカーの起動はサポートされていません。", /*1513,137*/ "ワーカーが終了されました。\"", /*1514,138*/ "前に一致する lock() がない unlock()", /*1515,139*/ "無効な条件タイムアウト値 : %1。", /*1516,140*/ "関連する mutex が所有されていない場合、条件は notify を実行できません。", /*1517,141*/ "関連する mutex が所有されていない場合、条件は notifyAll を実行できません。", /*1518,142*/ "関連する mutex が所有されていない場合、条件は wait を実行できません。", /*1519,143*/ "Condition を初期化できません。", /*1520,144*/ "Mutex を初期化できません。", /*1521,145*/ "ワーカーの親のみが start を呼び出せます。", /*2004,146*/ "パラメーターの 1 つが無効です。", /*2006,147*/ "指定したインデックスが境界外です。", /*2007,148*/ "パラメーター %1 は null 以外でなければなりません。", /*2008,149*/ "パラメーター %1 は承認された値の 1 つでなければなりません。", /*2012,150*/ "%1 クラスをインスタンス化することはできません。", /*2030,151*/ "ファイルの終端 (EOF) が検出されました。", /*2058,152*/ "圧縮データの解凍時にエラーが発生しました。", /*2085,153*/ "パラメーター %1 は空白以外の文字列でなければなりません。", /*2088,154*/ "Proxy クラスは、getProperty を実装しません。サブクラスでオーバーライドする必要があります。", /*2089,155*/ "Proxy クラスは、setProperty を実装しません。サブクラスでオーバーライドする必要があります。", /*2090,156*/ "Proxy クラスは、callProperty を実装しません。サブクラスでオーバーライドする必要があります。", /*2091,157*/ "Proxy クラスは、hasProperty を実装しません。サブクラスでオーバーライドする必要があります。", /*2092,158*/ "Proxy クラスは、deleteProperty を実装しません。サブクラスでオーバーライドする必要があります。", /*2093,159*/ "Proxy クラスは、getDescendants を実装しません。サブクラスでオーバーライドする必要があります。", /*2105,160*/ "Proxy クラスは、nextNameIndex を実装しません。サブクラスでオーバーライドする必要があります。", /*2106,161*/ "Proxy クラスは、nextName を実装しません。サブクラスでオーバーライドする必要があります。", /*2107,162*/ "Proxy クラスは、nextValue を実装しません。サブクラスでオーバーライドする必要があります。", /*2108,163*/ "値 %1 は有効な配列の長さではありません。", /*2173,164*/ "ストリーム内のオブジェクトを読み取れません。クラス %1 は flash.utils.IExternalizable を実装しませんが、外部化可能なクラスにエイリアス処理されます。" }, #endif #ifdef AVMPLUS_ERROR_LANG_zh_CN // zh_CN { /*1000,0*/ "系统内存不足。", /*1001,1*/ "未实现 %1 方法。", /*1002,2*/ "精度参数必须介于 %2 到 %3 之间;%1 无效。", /*1003,3*/ "基数参数必须介于 2 到 36 之间;当前值为 %1。", /*1004,4*/ "对不兼容的对象调用了方法 %1。", /*1005,5*/ "数组索引不是正整数 (%1)。", /*1006,6*/ "%1 不是函数。", /*1007,7*/ "尝试实例化的函数不是构造函数。", /*1008,8*/ "%1 有歧义;找到多个匹配的绑定。", /*1009,9*/ "无法访问空对象引用的属性或方法。", /*1010,10*/ "术语尚未定义,并且无任何属性。", /*1011,11*/ "方法 %1 包含非法 opcode %2 (偏移量为 %3)。", /*1012,12*/ "最后一条指令超出代码大小。", /*1013,13*/ "当 scopeDepth 为 0 时,无法调用 OP_findproperty。", /*1014,14*/ "无法找到类 %1。", /*1015,15*/ "方法 %1 无法设置默认 XML 命名空间", /*1016,16*/ "类型 %1 不支持后代运算符 (..)。", /*1017,17*/ "发生范围堆栈上溢。", /*1018,18*/ "发生范围堆栈下溢。", /*1019,19*/ "Getscopeobject %1 超出范围。", /*1020,20*/ "代码不能超出方法结尾。", /*1021,21*/ "至少一个分支目标不是方法中的有效指令。", /*1022,22*/ "void 类型只能用作函数返回类型。", /*1023,23*/ "发生堆栈上溢。", /*1024,24*/ "发生堆栈下溢。", /*1025,25*/ "访问了无效的注册 %1。", /*1026,26*/ "Slot %1 超出 %3 中 slotCount=%2 的限制。", /*1027,27*/ "Method_info %1 超出 method_count=%2 的限制。", /*1028,28*/ "Disp_id %1 超出 %3 中 max_disp_id=%2 的限制。", /*1029,29*/ "Disp_id %1 在 %2 上未定义。", /*1030,30*/ "堆栈深度不对称。%1 != %2。", /*1031,31*/ "范围深度不对称。%1 != %2。", /*1032,32*/ "Cpool 索引 %1 超出范围 %2。", /*1033,33*/ "Cpool 项 %1 类型错误。", /*1034,34*/ "强制转换类型失败:无法将 %1 转换为 %2。", /*1035,35*/ "发现方法 %1 中存在非法的 super 表达式。", /*1037,36*/ "无法在 %2 上为方法 %1 赋值。", /*1038,37*/ "%1 已定义。", /*1039,38*/ "在方法被引用之前无法对其进行验证。", /*1040,39*/ "instanceof 的右侧必须是类或函数。", /*1041,40*/ "运算符的右侧必须是类。", /*1042,41*/ "不是 ABC 文件。major_version=%1 minor_version=%2。", /*1043,42*/ "code_length=%1 无效。", /*1044,43*/ "MethodInfo-%1 不支持 flags=%2。", /*1045,44*/ "不支持 trait kind=%1。", /*1046,45*/ "MethodInfo-%1 被引用时未定义。", /*1047,46*/ "未找到入口点。", /*1049,47*/ "原型对象必须是 vanilla 对象。", /*1050,48*/ "无法将 %1 转换为原始类型。", /*1051,49*/ "对 %1 的早期绑定访问是非法的。", /*1052,50*/ "传递给 %1 函数的 URI 无效。", /*1053,51*/ "在 %2 中非法覆盖 %1。", /*1054,52*/ "异常处理函数中存在非法的范围或目标偏移量。", /*1056,53*/ "无法为 %2 创建属性 %1。", /*1057,54*/ "%1 只能包含方法。", /*1058,55*/ "非法的操作数类型: %1 必须是 %2。", /*1059,56*/ "ClassInfo-%1 被引用时未定义。", /*1060,57*/ "ClassInfo %1 超出 class_count=%2 的限制。", /*1061,58*/ "无法在不损失精度的情况下将值 %1 转换为 %2。", /*1063,59*/ "%1 的参数数量不匹配。应该有 %2 个,当前为 %3 个。", /*1064,60*/ "无法将方法 %1 作为构造函数调用。", /*1065,61*/ "变量 %1 未定义。", /*1066,62*/ "不支持 function('function body') 形式。", /*1067,63*/ "内置方法 %1 含有非法的方法正文。", /*1068,64*/ "%1 和 %2 无法协调一致。", /*1069,65*/ "在 %2 上找不到属性 %1,且没有默认值。", /*1070,66*/ "在 %2 上找不到方法 %1", /*1071,67*/ "函数 %1 已被绑定到 %2。", /*1072,68*/ "Disp_id 0 是非法的。", /*1073,69*/ "由于 disp_id %2 的重复,非覆盖方法 %1 已被替换。", /*1074,70*/ "%2 上存在对只读属性 %1 的非法写入。", /*1075,71*/ "Math 不是函数。", /*1076,72*/ "Math 不是构造函数。", /*1077,73*/ "%2 上存在对只写属性 %1 的非法读取。", /*1078,74*/ "非法的 opcode/multiname 组合: %1<%2>。", /*1079,75*/ "载入代码中不允许使用内置方法。", /*1080,76*/ "非法的命名空间值。", /*1081,77*/ "在 %2 上找不到属性 %1,且没有默认值。", /*1082,78*/ "未设置默认的命名空间。", /*1083,79*/ "元素“%2”的前缀“%1”未绑定。", /*1084,80*/ "元素或属性 (“%1”) 与 QName 定义不匹配: QName::=(NCName':')?NCName。", /*1085,81*/ "元素类型“%1”必须以匹配的结束标记“</%2>”结束。", /*1086,82*/ "%1 方法只能用于包含单一项目的列表。", /*1087,83*/ "不允许对索引 XML 进行赋值。", /*1088,84*/ "文档中根元素后面的标记格式必须正确。", /*1089,85*/ "不支持对包含多个项目的列表进行赋值。", /*1090,86*/ "XML 分析器失败: 元素格式不正确。", /*1091,87*/ "XML 分析器失败: CDATA 部分未结束。", /*1092,88*/ "XML 分析器失败: XML 声明未结束。", /*1093,89*/ "XML 分析器失败: DOCTYPE 声明未结束。", /*1094,90*/ "XML 分析器失败: 注释未结束。", /*1095,91*/ "XML 分析器失败: 属性未结束。", /*1096,92*/ "XML 分析器失败: 元素未结束。", /*1097,93*/ "XML 分析器失败: 正在处理的指令未结束。", /*1098,94*/ "no namespace 带有非法前缀 %1。", /*1100,95*/ "在由一个 RegExp 构建另一个的过程中无法提供标志。", /*1101,96*/ "无法验证具有未知范围的方法 %1。", /*1102,97*/ "类型 %1 的默认值非法。", /*1103,98*/ "类 %1 不能扩展最终基类。", /*1104,99*/ "已指定属性“%1”(针对元素“%2”)。", /*1107,100*/ "ABC 数据已损坏,尝试的读取操作超出范围。", /*1108,101*/ "OP_newclass opcode 使用的基类不正确。", /*1109,102*/ "尝试直接调用非绑定函数 %1 (从方法 %2 中调用)。", /*1110,103*/ "%1 无法扩展 %2。", /*1111,104*/ "%1 无法实现 %2。", /*1112,105*/ "类强制转换的参数数量不匹配。应为 1 个,当前为 %1 个。", /*1113,106*/ "方法中使用的 OP_newactivation 没有 NEED_ACTIVATION 标志。", /*1114,107*/ "使用的 OP_getglobalslot 或 OP_setglobalslot 不具有全局范围。", /*1115,108*/ "%1 不是构造函数。", /*1116,109*/ "Function.prototype.apply 的第二个参数必须是数组。", /*1117,110*/ "XML 名称无效: %1。", /*1118,111*/ "节点间存在非法循环。", /*1119,112*/ "类型 %1 的操作数不支持删除运算符。", /*1120,113*/ "无法为 %2 删除属性 %1。", /*1121,114*/ "方法 %1 具有重复的方法正文。", /*1122,115*/ "接口方法 %1 含有非法的方法正文。", /*1123,116*/ "类型 %1 不支持过滤运算符。", /*1124,117*/ "OP_hasnext2 要求对象和索引位于不同的寄存器。", /*1125,118*/ "索引 %1 超出范围 %2。", /*1126,119*/ "无法更改固定矢量的长度。", /*1127,120*/ "尝试对非参数化类型执行类型应用程序。", /*1128,121*/ "%1 的类型参数的个数不正确。应为 %2,当前为 %3。", /*1129,122*/ "循环结构无法转换为 JSON 字符串。", /*1131,123*/ "JSON stringifier 的 Replacer 参数必须是数组或两参数函数。", /*1132,124*/ "无效的 JSON 解析输入。", /*1500,125*/ "打开文件 %1 时出错。", /*1501,126*/ "写入文件 %1 时出错。", /*1502,127*/ "脚本的执行时间已经超过了 15 秒的默认超时设置。", /*1503,128*/ "脚本未能在 30 秒后退出而被终止。", /*1504,129*/ "文件结尾。", /*1505,130*/ "字符串索引 %1 超出范围;必须在 %2 到 %3 的范围内。", /*1506,131*/ "指定的范围无效。", /*1507,132*/ "参数 %1 不能为空。", /*1508,133*/ "为参数 %1 指定的值无效。", /*1510,134*/ "如果回调参数是某个类的方法,则可选参数“this”必须为空。", /*1511,135*/ "Worker 已启动。", /*1512,136*/ "不支持启动已失败的 Worker。", /*1513,137*/ "Worker 已终止。\"", /*1514,138*/ "unlock() 前面没有匹配的 lock()。", /*1515,139*/ "无效的条件超时值: %1。", /*1516,140*/ "如果未拥有关联的 mutex,条件无法 notify。", /*1517,141*/ "如果未拥有关联的 mutex,条件无法 notifyAll。", /*1518,142*/ "如果未拥有关联的 mutex,条件无法执行 wait。", /*1519,143*/ "无法初始化条件。", /*1520,144*/ "无法初始化 Mutex。", /*1521,145*/ "仅该 worker 的父级可以呼叫 start。", /*2004,146*/ "某个参数无效。", /*2006,147*/ "提供的索引超出范围。", /*2007,148*/ "参数 %1 不能为空。", /*2008,149*/ "参数 %1 必须是某个可接受的值。", /*2012,150*/ "无法实例化 %1 类。", /*2030,151*/ "遇到文件尾。", /*2058,152*/ "解压缩数据时出错。", /*2085,153*/ "参数 %1 必须为非空字符串。", /*2088,154*/ "Proxy 类不实现 getProperty。它必须由一个子类覆盖。", /*2089,155*/ "Proxy 类不实现 setProperty。它必须由一个子类覆盖。", /*2090,156*/ "Proxy 类不实现 callProperty。它必须由一个子类覆盖。", /*2091,157*/ "Proxy 类不实现 hasProperty。它必须由一个子类覆盖。", /*2092,158*/ "Proxy 类不实现 deleteProperty。它必须由一个子类覆盖。", /*2093,159*/ "Proxy 类不实现 getDescendants。它必须由一个子类覆盖。", /*2105,160*/ "Proxy 类不实现 nextNameIndex。它必须由一个子类覆盖。", /*2106,161*/ "Proxy 类不实现 nextName。它必须由一个子类覆盖。", /*2107,162*/ "Proxy 类不实现 nextValue。它必须由一个子类覆盖。", /*2108,163*/ "值 %1 不是有效的数组长度。", /*2173,164*/ "无法读取流中的对象。类 %1 虽未实现 flash.utils.IExternalizable,但由其别名可得知它为 externalizable 类。" }, #endif }; MMGC_STATIC_ASSERT((sizeof errorConstants/sizeof errorConstants[0]) == kLanguages); } #endif /* defined(DEBUGGER) && !defined(VMCFG_DEBUGGER_STUB) */ }
59.585938
184
0.50177
[ "object", "vector" ]
14b1c043b365f0c3a612c2d8f57a2f520f209a34
400
cpp
C++
Math/prime_sum.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Math/prime_sum.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Math/prime_sum.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool is_prime(int num) { if(num == 1) return false; for(int i = 2; i * i <= num; ++i) { if(num % i == 0) { return false; } } return true; } vector<int> primesum(int A) { for(int i = 2; i <= A / 2; ++i) { int p = i; int q = A - i; if(is_prime(p) && is_prime(q)) { return vector<int>{p, q}; } } return vector<int>{-1, -1}; }
14.285714
36
0.52
[ "vector" ]
14b2de6bc78015a08dae9dbcedeaeda57fce4442
10,070
cc
C++
chrome/browser/devtools/device/adb/adb_device_info_query.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
chrome/browser/devtools/device/adb/adb_device_info_query.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/devtools/device/adb/adb_device_info_query.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/devtools/device/adb/adb_device_info_query.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" namespace { const char kDeviceModelCommand[] = "shell:getprop ro.product.model"; const char kOpenedUnixSocketsCommand[] = "shell:cat /proc/net/unix"; const char kListProcessesCommand[] = "shell:ps"; const char kDumpsysCommand[] = "shell:dumpsys window policy"; const char kDumpsysScreenSizePrefix[] = "mStable="; const char kDevToolsSocketSuffix[] = "_devtools_remote"; const char kChromeDefaultName[] = "Chrome"; const char kChromeDefaultSocket[] = "chrome_devtools_remote"; const char kWebViewSocketPrefix[] = "webview_devtools_remote"; const char kWebViewNameTemplate[] = "WebView in %s"; struct BrowserDescriptor { const char* package; const char* socket; const char* display_name; }; const BrowserDescriptor kBrowserDescriptors[] = { { "com.android.chrome", kChromeDefaultSocket, kChromeDefaultName }, { "com.chrome.beta", kChromeDefaultSocket, "Chrome Beta" }, { "com.google.android.apps.chrome_dev", kChromeDefaultSocket, "Chrome Dev" }, { "com.chrome.canary", kChromeDefaultSocket, "Chrome Canary" }, { "com.google.android.apps.chrome", kChromeDefaultSocket, "Chromium" }, { "org.chromium.content_shell_apk", "content_shell_devtools_remote", "Content Shell" }, { "org.chromium.chrome.shell", "chrome_shell_devtools_remote", "Chrome Shell" }, { "org.chromium.android_webview.shell", "webview_devtools_remote", "WebView Test Shell" } }; const BrowserDescriptor* FindBrowserDescriptor(const std::string& package) { int count = sizeof(kBrowserDescriptors) / sizeof(kBrowserDescriptors[0]); for (int i = 0; i < count; i++) if (kBrowserDescriptors[i].package == package) return &kBrowserDescriptors[i]; return NULL; } typedef std::map<std::string, std::string> StringMap; static void MapProcessesToPackages(const std::string& response, StringMap& pid_to_package, StringMap& package_to_pid) { // Parse 'ps' output which on Android looks like this: // // USER PID PPID VSIZE RSS WCHAN PC ? NAME // std::vector<std::string> entries; Tokenize(response, "\n", &entries); for (size_t i = 1; i < entries.size(); ++i) { std::vector<std::string> fields; Tokenize(entries[i], " \r", &fields); if (fields.size() < 9) continue; std::string pid = fields[1]; std::string package = fields[8]; pid_to_package[pid] = package; package_to_pid[package] = pid; } } static StringMap MapSocketsToProcesses(const std::string& response, const std::string& channel_pattern) { // Parse 'cat /proc/net/unix' output which on Android looks like this: // // Num RefCount Protocol Flags Type St Inode Path // 00000000: 00000002 00000000 00010000 0001 01 331813 /dev/socket/zygote // 00000000: 00000002 00000000 00010000 0001 01 358606 @xxx_devtools_remote // 00000000: 00000002 00000000 00010000 0001 01 347300 @yyy_devtools_remote // // We need to find records with paths starting from '@' (abstract socket) // and containing the channel pattern ("_devtools_remote"). StringMap socket_to_pid; std::vector<std::string> entries; Tokenize(response, "\n", &entries); for (size_t i = 1; i < entries.size(); ++i) { std::vector<std::string> fields; Tokenize(entries[i], " \r", &fields); if (fields.size() < 8) continue; if (fields[3] != "00010000" || fields[5] != "01") continue; std::string path_field = fields[7]; if (path_field.size() < 1 || path_field[0] != '@') continue; size_t socket_name_pos = path_field.find(channel_pattern); if (socket_name_pos == std::string::npos) continue; std::string socket = path_field.substr(1); std::string pid; size_t socket_name_end = socket_name_pos + channel_pattern.size(); if (socket_name_end < path_field.size() && path_field[socket_name_end] == '_') { pid = path_field.substr(socket_name_end + 1); } socket_to_pid[socket] = pid; } return socket_to_pid; } } // namespace // static AndroidDeviceManager::BrowserInfo::Type AdbDeviceInfoQuery::GetBrowserType(const std::string& socket) { if (socket.find(kChromeDefaultSocket) == 0) return AndroidDeviceManager::BrowserInfo::kTypeChrome; if (socket.find(kWebViewSocketPrefix) == 0) return AndroidDeviceManager::BrowserInfo::kTypeWebView; return AndroidDeviceManager::BrowserInfo::kTypeOther; } // static std::string AdbDeviceInfoQuery::GetDisplayName(const std::string& socket, const std::string& package) { if (package.empty()) { // Derive a fallback display name from the socket name. std::string name = socket.substr(0, socket.find(kDevToolsSocketSuffix)); name[0] = base::ToUpperASCII(name[0]); return name; } const BrowserDescriptor* descriptor = FindBrowserDescriptor(package); if (descriptor) return descriptor->display_name; if (GetBrowserType(socket) == AndroidDeviceManager::BrowserInfo::kTypeWebView) return base::StringPrintf(kWebViewNameTemplate, package.c_str()); return package; } // static void AdbDeviceInfoQuery::Start(const RunCommandCallback& command_callback, const DeviceInfoCallback& callback) { new AdbDeviceInfoQuery(command_callback, callback); } AdbDeviceInfoQuery::AdbDeviceInfoQuery( const RunCommandCallback& command_callback, const DeviceInfoCallback& callback) : command_callback_(command_callback), callback_(callback) { DCHECK(CalledOnValidThread()); command_callback_.Run( kDeviceModelCommand, base::Bind(&AdbDeviceInfoQuery::ReceivedModel, base::Unretained(this))); } AdbDeviceInfoQuery::~AdbDeviceInfoQuery() { } void AdbDeviceInfoQuery::ReceivedModel(int result, const std::string& response) { DCHECK(CalledOnValidThread()); if (result < 0) { Respond(); return; } TrimWhitespaceASCII(response, base::TRIM_ALL, &device_info_.model); device_info_.connected = true; command_callback_.Run( kDumpsysCommand, base::Bind(&AdbDeviceInfoQuery::ReceivedDumpsys, base::Unretained(this))); } void AdbDeviceInfoQuery::ReceivedDumpsys(int result, const std::string& response) { DCHECK(CalledOnValidThread()); if (result >= 0) ParseDumpsysResponse(response); command_callback_.Run( kListProcessesCommand, base::Bind(&AdbDeviceInfoQuery::ReceivedProcesses, base::Unretained(this))); } void AdbDeviceInfoQuery::ParseDumpsysResponse(const std::string& response) { std::vector<std::string> lines; Tokenize(response, "\r", &lines); for (size_t i = 0; i < lines.size(); ++i) { std::string line = lines[i]; size_t pos = line.find(kDumpsysScreenSizePrefix); if (pos != std::string::npos) { ParseScreenSize( line.substr(pos + std::string(kDumpsysScreenSizePrefix).size())); break; } } } void AdbDeviceInfoQuery::ParseScreenSize(const std::string& str) { std::vector<std::string> pairs; Tokenize(str, "-", &pairs); if (pairs.size() != 2) return; int width; int height; std::vector<std::string> numbers; Tokenize(pairs[1].substr(1, pairs[1].size() - 2), ",", &numbers); if (numbers.size() != 2 || !base::StringToInt(numbers[0], &width) || !base::StringToInt(numbers[1], &height)) return; device_info_.screen_size = gfx::Size(width, height); } void AdbDeviceInfoQuery::ReceivedProcesses( int result, const std::string& processes_response) { DCHECK(CalledOnValidThread()); if (result < 0) { Respond(); return; } command_callback_.Run( kOpenedUnixSocketsCommand, base::Bind(&AdbDeviceInfoQuery::ReceivedSockets, base::Unretained(this), processes_response)); } void AdbDeviceInfoQuery::ReceivedSockets( const std::string& processes_response, int result, const std::string& sockets_response) { DCHECK(CalledOnValidThread()); if (result >= 0) ParseBrowserInfo(processes_response, sockets_response); Respond(); } void AdbDeviceInfoQuery::ParseBrowserInfo( const std::string& processes_response, const std::string& sockets_response) { DCHECK(CalledOnValidThread()); StringMap pid_to_package; StringMap package_to_pid; MapProcessesToPackages(processes_response, pid_to_package, package_to_pid); StringMap socket_to_pid = MapSocketsToProcesses(sockets_response, kDevToolsSocketSuffix); std::set<std::string> packages_for_running_browsers; typedef std::map<std::string, int> BrowserMap; BrowserMap socket_to_unnamed_browser_index; for (StringMap::iterator it = socket_to_pid.begin(); it != socket_to_pid.end(); ++it) { std::string socket = it->first; std::string pid = it->second; std::string package; StringMap::iterator pit = pid_to_package.find(pid); if (pit != pid_to_package.end()) { package = pit->second; packages_for_running_browsers.insert(package); } else { socket_to_unnamed_browser_index[socket] = device_info_.browser_info.size(); } AndroidDeviceManager::BrowserInfo browser_info; browser_info.socket_name = socket; browser_info.type = GetBrowserType(socket); browser_info.display_name = GetDisplayName(socket, package); device_info_.browser_info.push_back(browser_info); } } void AdbDeviceInfoQuery::Respond() { DCHECK(CalledOnValidThread()); callback_.Run(device_info_); delete this; }
30.331325
80
0.680834
[ "vector", "model" ]
14b4d150ea11e3abe98e12609299fd7ca1543d3f
10,089
cpp
C++
tensor/Tensor.cpp
DavidAce/acrotensor
809f82859fe5cb2012f7ed7025d64e6553acba1d
[ "MIT" ]
30
2017-09-19T23:53:40.000Z
2022-03-28T09:31:05.000Z
tensor/Tensor.cpp
DavidAce/acrotensor
809f82859fe5cb2012f7ed7025d64e6553acba1d
[ "MIT" ]
1
2021-05-31T18:48:45.000Z
2021-05-31T18:48:45.000Z
tensor/Tensor.cpp
DavidAce/acrotensor
809f82859fe5cb2012f7ed7025d64e6553acba1d
[ "MIT" ]
5
2018-03-20T03:04:29.000Z
2021-06-02T19:09:07.000Z
//Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory //Written by Aaron Fisher (fisher47@llnl.gov). LLNL-CODE-738419. //All rights reserved. //This file is part of Acrotensor. For details, see https://github.com/LLNL/acrotensor. #include "Tensor.hpp" #include "Util.hpp" #include "CudaUtil.hpp" #include <iostream> namespace acro { Tensor::Tensor() { Data = nullptr; DeviceData = nullptr; OwnsData = false; MappedToGPU = false; Initialized = false; } Tensor::Tensor(std::vector<int> &dims, double *hdata, double *ddata, bool ongpu) { Initialized = false; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2, d3}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, int d4, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2, d3, d4}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, int d4, int d5, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2, d3, d4, d5}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, int d4, int d5, int d6, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7, double *hdata, double *ddata, bool ongpu) { Initialized = false; std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6, d7}; Init(dims, hdata, ddata, ongpu); } Tensor::Tensor(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7, int d8, double *hdata, double *ddata, bool ongpu) { Initialized = false; Init(d0, d1, d2, d3, d4, d5, d6, d7, d8, hdata, ddata, ongpu); } void Tensor::Init(int d0, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, int d4, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3, d4}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, int d4, int d5, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, int d4, int d5, int d6, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6, d7}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7, int d8, double *hdata, double *ddata, bool ongpu) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6, d7, d8}; Init(dims, hdata, ddata, ongpu); } void Tensor::Init(std::vector<int> &dims, double *hdata, double *ddata, bool ongpu) { ACROBATIC_ASSERT(!IsInitialized(), "Can't initilize a tensor a second time.") ACROBATIC_ASSERT(dims.size() > 0, "Cant initilize tensor without any dimensions."); for (int d = 0; d < dims.size(); ++d) { ACROBATIC_ASSERT(dims[d] > 0, "Can't initilize tensor with non-positive dimensions."); } Dims = dims; UpdateStrides(); ComputeSize(); if (hdata == nullptr) { Data = new double[Size]; OwnsData = true; } else { Data = hdata; OwnsData = false; } MappedToGPU = false; DeviceData = ddata; if (ddata != nullptr) { ACROBATIC_ASSERT(hdata != nullptr, "Acrotensor does not currently support GPU only tensors."); MappedToGPU = true; } ACROBATIC_ASSERT(ddata != nullptr || !ongpu, "Acrotensor cannot mark external data as on the GPU if no GPU pointer is provided."); OnGPU = ongpu; Initialized = true; } Tensor::~Tensor() { if (OwnsData) { delete [] Data; if (IsMappedToGPU()) { UnmapFromGPU(); } } } void Tensor::Reshape(std::vector<int> &dims) { ACROBATIC_ASSERT(dims.size() > 0); for (int d = 0; d < dims.size(); ++d) { ACROBATIC_ASSERT(dims[d] > 0); } int new_size = 1; for (int d = 0; d < dims.size(); ++d) { new_size *= dims[d]; } ACROBATIC_ASSERT(new_size == Size); Dims = dims; UpdateStrides(); } void Tensor::Reshape(int d0) { std::vector<int> dims = {d0}; Reshape(dims); } void Tensor::Reshape(int d0, int d1) { std::vector<int> dims = {d0, d1}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2) { std::vector<int> dims = {d0, d1, d2}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3) { std::vector<int> dims = {d0, d1, d2, d3}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3, int d4) { std::vector<int> dims = {d0, d1, d2, d3, d4}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3, int d4, int d5) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3, int d4, int d5, int d6) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6, d7}; Reshape(dims); } void Tensor::Reshape(int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7, int d8) { std::vector<int> dims = {d0, d1, d2, d3, d4, d5, d6, d7, d8}; Reshape(dims); } void Tensor::Retarget(double *hdata, double *ddata) { ACROBATIC_ASSERT(!OwnsData); Data = hdata; DeviceData = ddata; } void Tensor::UpdateStrides() { Strides.resize(Dims.size()); int stride = 1; for (int d = Dims.size() - 1; d >= 0; --d) { Strides[d] = stride; stride *= Dims[d]; } } void Tensor::ComputeSize() { Size = 1; for (int d = 0; d < GetRank(); ++d) { Size *= Dims[d]; } ByteSize = Size*sizeof(double); } void Tensor::Set(double val) { if (!IsOnGPU()) { for (int i = 0; i < GetSize(); ++i) { Data[i] = val; } } else { #ifdef ACRO_HAVE_CUDA ensureCudaContext(); CudaSet<<<Size/512+1,512>>>(DeviceData, val, GetSize()); acroCudaErrorCheck(cudaPeekAtLastError()); #endif } } void Tensor::Mult(double c) { if (!IsOnGPU()) { for (int i = 0; i < GetSize(); ++i) { Data[i] *= c; } } else { #ifdef ACRO_HAVE_CUDA ensureCudaContext(); CudaMult<<<Size/512+1,512>>>(DeviceData, c, GetSize()); acroCudaErrorCheck(cudaPeekAtLastError()); #endif } } void Tensor::MapToGPU() { #ifdef ACRO_HAVE_CUDA ACROBATIC_ASSERT(!IsMappedToGPU(), "Trying to map data to the GPU a second time."); ensureCudaContext(); acroCudaErrorCheck(cudaMalloc((void**)&DeviceData, ByteSize)); MappedToGPU = true; #endif } void Tensor::MoveToGPU() { #ifdef ACRO_HAVE_CUDA if (!IsMappedToGPU()) { MapToGPU(); } if (!IsOnGPU()) { ensureCudaContext(); acroCudaErrorCheck(cudaMemcpy(DeviceData, Data, ByteSize, cudaMemcpyHostToDevice)); OnGPU = true; } #endif } void Tensor::SwitchToGPU() { #ifdef ACRO_HAVE_CUDA if (!IsMappedToGPU()) { MapToGPU(); } OnGPU = true; #endif } void Tensor::UnmapFromGPU() { #ifdef ACRO_HAVE_CUDA ACROBATIC_ASSERT(IsMappedToGPU(), "Can't unmap data that is not mapped to the GPU."); ensureCudaContext(); acroCudaErrorCheck(cudaFree(DeviceData)); MappedToGPU = false; OnGPU = false; #endif } void Tensor::MoveFromGPU() { #ifdef ACRO_HAVE_CUDA if (IsOnGPU()) { ensureCudaContext(); acroCudaErrorCheck(cudaMemcpy(Data, DeviceData, ByteSize, cudaMemcpyDeviceToHost)); OnGPU = false; } #endif } void Tensor::SwitchFromGPU() { #ifdef ACRO_HAVE_CUDA OnGPU = false; #endif } void Tensor::Print() { std::cout << "Dims: "; for (int d = 0; d < Dims.size(); ++d) { std::cout << Dims[d] << " "; } std::cout << std::endl; std::cout << "Strides: "; for (int d = 0; d < Dims.size(); ++d) { std::cout << Strides[d] << " "; } std::cout << std::endl; for (int i = 0; i < GetSize(); ++i) { std::cout << Data[i] << std::endl; } std::cout << std::endl; } }
21.790497
131
0.590247
[ "vector" ]
14b752ec2ec9e56813fe71d7788d50a4b6bf5ab0
413
cpp
C++
Algorithms/0739.Daily_Temperatures.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/0739.Daily_Temperatures.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/0739.Daily_Temperatures.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: vector<int> dailyTemperatures(vector<int>& ar) { stack<int> st; int n = ar.size(); vector<int> ans(n,0); for( int i = n-1 ; i >= 0 ; i-- ) { while(!st.empty() && ar[i] >= ar[st.top()]) st.pop(); if(!st.empty()) ans[i] = st.top() - i; st.push(i); } return ans; } };
25.8125
55
0.397094
[ "vector" ]
14ba9af88347b625b30556b61fbf1b1088147afb
1,649
cpp
C++
leetcode/problems/medium/1035-uncrossed-lines.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/1035-uncrossed-lines.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/1035-uncrossed-lines.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Uncrossed Lines We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way. Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2 Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000 */ class Solution { public: int maxUncrossedLines(vector<int>& A, vector<int>& B) { // typical longest common subsequence problem int m=A.size(),n=B.size(); int dp[m+1][n+1]; memset(dp,0,sizeof(dp)); for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(A[i-1]==B[j-1]){ // if the integers are same, take top left value plus one dp[i][j]=1+dp[i-1][j-1]; } else { // if not, take the max value from the left or the top value dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[m][n]; } };
27.949153
120
0.5755
[ "vector" ]
14bf57c317cd983a0a46951d1823a66823cc587f
2,637
hh
C++
include/aleph/containers/MeanShift.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
56
2019-04-24T22:11:15.000Z
2022-03-22T11:37:47.000Z
include/aleph/containers/MeanShift.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
48
2016-11-30T09:37:13.000Z
2019-01-30T21:43:39.000Z
include/aleph/containers/MeanShift.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
11
2019-05-02T11:54:31.000Z
2020-12-10T14:05:40.000Z
#ifndef ALEPH_CONTAINERS_MEAN_SHIFT_HH__ #define ALEPH_CONTAINERS_MEAN_SHIFT_HH__ #include <algorithm> #include <iterator> #include <vector> namespace aleph { namespace containers { /** Performs a mean--shift smoothing operation on a given container. This means that a set of function values will be assigned to each of the indices in the container. Subsequently, the local neighbours of the container are evaluated and used to perform a pre-defined number of smoothing steps. @param container Input container @param begin Input iterator to begin of function value range @param end Input iterator to end of function value range @param result Output iterator for storing the result @param k Number of neighbours to use for smoothing @param n Number of steps to use for smoothing */ template < class Wrapper , class Container , class InputIterator, class OutputIterator > void meanShiftSmoothing( const Container& container, InputIterator begin, InputIterator end, OutputIterator result, unsigned k, unsigned n = 1 ) { using T = typename std::iterator_traits<InputIterator>::value_type; auto N = container.size(); // Makes it easier to permit random access to the container; I am // assuming that the indices correspond to each other. std::vector<T> data( begin, end ); Wrapper nearestNeighbours( container ); using IndexType = typename Wrapper::IndexType; using ElementType = typename Wrapper::ElementType; std::vector< std::vector<IndexType> > indices; std::vector< std::vector<ElementType> > distances; nearestNeighbours.neighbourSearch( k+1, indices, distances ); for( unsigned iteration = 0; iteration < n; iteration++ ) { std::vector<T> data_( data.size() ); for( std::size_t i = 0; i < N; i++ ) { auto&& neighbours_ = indices[i]; auto&& distances_ = distances[i]; aleph::math::KahanSummation<T> value = 0.0; aleph::math::KahanSummation<T> sumOfWeights = 0.0; for( std::size_t j = 0; j < neighbours_.size(); j++ ) { auto index = neighbours_[j]; auto weight = distances_[j] > 0 ? 1.0 / ( distances_[j] * distances_[j] ) : 1.0; value += data[ index ] * weight; // use data values from *previous* step to // perform the smoothing! sumOfWeights += weight; } value /= sumOfWeights; data_[i] = value; } data.swap( data_ ); } std::copy( data.begin(), data.end(), result ); } } // namespace containers } // namespace aleph #endif
27.757895
90
0.659462
[ "vector" ]
14c304779c2b8c3e58c6d98486f1fa1f1120f5ad
2,446
cpp
C++
Problems/Google/Google_Hash_Code/2021/Qualification/Simulation/Simulation.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/Google/Google_Hash_Code/2021/Qualification/Simulation/Simulation.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/Google/Google_Hash_Code/2021/Qualification/Simulation/Simulation.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fi first #define se second #define maxc 1000 #define maxm 100000 #define maxn 100000 #define pb push_back using namespace std; typedef long long LL; typedef pair<int,int> pi; typedef pair<pi,int> pii; int d,n,m,c,p; int eSrc[maxm]; int eDist[maxm]; string eName[maxm]; vector<int> carEdgeId[maxc]; map<string,int> mpEdgeName; int schN; int cycleTotal[maxn]; vector<int> schVertex; vector<int> prefixSum[maxn]; vector<int> schEdges[maxn]; int currSchEdgeId[maxn]; queue<pii> qCars[maxm]; void input() { ifstream inFile; inFile.open("input.txt"); inFile >> d >> n >> m >> c >> p; for( int i = 0 ; i < m ; i++ ) { int dest; inFile >> eSrc[i] >> dest >> eName[i] >> eDist[i]; mpEdgeName[eName[i]] = i; } for( int i = 0 ; i < c ; i++ ) { int k,id; string e; inFile >> k; for( int j = 0 ; j < k ; j++ ) { inFile >> e; id = mpEdgeName[e]; carEdgeId[i].pb(id); } } inFile.close(); } void output() { ifstream outFile; outFile.open("output.txt"); outFile >> schN; for( int i = 0 ; i < schN ; i++ ) { int u,e,sum=0; outFile >> u >> e; schVertex.pb(u); for( int j = 0 ; j < e ; j++ ) { int len; string name; outFile >> name >> len; int id = mpEdgeName[name]; schEdges[u].pb(id); sum += len; prefixSum[u].pb(sum); } prefixSum[u][e-1] = 0; cycleTotal[u] = sum; } outFile.close(); } void sim() { int score = 0; int arrived = 0; for( int i = 0 ; i < c ; i++ ) { int eId = carEdgeId[i][0]; qCars[eId].push(pii( pi(i,0) , 0 )); } for( int t = 0 ; t <= d ; t++ ) { for( int sv = 0 ; sv < schN ; sv++ ) { int u = schVertex[sv]; int scheid = currSchEdgeId[u]; int eid = schEdges[u][scheid]; if(!qCars[eid].empty()) { pii car = qCars[eid].front(); int cid = car.fi.fi; int peid = car.fi.se + 1; int arrt = car.se; if(t >= arrt) { qCars[eid].pop(); int path = carEdgeId[cid].size(); int reeleid = carEdgeId[cid][peid]; if(peid == path-1) { if(t+eDist[reeleid] <= d) { arrived++; score += p + (d - (t+eDist[reeleid])); } } else qCars[reeleid].push( pii( pi(cid,peid) , t+eDist[reeleid] ) ); } } bool nxtEdge = ( ((t+1) % cycleTotal[u]) == prefixSum[u][scheid] ); currSchEdgeId[u] = (currSchEdgeId[u]+nxtEdge) % schEdges[u].size(); } } printf("%d , %d / %d\n",score,arrived,c); } int main() { input(); output(); sim(); return 0; }
20.728814
70
0.558054
[ "vector" ]
14c4a0c507e54f3aabc674593995bf5b2c702841
5,947
cpp
C++
Sandbox/src/Sandbox2D.cpp
lccatala/Fandango
8f2d7c85df8a839a8e578c4c0e7e5672b7e45260
[ "Apache-2.0" ]
1
2019-11-19T12:45:49.000Z
2019-11-19T12:45:49.000Z
Sandbox/src/Sandbox2D.cpp
lccatala/Fandango
8f2d7c85df8a839a8e578c4c0e7e5672b7e45260
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Sandbox2D.cpp
lccatala/Fandango
8f2d7c85df8a839a8e578c4c0e7e5672b7e45260
[ "Apache-2.0" ]
null
null
null
#include "Sandbox2D.h" #include <Fandango/Core/EntryPoint.h> #include "imgui/imgui.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Fandango/Platform/OpenGL/OpenGLShader.h" Sandbox2D::Sandbox2D() : Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f) {} void Sandbox2D::OnAttach() { FNDG_PROFILE_FUNCTION(); m_CheckerboardTexture = Fandango::Texture2D::Create("assets/textures/Checkerboard.png"); m_SpriteSheet = Fandango::Texture2D::Create("assets/game/textures/RPGpack_sheet_2X.png"); Fandango::FrameBufferSpec fbSpec; fbSpec.Width = 1280; fbSpec.Height = 720; m_FrameBuffer = Fandango::FrameBuffer::Create(fbSpec); } void Sandbox2D::OnDetach() { FNDG_PROFILE_FUNCTION(); } void Sandbox2D::OnUpdate(Fandango::TimeStep ts) { FNDG_PROFILE_FUNCTION(); m_CameraController.OnUpdate(ts); Fandango::Renderer2D::ResetStats(); m_FrameBuffer->Bind(); Fandango::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 }); Fandango::RenderCommand::Clear(); Fandango::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (float y = -5.0f; y < 5.0f; y += 0.5f) { for (float x = -5.0f; x < 5.0f; x += 0.5f) { glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f, 0.7f }; } } Fandango::Renderer2D::DrawQuadTexture({ 0.0f, 0.0f, 0.0f }, 0.0f, 1.0f, {0.45f, 0.45f}, m_SpriteSheet); Fandango::Renderer2D::EndScene(); m_FrameBuffer->Unbind(); #ifdef ENABLE_PARTICLES if (Fandango::Input::IsMouseButtonPressed(FNDG_MOUSE_BUTTON_LEFT)) { auto [x, y] = Fandango::Input::GetMousePosition(); auto width = Fandango::Application::Get().GetWindow().GetWidth(); auto height = Fandango::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetCameraBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_ParticleProps.Position = { x + pos.x, y + pos.y }; for (int i = 0; i < 10; i++) m_ParticleSystem.Emit(m_ParticleProps); } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); #endif } void Sandbox2D::OnImGuiRender() { FNDG_PROFILE_FUNCTION(); static bool showDockspace = true; static bool opt_fullscreen_persistant = true; static ImGuiDockNodeFlags opt_flags = ImGuiDockNodeFlags_None; bool opt_fullscreen = opt_fullscreen_persistant; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } // When using ImGuiDockNodeFlags_PassthruDockspace, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. if (opt_flags & ImGuiDockNodeFlags_PassthruDockspace) window_flags |= ImGuiWindowFlags_NoBackground; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", &showDockspace, window_flags); ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // Dockspace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), opt_flags); } if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Quit", NULL, false)) { showDockspace = false; Fandango::Application::Get().Close(); } ImGui::EndMenu(); } /* if (ImGui::BeginMenu("Docking")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); if (ImGui::MenuItem("Flag: NoSplit", "", (opt_flags & ImGuiDockNodeFlags_NoSplit) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoSplit; if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (opt_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; if (ImGui::MenuItem("Flag: NoResize", "", (opt_flags & ImGuiDockNodeFlags_NoResize) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoResize; if (ImGui::MenuItem("Flag: PassthruDockspace", "", (opt_flags & ImGuiDockNodeFlags_PassthruDockspace) != 0)) opt_flags ^= ImGuiDockNodeFlags_PassthruDockspace; ImGui::Separator(); if (ImGui::MenuItem("Close DockSpace", NULL, false)) showDockspace = false; ImGui::EndMenu(); } */ ImGui::EndMenuBar(); } ImGui::Begin("Settings"); auto stats = Fandango::Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertices: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor)); uint32_t textureID = m_FrameBuffer->GetColorAttachmentRendererID(); ImGui::Image((void*)textureID, ImVec2{ 1280, 720 }, ImVec2{ 0, 1 }, ImVec2{ 1, 0 }); ImGui::End(); ImGui::End(); } void Sandbox2D::OnEvent(Fandango::Event& e) { m_CameraController.OnEvent(e); }
34.982353
178
0.724399
[ "render" ]
14c6eba928055a1fee311e2c988f452ddb5e35c8
1,896
cpp
C++
C++/arraymanip.cpp
sockduct/Hackerrank
3f73370fe5e477701e1bb30b116a77b4a2efc888
[ "MIT" ]
null
null
null
C++/arraymanip.cpp
sockduct/Hackerrank
3f73370fe5e477701e1bb30b116a77b4a2efc888
[ "MIT" ]
null
null
null
C++/arraymanip.cpp
sockduct/Hackerrank
3f73370fe5e477701e1bb30b116a77b4a2efc888
[ "MIT" ]
null
null
null
#include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <tuple> #include <vector> // Long in MSVC same as int, for 10e9 need long long int: using bigint = long long int; using qvec = std::vector<std::tuple<int, int, bigint>>; bigint arrmanip(int n, qvec queries) { auto beginfunc = std::chrono::high_resolution_clock::now(); std::vector<bigint> arr(n, 0); bigint maxval = 0; // Iterate through array and perform requested operations... for (const auto& [left, right, inc]: queries) { for (bigint i = left - 1; i < right; ++i) { arr[i] += inc; } } auto endfunc = std::chrono::high_resolution_clock::now(); auto funcdur = std::chrono::duration_cast<std::chrono::microseconds>(endfunc - beginfunc); std::cout << "Completed array manipulation in " << funcdur.count() << " microseconds\n"; for (const auto& i: arr) { if (i > maxval) { maxval = i; } } endfunc = std::chrono::high_resolution_clock::now(); funcdur = std::chrono::duration_cast<std::chrono::microseconds>(endfunc - beginfunc); std::cout << "Found array maximum value in " << funcdur.count() << " microseconds\n"; return maxval; } int main() { auto beginfunc = std::chrono::high_resolution_clock::now(); int n, m; qvec queries; int a, b; bigint k, res; std::cin >> n >> m; for (int line = 0; line < m; ++line) { std::cin >> a >> b >> k; queries.push_back(std::make_tuple(a, b, k)); } auto endfunc = std::chrono::high_resolution_clock::now(); auto funcdur = std::chrono::duration_cast<std::chrono::microseconds>(endfunc - beginfunc); std::cout.imbue(std::locale("")); std::cout << "Read in queries in " << funcdur.count() << " microseconds\n"; res = arrmanip(n, queries); std::cout << std::fixed << res << "\n"; }
31.081967
94
0.60654
[ "vector" ]
14ccfc84a8dde232903e8f375eb5736a682fbe1d
1,947
cpp
C++
testsuite/TestModelParsing/main.cpp
KorfLab/StochHMM
965ee4fbe2f2dac8868387989901369cba452086
[ "MIT" ]
127
2015-01-16T13:05:48.000Z
2022-01-27T15:17:25.000Z
testsuite/TestModelParsing/main.cpp
johnson056029/nycuPPproj
a6231db4b0a29ddd509bff75e00d11c3f83d43a7
[ "MIT" ]
11
2015-03-19T16:51:42.000Z
2021-09-10T02:15:00.000Z
testsuite/TestModelParsing/main.cpp
johnson056029/nycuPPproj
a6231db4b0a29ddd509bff75e00d11c3f83d43a7
[ "MIT" ]
41
2015-06-04T02:02:09.000Z
2021-11-09T17:14:15.000Z
// // main.cpp // ModelParsing // // Created by Paul Lott on 10/14/11. // Copyright 2011 University of California, Davis. All rights reserved. // #include <iostream> #include <string> #include "hmm.h" #include "seqTracks.h" using namespace StochHMM; //typedef double (*transitionFunc) (const std::string*, const size_t, const std::string*, const size_t); //typedef double (*emissionFunc) (const std::string*, const size_t); double transFunc_Test(const std::string* seq, const size_t pos, const std::string* trb_seq, const size_t trb){ return -2.0; } double emissFunc_PWM(const std::string* seq , const size_t pos){ return -1.5; } StateFuncs stFuncs; int main (int argc, const char * argv[]) { std::string pwm="PWM"; stFuncs.assignEmmissionFunction(pwm, *emissFunc_PWM); std::string files[]={"TestModel1.hmm", "TestModel2.hmm","TestModel3.hmm", "TestModel4.hmm","TestModel5.hmm", "TestModel6.hmm","TestModel7.hmm", "TestModel8.hmm","TestModel9.hmm", "TestModel10.hmm","TestModel11.hmm", "TestModel12.hmm","TestModel13.hmm", "TestModel14.hmm","TestModel15.hmm", "TestModel16.hmm" }; for(int i=0;i<10;i++){ std::cout << files[i] <<std::endl; std::string file = "TestModels/ValidModels/" + files[i]; model test; if (test.import(file,&stFuncs)){ //test.print(); } else{ std::cerr << "Error reading in model "<< file << std::endl; } } for(int i=0;i<16;i++){ std::cout << files[i] <<std::endl; std::string file = "TestModels/InvalidModels/" + files[i]; model test; if (test.import(file,&stFuncs)){ test.print(); } else{ std::cerr << "Error reading in model "<< file << std::endl; } } return 0; }
23.743902
110
0.569594
[ "model" ]
14d673a6e3624d81b99b443c7168df6ea5b89287
24,083
cpp
C++
python_sdk_18.04/samples/gui/QtCheetahTriggerUI/QtCheetahTriggerUI.cpp
vignesh-narayanaswamy/camsdk
5c6aa96d0715cd77c42abb90449b740a2940d8a0
[ "Apache-2.0" ]
null
null
null
python_sdk_18.04/samples/gui/QtCheetahTriggerUI/QtCheetahTriggerUI.cpp
vignesh-narayanaswamy/camsdk
5c6aa96d0715cd77c42abb90449b740a2940d8a0
[ "Apache-2.0" ]
null
null
null
python_sdk_18.04/samples/gui/QtCheetahTriggerUI/QtCheetahTriggerUI.cpp
vignesh-narayanaswamy/camsdk
5c6aa96d0715cd77c42abb90449b740a2940d8a0
[ "Apache-2.0" ]
null
null
null
#include "QtCheetahTriggerUI.h" #include "IpxCameraApi.h" #include "IpxCameraGuiApi.h" #include "IpxImage.h" #include "IpxDisplay.h" #include <QTimer> #include <QGroupBox> #include <QSettings> #include "../common/inc/GrabbingThread.h" #include "../common/inc/ipxparammaphelper.h" // =========================================================================== // QtCheetahTriggerUI Constructor // // The Constructor initializes the ThreadDisplay, Camera, IpxDisplay, IpxStream, IpxDeviceInfo // modules to null. Then, it loads the Imperx Icon and initializes the System of the // GenTL Module Hierachy. // ============================================================================= QtCheetahTriggerUI::QtCheetahTriggerUI(QWidget *parent) : QMainWindow(parent) , m_timer(nullptr) , m_system(nullptr) , m_camera(nullptr) , m_stream(nullptr) , m_devInfo(nullptr) , m_grabThread(nullptr) , m_display(IpxDisplay::CreateComponent()) , m_parameterView(nullptr) , m_mapData(new IpxGui::IpxCamConfigMapper) , m_isConnected (false) { ui.setupUi(this); CreateLayout(); //-------------------- Connect the GUI signals with slots --------------------// connect(ui.actionConnect, &QAction::triggered, this, &QtCheetahTriggerUI::Connect); connect(ui.actionDisconnect, &QAction::triggered, this, &QtCheetahTriggerUI::Disconnect); connect(ui.actionPlay, &QAction::triggered, [this](){ // Check if the Imperx Camera is Connected if (!m_isConnected) return; StartAcquisition(); UpdateToolbarButtons(); }); connect(ui.actionStop, &QAction::triggered, [this](){ // Check if the Imperx Camera is Connected if (!m_isConnected) return; StopAcquisition(); UpdateToolbarButtons(); }); connect(ui.actionGenICamTree, &QAction::triggered, [this](){ if (m_parameterView) m_parameterView->show(); }); connect(ui.actionZoomIn, &QAction::triggered, this, [this](){ m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ZOOM_IN); }); connect(ui.actionZoomOut, &QAction::triggered, this, [this](){ m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ZOOM_OUT); }); connect(ui.actionFitToWindow, &QAction::triggered, this, [this](){ m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 1); }); connect(ui.actionSpreadToWindow, &QAction::triggered, [this](){ m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 2); }); connect(ui.actionActualSize, &QAction::triggered, this, [this](){ m_display->GetComponent()->SetParamInt((char*)IDP_VIEW_FIT, 3); }); connect(ui.actionCenterImage, &QAction::triggered, [this](){ m_display->GetComponent()->RunCommand((char*)IDPC_CMD_VIEW_ATCENTER); }); connect(this, &QtCheetahTriggerUI::cameraDisconnected, this, [this](){ Disconnect(); QMessageBox::critical(this, "ERROR", "The camera has lost connection!"); }, Qt::QueuedConnection ); //----------------------------------------------------------------------------// //----------------------- Create and initialize System -----------------------// if (!(m_system = IpxCam::IpxCam_GetSystem())) QMessageBox::critical(this, "Error", "ERROR: Unable to create the System Object."); //----------------------------------------------------------------------------// //-------------------------- Initialize the display --------------------------// if (m_display) { m_display->Initialize(m_displayLabel); ui.actionFitToWindow->trigger(); } else { QMessageBox::critical(this, "", "ERROR: Unable to create the Display Object."); } //----------------------------------------------------------------------------// UpdateToolbarButtons(); } void QtCheetahTriggerUI::closeEvent(QCloseEvent * event) { // Disconnect first Disconnect(); // because m_parameterView has not been given a parent we need to clean it up // make sure that parameter a set to nullptr delete m_parameterView; m_parameterView = nullptr; // Delete the grabbing thread delete m_grabThread; m_grabThread = nullptr; // Delete mapper delete m_mapData; m_mapData = nullptr; // Delete Display object, since main Window to be closed IpxDisplay::DeleteComponent(m_display); m_display = nullptr; QMainWindow::closeEvent(event); } void QtCheetahTriggerUI::CreateLayout() { QGroupBox *lInfoBox = CreateInfoGroup(); QGroupBox *lTriggerBox = CreateTriggerGroup(); QVBoxLayout *lLayoutLeft = new QVBoxLayout(); lLayoutLeft->addWidget(lInfoBox); lLayoutLeft->addWidget(lTriggerBox); lLayoutLeft->addStretch(); m_displayLabel = new QLabel; QVBoxLayout *displayLayout = new QVBoxLayout; displayLayout->addWidget(m_displayLabel); QGroupBox *lDisplayBox = new QGroupBox(tr("Display")); lDisplayBox->setLayout(displayLayout); QHBoxLayout *lMainLayout = new QHBoxLayout; lMainLayout->addLayout(lLayoutLeft); lMainLayout->addWidget(lDisplayBox); QFrame *lMainBox = new QFrame; lMainBox->setLayout(lMainLayout); setCentralWidget(lMainBox); setWindowTitle(tr("QtCheetahTriggerUI")); } QGroupBox *QtCheetahTriggerUI::CreateInfoGroup() { QLabel *lManufacturerLabel = new QLabel(tr("Manufacturer")); mManufacturerEdit = new QLineEdit; mManufacturerEdit->setReadOnly(true); mManufacturerEdit->setFocusPolicy(Qt::NoFocus); QLabel *lDeviceFamilyLabel = new QLabel(tr("Device Family")); mDeviceFamilyEdit = new QLineEdit; mDeviceFamilyEdit->setReadOnly(true); mDeviceFamilyEdit->setFocusPolicy(Qt::NoFocus); QLabel *lModelLabel = new QLabel(tr("Model")); mModelEdit = new QLineEdit; mModelEdit->setReadOnly(true); mModelEdit->setFocusPolicy(Qt::NoFocus); QLabel *lNameLabel = new QLabel(tr("Name")); mNameEdit = new QLineEdit; mNameEdit->setReadOnly(true); mNameEdit->setFocusPolicy(Qt::NoFocus); QLabel *lVersionLabel = new QLabel(tr("Version")); mVersionEdit = new QLineEdit; mVersionEdit->setReadOnly(true); mVersionEdit->setFocusPolicy(Qt::NoFocus); QLabel *lSerialNbrLabel = new QLabel(tr("SerialNumber")); mSerialNbrEdit = new QLineEdit; mSerialNbrEdit->setReadOnly(true); mSerialNbrEdit->setFocusPolicy(Qt::NoFocus); QGridLayout *lGridLayout = new QGridLayout; lGridLayout->addWidget(lManufacturerLabel, 0, 0); lGridLayout->addWidget(mManufacturerEdit, 0, 1); lGridLayout->addWidget(lDeviceFamilyLabel, 1, 0); lGridLayout->addWidget(mDeviceFamilyEdit, 1, 1); lGridLayout->addWidget(lModelLabel, 2, 0); lGridLayout->addWidget(mModelEdit, 2, 1); lGridLayout->addWidget(lNameLabel, 3, 0); lGridLayout->addWidget(mNameEdit, 3, 1); lGridLayout->addWidget(lVersionLabel, 4, 0); lGridLayout->addWidget(mVersionEdit, 4, 1); lGridLayout->addWidget(lSerialNbrLabel, 5, 0); lGridLayout->addWidget(mSerialNbrEdit, 5, 1); QGroupBox *lInfoBox = new QGroupBox(tr("Device Info")); lInfoBox->setLayout(lGridLayout); lInfoBox->setMaximumWidth(300); return lInfoBox; } QGroupBox *QtCheetahTriggerUI::CreateTriggerGroup() { QLabel *lModeLabel = new QLabel(tr("Mode:")); mTriggerMode = new QComboBox; mTriggerMode->setEnabled(false); QLabel *lSourceLabel = new QLabel(tr("Source:")); mTriggerSource = new QComboBox; mTriggerSource->setEnabled(false); QLabel *lActivationLabel = new QLabel(tr("Activation:")); mTriggerActivation = new QComboBox; mTriggerActivation->setEnabled(false); QLabel *lDebounceLabel = new QLabel(tr("Debounce:")); mTriggerDebounce = new QComboBox; mTriggerDebounce->setEnabled(false); mFlashSWTrigger = new QPushButton(tr("Software Trigger")); mFlashSWTrigger->setEnabled(false); QGridLayout *lExpGridLayout = new QGridLayout; lExpGridLayout->addWidget(lModeLabel, 0, 0); lExpGridLayout->addWidget(mTriggerMode, 0, 1); lExpGridLayout->addWidget(lSourceLabel, 1, 0); lExpGridLayout->addWidget(mTriggerSource, 1, 1); lExpGridLayout->addWidget(lActivationLabel, 2, 0); lExpGridLayout->addWidget(mTriggerActivation, 2, 1); lExpGridLayout->addWidget(lDebounceLabel, 3, 0); lExpGridLayout->addWidget(mTriggerDebounce, 3, 1); lExpGridLayout->addWidget(mFlashSWTrigger, 4, 1); QGroupBox *lTriggerBox = new QGroupBox(tr("Trigger Control")); lTriggerBox->setLayout(lExpGridLayout); lTriggerBox->setMaximumWidth(300); return lTriggerBox; } // ============================================================================= // Connect the Imperx Camera // ============================================================================= void QtCheetahTriggerUI::Connect() { Disconnect(); // Open camera selection dialog m_devInfo = IpxGui::SelectCameraA(m_system, "Get Device Selection"); // Check if any camera was selected if (!m_devInfo) return; // Create the Device object from DeviceInfo of selected Camera m_camera = IpxCam::IpxCam_CreateDevice(m_devInfo); if (!m_camera) { QMessageBox::critical(this, "ERROR", "Unable to retrieve camera device.\r\nMake sure an Imperx Camera is connected." ); return; } // Get the camera basic information and show it on GUI auto camParamArray = m_camera->GetCameraParameters(); if (!camParamArray) { QMessageBox::critical(this, "ERROR", "Unable to retrieve camParamArray."); return; } IpxGenParam::String* lModelName = camParamArray->GetString("DeviceModelName", nullptr); if (lModelName) { mModelEdit->setText(lModelName->GetValue()); mModelEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceModelName failed."); IpxGenParam::String* lNameParam = camParamArray->GetString("DeviceUserDefinedName", nullptr); if (!lNameParam) lNameParam = camParamArray->GetString("DeviceUserID", nullptr); if (lNameParam) { mNameEdit->setText(lNameParam->GetValue()); mNameEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceUserID failed."); IpxGenParam::String* lManufacturer = camParamArray->GetString("DeviceManufacturerName", nullptr); if (!lManufacturer) lManufacturer = camParamArray->GetString("DeviceVendorName", nullptr); if (lManufacturer) { mManufacturerEdit->setText(lManufacturer->GetValue()); mManufacturerEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceVendorName failed."); IpxGenParam::String* lDeviceFamily = camParamArray->GetString("DeviceFamilyName", nullptr); if (lDeviceFamily) { mDeviceFamilyEdit->setText(lDeviceFamily->GetValue()); mDeviceFamilyEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceFamilyName failed."); IpxGenParam::String* lVersion = camParamArray->GetString("DeviceVersion", nullptr); if (lVersion) { mVersionEdit->setText(lVersion->GetValue()); mVersionEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceVersion failed."); IpxGenParam::String* lSerialNbr = camParamArray->GetString("DeviceSerialNumber", nullptr); if (lSerialNbr) { mSerialNbrEdit->setText(lSerialNbr->GetValue()); mSerialNbrEdit->setCursorPosition(0); // text may not fit into edit } else QMessageBox::warning(this, "Warning", "Retrieving DeviceSerialNumber failed."); ////////////////////////////////////////////////////////////////////// /// example how to map enum parameter with combo box ////////////////////////////////////////////////////////////////////// m_mapData->mapEnumParam(camParamArray->GetEnum("TriggerMode", nullptr), mTriggerMode); m_mapData->mapEnumParam(camParamArray->GetEnum("TriggerSource", nullptr), mTriggerSource); m_mapData->mapEnumParam(camParamArray->GetEnum("TriggerActivation", nullptr), mTriggerActivation); m_mapData->mapEnumParam(camParamArray->GetEnum("TriggerDebounce", nullptr), mTriggerDebounce); ////////////////////////////////////////////////////////////////////// // example how to use timer to disable button while IsDone is not true ////////////////////////////////////////////////////////////////////// auto command = camParamArray->GetCommand("TriggerSoftware", nullptr); if (command) { // release an old one in case it exists if (m_timer) { m_timer->stop(); delete m_timer; } m_timer = new QTimer(this); m_timer->setInterval(500); QObject::connect(m_timer, &QTimer::timeout, [this, command](){ if (command->IsDone()) { mFlashSWTrigger->setEnabled(true); m_timer->stop(); } }); } ////////////////////////////////////////////////////////////////////// /// example how to map command parameter with push button ////////////////////////////////////////////////////////////////////// m_mapData->mapCommandParam(command, mFlashSWTrigger, m_timer); ////////////////////////////////////////////////////////////////////// /// other stuff ////////////////////////////////////////////////////////////////////// // Get first Stream from the Camera m_stream = m_camera->GetStreamByIndex(0); if (!m_stream) QMessageBox::critical(this, "ERROR", "Unable to retrieve camera stream." ); // Create the grabbing thread m_grabThread = new GrabbingThread(m_stream, m_display); ////////////////////////////////////////////////////////////////////// /// Create tree view of the parameters ////////////////////////////////////////////////////////////////////// if (!m_parameterView) // do not set parent so m_parameterView becomes a dialog m_parameterView = new IpxGui::IpxGenParamTreeView(); m_parameterView->setParams(camParamArray); // restore the settings of tree view QSettings settings(QStringLiteral("MyCompanyName"), QStringLiteral("MyApplicationName")); auto dataToBeRestored = settings.value(mModelEdit->text() + QStringLiteral("treeViewState")).toByteArray(); if (!dataToBeRestored.isEmpty()) m_parameterView->loadState(dataToBeRestored.constData()); m_parameterView->restoreGeometry(settings.value(QStringLiteral("treeViewGeometry")).toByteArray()); ////////////////////////////////////////////////////////////////////// /// Register callback ////////////////////////////////////////////////////////////////////// // Because we register event for a device we cannot release this device in the callback function // QtCommonStreamUI::CameraDisconnectCallback. So we will use signal slot connection with type // Qt::QueuedConnection. In other words callback should return before releasing the device object. // SEE connection in the constructor! m_camera->RegisterEvent(IpxCam::Device::CameraDisconnected, &QtCheetahTriggerUI::CameraDisconnectCallback, this); // Also you can register callback on an interface for device arrival and device left event // You will receive device id in the parameters eventData and eventSize of the callback function // Let us save the device's id to check later if we get notification for our device // Do not forget to comment registration line above so not to get notified twice if you want to use next line // And make sure you use correct QtCommonStreamUI::CameraDisconnectCallback method //m_camera->GetInfo()->GetInterface()->RegisterEvent(IpxCam::Device::CameraDisconnected, // &QtCheetahTriggerUI::CameraDisconnectCallback, this); m_isConnected = true; UpdateToolbarButtons(); } // ============================================================================= // Disconnect the Imperx Camera // ============================================================================= void QtCheetahTriggerUI::Disconnect() { if (!m_isConnected) return; // Stop the Acquisition if (m_grabThread) { if (m_grabThread->IsStarted()) StopAcquisition(); delete m_grabThread; m_grabThread = nullptr; } // crear mapper in case is not empty if (m_mapData) { IpxGenParam::Array *paramArray = nullptr; if (m_camera) paramArray = m_camera->GetCameraParameters(); m_mapData->clear(paramArray); } if (m_parameterView) { // save the settings of the tree view QSettings settings(QStringLiteral("MyCompanyName"), QStringLiteral("MyApplicationName")); auto dataToBeSaved = m_parameterView->saveState(); if (dataToBeSaved) settings.setValue(mModelEdit->text() + QStringLiteral("treeViewState"), QByteArray(dataToBeSaved)); // save geometry of the tree view settings.setValue(QStringLiteral("treeViewGeometry"), m_parameterView->saveGeometry()); // clear parameters in tree view before m_camera(IpxDevice) is dead m_parameterView->clearParams(); } QString empty; mModelEdit->setText(empty); mNameEdit->setText(empty); mManufacturerEdit->setText(empty); mDeviceFamilyEdit->setText(empty); mVersionEdit->setText(empty); mSerialNbrEdit->setText(empty); // Release the Stream object if(m_stream) m_stream->Release(); m_stream = nullptr; // Release the Camera Device object if(m_camera) m_camera->Release(); m_camera = nullptr; m_isConnected = false; UpdateToolbarButtons(); } // ============================================================================= // Start the Acquisition engine on the host. It will call the GenTL consumer to // start the transfer // ============================================================================= void QtCheetahTriggerUI::StartAcquisition() { QString errMsg("Sorry! Cannot start streaming."); // Allocate the minimal required buffer queue if (m_stream && m_stream->AllocBufferQueue(this, m_stream->GetMinNumBuffers()) == IPX_CAM_ERR_OK) { auto genParams = m_camera->GetCameraParameters(); if (genParams) { // Set the TLParamsLocked parameter to lock the parameters effecting to the Transport Layer if (genParams->SetIntegerValue("TLParamsLocked", 1) == IPX_CAM_ERR_OK) { if (m_stream->StartAcquisition() == IPX_CAM_ERR_OK) { m_grabThread->Start(); if (genParams->ExecuteCommand("AcquisitionStart") == IPX_CAM_ERR_OK) return; errMsg += "\r\nAcquisitionStart command failed."; m_stream->StopAcquisition(); } else errMsg += "\r\nCheck if there is enough memory.\r\nParticularly, on Linux machine!"; genParams->SetIntegerValue("TLParamsLocked", 0); } } m_stream->ReleaseBufferQueue(); } QMessageBox::critical(this, "ERROR", errMsg); } // ============================================================================= // Stop the Acquisition engine on the host. It will call the GenTL consumer to // stop the transfer // ============================================================================= void QtCheetahTriggerUI::StopAcquisition() { // Get camera parrameters array auto genParams = m_camera->GetCameraParameters(); if (genParams) { /// If any error occured with AcquisitionStop, run AcquisitionAbort if (genParams->ExecuteCommand("AcquisitionStop") != IPX_CAM_ERR_OK) genParams->ExecuteCommand("AcquisitionAbort"); // Reset the TLParamsLocked parameter to unlock the parameters effecting to the Transport Layer genParams->SetIntegerValue("TLParamsLocked", 0); m_grabThread->Stop(); if (m_stream) { m_stream->StopAcquisition(); m_stream->ReleaseBufferQueue(); } } } // ============================================================================= // UpdateToolBarButtons will enable/disable the Toolbar buttons according the connection state // ============================================================================= void QtCheetahTriggerUI::UpdateToolbarButtons() { auto actions = ui.toolBarFile->actions(); for (QAction *action: actions) action->setEnabled(m_isConnected); actions = ui.toolBarDisplay->actions(); for (QAction *action: actions) action->setEnabled(m_isConnected); actions = ui.toolBarView->actions(); for (QAction *action: actions) action->setEnabled(m_isConnected); // connect action should be opposite ui.actionConnect->setEnabled(!ui.actionConnect->isEnabled()); if (m_isConnected) { if (!m_grabThread || !m_grabThread->IsStarted()) ui.actionStop->setEnabled(false); else ui.actionPlay->setEnabled(false); } EnableControls(m_isConnected); } // ============================================================================= // EnableControls will enable/disable the GUI controls // ============================================================================= void QtCheetahTriggerUI::EnableControls(bool en) { mTriggerActivation->setEnabled(en); mTriggerDebounce->setEnabled(en); mTriggerSource->setEnabled(en); mTriggerMode->setEnabled(en); mFlashSWTrigger->setEnabled(en); } // ============================================================================= // Callback to be called when camera disconnects // ============================================================================= void IPXCAM_CALL QtCheetahTriggerUI::CameraDisconnectCallback(const void *eventData, size_t eventSize, void *pPrivate) { QtCheetahTriggerUI *pThis = static_cast<QtCheetahTriggerUI*>(pPrivate); Q_EMIT pThis->cameraDisconnected(); } // ============================================================================= // Callback to be called when camera disconnects // ============================================================================= // remove comments if you registered callback for interface // and comment the method above /*void IPXCAM_CALL QtCheetahTriggerUI::CameraDisconnectCallback(const void *eventData, size_t eventSize, void *pPrivate) { auto pThis = static_cast<QtCommonStreamUI*>(pPrivate); auto idEvent = static_cast<const char*>(eventData); auto id = pThis->m_camera->GetInfo()->GetID(); if (id && idEvent && eventSize) { QByteArray str; str.setRawData(idEvent, (uint)eventSize); if (str.startsWith(id)) Q_EMIT pThis->cameraDisconnected(); } }*/
37.107858
128
0.585268
[ "geometry", "object", "model" ]
14dc4bda7ab4c9946a2c50aad18792dffc9bbd7d
38,562
cpp
C++
dashel/dashel-posix.cpp
brettle/dashel
33b2ccdef1d1af411dd1eab9af9fa8fea93eae6a
[ "Unlicense" ]
null
null
null
dashel/dashel-posix.cpp
brettle/dashel
33b2ccdef1d1af411dd1eab9af9fa8fea93eae6a
[ "Unlicense" ]
null
null
null
dashel/dashel-posix.cpp
brettle/dashel
33b2ccdef1d1af411dd1eab9af9fa8fea93eae6a
[ "Unlicense" ]
null
null
null
/* Dashel A cross-platform DAta Stream Helper Encapsulation Library Copyright (C) 2007 -- 2015: Stephane Magnenat <stephane at magnenat dot net> (http://stephane.magnenat.net) Mobots group - Laboratory of Robotics Systems, EPFL, Lausanne (http://mobots.epfl.ch) Sebastian Gerlach Kenzan Technologies (http://www.kenzantech.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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of "Mobots", "Laboratory of Robotics Systems", "EPFL", "Kenzan Technologies" nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include <cassert> #include <cstdlib> #include <map> #include <vector> #include <valarray> #include <algorithm> #include <iostream> #include <sstream> #include <signal.h> #include <errno.h> #include <unistd.h> #include <termios.h> #include <fcntl.h> #include <netdb.h> #include <signal.h> #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <sys/ioctl.h> #include <pthread.h> #include <netinet/in.h> #ifdef __APPLE__ #define MACOSX #endif #ifdef MACOSX #define USE_POLL_EMU #endif #ifdef MACOSX #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/serial/IOSerialKeys.h> #endif #ifdef USE_LIBUDEV extern "C" { #include <libudev.h> } #endif #ifdef USE_HAL #include <hal/libhal.h> #endif #ifndef USE_POLL_EMU #include <poll.h> #else #include "poll_emu.h" #endif #include "dashel-private.h" #include "dashel-posix.h" /*! \file streams.cpp \brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library */ namespace Dashel { using namespace std; // Exception void Stream::fail(DashelException::Source s, int se, const char* reason) { string sysMessage; failedFlag = true; if (se) sysMessage = strerror(errno); failReason = reason; failReason += " "; failReason += sysMessage; throw DashelException(s, se, failReason.c_str(), this); } // Serial port enumerator std::map<int, std::pair<std::string, std::string> > SerialPortEnumerator::getPorts() { std::map<int, std::pair<std::string, std::string> > ports; #ifdef MACOSX // use IOKit to enumerates devices // get a matching dictionary to specify which IOService class we're interested in CFMutableDictionaryRef classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue); if (classesToMatch == NULL) throw DashelException(DashelException::EnumerationError, 0, "IOServiceMatching returned a NULL dictionary"); // specify all types of serial devices CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes)); // get an iterator to serial port services io_iterator_t matchingServices; kern_return_t kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, &matchingServices); if (KERN_SUCCESS != kernResult) throw DashelException(DashelException::EnumerationError, kernResult, "IOServiceGetMatchingServices failed"); // iterate over services io_object_t modemService; int index = 0; while((modemService = IOIteratorNext(matchingServices))) { // get path for device CFTypeRef bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); if (bsdPathAsCFString) { std::string path; char cStr[255]; std::string name; bool res = CFStringGetCString((CFStringRef) bsdPathAsCFString, cStr, 255, kCFStringEncodingUTF8); if(res) path = cStr; else throw DashelException(DashelException::EnumerationError, 0, "CFStringGetCString failed"); CFRelease(bsdPathAsCFString); CFTypeRef fn = IORegistryEntrySearchCFProperty(modemService, kIOServicePlane, CFSTR("USB Product Name"), kCFAllocatorDefault, kIORegistryIterateRecursively | kIORegistryIterateParents); if(fn) { res = CFStringGetCString((CFStringRef) fn, cStr, 255, kCFStringEncodingUTF8); if(res) name = cStr; else throw DashelException(DashelException::EnumerationError, 0, "CFStringGetString failed"); CFRelease(fn); } else name = "Serial Port"; name = name + " (" + path + ")"; ports[index++] = std::make_pair<std::string, std::string>(path, name); } else throw DashelException(DashelException::EnumerationError, 0, "IORegistryEntryCreateCFProperty returned a NULL path"); // release service IOObjectRelease(modemService); } IOObjectRelease(matchingServices); #elif defined(USE_LIBUDEV) struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct udev_device *dev; int index = 0; udev = udev_new(); if(!udev) throw DashelException(DashelException::EnumerationError, 0, "Cannot create udev context"); enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, "tty"); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); udev_list_entry_foreach(dev_list_entry, devices) { const char *sysfs_path; struct udev_device *usb_dev; const char * path; struct stat st; unsigned int maj,min; /* Get sysfs path and create the udev device */ sysfs_path = udev_list_entry_get_name(dev_list_entry); dev = udev_device_new_from_syspath(udev, sysfs_path); // Some sanity check path = udev_device_get_devnode(dev); if(stat(path, &st)) throw DashelException(DashelException::EnumerationError, 0, "Cannot stat serial port"); if(!S_ISCHR(st.st_mode)) throw DashelException(DashelException::EnumerationError, 0, "Serial port is not character device"); // Get the major/minor number maj = major(st.st_rdev); min = minor(st.st_rdev); // Ignore all the non physical ports if(!(maj == 2 || (maj == 4 && min < 64) || maj == 3 || maj == 5)) { ostringstream oss; // Check if usb, if yes get the device name usb_dev = udev_device_get_parent_with_subsystem_devtype(dev,"usb","usb_device"); if(usb_dev) oss << udev_device_get_sysattr_value(usb_dev,"product"); else oss << "Serial Port"; oss << " (" << path << ")"; ports[index++] = std::make_pair<std::string, std::string>(path,oss.str()); } udev_device_unref(dev); } udev_enumerate_unref(enumerate); udev_unref(udev); #elif defined(USE_HAL) // use HAL to enumerates devices DBusConnection* dbusConnection = dbus_bus_get(DBUS_BUS_SYSTEM, 0); if (!dbusConnection) throw DashelException(DashelException::EnumerationError, 0, "cannot connect to D-BUS."); LibHalContext* halContext = libhal_ctx_new(); if (!halContext) throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot create context"); if (!libhal_ctx_set_dbus_connection(halContext, dbusConnection)) throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot connect to D-BUS"); if (!libhal_ctx_init(halContext, 0)) throw DashelException(DashelException::EnumerationError, 0, "cannot create HAL context: cannot init context"); int devicesCount; char** devices = libhal_find_device_by_capability(halContext, "serial", &devicesCount, 0); for (int i = 0; i < devicesCount; i++) { char* devFileName = libhal_device_get_property_string(halContext, devices[i], "serial.device", 0); char* info = libhal_device_get_property_string(halContext, devices[i], "info.product", 0); int port = libhal_device_get_property_int(halContext, devices[i], "serial.port", 0); ostringstream oss; oss << info << " " << port; ports[devicesCount - i] = std::make_pair<std::string, std::string>(devFileName, oss.str()); libhal_free_string(info); libhal_free_string(devFileName); } libhal_free_string_array(devices); libhal_ctx_shutdown(halContext, 0); libhal_ctx_free(halContext); #endif return ports; }; // Asserted dynamic cast //! Asserts a dynamic cast. Similar to the one in boost/cast.hpp template<typename Derived, typename Base> inline Derived polymorphic_downcast(Base base) { Derived derived = dynamic_cast<Derived>(base); assert(derived); return derived; } // Streams #define RECV_BUFFER_SIZE 4096 SelectableStream::SelectableStream(const string& protocolName) : Stream(protocolName), fd(-1), writeOnly(false), pollEvent(POLLIN) { } SelectableStream::~SelectableStream() { // on POSIX, do not close stdin, stdout, nor stderr if (fd >= 3) close(fd); } //! In addition its parent, this stream can also make select return because of the target has disconnected class DisconnectableStream: public SelectableStream { protected: friend class Hub; unsigned char recvBuffer[RECV_BUFFER_SIZE]; //!< reception buffer size_t recvBufferPos; //!< position of read in reception buffer size_t recvBufferSize; //!< amount of data in reception buffer public: //! Create the stream and associates a file descriptor DisconnectableStream(const string& protocolName) : Stream(protocolName), SelectableStream(protocolName), recvBufferPos(0), recvBufferSize(0) { } //! Return true while there is some unread data in the reception buffer virtual bool isDataInRecvBuffer() const { return recvBufferPos != recvBufferSize; } }; //! Socket, uses send/recv for read/write class SocketStream: public DisconnectableStream { protected: #ifndef TCP_CORK //! Socket constants enum Consts { SEND_BUFFER_SIZE_INITIAL = 256, //!< initial size of the socket send sendBuffer SEND_BUFFER_SIZE_LIMIT = 65536 //!< when the socket send sendBuffer reaches this size, a flush is forced }; ExpandableBuffer sendBuffer; #endif public: //! Create a socket stream to the following destination SocketStream(const string& targetName) : Stream("tcp"), DisconnectableStream("tcp") #ifndef TCP_CORK ,sendBuffer(SEND_BUFFER_SIZE_INITIAL) #endif { target.add("tcp:host;port;connectionPort=-1;sock=-1"); target.add(targetName.c_str()); fd = target.get<int>("sock"); if (fd < 0) { // create socket fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd < 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot create socket."); IPV4Address remoteAddress(target.get("host"), target.get<int>("port")); // connect sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(remoteAddress.port); addr.sin_addr.s_addr = htonl(remoteAddress.address); if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot connect to remote host."); // overwrite target name with a canonical one target.add(remoteAddress.format().c_str()); target.erase("connectionPort"); } else { // remove file descriptor information from target name target.erase("sock"); } // setup TCP Cork for delayed sending #ifdef TCP_CORK int flag = 1; setsockopt(fd, IPPROTO_TCP, TCP_CORK, &flag , sizeof(flag)); #endif } virtual ~SocketStream() { if (!failed()) flush(); if (fd >= 0) shutdown(fd, SHUT_RDWR); } virtual void write(const void *data, const size_t size) { assert(fd >= 0); if (size == 0) return; #ifdef TCP_CORK send(data, size); #else if (size >= SEND_BUFFER_SIZE_LIMIT) { flush(); send(data, size); } else { sendBuffer.add(data, size); if (sendBuffer.size() >= SEND_BUFFER_SIZE_LIMIT) flush(); } #endif } //! Send all data over the socket void send(const void *data, size_t size) { assert(fd >= 0); unsigned char *ptr = (unsigned char *)data; size_t left = size; while (left) { #ifdef MACOSX ssize_t len = ::send(fd, ptr, left, 0); #else ssize_t len = ::send(fd, ptr, left, MSG_NOSIGNAL); #endif if (len < 0) { fail(DashelException::IOError, errno, "Socket write I/O error."); } else if (len == 0) { fail(DashelException::ConnectionLost, 0, "Connection lost."); } else { ptr += len; left -= len; } } } virtual void flush() { assert(fd >= 0); #ifdef TCP_CORK int flag = 0; setsockopt(fd, IPPROTO_TCP, TCP_CORK, &flag , sizeof(flag)); flag = 1; setsockopt(fd, IPPROTO_TCP, TCP_CORK, &flag , sizeof(flag)); #else send(sendBuffer.get(), sendBuffer.size()); sendBuffer.clear(); #endif } virtual void read(void *data, size_t size) { assert(fd >= 0); if (size == 0) return; unsigned char *ptr = (unsigned char *)data; size_t left = size; if (isDataInRecvBuffer()) { size_t toCopy = std::min(recvBufferSize - recvBufferPos, size); memcpy(ptr, recvBuffer + recvBufferPos, toCopy); recvBufferPos += toCopy; ptr += toCopy; left -= toCopy; } while (left) { ssize_t len = recv(fd, ptr, left, 0); if (len < 0) { fail(DashelException::IOError, errno, "Socket read I/O error."); } else if (len == 0) { fail(DashelException::ConnectionLost, 0, "Connection lost."); } else { ptr += len; left -= len; } } } virtual bool receiveDataAndCheckDisconnection() { assert(recvBufferPos == recvBufferSize); ssize_t len = recv(fd, &recvBuffer, RECV_BUFFER_SIZE, 0); if (len > 0) { recvBufferSize = len; recvBufferPos = 0; return false; } else { if (len < 0) fail(DashelException::IOError, errno, "Socket read I/O error."); return true; } } }; //! Socket server stream. /*! This stream is used for listening for incoming connections. It cannot be used for transfering data. */ class SocketServerStream : public SelectableStream { public: //! Create the stream and associates a file descriptor SocketServerStream(const std::string& targetName) : Stream("tcpin"), SelectableStream("tcpin") { target.add("tcpin:port=5000;address=0.0.0.0"); target.add(targetName.c_str()); IPV4Address bindAddress(target.get("address"), target.get<int>("port")); // create socket fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd < 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot create socket."); // reuse address int flag = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof (flag)) < 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot set address reuse flag on socket, probably the port is already in use."); // bind sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(bindAddress.port); addr.sin_addr.s_addr = htonl(bindAddress.address); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot bind socket to port, probably the port is already in use."); // Listen on socket, backlog is sort of arbitrary. if(listen(fd, 16) < 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot listen on socket."); } virtual void write(const void *data, const size_t size) { } virtual void flush() { } virtual void read(void *data, size_t size) { } virtual bool receiveDataAndCheckDisconnection() { return false; } virtual bool isDataInRecvBuffer() const { return false; } }; //! UDP Socket, uses sendto/recvfrom for read/write class UDPSocketStream: public MemoryPacketStream, public SelectableStream { private: mutable bool selectWasCalled; public: //! Create as UDP socket stream on a specific port UDPSocketStream(const string& targetName) : Stream("udp"), MemoryPacketStream("udp"), SelectableStream("udp"), selectWasCalled(false) { target.add("udp:port=5000;address=0.0.0.0;sock=-1"); target.add(targetName.c_str()); fd = target.get<int>("sock"); if (fd < 0) { // create socket fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (fd < 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot create socket."); IPV4Address bindAddress(target.get("address"), target.get<int>("port")); // bind sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(bindAddress.port); addr.sin_addr.s_addr = htonl(bindAddress.address); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) throw DashelException(DashelException::ConnectionFailed, errno, "Cannot bind socket to port, probably the port is already in use."); } else { // remove file descriptor information from target name target.erase("sock"); } // enable broadcast int broadcastPermission = 1; setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcastPermission, sizeof(broadcastPermission)); } virtual void send(const IPV4Address& dest) { sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(dest.port);; addr.sin_addr.s_addr = htonl(dest.address); ssize_t sent = sendto(fd, sendBuffer.get(), sendBuffer.size(), 0, (struct sockaddr *)&addr, sizeof(addr)); if (sent < 0 || static_cast<size_t>(sent) != sendBuffer.size()) fail(DashelException::IOError, errno, "UDP Socket write I/O error."); sendBuffer.clear(); } virtual void receive(IPV4Address& source) { unsigned char buf[4096]; sockaddr_in addr; socklen_t addrLen = sizeof(addr); ssize_t recvCount = recvfrom(fd, buf, 4096, 0, (struct sockaddr *)&addr, &addrLen); if (recvCount <= 0) fail(DashelException::ConnectionLost, errno, "UDP Socket read I/O error."); receptionBuffer.resize(recvCount); std::copy(buf, buf+recvCount, receptionBuffer.begin()); source = IPV4Address(ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)); } virtual bool receiveDataAndCheckDisconnection() { selectWasCalled = true; return false; } virtual bool isDataInRecvBuffer() const { bool ret = selectWasCalled; selectWasCalled = false; return ret; } }; //! File descriptor, uses send/recv for read/write class FileDescriptorStream: public DisconnectableStream { public: //! Create the stream and associates a file descriptor FileDescriptorStream(const string& protocolName) : Stream(protocolName), DisconnectableStream(protocolName) { } virtual void write(const void *data, const size_t size) { assert(fd >= 0); if (size == 0) return; const char *ptr = (const char *)data; size_t left = size; while (left) { ssize_t len = ::write(fd, ptr, left); if (len < 0) { fail(DashelException::IOError, errno, "File write I/O error."); } else if (len == 0) { fail(DashelException::ConnectionLost, 0, "File full."); } else { ptr += len; left -= len; } } } virtual void flush() { assert(fd >= 0); #ifdef MACOSX if (fsync(fd) < 0) #else if (fdatasync(fd) < 0) #endif { fail(DashelException::IOError, errno, "File flush error."); } } virtual void read(void *data, size_t size) { assert(fd >= 0); if (size == 0) return; char *ptr = (char *)data; size_t left = size; if (isDataInRecvBuffer()) { size_t toCopy = std::min(recvBufferSize - recvBufferPos, size); memcpy(ptr, recvBuffer + recvBufferPos, toCopy); recvBufferPos += toCopy; ptr += toCopy; left -= toCopy; } while (left) { ssize_t len = ::read(fd, ptr, left); if (len < 0) { fail(DashelException::IOError, errno, "File read I/O error."); } else if (len == 0) { fail(DashelException::ConnectionLost, 0, "Reached end of file."); } else { ptr += len; left -= len; } } } virtual bool receiveDataAndCheckDisconnection() { assert(recvBufferPos == recvBufferSize); ssize_t len = ::read(fd, &recvBuffer, RECV_BUFFER_SIZE); if (len > 0) { recvBufferSize = len; recvBufferPos = 0; return false; } else { if (len < 0) fail(DashelException::IOError, errno, "File read I/O error."); return true; } } }; //! Stream for file class FileStream: public FileDescriptorStream { public: //! Parse the target name and create the corresponding file stream FileStream(const string& targetName) : Stream("file"), FileDescriptorStream("file") { target.add("file:name;mode=read;fd=-1"); target.add(targetName.c_str()); fd = target.get<int>("fd"); if (fd < 0) { const std::string name = target.get("name"); const std::string mode = target.get("mode"); // open file if (mode == "read") fd = open(name.c_str(), O_RDONLY); else if (mode == "write") fd = creat(name.c_str(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP), writeOnly = true; else if (mode == "readwrite") fd = open(name.c_str(), O_RDWR); else throw DashelException(DashelException::InvalidTarget, 0, "Invalid file mode."); if (fd == -1) { string errorMessage = "Cannot open file " + name + " for " + mode + "."; throw DashelException(DashelException::ConnectionFailed, errno, errorMessage.c_str()); } } else { // remove file descriptor information from target name target.erase("fd"); } } }; //! Standard input stream, simply a FileStream with a specific target struct StdinStream: public FileStream { StdinStream(const string& targetName): Stream("file"), FileStream("file:name=/dev/stdin;mode=read;fd=0") {} }; //! Standard output stream, simply a FileStream with a specific target struct StdoutStream: public FileStream { StdoutStream(const string& targetName): Stream("file"), FileStream("file:name=/dev/stdout;mode=write;fd=1") {} }; //! Stream for serial port, in addition to FileDescriptorStream, save old state of serial port class SerialStream: public FileDescriptorStream { protected: struct termios oldtio; //!< old serial port state public: //! Parse the target name and create the corresponding serial stream SerialStream(const string& targetName) : Stream("ser"), FileDescriptorStream("ser") { target.add("ser:port=1;baud=115200;stop=1;parity=none;fc=none;bits=8;dtr=true"); target.add(targetName.c_str()); string devFileName; if (target.isSet("device")) { target.addParam("device", NULL, true); target.erase("port"); target.erase("name"); devFileName = target.get("device"); } else if (target.isSet("name")) { target.addParam("name", NULL, true); target.erase("port"); target.erase("device"); // Enumerates the ports std::string name = target.get("name"); std::map<int, std::pair<std::string, std:: string> > ports = SerialPortEnumerator::getPorts(); // Iterate on all ports to found one with "name" in its description std::map<int, std::pair<std::string, std:: string> >::iterator it; for (it = ports.begin(); it != ports.end(); it++) { if (it->second.second.find(name) != std::string::npos) { devFileName = it->second.first; std::cout << "Found " << name << " on port " << devFileName << std::endl; break; } } if (devFileName.size() == 0) throw DashelException(DashelException::ConnectionFailed, 0, "The specified name could not be find among the serial ports."); } else // port { target.erase("device"); target.erase("name"); std::map<int, std::pair<std::string, std::string> > ports = SerialPortEnumerator::getPorts(); std::map<int, std::pair<std::string, std::string> >::const_iterator it = ports.find(target.get<int>("port")); if (it != ports.end()) { devFileName = it->first; } else throw DashelException(DashelException::ConnectionFailed, 0, "The specified serial port does not exists."); } fd = open(devFileName.c_str(), O_RDWR); if (fd == -1) throw DashelException(DashelException::ConnectionFailed, 0, "Cannot open serial port."); int lockRes = flock(fd, LOCK_EX|LOCK_NB); if (lockRes != 0) { close(fd); throw DashelException(DashelException::ConnectionFailed, errno, (string("Cannot lock serial port: ") + strerror(errno)).c_str()); } struct termios newtio; // save old serial port state and clear new one tcgetattr(fd, &oldtio); memset(&newtio, 0, sizeof(newtio)); newtio.c_cflag |= CLOCAL; // ignore modem control lines. newtio.c_cflag |= CREAD; // enable receiver. switch (target.get<int>("bits")) // Set amount of bits per character { case 5: newtio.c_cflag |= CS5; break; case 6: newtio.c_cflag |= CS6; break; case 7: newtio.c_cflag |= CS7; break; case 8: newtio.c_cflag |= CS8; break; default: throw DashelException(DashelException::InvalidTarget, 0, "Invalid number of bits per character, must be 5, 6, 7, or 8."); } if (target.get("stop") == "2") newtio.c_cflag |= CSTOPB; // Set two stop bits, rather than one. if (target.get("fc") == "hard") newtio.c_cflag |= CRTSCTS; // enable hardware flow control if (target.get("parity") != "none") { newtio.c_cflag |= PARENB; // enable parity generation on output and parity checking for input. if (target.get("parity") == "odd") newtio.c_cflag |= PARODD; // parity for input and output is odd. } #ifdef MACOSX if (cfsetspeed(&newtio,target.get<int>("baud")) != 0) throw DashelException(DashelException::ConnectionFailed, errno, "Invalid baud rate."); #else switch (target.get<int>("baud")) { case 0: newtio.c_cflag |= B0; break; case 50: newtio.c_cflag |= B50; break; case 75: newtio.c_cflag |= B75; break; case 110: newtio.c_cflag |= B110; break; case 134: newtio.c_cflag |= B134; break; case 150: newtio.c_cflag |= B150; break; case 200: newtio.c_cflag |= B200; break; case 300: newtio.c_cflag |= B300; break; case 600: newtio.c_cflag |= B600; break; case 1200: newtio.c_cflag |= B1200; break; case 1800: newtio.c_cflag |= B1800; break; case 2400: newtio.c_cflag |= B2400; break; case 4800: newtio.c_cflag |= B4800; break; case 9600: newtio.c_cflag |= B9600; break; case 19200: newtio.c_cflag |= B19200; break; case 38400: newtio.c_cflag |= B38400; break; case 57600: newtio.c_cflag |= B57600; break; case 115200: newtio.c_cflag |= B115200; break; case 230400: newtio.c_cflag |= B230400; break; case 460800: newtio.c_cflag |= B460800; break; case 500000: newtio.c_cflag |= B500000; break; case 576000: newtio.c_cflag |= B576000; break; case 921600: newtio.c_cflag |= B921600; break; case 1000000: newtio.c_cflag |= B1000000; break; case 1152000: newtio.c_cflag |= B1152000; break; case 1500000: newtio.c_cflag |= B1500000; break; case 2000000: newtio.c_cflag |= B2000000; break; case 2500000: newtio.c_cflag |= B2500000; break; case 3000000: newtio.c_cflag |= B3000000; break; case 3500000: newtio.c_cflag |= B3500000; break; case 4000000: newtio.c_cflag |= B4000000; break; default: throw DashelException(DashelException::ConnectionFailed, 0, "Invalid baud rate."); } #endif newtio.c_iflag = IGNPAR; // ignore parity on input newtio.c_oflag = 0; newtio.c_lflag = 0; newtio.c_cc[VTIME] = 0; // block forever if no byte newtio.c_cc[VMIN] = 1; // one byte is sufficient to return // set attributes if ((tcflush(fd, TCIOFLUSH) < 0) || (tcsetattr(fd, TCSANOW, &newtio) < 0)) throw DashelException(DashelException::ConnectionFailed, 0, "Cannot setup serial port. The requested baud rate might not be supported."); // Enable or disable DTR int iFlags = TIOCM_DTR; if (target.get<bool>("dtr")) ioctl(fd, TIOCMBIS, &iFlags); else ioctl(fd, TIOCMBIC, &iFlags); } //! Destructor, restore old serial port state virtual ~SerialStream() { tcsetattr(fd, TCSANOW, &oldtio); } virtual void flush() { } }; /* We have decided to let the application choose what to do with signals. Hub::stop() being thread safe, it is ok to let the user decide. // Signal handler for SIGTERM typedef std::set<Hub*> HubsSet; typedef HubsSet::iterator HubsSetIterator; //! All instanciated Hubs, required for correctly terminating them on signal static HubsSet allHubs; //! Called when SIGTERM or SIGINT arrives, halts all running clients or servers in all threads void termHandler(int t) { for (HubsSetIterator it = allHubs.begin(); it != allHubs.end(); ++it) { (*it)->stop(); } } //! Class to setup SIGTERM or SIGINT handler static class SigTermHandlerSetuper { public: //! Private constructor that redirects SIGTERM SigTermHandlerSetuper() { struct sigaction new_act, old_act; new_act.sa_handler = termHandler; sigemptyset(&new_act.sa_mask); new_act.sa_flags = 0; sigaction(SIGTERM, &new_act, &old_act); sigaction(SIGINT, &new_act, &old_act); } } staticSigTermHandlerSetuper; */ // Hub Hub::Hub(const bool resolveIncomingNames): resolveIncomingNames(resolveIncomingNames) { int *terminationPipes = new int[2]; if (pipe(terminationPipes) != 0) abort(); hTerminate = terminationPipes; streamsLock = new pthread_mutex_t; pthread_mutex_init((pthread_mutex_t*)streamsLock, NULL); // commented because we let the users manage the signal themselves //allHubs.insert(this); } Hub::~Hub() { // commented because we let the users manage the signal themselves //allHubs.erase(this); int *terminationPipes = (int*)hTerminate; close(terminationPipes[0]); close(terminationPipes[1]); delete[] terminationPipes; for (StreamsSet::iterator it = streams.begin(); it != streams.end(); ++it) delete *it; pthread_mutex_destroy((pthread_mutex_t*)streamsLock); delete (pthread_mutex_t*) streamsLock; } Stream* Hub::connect(const std::string &target) { std::string proto, params; size_t c = target.find_first_of(':'); if (c == std::string::npos) throw DashelException(DashelException::InvalidTarget, 0, "No protocol specified in target."); proto = target.substr(0, c); params = target.substr(c+1); SelectableStream *s(dynamic_cast<SelectableStream*>(streamTypeRegistry.create(proto, target, *this))); if(!s) { std::string r = "Invalid protocol in target: "; r += proto; r += ", known protocol are: "; r += streamTypeRegistry.list(); throw DashelException(DashelException::InvalidTarget, 0, r.c_str()); } /* The caller must have the stream lock held */ streams.insert(s); if (proto != "tcpin") { dataStreams.insert(s); connectionCreated(s); } return s; } void Hub::run() { while (step(-1)); } bool Hub::step(const int timeout) { bool firstPoll = true; bool wasActivity = false; bool runInterrupted = false; pthread_mutex_lock((pthread_mutex_t*)streamsLock); do { wasActivity = false; size_t streamsCount = streams.size(); valarray<struct pollfd> pollFdsArray(streamsCount+1); valarray<SelectableStream*> streamsArray(streamsCount); // add streams size_t i = 0; for (StreamsSet::iterator it = streams.begin(); it != streams.end(); ++it) { SelectableStream* stream = polymorphic_downcast<SelectableStream*>(*it); streamsArray[i] = stream; pollFdsArray[i].fd = stream->fd; pollFdsArray[i].events = 0; if ((!stream->failed()) && (!stream->writeOnly)) pollFdsArray[i].events |= stream->pollEvent; i++; } // add pipe int *terminationPipes = (int*)hTerminate; pollFdsArray[i].fd = terminationPipes[0]; pollFdsArray[i].events = POLLIN; // do poll and check for error int thisPollTimeout = firstPoll ? timeout : 0; firstPoll = false; pthread_mutex_unlock((pthread_mutex_t*)streamsLock); #ifndef USE_POLL_EMU int ret = poll(&pollFdsArray[0], pollFdsArray.size(), thisPollTimeout); #else int ret = poll_emu(&pollFdsArray[0], pollFdsArray.size(), thisPollTimeout); #endif if (ret < 0) throw DashelException(DashelException::SyncError, errno, "Error during poll."); pthread_mutex_lock((pthread_mutex_t*)streamsLock); // check streams for errors for (i = 0; i < streamsCount; i++) { SelectableStream* stream = streamsArray[i]; // make sure we do not try to handle removed streams if (streams.find(stream) == streams.end()) continue; assert((pollFdsArray[i].revents & POLLNVAL) == 0); if (pollFdsArray[i].revents & POLLERR) { //std::cerr << "POLLERR" << std::endl; wasActivity = true; try { stream->fail(DashelException::SyncError, 0, "Error on stream during poll."); } catch (DashelException e) { assert(e.stream); } try { connectionClosed(stream, true); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } else if (pollFdsArray[i].revents & POLLHUP) { //std::cerr << "POLLHUP" << std::endl; wasActivity = true; try { connectionClosed(stream, false); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } else if (pollFdsArray[i].revents & stream->pollEvent) { //std::cerr << "POLLIN" << std::endl; wasActivity = true; // test if listen stream SocketServerStream* serverStream = dynamic_cast<SocketServerStream*>(stream); if (serverStream) { // accept connection struct sockaddr_in targetAddr; socklen_t l = sizeof (targetAddr); int targetFD = accept (stream->fd, (struct sockaddr *)&targetAddr, &l); if (targetFD < 0) { pthread_mutex_unlock((pthread_mutex_t*)streamsLock); throw DashelException(DashelException::SyncError, errno, "Cannot accept new stream."); } // create a target stream using the new file descriptor from accept ostringstream targetName; targetName << IPV4Address(ntohl(targetAddr.sin_addr.s_addr), ntohs(targetAddr.sin_port)).format(resolveIncomingNames); targetName << ";connectionPort="; targetName << atoi(serverStream->getTargetParameter("port").c_str()); targetName << ";sock="; targetName << targetFD; connect(targetName.str()); } else { bool streamClosed = false; try { if (stream->receiveDataAndCheckDisconnection()) { //std::cerr << "connection closed" << std::endl; connectionClosed(stream, false); streamClosed = true; } else { // read all data available on this socket while (stream->isDataInRecvBuffer()) incomingData(stream); //std::cerr << "incoming data" << std::endl; } } catch (DashelException e) { //std::cerr << "exception on POLLIN" << std::endl; assert(e.stream); } if (streamClosed) closeStream(stream); } } } // check pipe for termination if (pollFdsArray[i].revents) { char c; const ssize_t ret = read(pollFdsArray[i].fd, &c, 1); if (ret != 1) abort(); // poll did notify us that there was something to read, but we did not read anything, this is a bug runInterrupted = true; } // collect and remove all failed streams vector<Stream*> failedStreams; for (StreamsSet::iterator it = streams.begin(); it != streams.end();++it) if ((*it)->failed()) failedStreams.push_back(*it); for (size_t i = 0; i < failedStreams.size(); i++) { Stream* stream = failedStreams[i]; if (streams.find(stream) == streams.end()) continue; if (stream->failed()) { try { connectionClosed(stream, true); } catch (DashelException e) { assert(e.stream); } closeStream(stream); } } } while (wasActivity && !runInterrupted); pthread_mutex_unlock((pthread_mutex_t*)streamsLock); return !runInterrupted; } void Hub::lock() { pthread_mutex_lock((pthread_mutex_t*)streamsLock); } void Hub::unlock() { pthread_mutex_unlock((pthread_mutex_t*)streamsLock); } void Hub::stop() { int *terminationPipes = (int*)hTerminate; char c = 0; const ssize_t ret = write(terminationPipes[1], &c, 1); if (ret != 1) throw DashelException(DashelException::IOError, ret, "Cannot write to termination pipe."); } StreamTypeRegistry::StreamTypeRegistry() { reg("file", &createInstance<FileStream>); reg("stdin", &createInstance<StdinStream>); reg("stdout", &createInstance<StdoutStream>); reg("ser", &createInstance<SerialStream>); reg("tcpin", &createInstance<SocketServerStream>); reg("tcp", &createInstance<SocketStream>); reg("udp", &createInstance<UDPSocketStream>); } StreamTypeRegistry __attribute__((init_priority(1000))) streamTypeRegistry; }
28.085943
149
0.665526
[ "vector" ]
14e3fbdcb0e4bf856272c2a6140dcd7e1687a2cd
6,772
cpp
C++
src/uscxml/plugins/element/respond/RespondElement.cpp
stil/uscxml
647ed9387053a7694bdd35c115a6615114a6a4cb
[ "BSD-2-Clause" ]
82
2015-01-22T01:08:06.000Z
2021-12-18T13:09:33.000Z
src/uscxml/plugins/element/respond/RespondElement.cpp
stil/uscxml
647ed9387053a7694bdd35c115a6615114a6a4cb
[ "BSD-2-Clause" ]
117
2015-07-08T10:30:44.000Z
2021-06-29T12:37:39.000Z
src/uscxml/plugins/element/respond/RespondElement.cpp
stil/uscxml
647ed9387053a7694bdd35c115a6615114a6a4cb
[ "BSD-2-Clause" ]
51
2015-01-06T10:08:24.000Z
2022-03-21T09:29:21.000Z
/** * @file * @author 2017 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de) * @copyright Simplified BSD * * @cond * This program is free software: you can redistribute it and/or modify * it under the terms of the FreeBSD license as published by the FreeBSD * project. * * 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. * * You should have received a copy of the FreeBSD license along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license>. * @endcond */ #include "RespondElement.h" #include "uscxml/util/DOM.h" #include "uscxml/server/HTTPServer.h" #include "uscxml/interpreter/LoggingImpl.h" #include "uscxml/plugins/ioprocessor/http/HTTPIOProcessor.h" #ifdef BUILD_AS_PLUGINS #include <Pluma/Connector.hpp> #endif namespace uscxml { using namespace XERCESC_NS; void RespondElement::enterElement(XERCESC_NS::DOMElement* node) { // try to get the request id if (!HAS_ATTR(node, X("to"))) { ERROR_EXECUTION_THROW2("Respond element requires 'to' attribute", node); } if (HAS_ATTR(node, X("to")) && !_interpreter->getActionLanguage()->dataModel) { ERROR_EXECUTION_THROW2("Respond element with 'to' requires datamodel", node); } std::string requestId = _interpreter->getActionLanguage()->dataModel.evalAsData(ATTR(node, X("to"))).atom; auto ioProcs = _interpreter->getIOProcessors(); if (ioProcs.find("http") == ioProcs.end()) { ERROR_EXECUTION_THROW2("No HTTP ioprocessor associated with interpreter", node); } // try to get the request object IOProcessor ioProc = ioProcs["http"]; HTTPIOProcessor* http = (HTTPIOProcessor*)(ioProc.getImpl().operator->()); if (http->getUnansweredRequests().find(requestId) == http->getUnansweredRequests().end()) { ERROR_EXECUTION_THROW2("No unanswered HTTP request with given id", node); } HTTPServer::Request httpReq = http->getUnansweredRequests()[requestId].second; assert(httpReq.evhttpReq != NULL); HTTPServer::Reply httpReply(httpReq); // get the status or default to 200 std::string statusStr = (HAS_ATTR(node, X("status")) ? ATTR(node, X("status")) : "200"); if (!isNumeric(statusStr.c_str(), 10)) { ERROR_EXECUTION_THROW2("Respond element with non-numeric status: " + statusStr, node); } httpReply.status = strTo<int>(statusStr);; // extract the content std::list<DOMElement*> contents = DOMUtils::filterChildElements(XML_PREFIX(node).str() + "content", node); if (contents.size() > 0) { DOMElement* contentElem = contents.front(); if (HAS_ATTR(contentElem, kXMLCharExpr)) { // -- content is evaluated string from datamodel if (_interpreter->getActionLanguage()->dataModel) { try { Data contentData = _interpreter->getActionLanguage()->dataModel.evalAsData(ATTR(contentElem, kXMLCharExpr)); if (contentData.atom.length() > 0) { httpReply.content = contentData.atom; httpReply.headers["Content-Type"] = "text/plain"; } else if (contentData.binary) { httpReply.content = std::string(contentData.binary.getData(), contentData.binary.getSize()); httpReply.headers["Content-Type"] = contentData.binary.getMimeType(); } else if (contentData.node) { std::stringstream ss; ss << contentData.node; httpReply.content = ss.str();; httpReply.headers["Content-Type"] = "application/xml"; } else { httpReply.content = Data::toJSON(contentData); httpReply.headers["Content-Type"] = "application/json"; } } catch (Event e) { ERROR_EXECUTION_RETHROW(e, "Syntax error with expr in content child of respond element", node); } } else { ERROR_EXECUTION_THROW2("content element has expr attribute but no datamodel is specified", node); } } else if (HAS_ATTR(contentElem, X("file")) || HAS_ATTR(contents.front(), X("fileexpr"))) { // -- content is from file URL file; if (HAS_ATTR(contentElem, X("fileexpr"))) { if (_interpreter->getActionLanguage()->dataModel) { try { file = _interpreter->getActionLanguage()->dataModel.evalAsData(ATTR(contentElem, X("fileexpr"))).atom; } catch (Event e) { ERROR_EXECUTION_RETHROW(e, "Syntax error with fileexpr in content child of respond element", node); } } } else { file = ATTR(contentElem, X("file")); } if (file) { httpReply.content = file.getInContent(); size_t lastDot; if ((lastDot = file.path().find_last_of(".")) != std::string::npos) { std::string extension = file.path().substr(lastDot + 1); std::string mimeType = URL::getMimeType(extension); if (mimeType.length() > 0) { httpReply.headers["Content-Type"] = mimeType; } } } } else if (contentElem->hasChildNodes()) { // -- content embedded as child nodes ------ httpReply.content = X(contentElem->getFirstChild()->getNodeValue()).str(); } else { ERROR_EXECUTION_THROW2("content element does not specify any content", node); } } // process headers std::list<DOMElement*> headers = DOMUtils::filterChildElements(XML_PREFIX(node).str() + "header", node); for (auto headerElem : headers) { std::string name; if (HAS_ATTR(headerElem, kXMLCharName)) { name = ATTR(headerElem, kXMLCharName); } else if(HAS_ATTR(headerElem, X("nameexpr"))) { if (_interpreter->getActionLanguage()->dataModel) { try { name = _interpreter->getActionLanguage()->dataModel.evalAsData(ATTR(headerElem, X("nameexpr"))).atom; } catch (Event e) { ERROR_EXECUTION_RETHROW(e, "Syntax error with nameexpr in header child of Respond element", headerElem); } } else { ERROR_EXECUTION_THROW2("header element has nameexpr attribute but no datamodel is specified", headerElem); } } else { ERROR_EXECUTION_THROW2("header element has no name or nameexpr attribute", headerElem); } std::string value; if (HAS_ATTR(headerElem, X("value"))) { value = ATTR(headerElem, X("value")); } else if(HAS_ATTR(headerElem, X("valueexpr"))) { if (_interpreter->getActionLanguage()->dataModel) { try { value = _interpreter->getActionLanguage()->dataModel.evalAsData(ATTR(headerElem, X("valueexpr"))).atom; } catch (Event e) { ERROR_EXECUTION_RETHROW(e, "Syntax error with valueexpr in header child of Respond element", headerElem); } } else { ERROR_EXECUTION_THROW2("header element has valueexpr attribute but no datamodel is specified", headerElem); } } else { ERROR_EXECUTION_THROW2("header element has no value or valueexpr attribute", headerElem); return; } httpReply.headers[name] = value; } // send the reply HTTPServer::reply(httpReply); http->getUnansweredRequests().erase(requestId); } }
37.622222
113
0.695068
[ "object" ]
14e8c4998ce7c9b451140ef1c03884af071649c1
19,931
cc
C++
test/integration/recreate_entities.cc
marcoag/ign-gazebo
0f45c172f84a6ad83e1c9b7b5839432891b21a01
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/integration/recreate_entities.cc
marcoag/ign-gazebo
0f45c172f84a6ad83e1c9b7b5839432891b21a01
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/integration/recreate_entities.cc
marcoag/ign-gazebo
0f45c172f84a6ad83e1c9b7b5839432891b21a01
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 Open Source Robotics Foundation * * 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 <gtest/gtest.h> #include <algorithm> #include <vector> #include <ignition/common/Console.hh> #include <ignition/common/Util.hh> #include <ignition/utilities/ExtraTestMacros.hh> #include <sdf/World.hh> #include "ignition/gazebo/components/Factory.hh" #include "ignition/gazebo/components/Joint.hh" #include "ignition/gazebo/components/Link.hh" #include "ignition/gazebo/components/Model.hh" #include "ignition/gazebo/components/Name.hh" #include "ignition/gazebo/components/ParentEntity.hh" #include "ignition/gazebo/components/ParentLinkName.hh" #include "ignition/gazebo/components/Pose.hh" #include "ignition/gazebo/components/Recreate.hh" #include "ignition/gazebo/components/World.hh" #include "ignition/gazebo/Server.hh" #include "ignition/gazebo/SystemLoader.hh" #include "ignition/gazebo/test_config.hh" // NOLINT(build/include) #include "../helpers/Relay.hh" #include "../helpers/EnvTestFixture.hh" using namespace ignition; using namespace gazebo; using namespace components; using namespace std::chrono_literals; class RecreateEntitiesFixture : public InternalFixture<::testing::Test> { }; ///////////////////////////////////////////////// TEST_F(RecreateEntitiesFixture, IGN_UTILS_TEST_DISABLED_ON_WIN32(RecreateEntities)) { // Start server ServerConfig serverConfig; serverConfig.SetSdfFile(common::joinPaths(std::string(PROJECT_SOURCE_PATH), "test", "worlds", "shapes.sdf")); Server server(serverConfig); EXPECT_FALSE(server.Running()); EXPECT_FALSE(*server.Running(0)); EntityComponentManager *ecm = nullptr; bool recreateEntities = false; // Create a system that adds a recreate component to models test::Relay testSystem; testSystem.OnUpdate([&](const gazebo::UpdateInfo &, gazebo::EntityComponentManager &_ecm) { // cppcheck-suppress knownConditionTrueFalse if (!ecm) { ecm = &_ecm; recreateEntities = true; return; } if (recreateEntities) { _ecm.Each<components::Model>( [&](const ignition::gazebo::Entity &_entity, const components::Model *) -> bool { // add a components::Recreate to indicate that this entity // needs to be recreated _ecm.CreateComponent(_entity, components::Recreate()); return true; }); // recreate entities only once so set it back to false recreateEntities = false; return; } }); server.AddSystem(testSystem.systemPtr); // Run server and check we have the ECM EXPECT_EQ(nullptr, ecm); server.Run(true, 1, false); EXPECT_NE(nullptr, ecm); // model entity ids Entity boxModelEntity = kNullEntity; Entity cylModelEntity = kNullEntity; Entity sphModelEntity = kNullEntity; Entity capModelEntity = kNullEntity; Entity ellipModelEntity = kNullEntity; // link entity ids Entity boxLinkEntity = kNullEntity; Entity cylLinkEntity = kNullEntity; Entity sphLinkEntity = kNullEntity; Entity capLinkEntity = kNullEntity; Entity ellipLinkEntity = kNullEntity; auto validateEntities = [&]() { boxModelEntity = kNullEntity; cylModelEntity = kNullEntity; sphModelEntity = kNullEntity; capModelEntity = kNullEntity; ellipModelEntity = kNullEntity; boxLinkEntity = kNullEntity; cylLinkEntity = kNullEntity; sphLinkEntity = kNullEntity; capLinkEntity = kNullEntity; ellipLinkEntity = kNullEntity; // Check entities // 1 x world + 1 x (default) level + 1 x wind + 5 x model + 5 x link + 5 x // collision + 5 x visual + 1 x light EXPECT_EQ(24u, ecm->EntityCount()); Entity worldEntity = ecm->EntityByComponents(components::World()); EXPECT_NE(kNullEntity, worldEntity); // Check models unsigned int modelCount{0}; ecm->Each<components::Model, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &_entity, const components::Model *_model, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _model); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); modelCount++; EXPECT_EQ(worldEntity, _parent->Data()); if (modelCount == 1) { EXPECT_EQ(ignition::math::Pose3d(1, 2, 3, 0, 0, 1), _pose->Data()); EXPECT_EQ("box", _name->Data()); boxModelEntity = _entity; } else if (modelCount == 2) { EXPECT_EQ(ignition::math::Pose3d(-1, -2, -3, 0, 0, 1), _pose->Data()); EXPECT_EQ("cylinder", _name->Data()); cylModelEntity = _entity; } else if (modelCount == 3) { EXPECT_EQ(ignition::math::Pose3d(0, 0, 0, 0, 0, 1), _pose->Data()); EXPECT_EQ("sphere", _name->Data()); sphModelEntity = _entity; } else if (modelCount == 4) { EXPECT_EQ(ignition::math::Pose3d(-4, -5, -6, 0, 0, 1), _pose->Data()); EXPECT_EQ("capsule", _name->Data()); capModelEntity = _entity; } else if (modelCount == 5) { EXPECT_EQ(ignition::math::Pose3d(4, 5, 6, 0, 0, 1), _pose->Data()); EXPECT_EQ("ellipsoid", _name->Data()); ellipModelEntity = _entity; } return true; }); EXPECT_EQ(5u, modelCount); EXPECT_NE(kNullEntity, boxModelEntity); EXPECT_NE(kNullEntity, cylModelEntity); EXPECT_NE(kNullEntity, sphModelEntity); EXPECT_NE(kNullEntity, capModelEntity); EXPECT_NE(kNullEntity, ellipModelEntity); // Check links unsigned int linkCount{0}; ecm->Each<components::Link, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &_entity, const components::Link *_link, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _link); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); linkCount++; if (linkCount == 1) { EXPECT_EQ(ignition::math::Pose3d(0.1, 0.1, 0.1, 0, 0, 0), _pose->Data()); EXPECT_EQ("box_link", _name->Data()); EXPECT_EQ(boxModelEntity, _parent->Data()); boxLinkEntity = _entity; } else if (linkCount == 2) { EXPECT_EQ(ignition::math::Pose3d(0.2, 0.2, 0.2, 0, 0, 0), _pose->Data()); EXPECT_EQ("cylinder_link", _name->Data()); EXPECT_EQ(cylModelEntity, _parent->Data()); cylLinkEntity = _entity; } else if (linkCount == 3) { EXPECT_EQ(ignition::math::Pose3d(0.3, 0.3, 0.3, 0, 0, 0), _pose->Data()); EXPECT_EQ("sphere_link", _name->Data()); EXPECT_EQ(sphModelEntity, _parent->Data()); sphLinkEntity = _entity; } else if (linkCount == 4) { EXPECT_EQ(ignition::math::Pose3d(0.5, 0.5, 0.5, 0, 0, 0), _pose->Data()); EXPECT_EQ("capsule_link", _name->Data()); EXPECT_EQ(capModelEntity, _parent->Data()); capLinkEntity = _entity; } else if (linkCount == 5) { EXPECT_EQ(ignition::math::Pose3d(0.8, 0.8, 0.8, 0, 0, 0), _pose->Data()); EXPECT_EQ("ellipsoid_link", _name->Data()); EXPECT_EQ(ellipModelEntity, _parent->Data()); ellipLinkEntity = _entity; } return true; }); EXPECT_EQ(5u, linkCount); EXPECT_NE(kNullEntity, boxLinkEntity); EXPECT_NE(kNullEntity, cylLinkEntity); EXPECT_NE(kNullEntity, sphLinkEntity); EXPECT_NE(kNullEntity, capLinkEntity); EXPECT_NE(kNullEntity, ellipLinkEntity); }; // validate initial state validateEntities(); // store the original entity ids Entity originalboxModelEntity = boxModelEntity; Entity originalcylModelEntity = cylModelEntity; Entity originalsphModelEntity = sphModelEntity; Entity originalcapModelEntity = capModelEntity; Entity originalellipModelEntity = ellipModelEntity; Entity originalboxLinkEntity = boxLinkEntity; Entity originalcylLinkEntity = cylLinkEntity; Entity originalsphLinkEntity = sphLinkEntity; Entity originalcapLinkEntity = capLinkEntity; Entity originalellipLinkEntity = ellipLinkEntity; // Run once to let the test relay system creates the components::Recreate server.Run(true, 1, false); // Run again so that entities get recreated in the ECM server.Run(true, 1, false); // validate that the entities are recreated validateEntities(); // check that the newly recreated entities should have a different entity id EXPECT_NE(originalboxModelEntity, boxModelEntity); EXPECT_NE(originalcylModelEntity, cylModelEntity); EXPECT_NE(originalsphModelEntity, sphModelEntity); EXPECT_NE(originalcapModelEntity, capModelEntity); EXPECT_NE(originalellipModelEntity, ellipModelEntity); EXPECT_NE(originalboxLinkEntity, boxLinkEntity); EXPECT_NE(originalcylLinkEntity, cylLinkEntity); EXPECT_NE(originalsphLinkEntity, sphLinkEntity); EXPECT_NE(originalcapLinkEntity, capLinkEntity); EXPECT_NE(originalellipLinkEntity, ellipLinkEntity); // Run again to make sure the recreate components are removed and no // entities to to be recreated server.Run(true, 1, false); auto entities = ecm->EntitiesByComponents(components::Model(), components::Recreate()); EXPECT_TRUE(entities.empty()); } ///////////////////////////////////////////////// TEST_F(RecreateEntitiesFixture, IGN_UTILS_TEST_DISABLED_ON_WIN32(RecreateEntities_Joints)) { // Start server ServerConfig serverConfig; serverConfig.SetSdfFile(common::joinPaths(std::string(PROJECT_SOURCE_PATH), "test", "worlds", "double_pendulum.sdf")); Server server(serverConfig); EXPECT_FALSE(server.Running()); EXPECT_FALSE(*server.Running(0)); EntityComponentManager *ecm = nullptr; bool recreateEntities = false; // Create a system that adds a recreate component to models test::Relay testSystem; testSystem.OnUpdate([&](const gazebo::UpdateInfo &, gazebo::EntityComponentManager &_ecm) { // cppcheck-suppress knownConditionTrueFalse if (!ecm) { ecm = &_ecm; recreateEntities = true; return; } if (recreateEntities) { _ecm.Each<components::Model>( [&](const ignition::gazebo::Entity &_entity, const components::Model *) -> bool { // add a components::Recreate to indicate that this entity // needs to be recreated _ecm.CreateComponent(_entity, components::Recreate()); return true; }); // recreate entities only once so set it back to false recreateEntities = false; return; } }); server.AddSystem(testSystem.systemPtr); // Run server and check we have the ECM EXPECT_EQ(nullptr, ecm); server.Run(true, 1, false); EXPECT_NE(nullptr, ecm); auto validateEntities = [&]() { // Check entities // 1 x world + 1 x (default) level + 1 x wind + 5 x model + 5 x link + 5 x // collision + 5 x visual + 1 x light EXPECT_EQ(48u, ecm->EntityCount()); Entity worldEntity = ecm->EntityByComponents(components::World()); EXPECT_NE(kNullEntity, worldEntity); // Check models unsigned int modelCount{0}; ecm->Each<components::Model, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &/*_entity*/, const components::Model *_model, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _model); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); modelCount++; EXPECT_EQ(worldEntity, _parent->Data()); return true; }); EXPECT_EQ(3u, modelCount); // Check links unsigned int linkCount{0}; ecm->Each<components::Link, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &/*_entity*/, const components::Link *_link, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _link); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); linkCount++; return true; }); EXPECT_EQ(7u, linkCount); // Check links unsigned int jointCount{0}; ecm->Each<components::Joint, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &/*_entity*/, const components::Joint *_joint, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _joint); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); jointCount++; return true; }); EXPECT_EQ(4u, jointCount); }; // validate initial state validateEntities(); // Run once to let the test relay system creates the components::Recreate server.Run(true, 1, false); // Run again so that entities get recreated in the ECM server.Run(true, 1, false); // validate that the entities are recreated validateEntities(); // Run again to make sure the recreate components are removed and no // entities to to be recreated server.Run(true, 1, false); auto entities = ecm->EntitiesByComponents(components::Model(), components::Recreate()); EXPECT_TRUE(entities.empty()); } ///////////////////////////////////////////////// TEST_F(RecreateEntitiesFixture, IGN_UTILS_TEST_DISABLED_ON_WIN32(RecreateEntities_WorldJoint)) { // Start server ServerConfig serverConfig; serverConfig.SetSdfFile(common::joinPaths(std::string(PROJECT_SOURCE_PATH), "test", "worlds", "fixed_world_joint.sdf")); Server server(serverConfig); EXPECT_FALSE(server.Running()); EXPECT_FALSE(*server.Running(0)); EntityComponentManager *ecm = nullptr; bool recreateEntities = false; // Create a system that adds a recreate component to models test::Relay testSystem; testSystem.OnUpdate([&](const gazebo::UpdateInfo &, gazebo::EntityComponentManager &_ecm) { // cppcheck-suppress knownConditionTrueFalse if (!ecm) { ecm = &_ecm; recreateEntities = true; return; } if (recreateEntities) { _ecm.Each<components::Model>( [&](const ignition::gazebo::Entity &_entity, const components::Model *) -> bool { // add a components::Recreate to indicate that this entity // needs to be recreated _ecm.CreateComponent(_entity, components::Recreate()); return true; }); // recreate entities only once so set it back to false recreateEntities = false; return; } }); server.AddSystem(testSystem.systemPtr); // Run server and check we have the ECM EXPECT_EQ(nullptr, ecm); server.Run(true, 1, false); EXPECT_NE(nullptr, ecm); auto validateEntities = [&]() { // Check entities // 1 x world + 1 x (default) level + 1 x wind + 1 x model + 2 x link + 2 x // collision + 2 x visual + 2 x joint EXPECT_EQ(12u, ecm->EntityCount()); Entity worldEntity = ecm->EntityByComponents(components::World()); EXPECT_NE(kNullEntity, worldEntity); // Check models unsigned int modelCount{0}; ecm->Each<components::Model, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &/*_entity*/, const components::Model *_model, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _model); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); modelCount++; EXPECT_EQ(worldEntity, _parent->Data()); return true; }); EXPECT_EQ(1u, modelCount); // Check links unsigned int linkCount{0}; ecm->Each<components::Link, components::Pose, components::ParentEntity, components::Name>( [&](const Entity &/*_entity*/, const components::Link *_link, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name)->bool { EXPECT_NE(nullptr, _link); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); linkCount++; return true; }); EXPECT_EQ(2u, linkCount); // Check joint unsigned int jointCount{0}; ecm->Each<components::Joint, components::Pose, components::ParentEntity, components::Name, components::ParentLinkName>( [&](const Entity &/*_entity*/, const components::Joint *_joint, const components::Pose *_pose, const components::ParentEntity *_parent, const components::Name *_name, const components::ParentLinkName *_parentLinkName)->bool { EXPECT_NE(nullptr, _joint); EXPECT_NE(nullptr, _pose); EXPECT_NE(nullptr, _parent); EXPECT_NE(nullptr, _name); EXPECT_NE(nullptr, _parentLinkName); std::cout << "JointName[" << _name->Data() << "]\n"; if (_name->Data() == "world_fixed") { EXPECT_EQ("world", _parentLinkName->Data()); } jointCount++; return true; }); EXPECT_EQ(2u, jointCount); }; // validate initial state validateEntities(); // Run once to let the test relay system creates the components::Recreate server.Run(true, 1, false); // Run again so that entities get recreated in the ECM server.Run(true, 1, false); // validate that the entities are recreated validateEntities(); // Run again to make sure the recreate components are removed and no // entities to to be recreated server.Run(true, 1, false); auto entities = ecm->EntitiesByComponents(components::Model(), components::Recreate()); EXPECT_TRUE(entities.empty()); }
30.663077
78
0.619989
[ "vector", "model" ]
14f521ef172662649a2e74045684f419e87d0389
11,208
cc
C++
correlation/test/correlator/common.cc
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
correlation/test/correlator/common.cc
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
correlation/test/correlator/common.cc
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include <iostream> #include "com/centreon/broker/correlation/engine_state.hh" #include "com/centreon/broker/correlation/state.hh" #include "com/centreon/broker/correlation/internal.hh" #include "com/centreon/broker/correlation/issue.hh" #include "com/centreon/broker/correlation/issue_parent.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/events.hh" #include "test/correlator/common.hh" using namespace com::centreon::broker; /** * Add an engine state to a content. * * @param[out] content Content. * @param[in] started true if correlation engine is started, false * otherwise. */ void add_engine_state( QList<misc::shared_ptr<io::data> >& content, bool started) { misc::shared_ptr<correlation::engine_state> es(new correlation::engine_state); es->started = started; content.push_back(es); return ; } /** * Add an issue to a content. * * @param[out] content Content. * @param[in] ack_time Issue acknowledgement time. * @param[in] end_time Issue end time. * @param[in] host_id Issue host ID. * @param[in] service_id Issue service ID. * @param[in] start_time Issue start time. */ void add_issue( QList<misc::shared_ptr<io::data> >& content, time_t ack_time, time_t end_time, unsigned int host_id, unsigned int service_id, time_t start_time) { misc::shared_ptr<correlation::issue> i(new correlation::issue); i->ack_time = ack_time; i->end_time = end_time; i->host_id = host_id; i->service_id = service_id; i->start_time = start_time; content.push_back(i); return ; } /** * Add an issue parenting to a content. * * @param[out] content Content. * @param[in] child_host_id Child host ID. * @param[in] child_service_id Child service ID. * @param[in] child_start_time Child start time. * @param[in] end_time Parenting end time. * @param[in] parent_host_id Parent host ID. * @param[in] parent_service_id Parent service ID. * @param[in] parent_start_time Parent start time. * @param[in] start_time Parenting start time. */ void add_issue_parent( QList<misc::shared_ptr<io::data> >& content, unsigned int child_host_id, unsigned int child_service_id, time_t child_start_time, time_t end_time, unsigned int parent_host_id, unsigned int parent_service_id, time_t parent_start_time, time_t start_time) { misc::shared_ptr<correlation::issue_parent> ip(new correlation::issue_parent); ip->child_host_id = child_host_id; ip->child_service_id = child_service_id; ip->child_start_time = child_start_time; ip->end_time = end_time; ip->parent_host_id = parent_host_id; ip->parent_service_id = parent_service_id; ip->parent_start_time = parent_start_time; ip->start_time = start_time; content.push_back(ip); return ; } /** * Add a host state to a content. * * @param[out] content Content. * @param[in] ack_time Acknowledgement time. * @param[in] current_state Current service state. * @param[in] end_time State end time. * @param[in] host_id Host ID. * @param[in] in_downtime Is in downtime ? * @param[in] start_time State start time. */ void add_state( QList<misc::shared_ptr<io::data> >& content, time_t ack_time, int current_state, time_t end_time, unsigned int host_id, bool in_downtime, unsigned int service_id, time_t start_time) { misc::shared_ptr<correlation::state> s(new correlation::state); s->ack_time = ack_time; s->current_state = current_state; s->end_time = end_time; s->host_id = host_id; s->service_id = service_id; s->in_downtime = in_downtime; s->start_time = start_time; content.push_back(s); return ; } /** * Check the content read from a stream. * * @param[in] s Stream. * @param[in] content Content to match against stream. * * @return If all content was found and matched. Throw otherwise. */ void check_content( io::stream& s, QList<misc::shared_ptr<io::data> > const& content) { unsigned int i(0); for (QList<misc::shared_ptr<io::data> >::const_iterator it(content.begin()), end(content.end()); it != end;) { misc::shared_ptr<io::data> d; s.read(d); if (d.isNull()) throw (exceptions::msg() << "entry #" << i << " is null"); else if (d->type() == (*it)->type()) { if (d->type() == io::events::data_type<io::events::correlation, correlation::de_engine_state>::value) { misc::shared_ptr<correlation::engine_state> es1(d.staticCast<correlation::engine_state>()); misc::shared_ptr<correlation::engine_state> es2(it->staticCast<correlation::engine_state>()); if (es1->started != es2->started) throw (exceptions::msg() << "entry #" << i << " (engine_state) mismatch: got (started " << es1->started << "), expected (" << es2->started << ")"); } else if (d->type() == io::events::data_type<io::events::correlation, correlation::de_issue>::value) { misc::shared_ptr<correlation::issue> i1(d.staticCast<correlation::issue>()); misc::shared_ptr<correlation::issue> i2(it->staticCast<correlation::issue>()); if ((i1->ack_time != i2->ack_time) || (i1->end_time != i2->end_time) || (i1->host_id != i2->host_id) || (i1->service_id != i2->service_id) || (i1->start_time != i2->start_time)) throw (exceptions::msg() << "entry #" << i << " (issue) mismatch: got (ack time " << i1->ack_time << ", end time " << i1->end_time << ", host " << i1->host_id << ", service " << i1->service_id << ", start time " << i1->start_time << "), expected (" << i2->ack_time << ", " << i2->end_time << ", " << i2->host_id << ", " << i2->service_id << ", " << i2->start_time << ")"); } else if (d->type() == io::events::data_type<io::events::correlation, correlation::de_issue_parent>::value) { misc::shared_ptr<correlation::issue_parent> ip1(d.staticCast<correlation::issue_parent>()); misc::shared_ptr<correlation::issue_parent> ip2(it->staticCast<correlation::issue_parent>()); if ((ip1->child_host_id != ip2->child_host_id) || (ip1->child_service_id != ip2->child_service_id) || (ip1->child_start_time != ip2->child_start_time) || (ip1->end_time != ip2->end_time) || (ip1->parent_host_id != ip2->parent_host_id) || (ip1->parent_service_id != ip2->parent_service_id) || (ip1->parent_start_time != ip2->parent_start_time) || (ip1->start_time != ip2->start_time)) throw (exceptions::msg() << "entry #" << i << " (issue_parent) mismatch: got (child host " << ip1->child_host_id << ", child service " << ip1->child_service_id << ", child start time " << ip1->child_start_time << ", end time " << ip1->end_time << ", parent host " << ip1->parent_host_id << ", parent service " << ip1->parent_service_id << ", parent start time " << ip1->parent_start_time << ", start time " << ip1->start_time << "), expected (" << ip2->child_host_id << ", " << ip2->child_service_id << ", " << ip2->child_start_time << ", " << ip2->end_time << ", " << ip2->parent_host_id << ", " << ip2->parent_service_id << ", " << ip2->parent_start_time << ", " << ip2->start_time << ")"); } else if (d->type() == io::events::data_type<io::events::correlation, correlation::de_state>::value) { misc::shared_ptr<correlation::state> s1(d.staticCast<correlation::state>()); misc::shared_ptr<correlation::state> s2(it->staticCast<correlation::state>()); if ((s1->ack_time != s2->ack_time) || (s1->current_state != s2->current_state) || (s1->end_time != s2->end_time) || (s1->host_id != s2->host_id) || (s1->in_downtime != s2->in_downtime) || (s1->service_id != s2->service_id) || (s1->start_time != s2->start_time)) throw (exceptions::msg() << "entry #" << i << " (state) mismatch: got (ack time " << s1->ack_time << ", current state " << s1->current_state << ", end time " << s1->end_time << ", host " << s1->host_id << ", in downtime " << s1->in_downtime << ", service " << s1->service_id << ", start time " << s1->start_time << "), expected (" << s2->ack_time << ", " << s2->current_state << ", " << s2->end_time << ", " << s2->host_id << ", " << s2->in_downtime << ", " << s2->service_id << ", " << s2->start_time << ")"); } ++it; ++i; } } return ; } /** * Read. * * @param[out] d Next available event. * @param[in] deadline Unused. * * @return True. */ bool test_stream::read( com::centreon::broker::misc::shared_ptr<com::centreon::broker::io::data>& d, time_t deadline) { (void)deadline; d.clear(); if (!_events.empty() && _finalized) { d = _events.front(); _events.erase(_events.begin()); } return (true); } /** * Write. * * @param[in] d The event. * * @return 1. */ int test_stream::write( com::centreon::broker::misc::shared_ptr<com::centreon::broker::io::data> const& d) { if (!d.isNull()) _events.push_back(d); return (1); } /** * Get all the written events. * * @return The written events. */ std::vector<com::centreon::broker::misc::shared_ptr<com::centreon::broker::io::data> > const& test_stream::get_events() const { return (_events); } /** * Test stream started. */ void test_stream::starting() { _finalized = false; } /** * Test stream stopped. */ void test_stream::stopping() { } /** * Finalize the test stream. */ void test_stream::finalize() { _finalized = true; }
34.380368
104
0.580924
[ "vector" ]
14f9d5516b6f719b8f0082aa7820906797ded21d
8,771
cpp
C++
src/libsetuptools/Xcp_ArrayMemoryRange.cpp
hgmelectronics/xcpsetup
646d22537f58e59c3fe324da08c4dbe0d5881efa
[ "BSD-2-Clause" ]
null
null
null
src/libsetuptools/Xcp_ArrayMemoryRange.cpp
hgmelectronics/xcpsetup
646d22537f58e59c3fe324da08c4dbe0d5881efa
[ "BSD-2-Clause" ]
null
null
null
src/libsetuptools/Xcp_ArrayMemoryRange.cpp
hgmelectronics/xcpsetup
646d22537f58e59c3fe324da08c4dbe0d5881efa
[ "BSD-2-Clause" ]
null
null
null
#include "Xcp_ArrayMemoryRange.h" #include <functional> namespace SetupTools { namespace Xcp { ArrayMemoryRange::ArrayMemoryRange(MemoryRangeType type, quint32 dim, Xcp::XcpPtr base, bool writable, quint8 addrGran, MemoryRangeList *parent) : MemoryRange(type, base, memoryRangeTypeSize(type) * dim, writable, addrGran, parent), mQtType(QVariant::Type(memoryRangeTypeQtCode(type))), mElemSize(memoryRangeTypeSize(type)), mDim(dim), mReadCache(size()), mReadCacheLoaded(size()) { mData.reserve(dim); mSlaveData.reserve(dim); for(quint32 i = 0; i < dim; ++i) { mData.push_back(QVariant()); mSlaveData.push_back(QVariant()); } Q_ASSERT(dim > 0); Q_ASSERT(quint64(dim) * memoryRangeTypeSize(type) < std::numeric_limits<quint32>::max()); } bool ArrayMemoryRange::inRange(int index) const { return 0 <= index && index<count(); } bool ArrayMemoryRange::set(int index, const QVariant &value) { if(!inRange(index)) { return false; } QVariant convertedValue = value; convertedValue.convert(mQtType); // check for convertibility if(!convertedValue.isValid()) return false; if(updateDelta<>(mData[index], convertedValue)) { emit dataChanged(index, index + 1); emit valueChanged(); setWriteCacheDirty(true); } return true; } bool ArrayMemoryRange::setDataRange(const QList<QVariant> &data, quint32 beginIndex) { if((beginIndex + data.size()) > mDim) return false; QList<QVariant> convertedData = data; for(QVariant &item : convertedData) { item.convert(mQtType); if(!item.isValid()) { emit dataChanged(beginIndex, beginIndex + data.size()); emit valueChanged(); return false; } } bool changed = false; quint32 beginChanged, endChanged; for(quint32 index = beginIndex, endIndex = beginIndex + convertedData.size(); index != endIndex; ++index) { bool itemChanged = updateDelta<>(mData[index], convertedData[index]); if(itemChanged) { if(!changed) { changed = true; beginChanged = index; } endChanged = index + 1; } } if(changed) { emit dataChanged(beginChanged, endChanged); emit valueChanged(); setWriteCacheDirty(true); } return true; } void ArrayMemoryRange::resetCaches() { mReadCacheLoaded.reset(); std::fill(mSlaveData.begin(), mSlaveData.end(), QVariant()); setWriteCacheDirty(true); } bool ArrayMemoryRange::operator==(MemoryRange &other) { ArrayMemoryRange *castOther = qobject_cast<ArrayMemoryRange *>(&other); if(castOther == nullptr) return false; if(castOther->base() == base() && castOther->type() == type() && castOther->dim() == dim()) return true; return false; } void ArrayMemoryRange::download() { bool changed = false; quint32 beginChanged = 0; quint32 endChanged = 0; for(quint32 index = 0; index != dim(); ++index) { if(mData[index] != mSlaveData[index]) { if(!changed) { beginChanged = index; changed = true; } endChanged = index + 1; } } download(beginChanged, mData.mid(beginChanged, endChanged - beginChanged)); } void ArrayMemoryRange::download(quint32 beginIndex, const QList<QVariant> &data) { if(writable() && !data.empty()) { Q_ASSERT(beginIndex + data.size() <= mDim); std::vector<quint8> buffer(mElemSize * data.size()); quint8 *bufIt = buffer.data(); for(const QVariant &item : data) { convertToSlave(item, bufIt); bufIt += mElemSize; } connectionFacade()->download(base() + (beginIndex * mElemSize / addrGran()), buffer); } else { emit downloadDone(OpResult::Success); return; } } void ArrayMemoryRange::onUploadDone(SetupTools::OpResult result, Xcp::XcpPtr baseAddr, int len, std::vector<quint8> data) { Q_UNUSED(len); if(result == SetupTools::OpResult::Success) { if(baseAddr.ext != base().ext) return; quint32 dataEnd = baseAddr.addr + data.size() / addrGran(); if(end() <= baseAddr || base() >= dataEnd) return; quint32 beginAddr = std::max(baseAddr.addr, base().addr); quint32 endAddr = std::min(dataEnd, base().addr + size() / addrGran()); quint32 beginTableOffset = (beginAddr - base().addr) * addrGran(); quint32 endTableOffset = (endAddr - base().addr) * addrGran(); quint32 beginIndex = beginTableOffset / elemSize(); quint32 endIndex = (endTableOffset + elemSize() - 1) / elemSize(); quint32 beginFullIndex = (beginTableOffset + elemSize() - 1) / elemSize(); quint32 endFullIndex = endTableOffset / elemSize(); quint32 beginChangedIndex = std::numeric_limits<quint32>::max(); quint32 endChangedIndex = std::numeric_limits<quint32>::min(); std::function<void(quint32 index, QVariant value)> setDataValue = [this, &beginChangedIndex, &endChangedIndex](quint32 index, QVariant value)->void { mSlaveData[index] = value; bool changed = updateDelta<>(mData[index], value); if(changed) { beginChangedIndex = std::min(beginChangedIndex, index); endChangedIndex = std::max(endChangedIndex, index + 1); } }; for(quint32 i = beginFullIndex; i < endFullIndex; ++i) { quint32 elemDataOffset = i * elemSize() + (base().addr - baseAddr.addr) * addrGran(); setDataValue(i, convertFromSlave(data.data() + elemDataOffset)); mReadCacheLoaded.reset(i); } if(beginIndex < beginFullIndex) { quint32 beginDataOffset = (beginAddr - baseAddr.addr) * addrGran(); quint32 partSize = (beginFullIndex * elemSize()) - beginTableOffset; QVariant partValue = partialUpload(beginTableOffset, {data.data() + beginDataOffset, data.data() + beginDataOffset + partSize}); if(partValue.isValid()) setDataValue(beginIndex, partValue); } if(endIndex > endFullIndex) { quint32 endDataOffset = (endAddr - baseAddr.addr) * addrGran(); quint32 partSize = endTableOffset % elemSize(); quint32 beginDataOffset = endDataOffset - partSize; QVariant partValue = partialUpload(endFullIndex * elemSize(), {data.data() + beginDataOffset, data.data() + endDataOffset}); if(partValue.isValid()) setDataValue(endIndex - 1, partValue); } if(beginChangedIndex < endChangedIndex) { emit dataChanged(beginChangedIndex, endChangedIndex); emit valueChanged(); } setValid(true); emit dataUploaded(beginIndex, endIndex); emit uploadDone(result); setWriteCacheDirty(mData != mSlaveData); } else if(result == SetupTools::OpResult::SlaveErrorOutOfRange) { setValid(false); std::fill(mData.begin(), mData.end(), QVariant()); std::fill(mSlaveData.begin(), mSlaveData.end(), QVariant()); emit uploadDone(OpResult::Success); } else { emit uploadDone(result); } } QVariant ArrayMemoryRange::partialUpload(quint32 offset, boost::iterator_range<quint8 *> data) { QVariant newValue; std::copy(data.begin(), data.end(), mReadCache.begin() + offset); for(quint32 iCacheByte = offset, end = offset + data.size(); iCacheByte < end; ++iCacheByte) mReadCacheLoaded[iCacheByte] = true; quint32 index = offset / elemSize(); quint32 elemOffset = index * elemSize(); bool allLoaded = true; for(quint32 i = elemOffset, end = elemOffset + data.size(); i < end; ++i) { if(!mReadCacheLoaded[i]) { allLoaded = false; break; } } if(allLoaded) { newValue = convertFromSlave(mReadCache.data() + elemOffset); for(quint32 i = elemOffset, end = elemOffset + data.size(); i < end; ++i) mReadCacheLoaded.reset(i); } return newValue; } } // namespace Xcp } // namespace SetupTools
31.66426
147
0.581462
[ "vector" ]
14fdb02acfce05e181fb1fba65d93e5912671441
6,394
cc
C++
chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager.h" #include "base/memory/ptr_util.h" #include "base/time/time.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/safe_browsing/safe_browsing_navigation_observer.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/tab_contents/retargeting_details.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" using content::WebContents; namespace safe_browsing { // The expiration period of a user gesture. Any user gesture that happened 1.0 // second ago will be considered as expired and not relevant to upcoming // navigation events. static const double kUserGestureTTLInSecond = 1.0; // static bool SafeBrowsingNavigationObserverManager::IsUserGestureExpired( const base::Time& timestamp) { double now = base::Time::Now().ToDoubleT(); double timestamp_in_double = timestamp.ToDoubleT(); if (now <= timestamp_in_double) return true; return (now - timestamp_in_double) > kUserGestureTTLInSecond; } // static GURL SafeBrowsingNavigationObserverManager::ClearEmptyRef(const GURL& url) { if (url.has_ref() && url.ref().empty()) { url::Replacements<char> replacements; replacements.ClearRef(); return url.ReplaceComponents(replacements); } return url; } SafeBrowsingNavigationObserverManager::SafeBrowsingNavigationObserverManager() { registrar_.Add(this, chrome::NOTIFICATION_RETARGETING, content::NotificationService::AllSources()); } void SafeBrowsingNavigationObserverManager::RecordNavigationEvent( const GURL& nav_event_key, NavigationEvent* nav_event) { auto insertion_result = navigation_map_.insert( std::make_pair(nav_event_key, std::vector<NavigationEvent>())); insertion_result.first->second.push_back(std::move(*nav_event)); } void SafeBrowsingNavigationObserverManager::RecordUserGestureForWebContents( content::WebContents* web_contents, const base::Time& timestamp) { auto insertion_result = user_gesture_map_.insert(std::make_pair(web_contents, timestamp)); // Update the timestamp if entry already exists. if (!insertion_result.second) insertion_result.first->second = timestamp; } void SafeBrowsingNavigationObserverManager::OnUserGestureConsumed( content::WebContents* web_contents, const base::Time& timestamp) { auto it = user_gesture_map_.find(web_contents); // Remove entry from |user_gesture_map_| as a user_gesture is consumed by // a navigation event. if (it != user_gesture_map_.end() && timestamp >= it->second) user_gesture_map_.erase(it); } void SafeBrowsingNavigationObserverManager::RecordHostToIpMapping( const std::string& host, const std::string& ip) { auto insert_result = host_to_ip_map_.insert( std::make_pair(host, std::vector<ResolvedIPAddress>())); if (!insert_result.second) { // host_to_ip_map already contains this key. // If this IP is already in the vector, we update its timestamp. for (auto& vector_entry : insert_result.first->second) { if (vector_entry.ip == host) { vector_entry.timestamp = base::Time::Now(); return; } } } // If this is a new IP of this host, and we added to the end of the vector. insert_result.first->second.push_back( ResolvedIPAddress(base::Time::Now(), ip)); } void SafeBrowsingNavigationObserverManager::OnWebContentDestroyed( content::WebContents* web_contents) { user_gesture_map_.erase(web_contents); // TODO (jialiul): Will add other clean up tasks shortly. } SafeBrowsingNavigationObserverManager:: ~SafeBrowsingNavigationObserverManager() {} void SafeBrowsingNavigationObserverManager::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_RETARGETING) RecordRetargeting(details); } void SafeBrowsingNavigationObserverManager::RecordRetargeting( const content::NotificationDetails& details) { const RetargetingDetails* retargeting_detail = content::Details<const RetargetingDetails>(details).ptr(); DCHECK(retargeting_detail); content::WebContents* source_contents = retargeting_detail->source_web_contents; content::WebContents* target_contents = retargeting_detail->target_web_contents; DCHECK(source_contents); DCHECK(target_contents); content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( retargeting_detail->source_render_process_id, retargeting_detail->source_render_frame_id); // Remove the "#" at the end of URL, since it does not point to any actual // page fragment ID. GURL target_url = SafeBrowsingNavigationObserverManager::ClearEmptyRef( retargeting_detail->target_url); NavigationEvent nav_event; if (rfh) { nav_event.source_url = SafeBrowsingNavigationObserverManager::ClearEmptyRef( rfh->GetLastCommittedURL()); } nav_event.source_tab_id = SessionTabHelper::IdForTab(source_contents); nav_event.source_main_frame_url = SafeBrowsingNavigationObserverManager::ClearEmptyRef( source_contents->GetLastCommittedURL()); nav_event.original_request_url = target_url; nav_event.destination_url = target_url; nav_event.target_tab_id = SessionTabHelper::IdForTab(target_contents); nav_event.frame_id = rfh ? rfh->GetFrameTreeNodeId() : -1; auto it = user_gesture_map_.find(source_contents); if (it != user_gesture_map_.end() && !SafeBrowsingNavigationObserverManager::IsUserGestureExpired( it->second)) { nav_event.is_user_initiated = true; OnUserGestureConsumed(it->first, it->second); } else { nav_event.is_user_initiated = false; } auto insertion_result = navigation_map_.insert( std::make_pair(target_url, std::vector<NavigationEvent>())); insertion_result.first->second.push_back(std::move(nav_event)); } } // namespace safe_browsing
37.611765
83
0.76087
[ "vector" ]
09016db7c5c0aae8adba2149407ec8c8afc1c7fc
21,726
cpp
C++
Demos/FluidDemo/FluidModel.cpp
aibel18/phasechange
30fa880fbd063b26b7e8187be4231fb40c668335
[ "MIT" ]
2
2019-11-19T20:15:34.000Z
2021-11-27T05:08:30.000Z
Demos/FluidDemo/FluidModel.cpp
aibel18/phasechange
30fa880fbd063b26b7e8187be4231fb40c668335
[ "MIT" ]
null
null
null
Demos/FluidDemo/FluidModel.cpp
aibel18/phasechange
30fa880fbd063b26b7e8187be4231fb40c668335
[ "MIT" ]
1
2019-11-19T20:15:37.000Z
2019-11-19T20:15:37.000Z
#include "FluidModel.h" #include "PositionBasedDynamics/PositionBasedDynamics.h" #include "PositionBasedDynamics/SPHKernels.h" #include "Demos/Simulation/Constraints.h" #include <iostream> #include <fstream> #include "Demos/Utils/TetGenLoader.h" #include "Demos/Utils/OBJLoader.h" #include "Demos/Utils/Logger.h" using namespace PBD; FluidModel::FluidModel() : m_particles() { m_cloth_stiffness = 1.0; m_dilation = 0.001; m_density0 = 1000.0; m_particleRadius = 0.025; viscosity = 0.025; m_neighborhoodSearch = NULL; t_melting = 0; t_evaporation = 100.0; t_difusion = 100; LatentThreshhold = Vector2r(333, 2257); radioSolidification = 0.055; numMaxConstraints = 4; t_contact = false; t_tempContact = 0; } FluidModel::~FluidModel(void) { cleanupModel(); } void FluidModel::cleanupModel() { m_particles.release(); m_lambda.clear(); m_density.clear(); m_deltaX.clear(); /* for (unsigned int i = 0; i < m_constraints.size(); i++) delete m_constraints[i];*/ m_constraints.clear(); delete m_neighborhoodSearch; } void FluidModel::reset() { const unsigned int nPoints = m_particles.size(); for(unsigned int i=0; i < nPoints; i++) { const Vector3r& x0 = m_particles.getPosition0(i); m_particles.getPosition(i) = x0; m_particles.setTemp(i, m_particles.getTemp0(i)); m_particles.getLastPosition(i) = m_particles.getPosition(i); m_particles.getOldPosition(i) = m_particles.getPosition(i); m_particles.getVelocity(i).setZero(); m_particles.getAcceleration(i).setZero(); m_deltaX[i].setZero(); m_lambda[i] = 0.0; m_density[i] = 0.0; m_particles.getC(i) = 1000; m_particles.getConductivity(i) = 50.0; m_particles.getLatent(i).setZero(); m_particles.evalState(i,t_melting,t_evaporation); switch ((int)m_particles.getState(i)) { case 0: //, Vector3r(0.0f, this->getLatent()[0], this->getLatent()[1])); break; case 1: this->m_particles.getLatent(i)[1] = this->getLatent()[0]; break; case 2: this->m_particles.getLatent(i)[1] = this->getLatent()[0]; this->m_particles.getLatent(i)[2] = this->getLatent()[1]; this->m_particles.getVelocity(i)[1] = ((rand() % 900+150.0)*0.0002); this->m_particles.getVelocity(i)[1] = this->m_particles.getVelocity(i)[1] + 0.00390625; this->m_particles.getPosition(i)[1] = this->m_particles.getPosition(i)[1] + this->m_particles.getVelocity(i)[1] * 0.00390625; break; case -1: this->m_particles.getLatent(i)[1] = this->getLatent()[0]/2; break; case -2: this->m_particles.getLatent(i)[1] = this->getLatent()[0]; this->m_particles.getLatent(i)[2] = this->getLatent()[1] / 2; break; } /* if (i<nPoints / 2) { m_particles.getTemp(i) = 80; } else { m_particles.getTemp(i) = 0; } m_particles.setState(i, 1); //*/ } /// if exist the model 3d this->m_constraints.clear(); if (m_constraintsIndex.size()>0) { int numConstrainst = m_constraintsIndex.size(); for (int i = 0; i < numConstrainst;i+=2) { this->addDistanceConstraint(m_constraintsIndex[i], m_constraintsIndex[i+1]); } } } ParticleData & PBD::FluidModel::getParticles() { return m_particles; } std::vector<newDistanceConstraint> & PBD::FluidModel::getConstraints() { return m_constraints; } void FluidModel::initMasses() { const int nParticles = (int) m_particles.size(); const Real diam = 2.0*m_particleRadius; #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < nParticles; i++) { //if(m_particles.getActive(i)){ m_particles.setMass(i, 0.8 * diam*diam*diam * m_density0); // each particle represents a cube with a side length of r // mass is slightly reduced to prevent pressure at the beginning of the simulation /*} else { m_particles.setMass(i,0); }*/ } } } /** Resize the arrays containing the particle data. */ void FluidModel::resizeFluidParticles(const unsigned int newSize) { m_particles.resize(newSize); m_lambda.resize(newSize); m_density.resize(newSize); m_deltaX.resize(newSize); } /** Release the arrays containing the particle data. */ void FluidModel::releaseFluidParticles() { m_particles.release(); m_lambda.clear(); m_density.clear(); m_deltaX.clear(); } void FluidModel::initModel(const unsigned int nFluidParticles, Vector3r* fluidParticles, const unsigned int nBoundaryParticles, Vector3r* boundaryParticles) { releaseFluidParticles(); resizeFluidParticles(nFluidParticles); // init kernel CubicKernel::setRadius(m_supportRadius); // copy fluid positions #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int)nFluidParticles; i++) { m_particles.getPosition0(i) = fluidParticles[i]; } } m_boundaryX.resize(nBoundaryParticles); m_boundaryActive.resize(nBoundaryParticles); m_boundaryPsi.resize(nBoundaryParticles); m_boundaryVolume.resize(nBoundaryParticles); // copy boundary positions #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int)nBoundaryParticles; i++) { m_boundaryX[i] = boundaryParticles[i]; } } // initialize masses initMasses(); ////////////////////////////////////////////////////////////////////////// // Compute value psi for boundary particles (boundary handling) // (see Akinci et al. "Versatile rigid - fluid coupling for incompressible SPH", Siggraph 2012 ////////////////////////////////////////////////////////////////////////// // Search boundary neighborhood NeighborhoodSearchSpatialHashing neighborhoodSearchSH(nBoundaryParticles, m_supportRadius); neighborhoodSearchSH.neighborhoodSearch(&m_boundaryX[0]); unsigned int **neighbors = neighborhoodSearchSH.getNeighbors(); unsigned int *numNeighbors = neighborhoodSearchSH.getNumNeighbors(); #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int) nBoundaryParticles; i++) { Real delta = CubicKernel::W_zero(); for (unsigned int j = 0; j < numNeighbors[i]; j++) { const unsigned int neighborIndex = neighbors[i][j]; delta += CubicKernel::W(m_boundaryX[i] - m_boundaryX[neighborIndex]); } const Real volume = 1.0 / delta; m_boundaryPsi[i] = m_density0 * volume; m_boundaryVolume[i] = volume; } } // Initialize neighborhood search if (m_neighborhoodSearch == NULL) m_neighborhoodSearch = new NeighborhoodSearchSpatialHashing(m_particles.size(), m_supportRadius); m_neighborhoodSearch->setRadius(m_supportRadius); reset(); } void FluidModel::initModel( const unsigned int nBoundaryParticles, Vector3r* boundaryParticles, std::vector<bool>* boundaryActives) { // init kernel CubicKernel::setRadius(m_supportRadius); m_boundaryX.resize(nBoundaryParticles); m_boundaryActive.resize(nBoundaryParticles); m_boundaryVolume.resize(nBoundaryParticles); m_boundaryPsi.resize(nBoundaryParticles); // copy boundary positions #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int)nBoundaryParticles; i++) { m_boundaryX[i] = boundaryParticles[i]; m_boundaryActive[i] = (*boundaryActives)[i]; } } // initialize masses initMasses(); ////////////////////////////////////////////////////////////////////////// // Compute value psi for boundary particles (boundary handling) // (see Akinci et al. "Versatile rigid - fluid coupling for incompressible SPH", Siggraph 2012 ////////////////////////////////////////////////////////////////////////// // Search boundary neighborhood NeighborhoodSearchSpatialHashing neighborhoodSearchSH(nBoundaryParticles, m_supportRadius); neighborhoodSearchSH.neighborhoodSearch(&m_boundaryX[0]); unsigned int **neighbors = neighborhoodSearchSH.getNeighbors(); unsigned int *numNeighbors = neighborhoodSearchSH.getNumNeighbors(); #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int)nBoundaryParticles; i++) { Real delta = CubicKernel::W_zero(); for (unsigned int j = 0; j < numNeighbors[i]; j++) { const unsigned int neighborIndex = neighbors[i][j]; delta += CubicKernel::W(m_boundaryX[i] - m_boundaryX[neighborIndex]); } const Real volume = 1.0 / delta; m_boundaryPsi[i] = m_density0 * volume; m_boundaryVolume[i] = volume; } } // Initialize neighborhood search if (m_neighborhoodSearch == NULL) m_neighborhoodSearch = new NeighborhoodSearchSpatialHashing(m_particles.size(), m_supportRadius); m_neighborhoodSearch->setRadius(m_supportRadius); reset(); } void FluidModel::importMyModel(const char* path, std::vector<Vector3r>* vertices, std::vector<unsigned int>* edges, float scale, float fac) { std::ifstream file(path); int nVertices = 0; int nEdges = 0; if (!file) return; file >> nVertices >> nEdges; float x, y, z,minY=0.1f; for (int i = 0; i < nVertices; i++) { file >> x >> y >> z; if (y < minY) { minY = y; } //if( y < fac) vertices->push_back(Vector3r(x, y, z)); } for (int i = 0; i < vertices->size(); i++) { if ((*vertices)[i][1] < fac) { (*vertices)[i][1] = 0; } else //*/ (*vertices)[i][1] = (*vertices)[i][1] - minY; (*vertices)[i] = (*vertices)[i] * scale; } //* unsigned int v1, v2; for (int i = 0; i < nEdges; i++) { file >> v1 >> v2; edges->push_back(v1); edges->push_back(v2); }//*/ } void FluidModel::addModel(const std::string &nameFile, Real diam, Real temp, Real scale, Vector3r position,bool fixed,float fac) { std::vector<Vector3r> vertices; std::vector<unsigned int> edges; importMyModel(nameFile.c_str(), &vertices, &edges, scale,fac); int nLastParticles = m_particles.getNumberOfParticles();; int nVertices = vertices.size(); int nEdges = edges.size(); m_lambda.resize(nLastParticles + nVertices); m_density.resize(nLastParticles + nVertices); m_deltaX.resize(nLastParticles + nVertices); for (int i = 0, n = nLastParticles; i < nVertices; i++, n++) { this->m_particles.addVertex(vertices[i] + position); this->m_particles.setTemp(n, temp); this->m_particles.setTemp0(n, temp); if (fixed && vertices[i][1] < 1.9*diam) { this->m_particles.setActive(i, false); } this->m_particles.evalState(n, t_melting, t_evaporation); } /*for (unsigned int i = 0; i < nEdges; i += 2) { const unsigned int v1 = edges[i] + nLastParticles; const unsigned int v2 = edges[i + 1] + nLastParticles; addDistanceConstraint(v1, v2); m_constraintsIndex.push_back(v1); m_constraintsIndex.push_back(v2); }*/ //LOG_INFO << "Number vertices:" << nVertices << nEdges; printf("vertices: %d edges: %d\n", nVertices, nEdges); } void FluidModel::addObject(const std::string &nameFile, Real diam, Real temp, Vector3r size, Vector3r position) { std::vector<Vector3r> vertices; std::vector<unsigned int> tets; TetGenLoader::loadTetgenModel( nameFile + ".node" , nameFile + ".ele" , vertices, tets); int nLastParticles = m_particles.size(); int nParticles = vertices.size(); m_lambda.resize(nLastParticles + nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); position = position*diam; for (int i = 0, n = nLastParticles; i < nParticles; i++,n++) { vertices[i] = 0.5* vertices[i]; vertices[i][2] = -vertices[i][2]; this->m_particles.addVertex( vertices[i] + position); this->m_particles.setTemp(n, temp); this->m_particles.setTemp0(n, temp); this->m_particles.evalState(n, t_melting, t_evaporation); } TetModel *tetModel = new TetModel(); tetModel->initMesh(nParticles, (unsigned int)tets.size() / 4u, nLastParticles, tets.data()); //tetModel->attachVisMesh(); const unsigned int offset = tetModel->getIndexOffset(); const unsigned int nEdges = tetModel->getParticleMesh().numEdges(); const IndexedTetMesh::Edge *edges = tetModel->getParticleMesh().getEdges().data(); for (unsigned int i = 0; i < nEdges; i++) { const unsigned int v1 = edges[i].m_vert[0] + offset; const unsigned int v2 = edges[i].m_vert[1] + offset; addDistanceConstraint(v1, v2); m_constraintsIndex.push_back(v1); m_constraintsIndex.push_back(v2); //tetModel->updateMeshNormals(model.getParticles()); } delete tetModel; /* IndexedFaceMesh mesh; VertexData vertices; OBJLoader::loadObj(nameFile, vertices, mesh); int nLastParticles = m_particles.size(); int nParticles = vertices.size(); m_lambda.resize(nLastParticles + nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); position = position*diam; for (int i = 0, n = nLastParticles; i < nParticles; i++, n++) { vertices.getPosition(i) = 25 * vertices.getPosition(i); vertices.getPosition(i)[2] = - vertices.getPosition(i)[2]; this->m_particles.addVertex(vertices.getPosition(i) + position); this->m_particles.setTemp(n, temp); this->m_particles.setTemp0(n, temp); this->m_particles.evalState(n, t_melting, t_evaporation); } TriangleModel *triModel = new TriangleModel(); unsigned int startIndex = m_particles.size(); triModel->initMesh(nParticles, mesh.numFaces(), nLastParticles, mesh.getFaces().data(), mesh.getUVIndices(), mesh.getUVs()); const unsigned int offset = triModel->getIndexOffset(); const unsigned int nEdges = triModel->getParticleMesh().numEdges(); const IndexedFaceMesh::Edge *edges = triModel->getParticleMesh().getEdges().data(); for (unsigned int i = 0; i < nEdges; i++) { const unsigned int v1 = edges[i].m_vert[0] + offset; const unsigned int v2 = edges[i].m_vert[1] + offset; addDistanceConstraint(v1, v2); } //addTriModel(triModel);*/ } void FluidModel::addSolid(Real diam,Real temp,Vector3r size, Vector3r position) { int widthS = size[0]; int heightS = size[1]; int depthS = size[2]; int nLastParticles = m_particles.size(); int nParticles = widthS*heightS*depthS; m_lambda.resize(nLastParticles + nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); Vector3r initial = Vector3r(-diam*widthS*0.5, diam, -diam*depthS*0.5); //Vector3r initial = Vector3r(-diam * widthS*0.5 + diam * 0.5, diam*0.5, -diam * depthS*0.5 + diam * 0.5); for (int i = 0,n= nLastParticles; i < widthS; i++) { for (unsigned int j = 0; j < heightS; j++) { for (unsigned int k = 0; k < depthS; k++,n++) { this->m_particles.addVertex(diam*Vector3r((Real)i, (Real)j, (Real)k) +initial+position ); this->m_particles.setTemp(n, temp); this->m_particles.setTemp0(n, temp); this->m_particles.evalState(n,t_melting,t_evaporation); } } } std::vector<unsigned int> indices; for (unsigned int i = 0; i < widthS - 1; i++)//width { for (unsigned int j = 0; j < heightS - 1; j++)//height { for (unsigned int k = 0; k < depthS - 1; k++)//depth { // For each block, the 8 corners are numerated as: // 4*-----*7 // /| /| // / | / | // 5*-----*6 | // | 0*--|--*3 // | / | / // |/ |/ // 1*-----*2 unsigned int p0 = i * heightS * depthS + j * depthS + k; unsigned int p1 = p0 + 1; unsigned int p3 = (i + 1) * heightS * depthS + j * depthS + k; unsigned int p2 = p3 + 1; unsigned int p7 = (i + 1) * heightS * depthS + (j + 1) * depthS + k; unsigned int p6 = p7 + 1; unsigned int p4 = i * heightS * depthS + (j + 1) * depthS + k; unsigned int p5 = p4 + 1; // Ensure that neighboring tetras are sharing faces if ((i + j + k) % 2 == 1) { indices.push_back(p2); indices.push_back(p1); indices.push_back(p6); indices.push_back(p3); indices.push_back(p6); indices.push_back(p3); indices.push_back(p4); indices.push_back(p7); indices.push_back(p4); indices.push_back(p1); indices.push_back(p6); indices.push_back(p5); indices.push_back(p3); indices.push_back(p1); indices.push_back(p4); indices.push_back(p0); indices.push_back(p6); indices.push_back(p1); indices.push_back(p4); indices.push_back(p3); } else { indices.push_back(p0); indices.push_back(p2); indices.push_back(p5); indices.push_back(p1); indices.push_back(p7); indices.push_back(p2); indices.push_back(p0); indices.push_back(p3); indices.push_back(p5); indices.push_back(p2); indices.push_back(p7); indices.push_back(p6); indices.push_back(p7); indices.push_back(p0); indices.push_back(p5); indices.push_back(p4); indices.push_back(p0); indices.push_back(p2); indices.push_back(p7); indices.push_back(p5); } } } } TetModel *tetModel = new TetModel(); tetModel->initMesh(widthS*heightS*depthS, (unsigned int)indices.size() / 4u, nLastParticles, indices.data()); const unsigned int offset = tetModel->getIndexOffset(); const unsigned int nEdges = tetModel->getParticleMesh().numEdges(); const IndexedTetMesh::Edge *edges = tetModel->getParticleMesh().getEdges().data(); for (unsigned int i = 0; i < nEdges; i++) { const unsigned int v1 = edges[i].m_vert[0] + offset; const unsigned int v2 = edges[i].m_vert[1] + offset; addDistanceConstraint(v1, v2); m_constraintsIndex.push_back(v1); m_constraintsIndex.push_back(v2); //tetModel->updateMeshNormals(model.getParticles()); } delete tetModel; std::cout << "Number of particles Solid: " << nParticles << std::endl; } void FluidModel::addFluid(Real diam, Real temp, Vector3r size, Vector3r position) { int widthS = size[0]; int heightS = size[1]; int depthS = size[2]; int nLastParticles = m_particles.size(); int nParticles = widthS*heightS*depthS; m_lambda.resize(nLastParticles+nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); Vector3r initial = Vector3r(-diam*widthS*0.5 + diam * 0.5, diam*0.5, -diam*depthS*0.5 + diam * 0.5); for (int i = 0, n = nLastParticles; i < widthS; i++) { for (unsigned int j = 0; j < heightS; j++) { for (unsigned int k = 0; k < depthS; k++, n++) { //this->m_particles.addVertex(diam*Vector3r((Real)i- 28.0f*sin((j+10) / 9.0f) / pow(((j+10) / 5.0f), (1 / 3.0f)), (Real)j, (Real)k + 2*sin(j*0.5)) + initial + position ); this->m_particles.addVertex(diam*Vector3r((Real)i , (Real)j, (Real)k ) + initial + position); this->m_particles.setTemp(n, temp); this->m_particles.setTemp0(n, temp); this->m_particles.evalState(n, t_melting, t_evaporation); this->m_particles.setLatent(i,Vector3r(0.0f,this->getLatent()[0],0.0f)); } } } std::cout << "Number of particles Fluid: " << nParticles << std::endl; } void FluidModel::addGas(Real diam, Real temp, Vector3r size, Vector3r position) { int widthS = size[0]; int heightS = size[1]; int depthS = size[2]; int nLastParticles = m_particles.size(); int nParticles = widthS*heightS*depthS*0.25; m_lambda.resize(nLastParticles + nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); Vector3r initial = Vector3r(-diam*widthS*0.5 + diam * 0.5, 0, -diam*depthS*0.5 + diam * 0.5); for (int i = 0, n = nLastParticles; i < widthS; i+=2) { for (unsigned int j = 0; j < heightS; j++) { for (unsigned int k = 0; k < depthS; k+=2, n++) { //this->m_particles.addVertex(diam*Vector3r((Real)i- 28.0f*sin((j+10) / 9.0f) / pow(((j+10) / 5.0f), (1 / 3.0f)), (Real)j, (Real)k + 2*sin(j*0.5)) + initial + position ); this->m_particles.addVertex(diam*Vector3r((Real)i +(rand()%1000)*0.0018 , (Real)j*5 + (rand() % 1000)*0.0045, (Real)k + (rand() % 1000)*0.0018) + initial + position); float currentTemp = temp;//+(rand() % 1000)*0.01; //this->m_particles.getVelocity(i)[1] = -(rand() % 1000)*0.025; this->m_particles.setTemp(n, currentTemp); this->m_particles.setTemp0(n, currentTemp); this->m_particles.evalState(n, t_melting, t_evaporation); this->m_particles.setLatent(i, Vector3r(0.0f, this->getLatent()[0], this->getLatent()[1])); } } } std::cout << "Number of particles Gas: " << nParticles << std::endl; } void FluidModel::addAir(Real diam, Real temp, Vector3r size, Vector3r position, int density) { int widthS = size[0]; int heightS = size[1]; int depthS = size[2]; int nLastParticles = m_particles.size(); int nParticles = widthS * heightS*depthS*0.25; m_lambda.resize(nLastParticles + nParticles); m_density.resize(nLastParticles + nParticles); m_deltaX.resize(nLastParticles + nParticles); Vector3r initial = Vector3r(-diam * widthS*0.5, 0, -diam * depthS*0.5); float ratio = density * 0.001; for (int i = 0, n = nLastParticles; i < widthS; i += 2) { for (unsigned int j = 0; j < heightS; j++) { for (unsigned int k = 0; k < depthS; k += 2, n++) { //this->m_particles.addVertex(diam*Vector3r((Real)i- 28.0f*sin((j+10) / 9.0f) / pow(((j+10) / 5.0f), (1 / 3.0f)), (Real)j, (Real)k + 2*sin(j*0.5)) + initial + position ); this->m_particles.addVertex(diam*Vector3r((Real)i + (rand() % 1000)*0.0019, (Real)j * density + (rand() % 1000) * ratio, (Real)k + (rand() % 1000)*0.0019) + initial + position); float currentTemp = temp ; this->m_particles.setTemp(n, currentTemp); this->m_particles.setTemp0(n, currentTemp); this->m_particles.setActive(n,false); this->m_particles.evalState(n, t_melting, t_evaporation); this->m_particles.setLatent(i, Vector3r(0.0f, this->getLatent()[0], this->getLatent()[1])); } } } std::cout << "Number of particles Air: " << nParticles << std::endl; } bool FluidModel::addDistanceConstraint(const unsigned int particle1, const unsigned int particle2) { newDistanceConstraint c = newDistanceConstraint(); const bool res = c.initConstraint(*this, particle1, particle2); if (res) { m_constraints.push_back(c); //m_groupsInitialized = false; } return res; }
30.904694
181
0.673203
[ "mesh", "vector", "model", "3d", "solid" ]
090c6ac6fddaad6846ed71daa3ad8524bb2f728e
1,506
hh
C++
src/math/DirectLinearSolver.hh
lucydot/devsim
2c69fcc05551bb50ca134490279e206cdeaf91a6
[ "Apache-2.0" ]
100
2015-02-02T23:47:38.000Z
2022-03-15T06:15:15.000Z
src/math/DirectLinearSolver.hh
fendou1997/devsim
71c5a5a56f567b472f39e4968bedbe57a38d6ff6
[ "Apache-2.0" ]
75
2015-05-13T02:16:41.000Z
2022-02-23T12:20:21.000Z
src/math/DirectLinearSolver.hh
fendou1997/devsim
71c5a5a56f567b472f39e4968bedbe57a38d6ff6
[ "Apache-2.0" ]
50
2015-10-28T17:24:24.000Z
2022-03-30T17:48:46.000Z
/*** DEVSIM Copyright 2013 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #ifndef DS_DIRECT_LINEAR_SOLVER_HH #define DS_DIRECT_LINEAR_SOLVER_HH #include "LinearSolver.hh" namespace dsMath { // Special case // x = inv(A) b template <typename DoubleType> class DirectLinearSolver : public LinearSolver<DoubleType> { public: DirectLinearSolver(); ~DirectLinearSolver() {}; protected: private: bool SolveImpl(Matrix<DoubleType> &, Preconditioner<DoubleType> &, std::vector<DoubleType> &, std::vector<DoubleType> & ); bool ACSolveImpl(Matrix<DoubleType> &, Preconditioner<DoubleType> &, std::vector<std::complex<DoubleType>> &, std::vector<std::complex<DoubleType>> & ); bool NoiseSolveImpl(Matrix<DoubleType> &, Preconditioner<DoubleType> &, std::vector<std::complex<DoubleType>> &, std::vector<std::complex<DoubleType>> & ); DirectLinearSolver(const DirectLinearSolver &); DirectLinearSolver &operator=(const DirectLinearSolver &); }; } #endif
34.227273
163
0.737716
[ "vector" ]
0910bec794a10d946b0b91b86d29a272660fb53e
3,292
cpp
C++
core/topo/HalfEdgeMesh.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
6
2018-10-04T14:04:40.000Z
2018-12-21T16:04:47.000Z
core/topo/HalfEdgeMesh.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
null
null
null
core/topo/HalfEdgeMesh.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
null
null
null
#include "HalfEdgeMesh.h" #include <algorithm> HalfEdge::Vertex* HalfEdge::Mesh::createVertex(HalfEdge* leading) { auto * v = store->allocVertex(); v->leadingEdge = leading; vertices.pushBack(v); return v; } HalfEdge::HalfEdge* HalfEdge::Mesh::createHalfEdge(Vertex* srcVtx, HalfEdge* nextInFace, HalfEdge* nextInEdge, Face* face) { auto * he = store->allocHalfEdge(); he->srcVtx = srcVtx; if (srcVtx->leadingEdge == nullptr) { srcVtx->leadingEdge = he; } he->nextInFace = nextInFace; he->nextInEdge = nextInEdge; he->face = face; if (face->leadingEdge == nullptr) { face->leadingEdge = he; } halfEdges.pushBack(he); return he; } HalfEdge::Face* HalfEdge::Mesh::createFace(HalfEdge* leading) { auto * f = store->allocFace(); f->leadingEdge = leading; faces.pushBack(f); return f; } void HalfEdge::Mesh::insert(uint32_t vtxCount, uint32_t* indices, uint32_t* offsets, uint32_t faceCount) { auto vtxMark = vertices.size32(); for (uint32_t i = 0; i < vtxCount; i++) { createVertex(); } auto mark = halfEdges.size32(); Vector<HalfEdge*> loop; for (uint32_t f = 0; f < faceCount; f++) { auto * face = createFace(); auto N = offsets[f + 1] - offsets[f]; if (N < 3) { logger(1, "Degenerate face with less than 3 vertices."); } loop.resize(N); for (uint32_t i = 0; i < N; i++) { auto ix = indices[offsets[f] + i]; loop[i] = createHalfEdge(vertices[vtxMark + ix], nullptr, nullptr, face); if (0 < i) { loop[i - 1]->nextInFace = loop[i]; } } loop[N - 1]->nextInFace = loop[0]; } stitchRange(mark, halfEdges.size32()); } namespace { struct SortHelper { HalfEdge::HalfEdge* he; HalfEdge::Vertex* maj; HalfEdge::Vertex* min; }; } void HalfEdge::Mesh::stitchRange(uint32_t heA, uint32_t heB) { auto N = heB - heA; Vector<SortHelper> helper(N); for (uint32_t i = 0; i < N; i++) { auto & item = helper[i]; item.he = halfEdges[heA + i]; item.maj = item.he->srcVtx; item.min = item.he->nextInFace->srcVtx; if (item.maj < item.min) { auto t = item.maj; item.maj = item.min; item.min = t; } } // A bit lazy, but will wait until it is a problem to do something more clever. std::sort(helper.begin(), helper.end(), [](auto& a, auto& b) { if (a.maj == b.maj) { return a.min < b.min; } return a.maj < b.maj; }); for (uint32_t j = 0; j < N; ) { uint32_t i=j+1; for (; i < N && helper[j].maj == helper[i].maj && helper[j].min == helper[i].min; i++) ; auto abutting = i - j; if (abutting == 1) { boundaryEdges++; // stitch } else if (abutting == 2) { manifoldEdges++; // stitch } else { nonManifoldEdges++; // stitch } j = i; } logger(0, "Found %d boundary edges, %d manifold edges and %d non-manifold edges", boundaryEdges, manifoldEdges, nonManifoldEdges); } void HalfEdge::R3Mesh::insert(const Vec3f* vtx, uint32_t vtxCount, uint32_t* indices, uint32_t* offsets, uint32_t faceCount) { auto vtxMark = vertices.size32(); Mesh::insert(vtxCount, indices, offsets, faceCount); for (uint32_t i = 0; i < vtxCount; i++) { ((R3Vertex*)vertices[vtxMark + i])->pos = vtx[i]; } }
23.183099
132
0.601762
[ "mesh", "vector" ]
0913d39b8bbd241bef248cd63988ae8fca3a7e33
20,680
hpp
C++
external/swak/libraries/swakParsers/FieldValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/swakParsers/FieldValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/swakParsers/FieldValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*----------------------- -*- C++ -*- ---------------------------------------*\ Copyright: ICE Stroemungsfoschungs GmbH ------------------------------------------------------------------------------- License This file is part of swak. swak is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. swak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swak. If not, see <http://www.gnu.org/licenses/>. Description Contributors/Copyright: 2006-2013 Bernhard F.W. Gschaider <bgschaid@ice-sf.at> 2012 Bruno Santos <wyldckat@gmail.com> \*---------------------------------------------------------------------------*/ #ifndef VALUE_EXPRESSION_DRIVER_I_H #define VALUE_EXPRESSION_DRIVER_I_H #include "wallFvPatch.hpp" #include "wallPointPatch.hpp" #include "fixedValueFvPatchFields.hpp" #include "fixedValueFvsPatchFields.hpp" #include "zeroGradientFvPatchFields.hpp" #include "calculatedFvPatchFields.hpp" #include "calculatedFvsPatchFields.hpp" #include "mappedFvPatch.hpp" #include "mappedWallFvPatch.hpp" #include "volPointInterpolation.hpp" #include "interpolatePointToCell.hpp" #include "mappedPointPatch.hpp" #include "fixedValuePointPatchFields.hpp" #include "zeroGradientPointPatchFields.hpp" #include "calculatedPointPatchFields.hpp" namespace CML { template<class T> tmp<T> FieldValueExpressionDriver::getField(const word &name,bool getOldTime) { return tmp<T>( this->getOrReadField<T>( name, true, // fail if not found getOldTime ).ptr() ); } template<class T> tmp<T> FieldValueExpressionDriver::getPointField( const word &name, bool getOldTime ) { return tmp<T>( this->getOrReadPointField<T>( name, true, // fail if not found getOldTime ).ptr() ); } inline label FieldValueExpressionDriver::size() const { return mesh_.nCells(); } inline label FieldValueExpressionDriver::pointSize() const { return mesh_.nPoints(); } inline const fvMesh &FieldValueExpressionDriver::mesh() const { return mesh_; } inline bool FieldValueExpressionDriver::canBeValuePatch(const fvPatch &patch) { return isA<wallFvPatch>(patch) || isType<fvPatch>(patch) || isA<mappedWallFvPatch>(patch) || isA<mappedFvPatch>(patch); } inline bool FieldValueExpressionDriver::canBeValuePatch(const pointPatch &patch) { return isA<wallPointPatch>(patch) || isType<facePointPatch>(patch) || isA<mappedPointPatch>(patch); } template<class T> void FieldValueExpressionDriver::makePatches ( GeometricField<T,fvPatchField,volMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,fvPatchField,volMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<fvPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const fvPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if(isValuePatch){ bfNew[patchI]=new fixedValueFvPatchField<T>(patch,field); } else { bfNew[patchI]=new zeroGradientFvPatchField<T>(patch,field); } } else { bfNew[patchI]=bf[patchI].clone().ptr(); } } bf.clear(); bf.setSize(bfNew.size()); forAll(bf,i) { bf.set(i,bfNew[i]); } } // code duplication from the template above template<class T> void FieldValueExpressionDriver::makePatches ( GeometricField<T,fvsPatchField,surfaceMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,fvsPatchField,surfaceMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<fvsPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const fvPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if(isValuePatch){ bfNew[patchI]=new fixedValueFvsPatchField<T>(patch,field); } else { // this is the only line that is REALLY different bfNew[patchI]=new calculatedFvsPatchField<T>(patch,field); (*bfNew[patchI])==bf[patchI]; } } else { bfNew[patchI]=bf[patchI].clone().ptr(); } } bf.clear(); bf.setSize(bfNew.size()); forAll(bf,i) { bf.set(i,bfNew[i]); } } // code duplication from the template above template<class T> void FieldValueExpressionDriver::makePatches ( GeometricField<T,pointPatchField,pointMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,pointPatchField,pointMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<pointPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const pointPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if(isValuePatch){ bfNew[patchI]=new fixedValuePointPatchField<T>(patch,field); } else { bfNew[patchI]=new zeroGradientPointPatchField<T>(patch,field); } } else { bfNew[patchI]=bf[patchI].clone().ptr(); } } bf.clear(); bf.setSize(bfNew.size()); forAll(bf,i) { bf.set(i,bfNew[i]); } } template<class T> void FieldValueExpressionDriver::setCalculatedPatches ( GeometricField<T,fvPatchField,volMesh> &field, T unusedValue ) { typename GeometricField<T,fvPatchField,volMesh>::GeometricBoundaryField &bf=field.boundaryField(); forAll(bf,patchI) { fvPatchField<T> &pf=bf[patchI]; if( typeid(pf)==typeid(calculatedFvPatchField<T>) ) { pf==pf.patchInternalField(); } } field.correctBoundaryConditions(); } template<class T> void FieldValueExpressionDriver::setCalculatedPatches ( GeometricField<T,fvsPatchField,surfaceMesh> &field, T value ) { typename GeometricField<T,fvsPatchField,surfaceMesh>::GeometricBoundaryField &bf=field.boundaryField(); forAll(bf,patchI) { fvsPatchField<T> &pf=bf[patchI]; if( typeid(pf)==typeid(calculatedFvsPatchField<T>) ) { // pf==pf.patchInternalField(); pf==value; } } // field.correctBoundaryConditions(); } template<class T> void FieldValueExpressionDriver::setCalculatedPatches ( GeometricField<T,pointPatchField,pointMesh> &field, T unusedValue ) { typename GeometricField<T,pointPatchField,pointMesh>::GeometricBoundaryField &bf=field.boundaryField(); forAll(bf,patchI) { pointPatchField<T> &pf=bf[patchI]; if( typeid(pf)==typeid(calculatedPointPatchField<T>) ) { pf==pf.patchInternalField(); } } field.correctBoundaryConditions(); } template<class T> void FieldValueExpressionDriver::copyCalculatedPatches ( GeometricField<T,fvPatchField,volMesh> &field, const GeometricField<T,fvPatchField,volMesh> &orig ) { typename GeometricField<T,fvPatchField,volMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<fvPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { fvPatchField<T> &pf=bf[patchI]; if( typeid(pf)==typeid(calculatedFvPatchField<T>) ) { pf==pf.patchInternalField(); } } // field.correctBoundaryConditions(); } template<class T> void FieldValueExpressionDriver::copyCalculatedPatches ( GeometricField<T,fvsPatchField,surfaceMesh> &field, const GeometricField<T,fvsPatchField,surfaceMesh> &orig ) { typename GeometricField<T,fvsPatchField,surfaceMesh>::GeometricBoundaryField &bf=field.boundaryField(); const typename GeometricField<T,fvsPatchField,surfaceMesh>::GeometricBoundaryField &bfOrig=orig.boundaryField(); forAll(bf,patchI) { fvsPatchField<T> &pf=bf[patchI]; const fvsPatchField<T> &pfOrig=bfOrig[patchI]; if( typeid(pf)==typeid(calculatedFvsPatchField<T>) && typeid(pfOrig)==typeid(calculatedFvsPatchField<T>) ) { pf==pfOrig; } } } template<class T> void FieldValueExpressionDriver::copyCalculatedPatches ( GeometricField<T,pointPatchField,pointMesh> &field, const GeometricField<T,pointPatchField,pointMesh> &orig ) { typename GeometricField<T,pointPatchField,pointMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<pointPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { pointPatchField<T> &pf=bf[patchI]; if( typeid(pf)==typeid(calculatedPointPatchField<T>) ) { pf==pf.patchInternalField(); } } // field.correctBoundaryConditions(); } template<class T> void FieldValueExpressionDriver::setValuePatches ( GeometricField<T,fvPatchField,volMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,fvPatchField,volMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<fvPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const fvPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if(typeid(field.boundaryField()[patchI])==typeid(fixedValueFvPatchField<T>)) { fvPatchField<T> &pf=field.boundaryField()[patchI]; pf==pf.patchInternalField(); } } } } // Code duplication from above ... maybe there is a better way template<class T> void FieldValueExpressionDriver::setValuePatches ( GeometricField<T,fvsPatchField,surfaceMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,fvsPatchField,surfaceMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<fvsPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const fvPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if(typeid(field.boundaryField()[patchI])==typeid(fixedValueFvsPatchField<T>)) { fvsPatchField<T> &pf=field.boundaryField()[patchI]; // pf==pf.patchInternalField(); WarningInFunction << "There is no patchInternalField() for fvsPatchField. " << "Nothing done for patch " << patch.name() << " but setting it to " << pTraits<T>::zero << endl; pf==pTraits<T>::zero; } } } } // Code duplication from above ... maybe there is a better way template<class T> void FieldValueExpressionDriver::setValuePatches ( GeometricField<T,pointPatchField,pointMesh> &field, bool keepPatches, const wordList &fixedPatches ) { typename GeometricField<T,pointPatchField,pointMesh>::GeometricBoundaryField &bf=field.boundaryField(); List<pointPatchField<T> *>bfNew(bf.size()); forAll(bf,patchI) { const pointPatch &patch=bf[patchI].patch(); bool isValuePatch=false; forAll(fixedPatches,i) { if(fixedPatches[i]==patch.name()) { isValuePatch=true; } } if( ( !keepPatches || isValuePatch ) && ( canBeValuePatch(patch) ) ) { if( typeid(field.boundaryField()[patchI]) == typeid(fixedValuePointPatchField<T>) ) { pointPatchField<T> &pf=field.boundaryField()[patchI]; pf==pf.patchInternalField(); } } } } template<class FType> inline tmp<FType> FieldValueExpressionDriver::makeField( const Field<typename FType::value_type> &val ) { return makeFieldInternal<FType>( val, this->mesh() ); } template<class FType> inline tmp<FType> FieldValueExpressionDriver::makePointField( const Field<typename FType::value_type> &val ) { return makeFieldInternal<FType>( val, this->pMesh() ); } template<class FType,class Mesh> inline tmp<FType> FieldValueExpressionDriver::makeFieldInternal( const Field<typename FType::value_type> &val, const Mesh &actualMesh ) { std::ostringstream buff; buff << "field" << pTraits<typename FType::value_type>::typeName; tmp<FType> f( new FType( IOobject ( buff.str(), this->time(), this->mesh(), IOobject::NO_READ, IOobject::NO_WRITE, false // don't register ), actualMesh, pTraits<typename FType::value_type>::zero, "zeroGradient" ) ); if(val.size()!=f->internalField().size()) { FatalErrorInFunction << "Size " << val.size() << " of the assigned field is not the required " << f->internalField().size() << endl << exit(FatalError); } f->internalField()=val; correctField(f); return f; } template<class FType> inline tmp<FType> FieldValueExpressionDriver::makeConstantField( const typename FType::value_type &val, bool makeValuePatches ) { return makeConstantFieldInternal<FType>( val, mesh_, makeValuePatches ); } template<class FType> inline tmp<FType> FieldValueExpressionDriver::makePointConstantField( const typename FType::value_type &val, bool makeValuePatches ) { return makeConstantFieldInternal<FType>( val, this->pMesh(), makeValuePatches ); } template<class FType,class Mesh> inline tmp<FType> FieldValueExpressionDriver::makeConstantFieldInternal( const typename FType::value_type &val, const Mesh &mesh, bool makeValuePatches ) { std::ostringstream buff; buff << "constant" << pTraits<typename FType::value_type>::typeName; word defaultBC="calculated"; if(pTraits<typename FType::PatchFieldType>::typeName=="fvPatchField") { defaultBC="zeroGradient"; } if(makeValuePatches) { defaultBC="fixedValue"; } tmp<FType> f( new FType( IOobject ( buff.str(), time(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE, false // don't register ), mesh, val, defaultBC ) ); if(pTraits<typename FType::PatchFieldType>::typeName=="fvsPatchField") { setCalculatedPatches(f(),val); } return f; } template<class T> void FieldValueExpressionDriver::setResult( T *r, bool isSurfaceField,bool isPointField ) { resultField_.reset(r); // T &result=dynamicCast<T &>(resultField_()); // doesn't work with gcc 4.2 T &result=dynamic_cast<T &>(resultField_()); if(!resultDimension_.dimensionless()) { result.dimensions().reset(resultDimension_); } typ_=pTraits<T>::typeName; this->result().setResult(result.internalField(),isPointField); isLogical_=false; isSurfaceField_=isSurfaceField; isPointField_=isPointField; } template<class T> void FieldValueExpressionDriver::setLogicalResult( T *r, bool isSurfaceField, bool isPointField ) { resultField_.reset(r); // T &result=dynamicCast<T &>(resultField_()); // doesn't work with gcc 4.2 T &result=dynamic_cast<T &>(resultField_()); if(!resultDimension_.dimensionless()) { result.dimensions().reset(resultDimension_); } typ_=pTraits<bool>::typeName; Field<bool> yesOrNo(result.internalField().size()); forAll(yesOrNo,i) { yesOrNo[i]=mag(result.internalField()[i])>SMALL; } this->result().setResult(yesOrNo,isPointField); isLogical_=true; isSurfaceField_=isSurfaceField; isPointField_=isPointField; } template<class T> struct FieldValueExpressionDriver::correctBC { inline void operator()(const T &val) { if(debug) { Info << "No way to correct BC for type " << pTraits<T>:: typeName << endl; } // Doing nothing } }; template<class T> struct FieldValueExpressionDriver::correctBC<GeometricField<T,fvPatchField,volMesh> > { typedef GeometricField<T,fvPatchField,volMesh> theType; inline void operator()(const theType &val) { if(debug) { Info << "Correcting BC for " << val.name() << " of type " << pTraits<theType>::typeName << endl; } const_cast<theType&>( val ).correctBoundaryConditions(); } }; template<class T> struct FieldValueExpressionDriver::correctBC<GeometricField<T,pointPatchField,pointMesh> > { typedef GeometricField<T,pointPatchField,pointMesh> theType; inline void operator()(const theType &val) { if(debug) { Info << "Correcting BC for " << val.name() << " of type " << pTraits<theType>::typeName << endl; } const_cast<theType&>( val ).correctBoundaryConditions(); } }; template<class T> const T &FieldValueExpressionDriver::getResult(bool correct) const { if(!resultField_.valid()) { FatalErrorInFunction << "When asking for a " << pTraits<T>::typeName << ": No result present" << endl << exit(FatalError); } // return dynamicCast<const T &>(resultField_()); // doesn't work with gcc 4.2 const T &result=dynamic_cast<const T &>(resultField_()); if(correct) { correctBC<T>()(result); } return result; } template<class T> bool FieldValueExpressionDriver::resultIsTyp(bool isLogical) { if(!resultField_.valid()) { FatalErrorInFunction << "When asking for a " << pTraits<T>::typeName << ": No result present" << endl << exit(FatalError); } return ( resultField_().type() == pTraits<T>::typeName && isLogical == isLogical_ ); } template<class Type> inline autoPtr<GeometricField<Type,pointPatchField,pointMesh> > FieldValueExpressionDriver::cellToPointInterpolate( const GeometricField<Type,fvPatchField,volMesh> &field ) { typedef GeometricField<Type,pointPatchField,pointMesh> rType; volPointInterpolation interpol(this->mesh()); return autoPtr<rType>(interpol.interpolate(field).ptr()); } template<class Type> inline autoPtr<GeometricField<Type,fvPatchField,volMesh> > FieldValueExpressionDriver::pointToCellInterpolate( const GeometricField<Type,pointPatchField,pointMesh> &field ) { typedef GeometricField<Type,fvPatchField,volMesh> rType; autoPtr<rType> result( this->makeConstantField<rType>(pTraits<Type>::zero).ptr() ); forAll(result(),cellI) { result()[cellI]=interpolatePointToCell(field,cellI); } result->correctBoundaryConditions(); return result; } } // end namespace #endif
25.250305
116
0.615377
[ "mesh" ]
091eab1b66bc0752f915337de0c4dd08ce11445e
614
cpp
C++
leetcode/1306.jump-game-iii.cpp
pepper99/competitive-programming
dd1f610a76d9a8c199cd002359735d01c6604036
[ "MIT" ]
null
null
null
leetcode/1306.jump-game-iii.cpp
pepper99/competitive-programming
dd1f610a76d9a8c199cd002359735d01c6604036
[ "MIT" ]
null
null
null
leetcode/1306.jump-game-iii.cpp
pepper99/competitive-programming
dd1f610a76d9a8c199cd002359735d01c6604036
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=1306 lang=cpp * * [1306] Jump Game III */ // @lc code=start class Solution { public: bool canReach(vector<int>& arr, int start) { vector<bool> vs(arr.size()); queue<int> q; q.push(start); while(!q.empty()) { int x = q.front(); q.pop(); if(arr[x] == 0) return true; vs[x] = true; if(x - arr[x] >= 0 && !vs[x - arr[x]]) q.push(x - arr[x]); if(x + arr[x] < arr.size() && !vs[x + arr[x]]) q.push(x + arr[x]); } return false; } }; // @lc code=end
21.928571
78
0.433225
[ "vector" ]
091f4494c2266f00aae636888120eeff61c43961
16,444
cpp
C++
sox/presentation/presentation/presentation.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
sox/presentation/presentation/presentation.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
sox/presentation/presentation/presentation.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
#include "presentation.h" #include "../post/post.h" #include <snakeoil/gfx/render/render_2d.h> #include <snakeoil/gfx/text/text_render_2d.h> #include <snakeoil/gfx/plugs/framebuffer/predef_framebuffer.h> #include <snakeoil/gpx/system/render_system.h> #include <snakeoil/gpu/viewport/viewport_2d.h> #include <snakeoil/math/utility/3d/orthographic_projection.hpp> #include <snakeoil/log/global.h> using namespace sox_presentation ; //********************************************************* bool_t presentation::page_info::on_load( void_t ) { if( !loaded ) loaded = pptr->on_load() ; return loaded ; } //********************************************************* void_t presentation::page_info::on_unload( void_t ) { if( so_log::global_t::error( inited, "[presentation::page_info] : call on_release first" ) ) return ; if( loaded ) { loaded = so_core::is_not( pptr->on_unload() ) ; } } //********************************************************* bool_t presentation::page_info::on_init( void_t ) { if( !inited ) { inited = pptr->on_init() ; } return inited ; } //********************************************************* bool_t presentation::page_info::on_release( void_t ) { if( inited ) { inited = so_core::is_not( pptr->on_release() ) ; } return inited ; } //********************************************************* bool_t presentation::page_info::do_update( update_data_in_t ud ) { if( !on_load() ) return false ; if( !on_init() ) return false ; pptr->on_update( ud ) ; return true ; } //********************************************************* bool_t presentation::page_info::do_render( render_data_in_t rd ) { if( !on_load() ) return false ; if( !on_init() ) return false ; pptr->on_render( rd ) ; return true ; } // transition info // //********************************************************* bool_t presentation::transition_info::on_load( void_t ) { if( !loaded ) loaded = pptr->on_load() ; return loaded ; } //********************************************************* void_t presentation::transition_info::on_unload( void_t ) { if( loaded ) { loaded = so_core::is_not( pptr->on_unload() ) ; } } //********************************************************* bool_t presentation::transition_info::on_init( void_t ) { if( !inited ) { inited = pptr->on_init() ; } return inited ; } //********************************************************* bool_t presentation::transition_info::on_release( void_t ) { if( inited ) { inited = so_core::is_not( pptr->on_release() ) ; } return inited ; } //********************************************************* bool_t presentation::transition_info::on_clear( void_t ) const { return pptr->on_clear() ; } //********************************************************* bool_t presentation::transition_info::do_update( update_data_in_t ud ) { if( !on_load() ) return false ; if( !on_init() ) return false ; pptr->on_update( ud ) ; return true ; } //********************************************************* bool_t presentation::transition_info::do_render( itransition::render_type const rt, render_data_in_t rd ) { if( !on_load() ) return false ; if( !on_init() ) return false ; pptr->on_render( rt, rd ) ; return true ; } //********************************************************* presentation::presentation( so_gpx::render_system_ptr_t ptr ) noexcept { _rs = ptr ; _fb_c0 = so_gfx::predef_framebuffer_t::create( so_gfx::predef_framebuffer_t( so_gfx::predef_framebuffer_type::color888_alpha8_depth32, _rs ), "[presentation::presentation] : predef framebuffer" ) ; _fb_c1 = so_gfx::predef_framebuffer_t::create( so_gfx::predef_framebuffer_t( so_gfx::predef_framebuffer_type::color888_alpha8_depth32, _rs ), "[presentation::presentation] : predef framebuffer" ) ; _fb_cx = so_gfx::predef_framebuffer_t::create( so_gfx::predef_framebuffer_t( so_gfx::predef_framebuffer_type::color888_alpha8_depth32, _rs ), "[presentation::presentation] : predef framebuffer" ) ; _fb_cm = so_gfx::predef_framebuffer_t::create( so_gfx::predef_framebuffer_t( so_gfx::predef_framebuffer_type::color888_alpha8, _rs ), "[presentation::presentation] : predef framebuffer" ) ; _fb_blt = so_gfx::predef_framebuffer_t::create( so_gfx::predef_framebuffer_t( so_gfx::predef_framebuffer_type::invalid, _rs ), "[presentation::presentation] : predef framebuffer blt" ) ; _post = sox_presentation::post_t::create( sox_presentation::post_t(_rs ), "[presentation::presentation] : sox_presentation::post_t" ) ; _rnd_2d = so_gfx::render_2d_t::create( so_gfx::render_2d_t( _rs ), "[presentation::presentation] : so_gfx::render_2d_t" ) ; _txt_rnd = so_gfx::text_render_2d_t::create( so_gfx::text_render_2d_t( _rs ), "[presentation::presentation] : so_gfx::render_2d_t" ) ; } //********************************************************* presentation::presentation( this_rref_t rhv ) noexcept { _pages = std::move( rhv._pages ) ; _transitions = std::move( rhv._transitions ) ; _cur_index = rhv._cur_index ; _tgt_index = rhv._tgt_index ; so_move_member_ptr( _fb_c0, rhv ) ; so_move_member_ptr( _fb_c1, rhv ) ; so_move_member_ptr( _fb_cx, rhv ) ; so_move_member_ptr( _fb_cm, rhv ) ; so_move_member_ptr( _fb_blt, rhv ) ; so_move_member_ptr( _post, rhv ) ; so_move_member_ptr( _rnd_2d, rhv ) ; so_move_member_ptr( _txt_rnd, rhv ) ; _vp = rhv._vp ; } //********************************************************* presentation::~presentation( void_t ) noexcept { for( auto & item : _pages ) { item.pptr->destroy() ; } for( auto item : _transitions ) { item.pptr->destroy() ; } so_gfx::predef_framebuffer_t::destroy( _fb_c0 ) ; so_gfx::predef_framebuffer_t::destroy( _fb_c1 ) ; so_gfx::predef_framebuffer_t::destroy( _fb_cx ) ; so_gfx::predef_framebuffer_t::destroy( _fb_cm ) ; so_gfx::predef_framebuffer_t::destroy( _fb_blt ) ; so_gfx::render_2d_t::destroy( _rnd_2d ) ; so_gfx::text_render_2d_t::destroy( _txt_rnd ) ; sox_presentation::post_t::destroy( _post ) ; } //********************************************************* presentation::this_ptr_t presentation::create( this_rref_t rhv, so_memory::purpose_cref_t p ) noexcept { return so_memory::global_t::alloc( std::move( rhv ), p ) ; } //********************************************************* void_t presentation::destroy( this_ptr_t ptr ) noexcept { so_memory::global_t::dealloc( ptr ) ; } //********************************************************* void_t presentation::init( so_gpu::viewport_2d_cref_t vp, so_io::path_cref_t path ) noexcept { _vp = vp ; _fb_c0->init( "presentation.scene.0", _vp.get_width(), _vp.get_height() ) ; _fb_c0->schedule_for_init() ; _fb_c1->init( "presentation.scene.1", _vp.get_width(), _vp.get_height() ) ; _fb_c1->schedule_for_init() ; _fb_cx->init( "presentation.cross", _vp.get_width(), _vp.get_height() ) ; _fb_cx->schedule_for_init() ; _fb_cm->init( "presentation.mask", _vp.get_width(), _vp.get_height() ) ; _fb_cm->schedule_for_init() ; _fb_blt->init( "scene", _vp.get_width(), _vp.get_height(), 0 ) ; _post->init( "presentation.scene.0", "presentation.scene.1", "presentation.cross", "presentation.mask", "" ) ; _rnd_2d->init() ; _txt_rnd->init_fonts( 50, { path } ) ; } //********************************************************* void_t presentation::render( void_t ) noexcept { { so_gfx::text_render_2d_t::canvas_info_t ci ; ci.vp = _vp ; // so_gpu::viewport_2d_t( 0, 0, 1920, 1080 ) ; _txt_rnd->set_canvas_info( ci ) ; //_txt_rnd->set_view_projection( so_math::mat4f_t().identity(), //so_math::mat4f_t().identity() ) ; // so_math::so_3d::orthographic<float_t>::create( 1920.0f, 1080.0f, 0.1f, 1000.0f ) ) ; } render_data_t rd ; rd.rnd_2d = _rnd_2d ; rd.txt_rnd = _txt_rnd ; size_t layer_start = 0 ; size_t layer_end = 10 ; _rnd_2d->prepare_for_rendering() ; _txt_rnd->prepare_for_rendering() ; // 1. do current page { this_t::cur_page( [&] ( page_info_ref_t pi ) { layer_start = 0 ; layer_end = 10 ; _fb_c0->set_clear_color( so_math::vec4f_t(1.0f, 1.0f, 1.0f, 1.0f) ) ; _fb_c0->schedule_for_begin() ; _fb_c0->schedule_for_clear() ; pi.do_render( rd ) ; for( size_t i=layer_start; i<=layer_end; ++i ) { rd.rnd_2d->render( i ) ; rd.txt_rnd->render( i ) ; } _fb_c0->schedule_for_end() ; } ) ; } // 2. do transition if( this_t::in_transition() ) { bool_t const res = this_t::cur_transition( [&] ( transition_info_ref_t ti ) { { layer_start = layer_end + 1 ; layer_end = layer_start + 10 ; _fb_cx->set_clear_color( so_math::vec4f_t( 1.0f,1.0f,1.0f,1.0f ) ) ; _fb_cx->schedule_for_begin() ; _fb_cx->schedule_for_clear() ; ti.do_render( itransition::render_type::scene, rd ) ; for( size_t i = layer_start; i <= layer_end; ++i ) { rd.rnd_2d->render( i ) ; rd.txt_rnd->render( i ) ; } _fb_cx->schedule_for_end() ; } { _fb_cm->schedule_for_begin() ; if( ti.on_clear() ) _fb_cm->schedule_for_clear() ; ti.do_render( itransition::render_type::mask, rd ) ; _fb_cm->schedule_for_end() ; } } ) ; } // 3. do next page if( this_t::in_transition() ) { layer_start = layer_end + 1 ; layer_end = layer_start + 10 ; this_t::tgt_page( [&] ( page_info_ref_t pi ) { _fb_c1->set_clear_color( so_math::vec4f_t( 1.0f, 1.0f, 1.0f, 1.0f ) ) ; _fb_c1->schedule_for_begin() ; _fb_c1->schedule_for_clear() ; pi.do_render( rd ) ; //#if 0 for( size_t i = layer_start; i <= layer_end; ++i ) { rd.rnd_2d->render( i ) ; rd.txt_rnd->render( i ) ; } //#endif _fb_c1->schedule_for_end() ; } ) ; } // 4. do post { _fb_blt->schedule_for_begin() ; _post->render( this_t::in_transition() ) ; } } //********************************************************* void_t presentation::update( void_t ) noexcept { auto const dt = std::chrono::duration_cast<std::chrono::microseconds>( so_core::clock_t::now() - _utime ) ; _utime = so_core::clock_t::now() ; update_data_t ud ; ud.rnd_2d = _rnd_2d ; ud.txt_rnd = _txt_rnd ; // 0. check for abort transition if( _abort_transition ) { change_to_target() ; _abort_transition = false ; } std::chrono::microseconds dur(0) ; // x. check transition if( this_t::in_transition() ) { this_t::cur_transition( [&] ( transition_info_ref_t ti ) { dur = std::chrono::duration_cast< std::chrono::microseconds >( ti.pptr->get_duration() ) ; } ) ; // is transition done? if( _tdur > dur ) { change_to_target() ; _tdur = std::chrono::microseconds( 0 ) ; } } // 1. do current page { ud.layer_start = 0 ; ud.layer_end = 10 ; this_t::cur_page( [&] ( page_info_ref_t pi ) { pi.do_update( ud ) ; } ) ; } // 2. do transition { this_t::cur_transition( [&] ( transition_info_ref_t ti ) { ti.on_load() ; } ) ; if( this_t::in_transition() ) { ud.layer_start = ud.layer_end + 1 ; ud.layer_end = ud.layer_start + 10 ; ud.ms = std::chrono::duration_cast<std::chrono::milliseconds>(_tdur) ; this_t::cur_transition( [&] ( transition_info_ref_t ti ) { ti.do_update( ud ) ; } ) ; } } // 3. do target page { this_t::tgt_page( [&] ( page_info_ref_t pi ) { pi.on_load() ; if( this_t::in_transition() ) { ud.layer_start = ud.layer_end + 1 ; ud.layer_end = ud.layer_start + 10 ; pi.do_update( ud ) ; } } ) ; } // 4. guess to load the next page { this_t::nxt_page( [&] ( page_info_ref_t pi ) { pi.on_load() ; } ) ; } // 5. do unload { size_t i ; if( this_t::cur_index( i ) && i > 2 ) { _pages[ i - 2 ].on_unload() ; } } // 6. update transition duration { auto const tmp = _tdur + dt ; _tdur = _tdur != dur && tmp > dur ? dur : tmp ; } } //********************************************************* void_t presentation::release( void_t ) { for( auto & item : _pages ) { item.pptr->on_release() ; item.pptr->on_unload() ; } for( auto item : _transitions ) { item.pptr->on_release() ; item.pptr->on_unload() ; } _fb_c0->schedule_for_release() ; _fb_c1->schedule_for_release() ; _fb_cx->schedule_for_release() ; _fb_cm->schedule_for_release() ; } //********************************************************* void_t presentation::change_to_target( void_t ) noexcept { this_t::cur_page( [&] ( page_info_ref_t pi ) { pi.on_release() ; } ) ; this_t::cur_transition( [&] ( transition_info_ref_t ti ) { ti.on_release() ; } ) ; _cur_index = _tgt_index ; this_t::cur_page( [&] ( page_info_ref_t pi ) { pi.on_init() ; } ) ; } //********************************************************* void_t presentation::add_page( sox_presentation::ipage_utr_t pptr ) noexcept { { auto const iter = std::find_if( _pages.begin(), _pages.end(), [&]( page_info_cref_t item ) { return item.pptr == pptr ; } ) ; if( iter != _pages.end() ) return ; } { this_t::page_info_t pi ; pi.loaded = false ; pi.pptr = pptr ; _pages.emplace_back( pi ) ; } if( _cur_index == size_t( -1 ) ) { _cur_index = 0 ; _tgt_index = 0 ; } } //********************************************************* void_t presentation::add_transition( sox_presentation::itransition_utr_t ptr ) noexcept { { auto const iter = std::find_if( _transitions.begin(), _transitions.end(), [&]( transition_info_cref_t item ) { return item.pptr == ptr ; } ) ; if( iter != _transitions.end() ) return ; } { this_t::transition_info_t i ; i.loaded = false ; i.pptr = ptr ; _transitions.emplace_back( i ) ; } } //********************************************************* bool_t presentation::next_page( void_t ) noexcept { if( this_t::in_transition() ) { _abort_transition = true ; } else { this_t::nxt_index( _tgt_index ) ; } _tdur = std::chrono::microseconds( 0 ) ; return _tgt_index != size_t( -1 ) ; } //********************************************************* bool_t presentation::prev_page( void_t ) noexcept { if( this_t::in_transition() ) { _abort_transition = true ; } else { this_t::prv_index( _tgt_index ) ; } _tdur = std::chrono::microseconds( 0 ) ; return _tgt_index != size_t( -1 ) ; } //********************************************************* bool_t presentation::change_page( size_t const ) noexcept { return false ; }
26.957377
102
0.511372
[ "render", "3d" ]
0920708c286930ace9c8b20ddda57863398f1c02
8,545
cpp
C++
code/engine/xrGame/aimers_base.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/engine/xrGame/aimers_base.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/engine/xrGame/aimers_base.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
//////////////////////////////////////////////////////////////////////////// // Module : aimers_base.cpp // Created : 04.04.2008 // Modified : 08.04.2008 // Author : Dmitriy Iassenev // Description : aimers base class //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "aimers_base.h" #include "gameobject.h" #include "xrRender/kinematics.h" #include "animation_movement_controller.h" using aimers::base; base::base(CGameObject* object, LPCSTR animation_id, bool animation_start, Fvector const& target) : m_object(*object), m_kinematics(smart_cast<IKinematics&>(*object->Visual())), m_animated(smart_cast<IKinematicsAnimated&>(*object->Visual())), m_target(target), m_animation_id(m_animated.LL_MotionID(animation_id)), m_animation_start(animation_start) { animation_movement_controller const* controller = m_object.animation_movement(); if (!controller) m_start_transform = m_object.XFORM(); else m_start_transform = controller->start_transform(); VERIFY(xr::valid(m_start_transform)); } void base::callback(CBoneInstance* bone) { VERIFY(bone); Fmatrix* rotation = static_cast<Fmatrix*>(bone->callback_param()); VERIFY(rotation); VERIFY2(xr::valid(*rotation), "base::callback[rotation] "); Fvector position = bone->mTransform.c; bone->mTransform.mulA_43(*rotation); bone->mTransform.c = position; VERIFY2(xr::valid(bone->mTransform), "base::callback "); } void base::aim_at_position(Fvector const& bone_position, Fvector const& object_position, Fvector object_direction, Fmatrix& result) { #if 0 Msg ( "[%d][%s] bone_position[%f][%f][%f] object_position[%f][%f][%f] object_direction[%f][%f][%f]", Device.dwFrame, m_animated.LL_MotionDefName_dbg(m_animation_id).first, VPUSH(bone_position), VPUSH(object_position), VPUSH(object_direction) ); #endif // #if 0 VERIFY2(xr::valid(bone_position), make_string("[%f][%f][%f]", VPUSH(bone_position))); VERIFY2(xr::valid(object_position), make_string("[%f][%f][%f]", VPUSH(object_position))); VERIFY2(xr::valid(object_direction), make_string("[%f][%f][%f]", VPUSH(object_direction))); VERIFY2(xr::valid(m_target), make_string("[%f][%f][%f]", VPUSH(m_target))); VERIFY2(object_direction.square_magnitude() > EPS_L, make_string("[%f]", object_direction.square_magnitude())); object_direction.normalize(); Fvector const object2bone = Fvector().sub(bone_position, object_position); VERIFY(xr::valid(object2bone)); float const offset = object2bone.dotproduct(object_direction); VERIFY(xr::valid(offset)); Fvector const current_point = Fvector().mad(object_position, object_direction, offset); VERIFY(xr::valid(current_point)); Fvector bone2current = Fvector().sub(current_point, bone_position); VERIFY(xr::valid(bone2current)); if (bone2current.magnitude() < EPS_L) bone2current.set(0.f, 0.f, EPS_L); VERIFY(xr::valid(bone2current)); float const sphere_radius_sqr = bone2current.square_magnitude(); VERIFY(xr::valid(sphere_radius_sqr)); Fvector direction_target = Fvector().sub(m_target, bone_position); VERIFY(xr::valid(direction_target)); if (direction_target.magnitude() < EPS_L) direction_target.set(0.f, 0.f, EPS_L); VERIFY(xr::valid(direction_target)); float const invert_magnitude = 1.f / direction_target.magnitude(); direction_target.mul(invert_magnitude); VERIFY2(fsimilar(direction_target.magnitude(), 1.f), make_string("[%f][%f] [%f][%f][%f] [%f][%f][%f]", direction_target.magnitude(), invert_magnitude, VPUSH(m_target), VPUSH(bone_position))); float const to_circle_center = sphere_radius_sqr * invert_magnitude; VERIFY(xr::valid(to_circle_center)); Fvector const circle_center = Fvector().mad(bone_position, direction_target, to_circle_center); VERIFY(xr::valid(circle_center)); Fplane const plane = Fplane().build(circle_center, direction_target); VERIFY2(xr::valid(plane), make_string("[%f][%f][%f] [%f][%f][%f] [%f][%f][%f] %f", VPUSH(circle_center), VPUSH(direction_target), VPUSH(plane.n), plane.d)); Fvector projection; plane.project(projection, current_point); VERIFY(xr::valid(projection)); Fvector projection2circle_center = Fvector().sub(projection, circle_center); VERIFY(xr::valid(projection2circle_center)); if (projection2circle_center.magnitude() < EPS_L) projection2circle_center.set(0.f, 0.f, EPS_L); VERIFY(xr::valid(projection2circle_center)); Fvector const center2projection_direction = projection2circle_center.normalize(); VERIFY(xr::valid(center2projection_direction)); float circle_radius_sqr = sphere_radius_sqr - xr::sqr(to_circle_center); VERIFY(xr::valid(circle_radius_sqr)); if (circle_radius_sqr < 0.f) circle_radius_sqr = 0.f; VERIFY(xr::valid(circle_radius_sqr)); float const circle_radius = std::sqrt(circle_radius_sqr); VERIFY(xr::valid(circle_radius)); Fvector const target_point = Fvector().mad(circle_center, center2projection_direction, circle_radius); VERIFY(xr::valid(target_point)); Fvector const current_direction = Fvector(bone2current).normalize(); VERIFY(xr::valid(current_direction)); Fvector target2bone = Fvector().sub(target_point, bone_position); VERIFY(xr::valid(target2bone)); if (target2bone.magnitude() < EPS_L) target2bone.set(0.f, 0.f, EPS_L); VERIFY(xr::valid(target2bone)); Fvector const target_direction = target2bone.normalize(); VERIFY(xr::valid(target_direction)); Fmatrix transform0; { Fvector cross_product = Fvector().crossproduct(current_direction, target_direction); VERIFY(xr::valid(cross_product)); float const sin_alpha = clampr(cross_product.magnitude(), -1.f, 1.f); if (!fis_zero(sin_alpha)) { float cos_alpha = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f); transform0.rotation(cross_product.div(sin_alpha), atan2f(sin_alpha, cos_alpha)); VERIFY(xr::valid(transform0)); } else { float const dot_product = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f); if (fsimilar(xr::abs(dot_product), 0.f)) transform0.identity(); else { VERIFY(fsimilar(xr::abs(dot_product), 1.f)); cross_product.crossproduct(current_direction, direction_target); float const sin_alpha2 = clampr(cross_product.magnitude(), -1.f, 1.f); if (!fis_zero(sin_alpha2)) { transform0.rotation(cross_product.div(sin_alpha2), dot_product > 0.f ? 0.f : PI); VERIFY(xr::valid(transform0)); } else { transform0.rotation(Fvector().set(0.f, 0.f, 1.f), dot_product > 0.f ? 0.f : PI); VERIFY(xr::valid(transform0)); } } } } Fmatrix transform1; { Fvector target2target_point = Fvector().sub(m_target, target_point); if (target2target_point.magnitude() < EPS_L) target2target_point.set(0.f, 0.f, EPS_L); Fvector const new_direction = target2target_point.normalize(); Fvector old_direction; transform0.transform_dir(old_direction, object_direction); Fvector cross_product = Fvector().crossproduct(old_direction, new_direction); float const sin_alpha = clampr(cross_product.magnitude(), -1.f, 1.f); if (!fis_zero(sin_alpha)) { float const cos_alpha = clampr(old_direction.dotproduct(new_direction), -1.f, 1.f); transform1.rotation(cross_product.div(sin_alpha), atan2f(sin_alpha, cos_alpha)); } else { float const dot_product = clampr(current_direction.dotproduct(target_direction), -1.f, 1.f); if (fsimilar(xr::abs(dot_product), 0.f)) transform1.identity(); else { VERIFY(fsimilar(xr::abs(dot_product), 1.f)); transform1.rotation(target_direction, dot_product > 0.f ? 0.f : PI); } } } VERIFY(xr::valid(transform0)); VERIFY(xr::valid(transform1)); result.mul_43(transform1, transform0); VERIFY(xr::valid(result)); }
43.375635
100
0.649503
[ "object" ]
0923d51a3fe5f22d058494f864f164d350a30f57
2,126
hpp
C++
rayt-cpp/hittable_list.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
11
2020-07-04T13:35:10.000Z
2022-03-30T17:34:27.000Z
rayt-cpp/hittable_list.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
null
null
null
rayt-cpp/hittable_list.hpp
gkmngrgn/rayt
726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a
[ "CC0-1.0", "MIT" ]
2
2021-03-02T06:31:43.000Z
2022-03-30T17:34:28.000Z
#ifndef HITTABLE_LIST_HPP #define HITTABLE_LIST_HPP //============================================================================== // Originally written in 2016 by Peter Shirley <ptrshrl@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy (see file COPYING.txt) of the CC0 Public // Domain Dedication along with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== #include "hittable.hpp" #include "utils.hpp" #include <vector> class hittable_list : public hittable { public: hittable_list() {} hittable_list(shared_ptr<hittable> object) { add(object); } void clear() { objects.clear(); } void add(shared_ptr<hittable> object) { objects.push_back(object); } virtual bool hit(const ray &r, double tmin, double tmax, hit_record &rec) const override; virtual bool bounding_box(double t0, double t1, aabb &output_box) const override; public: std::vector<shared_ptr<hittable>> objects; }; bool hittable_list::hit(const ray &r, double t_min, double t_max, hit_record &rec) const { hit_record temp_rec; auto hit_anything = false; auto closest_so_far = t_max; for (const auto &object : objects) { if (object->hit(r, t_min, closest_so_far, temp_rec)) { hit_anything = true; closest_so_far = temp_rec.t; rec = temp_rec; } } return hit_anything; } bool hittable_list::bounding_box(double t0, double t1, aabb &output_box) const { if (objects.empty()) { return false; } aabb temp_box; bool first_box = true; for (const auto &object : objects) { if (!object->bounding_box(t0, t1, temp_box)) { return false; } output_box = first_box ? temp_box : surrounding_box(output_box, temp_box); first_box = false; } return true; } #endif
27.973684
80
0.632643
[ "object", "vector" ]