blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
fe561508ee97fe3a1076a09914b9db3eed7e30fa
d0ff60631a8d4bbf6ecfe5ad3a9672a29e56467b
/InitialSetup.cpp
393eddd540320fa0b550202ed8da5245e9778403
[ "Apache-2.0" ]
permissive
erhoof/Hardy-u_t5-qt-3
46c47a30e33942c02b7bcdc5327d2c4fd6c30266
47fd313cdd44f5cc5c8c93e3536032f5dff905cd
refs/heads/master
2023-04-03T21:31:18.347051
2021-04-13T10:00:23
2021-04-13T10:00:23
301,150,615
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
InitialSetup.cpp
#include "InitialSetup.h" #include "ui_InitialSetup.h" #include "HardDriveInfo.h" #include "MainWindow.h" InitialWindow::InitialWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::InitialWindow) { ui->setupUi(this); } InitialWindow::~InitialWindow() { delete ui; } void InitialWindow::on_pushButton_next_clicked() { switch(ui->stackedWidget->currentIndex()) { case 0: ui->stackedWidget->setCurrentIndex(1); ui->pushButton_prev->setEnabled(true); break; case 1: { auto info = new HardDriveInfo(); info->m_accessTime = ui->lineEdit_accessTime->text().toFloat(); info->m_rotationDelay = ui->lineEdit_rotationDelay->text().toFloat(); info->m_transferSpeed = ui->lineEdit_transferSpeed->text().toFloat(); info->m_cylinders = ui->lineEdit_cylinders->text().toInt(); info->m_heads = ui->lineEdit_heads->text().toInt(); info->m_sectors = ui->lineEdit_sectors->text().toInt(); auto mainWindow = new MainWindow(this, info); mainWindow->show(); hide(); break; } default: break; } } void InitialWindow::on_pushButton_prev_clicked() { ui->stackedWidget->setCurrentIndex(0); ui->pushButton_prev->setEnabled(false); }
2d4e1a64d5a93fdb7e86fe9add099ba403afdece
1c024dfbca35f4c829d4b47bdfe900d1b1a2303b
/shell/common/gin_helper/promise.h
6acf9b49ea24885609afac5c86655250e02c96f0
[ "MIT" ]
permissive
electron/electron
1ba6e31cf40f876044bff644ec49f8ec4923ca6a
0b0707145b157343c42266d2586ed9413a1d54f5
refs/heads/main
2023-09-01T04:28:11.016383
2023-08-31T14:36:43
2023-08-31T14:36:43
9,384,267
99,768
18,388
MIT
2023-09-14T19:50:49
2013-04-12T01:47:36
C++
UTF-8
C++
false
false
6,284
h
promise.h
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_ #include <string> #include <tuple> #include <type_traits> #include <utility> #include "base/memory/raw_ptr.h" #include "base/strings/string_piece.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/common/gin_converters/std_converter.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/process_util.h" namespace gin_helper { // A wrapper around the v8::Promise. // // This is the non-template base class to share code between templates // instances. // // This is a move-only type that should always be `std::move`d when passed to // callbacks, and it should be destroyed on the same thread of creation. class PromiseBase { public: explicit PromiseBase(v8::Isolate* isolate); PromiseBase(v8::Isolate* isolate, v8::Local<v8::Promise::Resolver> handle); PromiseBase(); ~PromiseBase(); // disable copy PromiseBase(const PromiseBase&) = delete; PromiseBase& operator=(const PromiseBase&) = delete; // Support moving. PromiseBase(PromiseBase&&); PromiseBase& operator=(PromiseBase&&); // Helper for rejecting promise with error message. // // Note: The parameter type is PromiseBase&& so it can take the instances of // Promise<T> type. static void RejectPromise(PromiseBase&& promise, base::StringPiece errmsg) { if (electron::IsBrowserProcess() && !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( // Note that this callback can not take StringPiece, // as StringPiece only references string internally and // will blow when a temporary string is passed. [](PromiseBase&& promise, std::string str) { promise.RejectWithErrorMessage(str); }, std::move(promise), std::string(errmsg.data(), errmsg.size()))); } else { promise.RejectWithErrorMessage(errmsg); } } v8::Maybe<bool> Reject(); v8::Maybe<bool> Reject(v8::Local<v8::Value> except); v8::Maybe<bool> RejectWithErrorMessage(base::StringPiece message); v8::Local<v8::Context> GetContext() const; v8::Local<v8::Promise> GetHandle() const; v8::Isolate* isolate() const { return isolate_; } protected: v8::Local<v8::Promise::Resolver> GetInner() const; private: raw_ptr<v8::Isolate> isolate_; v8::Global<v8::Context> context_; v8::Global<v8::Promise::Resolver> resolver_; }; // Template implementation that returns values. template <typename RT> class Promise : public PromiseBase { public: using PromiseBase::PromiseBase; // Helper for resolving the promise with |result|. static void ResolvePromise(Promise<RT> promise, RT result) { if (electron::IsBrowserProcess() && !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([](Promise<RT> promise, RT result) { promise.Resolve(result); }, std::move(promise), std::move(result))); } else { promise.Resolve(result); } } // Returns an already-resolved promise. static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate, RT result) { Promise<RT> resolved(isolate); resolved.Resolve(result); return resolved.GetHandle(); } // Convert to another type. template <typename NT> Promise<NT> As() { return Promise<NT>(isolate(), GetInner()); } // Promise resolution is a microtask // We use the MicrotasksRunner to trigger the running of pending microtasks v8::Maybe<bool> Resolve(const RT& value) { gin_helper::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); gin_helper::MicrotasksScope microtasks_scope( isolate(), GetContext()->GetMicrotaskQueue()); v8::Context::Scope context_scope(GetContext()); return GetInner()->Resolve(GetContext(), gin::ConvertToV8(isolate(), value)); } template <typename... ResolveType> v8::MaybeLocal<v8::Promise> Then( base::OnceCallback<void(ResolveType...)> cb) { static_assert(sizeof...(ResolveType) <= 1, "A promise's 'Then' callback should only receive at most one " "parameter"); static_assert( std::is_same<RT, std::tuple_element_t<0, std::tuple<ResolveType...>>>(), "A promises's 'Then' callback must handle the same type as the " "promises resolve type"); gin_helper::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); v8::Context::Scope context_scope(GetContext()); v8::Local<v8::Value> value = gin::ConvertToV8(isolate(), std::move(cb)); v8::Local<v8::Function> handler = value.As<v8::Function>(); return GetHandle()->Then(GetContext(), handler); } }; // Template implementation that returns nothing. template <> class Promise<void> : public PromiseBase { public: using PromiseBase::PromiseBase; // Helper for resolving the empty promise. static void ResolvePromise(Promise<void> promise); // Returns an already-resolved promise. static v8::Local<v8::Promise> ResolvedPromise(v8::Isolate* isolate); v8::Maybe<bool> Resolve(); }; } // namespace gin_helper namespace gin { template <typename T> struct Converter<gin_helper::Promise<T>> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const gin_helper::Promise<T>& val) { return val.GetHandle(); } // TODO(MarshallOfSound): Implement FromV8 to allow promise chaining // in native land // static bool FromV8(v8::Isolate* isolate, // v8::Local<v8::Value> val, // Promise* out); }; } // namespace gin #endif // ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_
7ff502e8df52e7ed2a8f6b4e9560b0c8d0c66c25
c73dfe12abca9fb5d97379b6e88e762fc11a2d98
/lifo/lifo_allocator.h
78eeba7749afd176015fd7670358b776d3e9adae
[]
no_license
giucamp/mmemo
144467207a515bc43f17f2c675c670712403f8d0
cd0c31225ac08fc046ef27956c81e4ef40efa302
refs/heads/master
2021-01-23T12:16:12.311853
2015-08-23T16:12:26
2015-08-23T16:12:26
38,153,302
0
0
null
null
null
null
UTF-8
C++
false
false
5,723
h
lifo_allocator.h
#ifndef MEMO_LIFO_ALLOC_DEBUG #error MEMO_LIFO_ALLOC_DEBUG must be defined in memo_externals.h #endif namespace memo { /** \class LifoAllocator Class implementing LIFO-ordered allocation services. A LIFO allocator provides allocation\deallocation services with the constrain that only the memory block of top (BOT) can be reallocated or freed. The BOT is the last allocated or resized memory block. After it is freed, the previously allocated block is the new BOT. LifoAllocator is initialized with a memory buffer, which is used to allocate the memory blocks fo the user. If the space remaining in the buffer is not enough to accomplish the alloc or realloc, this class just returns nullptr. LifoAllocator does not provide a deallocation callback, so you have to destroy manually any non-POD object. See also memo::ObjectLifoAllocator. This class is not thread safe. */ class LifoAllocator { public: /// allocation services /// /** default constructor. The memory buffer must be assigned before using the LifoAllocator (see set_buffer) */ LifoAllocator(); /** constructor that assigns soon the memory buffer */ LifoAllocator( void * i_buffer_start_address, size_t i_buffer_length ); /** destroys the allocator. All the allocations are freed. */ ~LifoAllocator(); /** assigns the memory buffer. @param i_buffer_start_address pointer to the first byte in the buffer @param i_buffer_length number of bytes in the buffer */ void set_buffer( void * i_buffer_start_address, size_t i_buffer_length ); /** allocates a new memory block, respecting the requested alignment with an offset from the beginning of the block. If the allocation fails nullptr is returned. If the requested size is zero the return value is a non-null address. The content of the newly allocated block is undefined. @param i_size size of the block in bytes @param i_alignment alignment requested for the block. It must be an integer power of 2 @param i_alignment_offset offset from beginning of the block of the address that respects the alignment @return the address of the first byte in the block, or nullptr if the allocation fails */ void * alloc( size_t i_size, size_t i_alignment, size_t i_alignment_offset ); /** changes the size of the memory block on top of the stack. The content of the memory block is preserved up to the lesser of the new size and the old size, while the content of the newly allocated portion is undefined. The alignment and the offset of the alignment of an existing memory block cannot be changed by realloc. If the reallocation fails false is returned, and the memory block is left unchanged. @param i_address address of the memory block to reallocate. This parameter cannot be nullptr. @param i_new_size new size of the block in bytes @return true if the reallocations succeeds, false otherwise */ bool realloc( void * i_address, size_t i_new_size ); /** deallocates a memory block allocated by alloc or realloc. @param i_address address of the memory block to free. It must be the block on top. It cannot be nullptr. */ void free( void * i_address ); /** resets the allocator, freeing all the allocated memory blocks. */ void free_all(); /// getters /// /** retrieves the beginning of the buffer used to perform allocations. Writing this buffer causes memory corruption. @return pointer to the beginning if the buffer */ const void * get_buffer_start() const; /** retrieves the size of the buffer. @return size of the buffer in bytes */ size_t get_buffer_size() const; /** retrieves the size of the free portion of the buffer, that is the remaining space. @return free space in bytes */ size_t get_free_space() const; /** retrieves the size of the used portion of the buffer, that is the allocated space. @return used space in bytes */ size_t get_used_space() const; #if MEMO_LIFO_ALLOC_DEBUG /** retrieves the numbler of blocks currently allocated. @return number of blocks. */ size_t dbg_get_curr_block_count() const; /** retrieves the last non-freed allocated block, that is the BOT. @return address of the last allocated block. */ void * dbg_get_block_on_top() const; #endif /// tester /// #if MEMO_ENABLE_TEST /** encapsulates a test session to discover bugs in LifoAllocator */ class TestSession { public: /** construct a test session with a lifo allocator */ TestSession( size_t i_buffer_size ); void fill_and_empty_test(); ~TestSession(); private: // internal services /** tries to make an allocation */ bool allocate(); /** tries to deallocate the BOT */ bool reallocate(); /** frees the BOT if it exists */ bool free(); static void check_val( const void * i_address, size_t i_size, uint8_t i_value ); private: // data members struct Allocation { void * m_block; size_t m_block_size; }; std_vector< Allocation >::type m_allocations; LifoAllocator * m_lifo_allocator; void * m_buffer; }; #endif // #if MEMO_ENABLE_TEST private: // not implemented LifoAllocator( const LifoAllocator & ); LifoAllocator & operator = ( const LifoAllocator & ); private: // data members void * m_curr_address, * m_start_address, * m_end_address; #if MEMO_LIFO_ALLOC_DEBUG std_vector< void* >::type m_dbg_allocations; /** debug address stack used to check the LIFO consistency */ static const uint8_t s_dbg_initialized_mem = 0x17; static const uint8_t s_dbg_allocated_mem = 0xAA; static const uint8_t s_dbg_freed_mem = 0xFD; #endif }; } // namespace memo
c0ee31a15e4b3f36b69658822a68811a6d4d30ff
cd0515449a11d4fc8c3807edfce6f2b3e9b748d3
/src/yb/encryption/encryption_test_util.h
f7a1c46b26be84f93191693a4040c82bcd0c3289
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
wwjiang007/yugabyte-db
27e14de6f26af8c6b1c5ec2db4c14b33f7442762
d56b534a0bc1e8f89d1cf44142227de48ec69f27
refs/heads/master
2023-07-20T13:20:25.270832
2023-07-11T08:55:18
2023-07-12T10:21:24
150,573,130
0
0
Apache-2.0
2019-07-23T06:48:08
2018-09-27T10:59:24
C
UTF-8
C++
false
false
1,981
h
encryption_test_util.h
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #pragma once #include "yb/encryption/encryption_util.h" #include "yb/util/slice.h" #include "yb/util/test_util.h" namespace yb { namespace encryption { void DoTest(const std::function<void(size_t, size_t)>& file_op, size_t size); template <typename Writable> void TestWrites(Writable* file, const Slice& data) { DoTest([&](size_t begin, size_t end) { ASSERT_OK(file->Append(Slice(data.data() + begin, end - begin))); }, data.size()); } template <typename BufType, typename Readable> void TestRandomAccessReads(Readable* file, const Slice& data) { auto buf = static_cast<BufType*>(EncryptionBuffer::Get()->GetBuffer(data.size())); DoTest([&](size_t begin, size_t end) { Slice result; ASSERT_OK(file->Read(begin, end - begin, &result, buf)); ASSERT_EQ(result.ToDebugHexString(), Slice(data.data() + begin, end - begin).ToDebugHexString()); }, data.size()); } template <typename BufType, typename Readable> void TestSequentialReads(Readable* file, const Slice& data) { DoTest([&](size_t begin, size_t end) { auto buf = static_cast<BufType*>(EncryptionBuffer::Get()->GetBuffer(data.size())); Slice result; ASSERT_OK(file->Read(end - begin, &result, buf)); ASSERT_EQ(result.ToDebugHexString(), Slice(data.data() + begin, end - begin).ToDebugHexString()); }, data.size()); } } // namespace encryption } // namespace yb
9b0def13ecbec7aa0a744cd41ef329880f993790
1f87cd9f78c3de4795f8d4be0f003e54bb9c4f21
/code/Greedy Tino.cpp
a2703e758ae00476c3bcdc0d4780b45222ced133
[]
no_license
xry224/newcode
83a765f9ca6210cddd3cde80526898c8a0c7062d
3507698e1f6111c93f0f2f92063f6789e51d03c0
refs/heads/master
2020-05-26T14:23:34.068502
2019-09-26T00:32:56
2019-09-26T00:32:56
188,262,830
1
1
null
2019-09-25T10:15:54
2019-05-23T15:41:07
C++
GB18030
C++
false
false
1,044
cpp
Greedy Tino.cpp
#include <iostream> #include <limits.h> #define off 2000 using namespace std; int max(int a, int b) { return a > b ? a : b; } int dp[101][4001]; int main() { int orange[101]; int T; cin >> T; for (int i = 1; i <= T; i++) { int n; cin >> n; int cnt = 0;//统计重0的柑橘的数量 for (int j = 1; j <= n; j++) { cin >> orange[j]; if (orange[j] == 0) { cnt++; } } for (int i = -2000; i <= 2000; i++) { dp[0][i + off] = INT_MIN; } dp[0][0 + off] = 0; for (int i = 1; i <= n; i++) { for (int j = -2000; j <= 2000; j++) { if (j + orange[i] <= 2000 && j - orange[i] >= -2000) { dp[i][j + off] = max(dp[i - 1][j + off], max(dp[i - 1][j + off - orange[i]] + orange[i], dp[i - 1][j + off + orange[i]] + orange[i])); } } } cout << "Case " << i << ": "; if (dp[n][0 + off] == 0) { int ans = cnt == 0 ? -1 : 0; cout << ans << endl; } else { cout << dp[n][0 + off] / 2 << endl; } } return 0; }
383cf6d13fb7e369f084c6322efa90cbe4741eb8
e5d5fa28999bcc6c642bb42dda93afd38e272b81
/POJ/1852 - Ants/solve2.cc
dbada2d2bc842d78200299aea93897176c94c7ed
[]
no_license
chiahsun/problem_solving
cd3105969983d16d3d5d416d4a0d5797d4b58e91
559fafa92dd5516058bdcea82a438eadf5aa1ede
refs/heads/master
2023-02-05T06:11:27.536617
2023-01-26T10:51:23
2023-01-26T10:51:23
30,732,382
3
0
null
null
null
null
UTF-8
C++
false
false
608
cc
solve2.cc
#include <cstdio> #include <algorithm> int main() { int nCase; scanf("%d", &nCase); while (nCase--) { int lenPole, nAnts, x; scanf("%d%d", &lenPole, &nAnts); int least = 0, distance_min = lenPole, distance_max = 0; for (int i = 0; i < nAnts; ++i) { scanf("%d", &x); least = std::max(least, std::min(x, lenPole-x)); distance_min = std::min(distance_min, x); distance_max = std::max(distance_max, x); } printf("%d %d\n", least, std::max(lenPole - distance_min, distance_max)); } return 0; }
b76f97382da9cd514b4fa7397779a75d149eda09
f788b786c4f678060aaf9b1e7704fc3fdbcbfa94
/src/draw_line.cpp
5507f7e9d586eae1882ec375c4fe7f4958cee47f
[ "MIT", "CC-BY-3.0", "Unlicense" ]
permissive
Rapidash99/CGGD-Assignment-1
cf50206124273413ccbf05fa0cec2bce45d172b7
7237df71155c0bf2216b57fa2812373420621f12
refs/heads/main
2023-01-09T04:53:18.080980
2020-11-06T21:13:49
2020-11-06T21:13:49
306,553,570
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
cpp
draw_line.cpp
#include "draw_line.h" #include <cmath> #include <algorithm> #define M_PI 3.14159265358979323846 cg::LineDrawing::LineDrawing(unsigned short width, unsigned short height): cg::ClearRenderTarget(width, height) { } cg::LineDrawing::~LineDrawing() = default; void cg::LineDrawing::DrawLine(unsigned xBegin, unsigned yBegin, unsigned xEnd, unsigned yEnd, color color) { const bool steep = abs((int)yEnd - (int)yBegin) > abs((int)xEnd - (int)xBegin); if (steep) { std::swap(xBegin, yBegin); std::swap(xEnd, yEnd); } if (xBegin > xEnd) { std::swap(xBegin, xEnd); std::swap(yBegin, yEnd); } const float dx = ((float)xEnd - (float)xBegin); const float dy = std::abs((float)yEnd - (float)yBegin); float error = dx / 2.f; const int yStep = (yBegin < yEnd) ? 1 : -1; unsigned y = yBegin; for (unsigned x = xBegin; x <= xEnd; x++) { if (steep) { SetPixel(y, x, color); } else { SetPixel(x, y, color); } error -= dy; if (error < 0) { y += yStep; error += dx; } } } void cg::LineDrawing::DrawScene() { unsigned xCenter = width / 2; unsigned yCenter = height / 2; unsigned radius = std::min(xCenter, yCenter) - 1; for (double angle = 0.0; angle < 360.0; angle += 5.0) { DrawLine( xCenter, yCenter, static_cast<unsigned>(xCenter + radius * cos(angle * M_PI / 180)), static_cast<unsigned>(yCenter + radius * sin(angle * M_PI / 180)), color( static_cast<unsigned char>(255 * sin(angle * M_PI / 180)), static_cast<unsigned char>(255 * cos(angle * M_PI / 180)), 255 ) ); } }
0d04b3e83d418b2770a2284c9cc05b14563d4986
218f47f7418d35c5ec8e843f2302d151fc49c7c6
/ROV15/resizable_label.cpp
8cef13a9f110448780b1f7b99a8542ac74147d0c
[]
no_license
youssefMagdy29/ROV-15
d61eb355aaf69c79987c98071102fd2f5ea32cab
b2eb101895bf567148d433901680ba9bec3d20fe
refs/heads/master
2021-01-01T16:21:02.061739
2015-04-19T04:56:11
2015-04-19T04:56:11
30,868,121
0
0
null
2015-04-19T04:56:13
2015-02-16T12:51:52
C++
UTF-8
C++
false
false
446
cpp
resizable_label.cpp
#include "resizable_label.h" #include <QResizeEvent> ResizableLabel::ResizableLabel(QWidget *parent) : QLabel(parent) { image = new QImage(); } void ResizableLabel::resizeEvent(QResizeEvent *e) { QPixmap p = QPixmap::fromImage(image->scaled(e->size().width(), e->size().height())); this->setPixmap(p); } void ResizableLabel::setImage(QImage *image) { this->image = image; this->setPixmap(QPixmap::fromImage(*image)); }
fcd8be443157c40521c3748feec2f37e1079dfa2
f1e29bf7c34e5a6bc268e8d96d408fd276ac2c77
/Airplanes/Airplanes/Player.cpp
8d036e9da1cb06c3ffbe1cc67a40da224f36483a
[]
no_license
zVoxty/Games
40def88268842401bff4389e1037e99ddaa0a60e
b226b6c71fe11df553f2ec8586e67d04b024d704
refs/heads/master
2021-01-11T05:16:13.581949
2017-04-28T16:28:54
2017-04-28T16:28:54
71,296,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
Player.cpp
#include "Player.h" #include "Game.h" #include <QGraphicsItem> extern Game * game; Player::Player(QGraphicsItem *parent): QObject(), QGraphicsPixmapItem(parent) { QPixmap image(":/Images/plane.png"); setPixmap(image.scaled(QSize(70,70))); } Player::~Player() { } void Player::keyPressEvent(QKeyEvent * event){ if (event->key() == Qt::Key_Left) { if(pos().x() > 0) setPos(x() - 10, y()); qDebug() << pos().x() << pos().y(); } else if (event->key() == Qt::Key_Right) { if(pos().x() < game->windowWidth - 70) setPos(x() + 10, y()); qDebug() << pos().x() << pos().y(); } /*else if (event->key() == Qt::Key_Up) { setPos(x(), y()+10); qDebug() << pos().x() << pos().y(); } else if (event->key() == Qt::Key_Down) { setPos(x(), y() - 10); qDebug() << pos().x() << pos().y(); }*/ else if (event->key() == Qt::Key_Space) { Bullets * bullet = new Bullets(); bullet->setPos(x() + 32, y()); scene()->addItem(bullet); } } void Player::spawn() { //create an enemy Enemy * enemy = new Enemy(); scene()->addItem(enemy); }
a46e3ac9d5070820d2e8260e2b383d4e01f41955
1b8b2079d162f767e25a842f96cd7b6e8a2497d1
/AutoFileBackup-v2/AutoFileBackup-v2/Config.cpp
66684d66a1c61716b6923f54a36bd81b440a75fe
[]
no_license
AkrionXxarr/AutoFileBackup
405255ba32a169a370c45ce86a805cbb6e9dd996
b22009a7e2d27966c6fc1e389eed37e1a6ce5e84
refs/heads/master
2020-12-30T11:15:17.472341
2015-04-22T20:04:03
2015-04-22T20:04:03
30,620,504
0
0
null
null
null
null
UTF-8
C++
false
false
11,362
cpp
Config.cpp
#include "Config.hpp" #include <stdlib.h> #include <fstream> #include <sstream> #include <iostream> using namespace std; ///////////////// // NewConfig() // ///////////////// // Generate new config.txt, properly formatted bool NewConfig() { cout << "Creating " << CONFIGFILE << "..." << endl; ofstream configFile(CONFIGFILE); if (configFile.fail()) { configFile.clear(); configFile.close(); cout << "Error: configFile.fail() triggered..." << endl; return false; } else if (configFile.is_open()) { configFile << "=== Configuration ===" << endl; configFile << "$Password=" << endl; configFile << "$Online Mode=on" << endl; configFile << "$Server Port Number=" << endl; configFile << "$Batch File Path=" << endl; configFile << "$Map Source Path=" << endl; configFile << "$Map Dest Path=" << endl; configFile << "$Backup Directory Name=" << endl; configFile << "$Backup Interval (in minutes)=" << endl; configFile << "$Unique Backups=" << endl << endl; configFile << "=== No Modify ===" << endl; configFile << "$Last Backup Number=1" << endl; } else { cout << "Error: " << CONFIGFILE << " could not be opened." << endl; configFile.close(); return false; } configFile.close(); return true; } ////////////////// // LoadConfig() // ////////////////// // Load config file into ConfigInfo struct. bool ValidCharacter(char ch, bool filePath); bool LoadConfig(ConfigInfo& config) { // variables // bool foundEquals = false; bool foundColon = false; // This is used to check the availability of the correct variables. short variableCheck = 0; const short varibalCount = 10; string fileParse; string strVariable; string::iterator sIterate; // ========= // ifstream configFile(CONFIGFILE); if (configFile.is_open()) { // file parser, checks one line at a time. while (getline(configFile, fileParse)) { foundEquals = false; foundColon = false; // .find checks if its argument exists anywhere in the line(s) it currently holds. if (fileParse.find("$Password=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (!ValidCharacter((char)*sIterate, false)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable.size() == 0) { config.password = " "; } else { config.password = strVariable; } } else if (fileParse.find("$Online Mode=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (!ValidCharacter((char)*sIterate, false)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.onlineMode = strVariable; } else if (fileParse.find("$Server Port Number=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (!ValidCharacter((char)*sIterate, false)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.serverPort = strVariable; } else if (fileParse.find("$Batch File Path=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (*sIterate == '/') { *sIterate = '\\'; } else if (*sIterate == ':' && !foundColon) { foundColon = true; } else if (!ValidCharacter((char)*sIterate, true)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.batchPath = strVariable; } else if (fileParse.find("$Map Source Path=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (*sIterate == '/') { *sIterate = '\\'; } else if (*sIterate == ':' && !foundColon) { foundColon = true; } else if (!ValidCharacter((char)*sIterate, true)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.mapSourcePath = strVariable; } else if (fileParse.find("$Map Dest Path=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (*sIterate == '/') { *sIterate = '\\'; } else if (*sIterate == ':' && !foundColon) { foundColon = true; } else if (!ValidCharacter((char)*sIterate, true)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.mapDestPath = strVariable; } else if (fileParse.find("$Backup Directory Name=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { if (!ValidCharacter((char)*sIterate, true)) { cout << "Error: Invalid character (" << *sIterate << ") found in: " << endl; cout << fileParse << endl; return false; } strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.backupDirName = strVariable; } else if (fileParse.find("$Backup Interval (in minutes)=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.backupInterval = atoi(strVariable.c_str()); } else if (fileParse.find("$Unique Backups=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.numOfBackups = atoi(strVariable.c_str()); } else if (fileParse.find("$Last Backup Number=") != -1) { variableCheck++; strVariable.clear(); for (sIterate = fileParse.begin(); sIterate < fileParse.end(); sIterate++) { if (foundEquals) { strVariable.push_back(*sIterate); } else if (*sIterate == '=') { foundEquals = true; } } if (strVariable == "") { cout << "Error: empty veriable for " << fileParse << endl; return false; } config.backupSwitch = atoi(strVariable.c_str()); } } } else { cout << "Error: Unable to open file" << endl; configFile.close(); return false; } // Missing or duplicate variables in configuration file if (variableCheck != varibalCount) { if (variableCheck < varibalCount) { cout << "Error: " << CONFIGFILE << " is missing variables, or conflicting with another file of the same name." << endl; } else if (variableCheck > varibalCount) { cout << "Error: " << CONFIGFILE << " has duplicate variables." << endl; } cout << "Delete or move " << CONFIGFILE << " out of the folder and run this program again to generate a new one." << endl; return false; } configFile.close(); return true; } // Check validity of characters bool ValidCharacter(char ch, bool filePath) { if (!filePath) { switch (ch) { case '/': case '\\': return false; } } switch (ch) { case '"': case '<': case '>': case ':': case '|': case '?': case '*': return false; default: return true; } cout << "Error: switch in ValidCharacter failed" << endl; return false; } bool SaveConfig(ConfigInfo& config) { ofstream configFile(CONFIGFILE, ios::trunc); if (configFile.fail()) { configFile.clear(); configFile.close(); cout << "Error: configFile.fail() triggered..." << endl; return false; } else if (configFile.is_open()) { configFile << "=== Configuration ===" << endl; configFile << "$Password=" << config.password << endl; configFile << "$Online Mode=" << config.onlineMode << endl; configFile << "$Server Port Number=" << config.serverPort << endl; configFile << "$Batch File Path=" << config.batchPath << endl; configFile << "$Map Source Path=" << config.mapSourcePath << endl; configFile << "$Map Dest Path=" << config.mapDestPath << endl; configFile << "$Backup Directory Name=" << config.backupDirName << endl; configFile << "$Backup Interval (in minutes)=" << config.backupInterval << endl; configFile << "$Unique Backups=" << config.numOfBackups << endl << endl; configFile << "=== No Modify ===" << endl; configFile << "$Last Backup Number=" << config.backupSwitch << endl; } else { cout << "Error: " << CONFIGFILE << " could not be opened." << endl; configFile.close(); return false; } configFile.close(); return true; }
6f8995918a6d1e5ef8c7c807f2fc3d20e3c09bfb
59760e7e351fa25a9d974f105b9ac323f9115665
/HYJ/boj/Binary Search/boj1654.cpp
6deeaaddfe8f087c64d7b4e14b5a46a2849c1156
[]
no_license
grighth12/algorithm
f01ba85b75cded2c717666c68aac82ed66d0a563
21778b86e97acc5ffc80d4933855b94b89e9ffd3
refs/heads/main
2023-07-14T15:59:35.078846
2021-08-21T16:45:47
2021-08-21T16:45:47
375,053,162
0
2
null
2021-08-21T16:45:48
2021-06-08T15:10:58
C++
UHC
C++
false
false
948
cpp
boj1654.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int N, K; bool cmp(int a, int b) { return a > b; } bool countingLAN(vector<long> v, long long norm) { int sum = 0; for (int i = 0; i < v.size(); i++) { sum += (v[i] / norm); } return sum >= K; } int main() { cin >> N >> K; vector<long> v(N, 0); for (int i = 0; i < N; i++) { cin >> v[i]; } sort(v.begin(), v.end(), cmp); // 가장 긴 길이 long long high = v[0]; long long low = 1; long long result = 0; while (low <= high) { long long mid = (low + high) / 2; // 만약 자르는게 가능하면, 길이를 늘리는 방안도 고려할 수가 있다. if (countingLAN(v, mid)) { // 자르는 길이를 늘려서 result보다 크다면 교체 if (result < mid) result = mid; low = mid + 1; } // 자르는게 불가능하면, 길이를 줄인다. else { high = mid - 1; } } cout << result; return 0; }
1ccca9ba8a8b28928ef7d574379e82b4470e11da
33a82980352cf366b9c288cf8a74d2740272d90b
/print/OEM Printer Customization Plug-in Samples/C++/ThemeUI/fusutils.cpp
0f9bf2c30922e3322a614210774650e780a36e98
[ "MS-PL", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "MS-LPL" ]
permissive
microkatz/Windows-driver-samples
d249ecb8ab1be5a05bf8644ebeaca0bf13db1dad
98a43841cb18b034c7808bc570c47556e332df2f
refs/heads/master
2022-05-09T17:42:10.796047
2022-04-20T20:47:03
2022-04-20T20:47:03
161,238,613
2
0
MS-PL
2022-04-20T20:47:03
2018-12-10T21:28:00
C
UTF-8
C++
false
false
2,764
cpp
fusutils.cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright 1998 - 2003 Microsoft Corporation. All Rights Reserved. // // FILE: fsutils.h // // // PURPOSE: Fusion utilities // #include "precomp.h" #include "globals.h" #include "fusutils.h" #define MAX_LOOP 10 // This indicates to Prefast that this is a usermode driver file. _Analysis_mode_(_Analysis_code_type_user_driver_); HANDLE GetMyActivationContext() { // Make sure we've created our activation context. CreateMyActivationContext(); // Return the global. return ghActCtx; } BOOL CreateMyActivationContext() { if(INVALID_HANDLE_VALUE != ghActCtx) { return TRUE; } ghActCtx = CreateActivationContextFromResource(ghInstance, MAKEINTRESOURCE(MANIFEST_RESOURCE)); return (INVALID_HANDLE_VALUE != ghActCtx); } HANDLE CreateActivationContextFromResource(HMODULE hModule, LPCTSTR pszResourceName) { DWORD dwSize = MAX_PATH; DWORD dwUsed = 0; DWORD dwLoop; PTSTR pszModuleName = NULL; ACTCTX act; HANDLE hActCtx = INVALID_HANDLE_VALUE; // Get the name for the module that contains the manifest resource // to create the Activation Context from. dwLoop = 0; do { // May need to allocate or re-alloc buffer for module name. if(NULL != pszModuleName) { // Need to re-alloc bigger buffer. // First, delete old buffer. delete[] pszModuleName; // Second, increase buffer alloc size. dwSize <<= 1; } pszModuleName = new TCHAR[dwSize]; if(NULL == pszModuleName) { goto Exit; } // Try to get the module name. dwUsed = GetModuleFileName(hModule, pszModuleName, dwSize); // Check to see if it failed. if(0 == dwUsed) { goto Exit; } // If dwUsed is equla to dwSize or larger, // the buffer passed in wasn't big enough. } while ( (dwUsed >= dwSize) && (++dwLoop < MAX_LOOP) ); // Now let's try to create an activation context // from manifest resource. ::ZeroMemory(&act, sizeof(act)); act.cbSize = sizeof(act); act.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID; act.lpResourceName = pszResourceName; act.lpSource = pszModuleName; hActCtx = CreateActCtx(&act); Exit: // // Clean up. // if(NULL != pszModuleName) { delete[] pszModuleName; } return hActCtx; }
3779d2ed50fb23359b6c424ded5219a57bfabb27
f36a63974b865b29560c8dc462e5fa0243079487
/animal.cpp
659e4e0de8838ad31b77ea5d08636b4258cce07b
[]
no_license
toripizi/Virtual-World
052226b858ff4146276eb9e1fbc9400975f0254c
cfd128fb0a668bc96f8d99afe8c8b26b5438e215
refs/heads/main
2023-04-23T03:30:27.586820
2021-05-09T19:52:34
2021-05-09T19:52:34
363,051,925
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
4,393
cpp
animal.cpp
#include "animal.h" #include "plant.h" #include "Human.h" //00 00 00 //00 00 00 //00 00 00 Animal::~Animal() { world.organisms.DELETE_ELEMENT(this); } void Animal::checkField(int newX, int newY) { if(newX >= 0 && newX < world.getWidth() && newY >= 0 && newY < world.getHeight()) { tab[0][numberOfAvailableFields] = newX; tab[1][numberOfAvailableFields] = newY; numberOfAvailableFields++; } } void Animal::move() { if (!this->getBaby()) { numberOfAvailableFields = 0; checkField(x - 1, y); checkField(x - 1, y + 1); checkField(x, y + 1); checkField(x + 1, y + 1); checkField(x + 1, y); checkField(x + 1, y - 1); checkField(x, y - 1); checkField(x - 1, y - 1); if (numberOfAvailableFields) { int random = rand() % numberOfAvailableFields; xX = tab[0][random]; yY = tab[1][random]; } } else { this->setBaby(false); } } void Animal::action() { if (x != xX || y != yY) { if (world.tab[xX][yY].organism == nullptr) { display(); } else if (world.tab[xX][yY].organism->getName() != "zolw" ) { world.tab[xX][yY].organism->conflict(this); } else if (this->getName() == "zolw") { world.tab[xX][yY].organism->conflict(this); } else if (strength >= 5) { world.tab[xX][yY].organism->conflict(this); } else { xX = x; yY = y; } } } void Animal::checkFieldToChild(int newX, int newY) { if (newX >= 0 && newX < world.getWidth() && newY >= 0 && newY < world.getHeight() && World->tab[newX][newY].organism == nullptr) { tab[0][numberOfAvailableFields] = newX; tab[1][numberOfAvailableFields] = newY; numberOfAvailableFields++; } } int Animal::duplicate() { numberOfAvailableFields = 0; checkFieldToChild(x - 1, y); checkFieldToChild(x - 1, y + 1); checkFieldToChild(x, y + 1); checkFieldToChild(x + 1, y + 1); checkFieldToChild(x + 1, y); checkFieldToChild(x + 1, y - 1); checkFieldToChild(x, y - 1); checkFieldToChild(x - 1, y - 1); return numberOfAvailableFields; } void Animal::conflict(Organism* enemy) { if (Animal* animal = dynamic_cast<Animal*>(enemy)) { if (enemy->getName() == this->getName()) { //rozmnażanie //duplicate() sprawdza czy są gdzies wolne miejsca int numberOfAvailableFieldsThis = this->duplicate(); int numberOfAvailableFieldsAnimal = animal->duplicate(); int razem = numberOfAvailableFieldsThis + numberOfAvailableFieldsAnimal; //sumuje wszytskie wolne miejsca if (razem) { //jeśli istnieją //losuje jedno z nich int random = rand() % razem; //sprawdzam czy wylosowana liczba miesci sie w zakresie dostepnych pól dla this if (random < numberOfAvailableFieldsThis) { this->createChild(this->tab[0][random], this->tab[1][random]); } else { // jesli nie //to dziecko rodzi sie na polu dostepnemu dla animal animal->createChild( animal->tab[0][random-numberOfAvailableFieldsThis], animal->tab[1][random-numberOfAvailableFieldsThis]); //createChild(int x, int y) //tworzy nowe zwierze //metoda ta jest zadeklarowna w każdym zwierzęciu osobno } } } else if (enemy->getStrength() >= this->strength) { //atakujący wygrywa //wyświetlam atakującego na nowym polu enemy->display(); //komunikat //cout << this->getName() << " zostal zjedzony przez: " << enemy->getName() << " ||| "; //jeśli this jest człowiek, kończymy gre if (Human* human = dynamic_cast<Human*>(this)) { world.setGameOver(); } //usuwam this delete this; } else { //atakujący przegrywa //więc ustawiam jego polna na puste world.tab[enemy->getX()][enemy->getY()].setSign(' '); world.tab[enemy->getX()][enemy->getY()].organism = nullptr; //komunikat //cout << enemy->getName() << " zostal zjedzony przez: " << this->getName() << " ||| "; //jeśli atakującym jest człowiek, kończymy gre if (Human* human = dynamic_cast<Human*>(enemy)) { world.setGameOver(); } //usuwam atakującego delete animal; } } else if (Plant* plant = dynamic_cast<Plant*>(world.tab[xX][yY].organism)) { } } void Animal::display() { //this wygrywa //wiec ustawiam jego pola na puste world.tab[x][y].setSign(' '); world.tab[x][y].organism = nullptr; //zmieniam x i y na xX i yY changeXY(xX, yY); //ustawiam nowe pole na this world.tab[x][y].organism = this; world.tab[x][y].setSign(this->getSign()); }
8ac1139a68bc7caff9087754b3f4073a204590b5
8a86112c043d3e2e62521399cb503b01e1e4a0c8
/Crypto/mbedUtils.cc
8e338cc26bb6a7705f365d3801fa6cfc61117ccf
[ "Apache-2.0", "BUSL-1.1" ]
permissive
Dushistov/couchbase-lite-core
dcc1f53275518390036305a526ec2c14555fde95
0d8d68be025a95a1cc061ec59d16f00c621be300
refs/heads/master
2023-05-11T08:54:11.308862
2023-05-09T10:32:59
2023-05-09T10:32:59
178,002,169
0
0
Apache-2.0
2020-03-17T11:11:09
2019-03-27T13:39:35
C++
UTF-8
C++
false
false
5,125
cc
mbedUtils.cc
// // mbedUtils.cc // // Copyright 2019-Present Couchbase, Inc. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL-Couchbase.txt. As of the Change Date specified // in that file, in accordance with the Business Source License, use of this // software will be governed by the Apache License, Version 2.0, included in // the file licenses/APL2.txt. // #include "mbedUtils.hh" #include "Error.hh" #include "Logging.hh" #include "StringUtil.hh" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation-deprecated-sync" #include "mbedtls/ctr_drbg.h" #include "mbedtls/entropy.h" #include "mbedtls/error.h" #include "mbedtls/pem.h" #include "mbedtls/x509_crt.h" #pragma clang diagnostic pop #include <mutex> #if defined(_MSC_VER) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #include <Windows.h> #include <bcrypt.h> #endif namespace litecore { namespace crypto { using namespace std; using namespace fleece; [[noreturn]] void throwMbedTLSError(int err) { char description[100]; mbedtls_strerror(err, description, sizeof(description)); WarnError("mbedTLS error %s0x%x: %s", (err < 0 ? "-" : ""), abs(err), description); error::_throw(error::MbedTLS, err); } alloc_slice getX509Name(mbedtls_x509_name *xname) { char nameBuf[256]; TRY( mbedtls_x509_dn_gets(nameBuf, sizeof(nameBuf), xname) ); return alloc_slice(nameBuf); } mbedtls_ctr_drbg_context* RandomNumberContext() { static mbedtls_entropy_context sEntropyContext; static mbedtls_ctr_drbg_context sRandomNumberContext; static const char *kPersonalization = "LiteCore"; static once_flag f; call_once(f, []() { // One-time initializations: Log( "Seeding the mbedTLS random number generator..." ); mbedtls_entropy_init( &sEntropyContext ); #if defined(_MSC_VER) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) auto uwp_entropy_poll = [](void *data, unsigned char *output, size_t len, size_t *olen) -> int { NTSTATUS status = BCryptGenRandom(NULL, output, (ULONG)len, BCRYPT_USE_SYSTEM_PREFERRED_RNG); if (status < 0) { return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; } *olen = len; return 0; }; mbedtls_entropy_add_source(&sEntropyContext, uwp_entropy_poll, NULL, 32, MBEDTLS_ENTROPY_SOURCE_STRONG); #endif mbedtls_ctr_drbg_init( &sRandomNumberContext ); TRY( mbedtls_ctr_drbg_seed(&sRandomNumberContext, mbedtls_entropy_func, &sEntropyContext, (const unsigned char *) kPersonalization, strlen(kPersonalization)) ); }); return &sRandomNumberContext; } alloc_slice allocString(size_t maxSize, function_ref<int(char*,size_t)> writer) { alloc_slice data(maxSize); int len = TRY( writer((char*)data.buf, data.size) ); Assert(len <= maxSize); data.resize(len); return data; } alloc_slice allocDER(size_t maxSize, function_ref<int(uint8_t*,size_t)> writer) { alloc_slice data(maxSize); int len = TRY( writer((uint8_t*)data.buf, data.size) ); Assert(len <= maxSize); memmove((char*)&data[0], &data[data.size - len], len); data.resize(len); return data; } void parsePEMorDER(slice data, const char *what, ParseCallback fn) { int err; if (data.containsBytes("-----BEGIN "_sl) && !data.hasSuffix('\0')) { // mbedTLS requires a null byte at the end of PEM data: alloc_slice adjustedData(data); adjustedData.resize(data.size + 1); *((char*)adjustedData.end() - 1) = '\0'; err = fn((const uint8_t*)adjustedData.buf, adjustedData.size); } else { err = fn((const uint8_t*)data.buf, data.size); } if (err != 0) { char buf[100]; mbedtls_strerror(err, buf, sizeof(buf)); error::_throw(error::CryptoError, "Can't parse %s data (%s)", what, buf); } } alloc_slice convertToPEM(const slice &data, const char *name NONNULL) { return allocString(10000, [&](char *buf, size_t size) { size_t olen = 0; int err = mbedtls_pem_write_buffer(format("-----BEGIN %s-----\n", name).c_str(), format("-----END %s-----\n", name).c_str(), (const uint8_t*)data.buf, data.size, (uint8_t*)buf, size, &olen); if (err != 0) return err; if (olen > 0 && buf[olen-1] == '\0') --olen; return (int)olen; }); } } }
dec9bb59abb3d097a83dfcc3eeb5aacbeb7f8e0e
f1cc499a8f878eb90f490ed9a422ca1787abdc9a
/algorithmwidget.cpp
e9e0b33fd861ae3e8bfaebcbf2f245e4d8e4f7df
[]
no_license
ancaboriceanu/Licenta
4be89b47d87367c7c1a3f319f220782dea948d5a
ea1bdeea944bb89a704fa63df30103c7a52a5b57
refs/heads/master
2020-05-07T20:42:33.707297
2019-07-02T06:04:00
2019-07-02T06:04:00
180,871,136
0
0
null
null
null
null
UTF-8
C++
false
false
76
cpp
algorithmwidget.cpp
#include "algorithmwidget.h" AlgorithmWidget::AlgorithmWidget() { }
de443c62b79f2e5f539a2185b2a3eba923fff9fe
f88cdcf0a186104d11ce2ee20b51df0458110281
/Practice5/5/5.cpp
34961940ab0fa8ac8f7a45bc20a8e0f74257679e
[]
no_license
sobol-mo/KHPI_Progr_Fundamentals
d452a6e6f9242a7a599e9e3c978bd80b9aead800
bc0f527ab82a2874f02384ad2c87e41b2cac708d
refs/heads/master
2023-07-31T02:51:01.238400
2021-09-27T14:02:03
2021-09-27T14:02:03
282,931,371
2
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
5.cpp
/* Приклад 5. Див. Практична робота 5.docx */ // Перетворення десяткового числа в двійкове #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "windows.h" using namespace std; int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); int dec; // десяткове число int v; // вага формованого розряду int i; // номер формованого розряду printf("\Перетворення десяткового числа в двійкове \n"); printf("Введіть ціле число від 0 до 255 "); printf("і натисніть < Enter> -> "); scanf("%i", &dec); printf("Десятковому числу %i відповідає двійкове ", dec); v = 128; // вага старшого (восьмого) розряду for (i = 1; i <= 8; i++) { if (dec >= v) { printf("1"); dec -= v; } else printf("0"); v = v / 2; // вага наступного розряду // в два рази менше } return 0; }
9ba56118ecd8d5dc2d5fa2174144906219696df9
6c996d752073a89c208398266e8edbc7f1c7d8f5
/Engine/Coordenada.h
acc511b85f8f884639a9ea0b2a7dbd8ecb874ff6
[]
no_license
Gagv/Snek_Game
a6f4447dc4cb519fe1afedb70a45a9e82d41191f
b0320ca08f246e708c2b341f64d19b3cdc27e25c
refs/heads/master
2020-03-23T21:10:37.480481
2018-07-24T01:22:43
2018-07-24T01:22:43
142,084,373
0
0
null
null
null
null
UTF-8
C++
false
false
258
h
Coordenada.h
#pragma once #include "Graphics.h" class Coordenada { public: Coordenada(); Coordenada(int in_x, int in_y, Color c); ~Coordenada(); bool operator==(const Coordenada& com) const { return x == com.x && y == com.y; } int x; int y; Color c; };
e5a8420bbdd567e0eea1ffa7cd05d8b6ba080622
c05c5af550ec7c99b951dcdf0da3d20a2f7a34cd
/lib/src/environment.cc
e8d83fc05ea469547f4039e858087795b06d682e
[ "Apache-2.0" ]
permissive
isabella232/libral
f42d0a881dd91ac91b1534fff0612b74f614e402
8f18f1022ef3676a3df6d13d6b483d2100c5bc97
refs/heads/master
2021-09-12T16:25:34.921120
2018-04-18T15:23:39
2018-04-18T15:23:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
cc
environment.cc
#include <libral/environment.hpp> #include <libral/ral.hpp> #include <libral/target/base.hpp> namespace libral { namespace aug = libral::augeas; const std::vector<std::string>& environment::data_dirs() const { return _ral->data_dirs(); } libral::command::uptr environment::command(const std::string& cmd) { return _ral->target()->command(cmd); } libral::command::uptr environment::script(const std::string& cmd) { return _ral->target()->script(cmd); } std::string environment::which(const std::string& cmd) const { return _ral->target()->which(cmd); } bool environment::is_local() const { return _ral->is_local(); } result<std::shared_ptr<augeas::handle>> environment::augeas(const std::vector<std::pair<std::string, std::string>>& xfms) { return _ral->target()->augeas(xfms); } result<prov::spec> environment::parse_spec(const std::string& name, const std::string& desc, bool suitable) { return prov::spec::read(*this, name, desc, suitable); } }
67f468fc5aeefb0383aaff9dc84db3a42be89730
fda8876a6c122fb2c84b796ff2c39bc592ba5219
/MotifyDlg.cpp
f6498c8760cbc7bbb35bd9d102d63e219d51d17e
[]
no_license
double0517/Recipe
802b3750056f588bc2c565bc17da7797fc0161d3
843217b93b068ebf4924567333cba3a6fc24cc9c
refs/heads/master
2016-08-11T10:24:46.391288
2015-11-28T06:49:03
2015-11-28T06:49:03
47,013,424
0
0
null
null
null
null
GB18030
C++
false
false
1,773
cpp
MotifyDlg.cpp
// MotifyDlg.cpp : 实现文件 // #include "stdafx.h" #include "Recipe.h" #include "MotifyDlg.h" #include "afxdialogex.h" // MotifyDlg 对话框 CString MotifyDlg::strDisName = ""; CString MotifyDlg::strDisCount = ""; CString MotifyDlg::strDisPrice = ""; CString MotifyDlg::strDisDanPrice = ""; IMPLEMENT_DYNAMIC(MotifyDlg, CDialogEx) MotifyDlg::MotifyDlg(CWnd* pParent /*=NULL*/) : CDialogEx(MotifyDlg::IDD, pParent) , m_name(_T("")) , m_count(_T("")) , m_price(_T("")) , m_danprice(_T("")) // , strDisName(_T("")) //, strDisCount(_T("")) ///,strDisPrice (_T("")) //,strDisDanPrice (_T("")) { } MotifyDlg::~MotifyDlg() { } void MotifyDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_STATIC_name, m_name); DDX_Text(pDX, IDC_EDIT_count, m_count); DDX_Text(pDX, IDC_STATIC_price, m_price); DDX_Text(pDX, IDC_Danprice, m_danprice); } BEGIN_MESSAGE_MAP(MotifyDlg, CDialogEx) ON_WM_KILLFOCUS() END_MESSAGE_MAP() // MotifyDlg 消息处理程序 BOOL MotifyDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 m_name = strDisName ; m_count = strDisCount ; m_price = strDisPrice ; m_danprice = strDisDanPrice ; UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void MotifyDlg::OnKillfocusEDITcount() { // TODO: Add your control notification handler code here } void MotifyDlg::OnOK() { // TODO: 在此添加专用代码和/或调用基类 UpdateData(TRUE); int price ; price = atoi(m_count)*atoi(m_danprice) ; m_price.Format("%d",price); m_price=m_price+"元"; strDisCount = m_count; strDisPrice = m_price ; UpdateData(FALSE); CDialogEx::OnOK(); }
eb2f3434394db244be44097af2f9f365863a7891
6a47b5f04c74ed475b632e6561a675135e3baa80
/core/storage/trie/polkadot_trie/polkadot_trie.hpp
becbfe3725c0a06683a9135b6ae181814218fb9d
[ "Apache-2.0" ]
permissive
DiamondNetwork/kagome
3f89afcc7432c7047b2ce2a3ef6bf7a6ee878423
c018130a5595eeb69e439ea4695c7b7db1c7ee43
refs/heads/master
2023-08-05T01:19:31.739959
2021-10-08T14:01:45
2021-10-08T14:01:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,156
hpp
polkadot_trie.hpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_STORAGE_TRIE_POLKADOT_TRIE_HPP #define KAGOME_STORAGE_TRIE_POLKADOT_TRIE_HPP #include "storage/buffer_map_types.hpp" #include "storage/trie/polkadot_trie/polkadot_node.hpp" #include "storage/trie/polkadot_trie/polkadot_trie_cursor.hpp" namespace kagome::storage::trie { /** * For specification see Polkadot Runtime Environment Protocol Specification * '2.1.2 The General Tree Structure' and further */ class PolkadotTrie : public face::GenericMap<common::Buffer, common::Buffer> { public: using NodePtr = std::shared_ptr<PolkadotNode>; using BranchPtr = std::shared_ptr<BranchNode>; using NodeRetrieveFunctor = std::function<outcome::result<void>(NodePtr &)>; /** * This callback is called when a node is detached from a trie. It is called * for each leaf from the detached node subtree */ using OnDetachCallback = std::function<outcome::result<void>( const common::Buffer &key, boost::optional<common::Buffer> &&value)>; /** * Remove all trie entries which key begins with the supplied prefix * @param prefix key prefix for nodes to be removed * @param limit number of elements to remove, boost::none if no limit * @param callback function that will be called for each node removal * @returns tuple first element true if removed all nodes to be removed, * second tuple element is a number of removed elements */ virtual outcome::result<std::tuple<bool, uint32_t>> clearPrefix( const common::Buffer &prefix, boost::optional<uint64_t> limit, const OnDetachCallback &callback) = 0; /** * @return the root node of the trie */ virtual NodePtr getRoot() const = 0; /** * @returns a child node pointer of a provided \arg parent node * at the index \idx */ virtual outcome::result<NodePtr> retrieveChild(BranchPtr parent, uint8_t idx) const = 0; /** * @returns a node which is a descendant of \arg parent found by following * \arg key_nibbles (includes parent's key nibbles) */ virtual outcome::result<NodePtr> getNode( NodePtr parent, const KeyNibbles &key_nibbles) const = 0; /** * @returns a sequence of nodes in between \arg parent and the node found by * following \arg key_nibbles. The parent is included, the end node isn't. */ virtual outcome::result<std::list<std::pair<BranchPtr, uint8_t>>> getPath( NodePtr parent, const KeyNibbles &key_nibbles) const = 0; virtual std::unique_ptr<PolkadotTrieCursor> trieCursor() = 0; std::unique_ptr<BufferMapCursor> cursor() final { return trieCursor(); } inline static outcome::result<void> defaultNodeRetrieveFunctor( NodePtr &node) { BOOST_ASSERT_MSG(not node or not node->isDummy(), "Dummy node unexpected."); return outcome::success(); } }; } // namespace kagome::storage::trie #endif // KAGOME_STORAGE_TRIE_POLKADOT_TRIE_HPP
9ffdb9a3fa342ae0fd8b57574701802c0187fbd6
1012d4b546bce6e3de2357a499dbb80c488f3817
/Graphics/Scene/RenderLayerSceneRendererCommand.h
825b06fbfd223257059d852b98f8fb0231094ca5
[]
no_license
ror3d/mastervj-basic-engine
f35e18650dc968258914cc75ae0136057caf44d5
2023ac0334219a0d578079a051476e212baf2f75
refs/heads/master
2021-06-05T11:11:20.817620
2016-11-04T03:28:35
2016-11-04T03:28:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
403
h
RenderLayerSceneRendererCommand.h
#ifndef RENDER_LAYER_SCENE_RENDERER_COMMAND_H #define RENDER_LAYER_SCENE_RENDERER_COMMAND_H #include "Scene/StagedTexturedSceneRendererCommand.h" class CRenderLayerSceneRendererCommand : public CStagedTexturedSceneRendererCommand { private: std::string m_layerName; bool m_zSort; public: CRenderLayerSceneRendererCommand(CXMLTreeNode &TreeNode); void Execute(CContextManager &_context); }; #endif
22f964d84331b0d9207f31b8e82b56a9599f5e09
4e28f29570ec583dfa4c18444dae4cefdd871895
/src/util/util_time.h
34a53bbe137c7654b69297a28436fcf8a43a84ef
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
bmatheny/memkeys
e718a48886dd445b1e4ab7f03565ee4af2e8bc99
7c521c465c9661ff298ca32d974d22c4318556aa
refs/heads/master
2021-05-16T05:28:48.394845
2018-04-25T01:37:57
2018-04-25T01:37:57
9,477,378
51
26
Apache-2.0
2021-02-08T14:55:26
2013-04-16T16:42:37
C++
UTF-8
C++
false
false
1,159
h
util_time.h
#ifndef _UTIL_UTIL_TIME_H #define _UTIL_UTIL_TIME_H #include <cstdint> #include <cstring> extern "C" { #include <sys/time.h> #include <unistd.h> #include <time.h> } namespace mckeys { class UtilTime { public: static inline uint64_t currentTimeMillis() { struct timeval t; gettimeofday(&t, NULL); return (1000L * t.tv_sec) + (t.tv_usec / 1000); } static inline struct timespec millisToTimespec(long millis) { struct timespec interval; interval.tv_sec = UtilTime::millisToSeconds(millis); interval.tv_nsec = UtilTime::millisToNanos(millis) - UtilTime::secondsToNanos(interval.tv_sec); return interval; } static inline long millisToNanos(long millis) { return millis*1000000L; } static inline long millisToMicros(long millis) { return millis*1000L; } static inline long millisToSeconds(long millis) { return millis/1000L; } static inline long nanosToMillis(long nanos) { return nanos/1000000L; } static inline long microsToMillis(long micros) { return micros/1000L; } static inline long secondsToNanos(long secs) { return secs*1000000000L; } }; } // end namespace #endif
726f7cf775a6138acbea3031f02d2a730b8cc967
d9db6449de08b2341c70597290d3005abf00f47e
/CodeForces/B/Queue_At_school.cpp
346e56defb2bbe6876add7ad4ff789b596b72df2
[]
no_license
Harshsngh07/DataStructures_and_Algorithms
bd22af0b83017a7e00a6f85d12b12b2316fc8b15
451d54d9fa9f8708fd545a17d57cb85b5fdde2f9
refs/heads/master
2023-07-31T14:13:10.404941
2021-06-22T05:25:18
2021-06-22T05:25:18
252,812,769
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
Queue_At_school.cpp
#include <bits/stdc++.h> #include <vector> using namespace std; #define ll long long #define MOD 1000000007 #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); #define FIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); int main() { OJ; int n, t; cin >> n >> t; char a[n]; for (int i = 0; i < n; i++) cin >> a[i]; int j = n - 1; while (t--) { for (int i = 0; i < n; i++) { if (a[i] == 'B' && a[i + 1] == 'G') { swap(a[i], a[i + 1]); i++; } } // if (i != n / 2) // if (a[j - 1] == 'B' && a[j] == 'G') // { // swap(a[j - 1], a[j]); // j--; // } } for (int i = 0; i < n; i++) cout << a[i]; return 0; }
955ac24b3950431fd4dcdcb3e4e1819c7abc708e
2ce68c34402740f8beca81630d995acac07d21a4
/include/libnative.h
465aea368c45e562fbca181c986b133625c8844d
[]
no_license
emdagh/dotnet-interop
0e4ca80578a3db236613c3bd980426fae79cc283
8097fe428bfc8c87de96f55ef13e10e8a2fd292b
refs/heads/master
2023-04-01T10:33:10.740478
2020-08-24T20:44:52
2020-08-24T20:44:52
284,217,549
0
0
null
null
null
null
UTF-8
C++
false
false
506
h
libnative.h
#ifndef LIBNATIVE_H_ #define LIBNATIVE_H_ #include <cstdint> #include <string> #include <vector> namespace ns { extern "C" size_t get_array(unsigned int* res, size_t len); extern "C" void do_wstring_array(wchar_t**, int); extern "C" void do_wstring(wchar_t*); extern "C" void do_vector(std::vector<int>&); extern "C" void do_real_wstring(const std::wstring&); extern "C" void do_wstring_vector(std::vector<std::wstring>&); extern "C" std::wstring return_wstring(); } #endif
d9d419e5c2006b4af66b1a9a8d2393d6b0082ee2
9bd2b92b924d65f19bc534b543f90ae63ea23637
/contest/cdut-search/K.cpp
9111278444dfdb4cb47a1621a6693f26b1afa9e0
[]
no_license
mooleetzi/ICPC
d5196b07e860721c8a4fe41a5ccf5b58b6362678
cd35ce7dbd340df1e652fdf2f75b35e70e70b472
refs/heads/master
2020-06-09T12:13:48.571843
2019-12-01T11:39:20
2019-12-01T11:39:20
193,435,046
3
0
null
null
null
null
GB18030
C++
false
false
1,397
cpp
K.cpp
#include<iostream> #include<cstring> #include<queue> #define rep(i,x,y) for (int i=x;i<y;i++) #define mt(a,x) memset(a,x,sizeof a) #define maxn 10010 using namespace std; const int dx[]={0,1,0,-1}; const int dy[]={1,0,-1,0}; int a[5][5]; struct node{ int x,y,pre; }; node que[maxn]; int fa[maxn]; int vis[5][5]; int l,r; void print(); void bfs(); int main(){ ios::sync_with_stdio(false); mt(vis,0); rep(i,0,5) rep(j,0,5) cin>>a[i][j]; cout<<"(0, 0)\n"; bfs(); print(); return 0; } void bfs(){ que[0].x=0; que[0].y=0; que[0].pre=-1; vis[0][0]=1; l=0;r=1; while(l<r){ int x,y; rep(i,0,4){ x=que[l].x+dx[i]; y=que[l].y+dy[i]; if (x>-1&&x<5&&y>-1&&y<5&&!vis[x][y]&&!a[x][y]){ que[r].x=x; que[r].y=y; que[r].pre=l; vis[x][y]=1; if (x==4&&y==4){ print(); return; } r++; } } l++;//队首元素出队 } return; } void print(){ int xx[maxn],yy[maxn]; mt(xx,0); mt(yy,0); int i=0; while(que[r].pre!=-1){ xx[i]=que[r].x; yy[i++]=que[r].y; r=que[r].pre; } for (int j=i-1;j>-1;j--) cout<<"("<<xx[j]<<", "<<yy[j]<<")\n"; return; }
dcc1bf6ba6fc459695c67d8093874d81b97f49d7
3be85ac20744896f0afb84010b63f8cfc6c9c3aa
/src/Main.cpp
186882c28516f97069b6bee739af849af4b0c5a5
[]
no_license
chsoto97/rv2
9c1e8e6fa517079ee3ec429f38bf0e05a43aec17
ad5a8b1251e951a43ee08e4ae460893e5b0071e4
refs/heads/master
2022-07-17T04:34:45.106704
2020-05-18T16:51:16
2020-05-18T16:51:16
259,931,850
1
0
null
null
null
null
UTF-8
C++
false
false
46,573
cpp
Main.cpp
#include <opencv2/opencv.hpp> #include <opencv2/features2d.hpp> #include <opencv2/xfeatures2d.hpp> #include <fstream> using namespace cv; using namespace cv::xfeatures2d; int main(int argc, const char* argv[]) { //load images cv::Mat img_1 = cv::imread("./IMG_CAL_DATA/left08.png", 0); cv::Mat img_2 = cv::imread("./IMG_CAL_DATA/right08.png", 0); cv::Ptr<SURF> SURF = SURF::create(); //SURF feature extractor Ptr<SIFT> SIFT = SIFT::create(); //SIFT feature extractor cv::Ptr<Feature2D> ORB = ORB::create(); //ORB feature extractor std::vector<KeyPoint> keypoints_1, keypoints_2; //keypoints vectors Mat img_keypoints1, img_keypoints2; //img matrix for the keypoints Mat descriptors_1, descriptors_2; //descriptors int normType = NORM_L2; //should be different for each feature detector, but works well on all of them with L1 Ptr<BFMatcher> matcher = BFMatcher::create(normType); //BF matcher std::vector< std::vector<DMatch >> allMatches; //matches vector double ratio = 0.6; //ratio test Mat img_matches; //img showing matches int noOfLines = 40; //number of epipolar lines std::vector<Point2f> points1(noOfLines); //points of the 1st image for epipolar lines std::vector<Point2f> points2(noOfLines); //points of the 2nd image for epipolar lines std::vector< DMatch > epipolarMatches; //matches used for the drawing of epipolar lines int point_count = 15; //points used for FM & EM estimation std::vector<Point2f> points1fm(point_count); //points for the FM estimation std::vector<Point2f> points2fm(point_count); //points for the FM estimation Mat fundamental_matrix; //fundamental matrix Mat essential_matrix; //essential matrix Mat epipolarLines; //epipolar vector lines Mat epipolar_img; //image with epipolar lines cv::RNG rng(0); //random color generator Mat img_1rgb; //complemental image with the same colors as epipolar_img for concatenation //K matrix for each camera double kl[3][3] = {{9.842439e+02, 0.000000e+00, 6.900000e+02}, {0.000000e+00, 9.808141e+02, 2.331966e+02}, {0.000000e+00, 0.000000e+00, 1.000000e+00}}; Mat KL = Mat(3, 3, CV_64F, kl); double kr[3][3] = {{9.895267e+02, 0.000000e+00, 7.020000e+02}, {0.000000e+00, 9.878386e+02, 2.455590e+02}, {0.000000e+00, 0.000000e+00, 1.000000e+00}}; Mat KR = Mat(3, 3, CV_64F, kr); Mat Kavg = (KL+KR)*0.5; //-----------------------------------------SURF LR--------------------------------------------------------// //detect keypoints SURF->detect( img_1, keypoints_1 ); SURF->detect( img_2, keypoints_2 ); drawKeypoints( img_1, keypoints_1, img_keypoints1 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/SURF/left08-SURF.png", img_keypoints1); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/SURF/right08-SURF.png", img_keypoints2); //calculate descriptors SURF->compute( img_1, keypoints_1, descriptors_1 ); SURF->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); std::vector<DMatch> matches; //ratio test ratio = 0.2; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LR/SURF/LR-SURF.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } //calculate matrix fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file("./LR/SURF/LR-SURF-8pt.txt", cv::FileStorage::WRITE); file << "Fundamental Matrix" << fundamental_matrix; file << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); cv::Scalar color(rng(256),rng(256),rng(256)); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2fm[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SURF/LR-SURF-epipolar-8pt.png", epipolar_img); //calculate matrix fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file1("./LR/SURF/LR-SURF-RANSAC.txt", cv::FileStorage::WRITE); file1 << "Fundamental Matrix" << fundamental_matrix; file1 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SURF/LR-SURF-epipolar-RANSAC.png", epipolar_img); //calculate matrix essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file16("./LR/SURF/LR-SURF-5pt.txt", cv::FileStorage::WRITE); file16 << "Fundamental Matrix" << fundamental_matrix; file16 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SURF/LR-SURF-epipolar-5pt.png", epipolar_img); //debugging std::cout << "[DEBUG] Finished LR SURF" << std::endl; std::cout.flush(); //-----------------------------------------------------SIFT LR--------------------------------------------------// //detect keypoints SIFT->detect( img_1, keypoints_1 ); SIFT->detect( img_2, keypoints_2 ); drawKeypoints( img_1, keypoints_1, img_keypoints1 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/SIFT/left08-SIFT.png", img_keypoints1); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/SIFT/right08-SIFT.png", img_keypoints2); //calculate descriptors SIFT->compute( img_1, keypoints_1, descriptors_1 ); SIFT->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.3; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LR/SIFT/LR-SIFT.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file2("./LR/SIFT/LR-SIFT-8pt.txt", cv::FileStorage::WRITE); file2 << "Fundamental Matrix" << fundamental_matrix; file2 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SIFT/LR-SIFT-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file3("./LR/SIFT/LR-SIFT-RANSAC.txt", cv::FileStorage::WRITE); file3 << "Fundamental Matrix" << fundamental_matrix; file3 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SIFT/LR-SIFT-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file17("./LR/SIFT/LR-SIFT-5pt.txt", cv::FileStorage::WRITE); file17 << "Fundamental Matrix" << fundamental_matrix; file17 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/SIFT/LR-SIFT-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LR SIFT" << std::endl; std::cout.flush(); //------------------------------------------------------ORB LR---------------------------------------------------// //detect keypoints ORB->detect( img_1, keypoints_1 ); ORB->detect( img_2, keypoints_2 ); drawKeypoints( img_1, keypoints_1, img_keypoints1 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/ORB/left08-ORB.png", img_keypoints1); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/ORB/right08-ORB.png", img_keypoints2); //calculate descriptors ORB->compute( img_1, keypoints_1, descriptors_1 ); ORB->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.6; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LR/ORB/LR-ORB.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file4("./LR/ORB/LR-ORB-8pt.txt", cv::FileStorage::WRITE); file4 << "Fundamental Matrix" << fundamental_matrix; file4 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/ORB/LR-ORB-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file5("./LR/ORB/LR-ORB-RANSAC.txt", cv::FileStorage::WRITE); file5 << "Fundamental Matrix" << fundamental_matrix; file5 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/ORB/LR-ORB-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file18("./LR/ORB/LR-ORB-5pt.txt", cv::FileStorage::WRITE); file18 << "Fundamental Matrix" << fundamental_matrix; file18 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/ORB/LR-ORB-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LR ORB" << std::endl; std::cout.flush(); //------------------------------------------------------FAST+BRIEF LR------------------------------------------------// //detect keypoints int treshold = 120; //filter parameter cv::FAST(img_1, keypoints_1, treshold, true); cv::FAST(img_2, keypoints_2, treshold, true); drawKeypoints( img_1, keypoints_1, img_keypoints1 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/FAST+BRIEF/left08-FAST.png", img_keypoints1); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LR/FAST+BRIEF/right08-FAST.png", img_keypoints2); //create descriptor extractor and calculate descriptors Ptr<DescriptorExtractor> featureExtractor = cv::xfeatures2d::BriefDescriptorExtractor::create(); featureExtractor->compute(img_1, keypoints_1, descriptors_1); featureExtractor->compute(img_2, keypoints_2, descriptors_2); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.5; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LR/FAST+BRIEF/LR-FAST+BRIEF.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file6("./LR/FAST+BRIEF/LR-FAST-8pt.txt", cv::FileStorage::WRITE); file6 << "Fundamental Matrix" << fundamental_matrix; file6 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/FAST+BRIEF/LR-FAST-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file7("./LR/FAST+BRIEF/LR-FAST-RANSAC.txt", cv::FileStorage::WRITE); file7 << "Fundamental Matrix" << fundamental_matrix; file7 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/FAST+BRIEF/LR-FAST-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file19("./LR/FAST+BRIEF/LR-FAST-5pt.txt", cv::FileStorage::WRITE); file19 << "Fundamental Matrix" << fundamental_matrix; file19 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LR/FAST+BRIEF/LR-FAST-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LR FAST" << std::endl; std::cout.flush(); //------------------------------------------------------LL-----------------------------------------------------// //load images img_2 = cv::imread("./IMG_CAL_DATA/left10.png", 0); //----------------------------------------------------------SURF LL----------------------------------------------------// //detect keypoints SURF->detect( img_1, keypoints_1 ); SURF->detect( img_2, keypoints_2 ); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LL/SURF/left10-SURF.png", img_keypoints2); //calculate descriptors SURF->compute( img_1, keypoints_1, descriptors_1 ); SURF->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.2; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LL/SURF/LL-SURF.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file8("./LL/SURF/LL-SURF-8pt.txt", cv::FileStorage::WRITE); file8 << "Fundamental Matrix" << fundamental_matrix; file8 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2fm[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SURF/LL-SURF-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file9("./LL/SURF/LL-SURF-RANSAC.txt", cv::FileStorage::WRITE); file9 << "Fundamental Matrix" << fundamental_matrix; file9 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SURF/LL-SURF-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file20("./LL/SURF/LL-SURF-5pt.txt", cv::FileStorage::WRITE); file20 << "Fundamental Matrix" << fundamental_matrix; file20 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SURF/LL-SURF-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LL SURF" << std::endl; std::cout.flush(); //----------------------------------------------------------SIFT LL----------------------------------------------------// //detect keypoints SIFT->detect( img_1, keypoints_1 ); SIFT->detect( img_2, keypoints_2 ); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LL/SIFT/left10-SIFT.png", img_keypoints2); //calculate descriptors SIFT->compute( img_1, keypoints_1, descriptors_1 ); SIFT->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.2; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LL/SIFT/LL-SIFT.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file10("./LL/SIFT/LL-SIFT-8pt.txt", cv::FileStorage::WRITE); file10 << "Fundamental Matrix" << fundamental_matrix; file10 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2fm[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SIFT/LL-SIFT-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file11("./LL/SIFT/LL-SIFT-RANSAC.txt", cv::FileStorage::WRITE); file11 << "Fundamental Matrix" << fundamental_matrix; file11 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SIFT/LL-SIFT-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file21("./LL/SIFT/LL-SIFT-5pt.txt", cv::FileStorage::WRITE); file21 << "Fundamental Matrix" << fundamental_matrix; file21 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/SIFT/LL-SIFT-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LL SIFT" << std::endl; std::cout.flush(); //----------------------------------------------------------ORB LL----------------------------------------------------// //detect keypoints ORB->detect( img_1, keypoints_1 ); ORB->detect( img_2, keypoints_2 ); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LL/ORB/left10-ORB.png", img_keypoints2); //calculate descriptors ORB->compute( img_1, keypoints_1, descriptors_1 ); ORB->compute( img_2, keypoints_2, descriptors_2 ); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.8; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LL/ORB/LL-ORB.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file12("./LL/ORB/LL-ORB-8pt.txt", cv::FileStorage::WRITE); file12 << "Fundamental Matrix" << fundamental_matrix; file12 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2fm[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/ORB/LL-ORB-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file13("./LL/ORB/LL-ORB-RANSAC.txt", cv::FileStorage::WRITE); file13 << "Fundamental Matrix" << fundamental_matrix; file13 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/ORB/LL-ORB-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file22("./LL/ORB/LL-ORB-5pt.txt", cv::FileStorage::WRITE); file22 << "Fundamental Matrix" << fundamental_matrix; file22 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/ORB/LL-ORB-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LL ORB" << std::endl; std::cout.flush(); //----------------------------------------------------------FAST+BRIEF LL--------------------------------------------// //detect keypoints cv::FAST(img_1, keypoints_1, treshold, true); cv::FAST(img_2, keypoints_2, treshold, true); drawKeypoints( img_2, keypoints_2, img_keypoints2 ); //-- Show detected (drawn) keypoints cv::imwrite("./LL/FAST+BRIEF/left10-FAST.png", img_keypoints2); //calculate descriptors featureExtractor->compute(img_1, keypoints_1, descriptors_1); featureExtractor->compute(img_2, keypoints_2, descriptors_2); //match descriptors using BFMatcher allMatches.clear(); matcher->knnMatch( descriptors_1, descriptors_2, allMatches, 2); matches.clear(); ratio = 0.5; for(int i = 0; i < allMatches.size(); i++){ if(allMatches[i][0].distance < ratio * allMatches[i][1].distance) matches.push_back(allMatches[i][0]); } //draw results to image drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches, Scalar::all(-1), Scalar::all(-1), std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //save image cv::imwrite("./LL/FAST+BRIEF/LL-FAST+BRIEF.png", img_matches); // initialize the points for the epipolar lines ... */ for( int i = 0; i < noOfLines; i++ ) { points1[i] = keypoints_1[matches[i].queryIdx].pt; points2[i] = keypoints_2[matches[i].trainIdx].pt; epipolarMatches.push_back(matches[i]); } // initialize the points for the fundamental matrix calculation ... */ for( int i = 0; i < point_count; i++ ) { points1fm[i] = keypoints_1[matches[i].queryIdx].pt; points2fm[i] = keypoints_2[matches[i].trainIdx].pt; } fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_8POINT); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file14("./LL/FAST+BRIEF/LL-FAST-8pt.txt", cv::FileStorage::WRITE); file14 << "Fundamental Matrix" << fundamental_matrix; file14 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2fm[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/FAST+BRIEF/LL-FAST-epipolar-8pt.png", epipolar_img); fundamental_matrix = findFundamentalMat(points1fm, points2fm, FM_RANSAC); essential_matrix = KR.t()*fundamental_matrix*KL; //output to text file cv::FileStorage file15("./LL/FAST+BRIEF/LL-FAST-RANSAC.txt", cv::FileStorage::WRITE); file15 << "Fundamental Matrix" << fundamental_matrix; file15 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/FAST+BRIEF/LL-FAST-epipolar-RANSAC.png", epipolar_img); essential_matrix = cv::findEssentialMat(points1fm, points2fm, Kavg, RANSAC); fundamental_matrix = KR.t().inv()*essential_matrix*KL.inv(); //output to text file cv::FileStorage file23("./LL/FAST+BRIEF/LL-FAST-5pt.txt", cv::FileStorage::WRITE); file23 << "Fundamental Matrix" << fundamental_matrix; file23 << "Essential Matrix" << essential_matrix; //calculate epipolar lines of right using left points cv::computeCorrespondEpilines(points1, 1, fundamental_matrix, epipolarLines); //prepare output image epipolar_img = img_2.clone(); cvtColor(epipolar_img, epipolar_img, COLOR_GRAY2BGR); //draw epipolar lines and keypoints of the right image for( int i = 0; i < noOfLines; i++ ) { line(epipolar_img, cv::Point(0,-epipolarLines.at<Point3f>(i, 0).z/epipolarLines.at<Point3f>(i, 0).y), cv::Point(epipolar_img.cols,-(epipolarLines.at<Point3f>(i, 0).z+epipolarLines.at<Point3f>(i, 0).x*epipolar_img.cols)/epipolarLines.at<Point3f>(i, 0).y), color); cv::circle(epipolar_img, points2[i], 3, color); } //output cvtColor(img_1, img_1rgb, COLOR_GRAY2BGR); hconcat(img_1rgb, epipolar_img, epipolar_img); cv::imwrite("./LL/FAST+BRIEF/LL-FAST-epipolar-5pt.png", epipolar_img); std::cout << "[DEBUG] Finished LL FAST" << std::endl; std::cout.flush(); return 0; }
0bf9b6e0abc6cf9dd26bd108f87aa5d9bf5d8cda
0b69a011c9ffee099841c140be95ed93c704fb07
/problemsets/Codeforces/C++/A580.cpp
814a7b9e00d6a18d60a59151e1733759e1eaec42
[ "Apache-2.0" ]
permissive
juarezpaulino/coderemite
4bd03f4f2780eb6013f07c396ba16aa7dbbceea8
a4649d3f3a89d234457032d14a6646b3af339ac1
refs/heads/main
2023-01-31T11:35:19.779668
2020-12-18T01:33:46
2020-12-18T01:33:46
320,931,351
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
A580.cpp
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <bits/stdc++.h> using namespace std; int main() { int n, l = 0, ret = 0, u = -1, x; cin >> n; while (n--) { cin >> x; if (x >= u) l++, ret = max(ret, l); else l = 1; u = x; } cout << ret; }
0e46e866ec13bcadb2e9b44967d0a0fbfd7c4337
b53575b4f1da8246e9abbb2bf4d297fd0af75ebb
/UVa/100/193.graph-coloring.cpp
6e4c365979a50b2cba4477b7ac25f639074e622b
[]
no_license
mauriciopoppe/competitive-programming
217272aa3ee1c3158ca2412652f5ccd6596eb799
32b558582402e25c9ffcdd8840d78543bebd2245
refs/heads/master
2023-04-09T11:56:07.487804
2023-03-19T20:45:00
2023-03-19T20:45:00
120,259,279
8
1
null
null
null
null
UTF-8
C++
false
false
1,456
cpp
193.graph-coloring.cpp
#include<iostream> #include<cstdlib> #include<string> #include<cmath> #include<algorithm> #include<bitset> #include<vector> #include<map> #include<set> #define N 105 using namespace std; bool g[N][N], color[N], mk[N]; int n, m, ans; bool ok(int u) { for(int i = 1; i <= n; i++) { if(g[u][i] && color[i]) return 0; } return 1; } void bt(int u, int cnt) { if(u>n) { if(cnt > ans) { ans = cnt; for(int i = 1; i <= n; i++) mk[i] = color[i]; } return; } if(cnt+n-u+1<=ans) return; if(ok(u)) { color[u]=1; bt(u+1,cnt+1); color[u]=0; } bt(u+1,cnt); } int main() { int t; scanf("%d", &t); while(t--) { ans = 0; memset(g, 0, sizeof(g)); memset(mk, 0, sizeof(mk)); memset(color, 0, sizeof(color)); scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int a, b; scanf("%d %d", &a, &b); g[a][b] = g[b][a] = 1; } bt(1, 0); printf("%d\n", ans); bool flag = 1; for(int i = 1; i <= n; i++) { if(mk[i]) { if(flag) flag = 0; else printf(" "); printf("%d", i); } } printf("\n"); } return 0; }
8450cd14715667c138cc6d4823e2185daf0b7ec1
611142068bdce049f8eb29ed327524e63f751197
/src/LSM6DS3.cpp
82798cebe08c1bec0e48dfd47ee1d1e831785e5d
[]
no_license
mslawicz/NucleoYoke
313752e3774d46a87bd81fc7e0c5637c62c0cebc
db8ef8c4a48ef4c0565c3f0430bd555b08254fae
refs/heads/master
2020-06-28T08:53:45.584329
2019-12-14T19:26:47
2019-12-14T19:26:47
200,192,386
0
0
null
null
null
null
UTF-8
C++
false
false
2,041
cpp
LSM6DS3.cpp
/* * LSM6DS3.cpp * * Created on: 03.09.2019 * Author: Marcin */ #include "LSM6DS3.h" LSM6DS3::LSM6DS3(I2cBus* pBus, DeviceAddress deviceAddress) : I2cDevice(pBus, deviceAddress), address(deviceAddress) { // Gyroscope Data Ready to INT1 pin for test only writeRequest(address, LSM6DS3Register::LSM6DS3_INT1_CTRL, std::vector<uint8_t>{0x02}); // Accelerometer ODR=52 Hz, full scale +-2g // Gyroscope ODR=52 Hz, full scale 250 dps writeRequest(address, LSM6DS3Register::LSM6DS3_CTRL1_XL, std::vector<uint8_t>{0x30, 0x30}); // Gyroscope digital high-pass filter enable, 0.0324 Hz writeRequest(address, LSM6DS3Register::LSM6DS3_CTRL7_G, std::vector<uint8_t>{0x50}); } /* * returns float vector of measured angular rate in rad/s * positive slope fot moving joystick forward, right and twisting right */ FloatVector LSM6DS3::getAngularRate(void) { return FloatVector { -static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[2])) / MeasurementRegisterFullScaleValue * gyroscopeFullScaleValue, -static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[0])) / MeasurementRegisterFullScaleValue * gyroscopeFullScaleValue, static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[4])) / MeasurementRegisterFullScaleValue * gyroscopeFullScaleValue }; } /* * returns float vector of measured acceleration in g * positive values for Z in neutral and joystick forward and to right */ FloatVector LSM6DS3::getAcceleration(void) { return FloatVector { static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[8])) / MeasurementRegisterFullScaleValue * accelerometerFullScaleValue, -static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[6])) / MeasurementRegisterFullScaleValue * accelerometerFullScaleValue, -static_cast<float>(*reinterpret_cast<int16_t*>(&receiveBuffer[10])) / MeasurementRegisterFullScaleValue * accelerometerFullScaleValue }; }
b83573ddc04d0200f16e16a977132eb637d1319f
888875952c0d1e28c1a0558dc4c15ccffb564333
/src/physics/ray.cpp
33fcb21a28bcab146a54d2f97d6fdc6cdc9b70dd
[]
no_license
anthonydito/ditorender
b99ce7722752bea4b398c3c8efe5fb76bea27b8e
f59d885144267ee74ae50ff1e821385f5198f98a
refs/heads/master
2023-06-21T23:15:26.260872
2021-07-26T03:27:44
2021-07-26T03:27:44
371,460,515
0
0
null
2021-07-18T02:25:23
2021-05-27T17:57:47
C++
UTF-8
C++
false
false
3,122
cpp
ray.cpp
#include "ray.hpp" #include <algorithm> #include "math.h" #include "../util/tuple.hpp" #include "intersection.hpp" using namespace dito::util; using namespace dito::physics; Ray::Ray(Point origin, Vector direction) { this->_origin = origin; this->_direction = direction; } Point Ray::origin() const { return this->_origin; } Vector Ray::direction() const { return this->_direction; } Point Ray::position(double time) const { return this->origin() + (this->direction() * time); } Intersections Ray::intersets(std::shared_ptr<Sphere> sphere) const { Ray transform_ray = this->transform(sphere->transform().inverse()); Intersections intersection_points; Tuple sphere_to_ray = transform_ray.origin() - sphere->origin(); auto a = transform_ray.direction().dot(transform_ray.direction()); auto b = 2 * transform_ray.direction().dot(sphere_to_ray); auto c = sphere_to_ray.dot(sphere_to_ray) - 1; auto discriminant = pow(b, 2) - (4 * a * c); if (discriminant < 0) { // No intersection points return intersection_points; } auto sqrt_discriminant = sqrt(discriminant); auto t1 = (-b - sqrt_discriminant) / (2 * a); auto t2 = (-b + sqrt_discriminant) / (2 * a); intersection_points.push_back(Intersection(t1, sphere)); intersection_points.push_back(Intersection(t2, sphere)); return intersection_points; } Intersections Ray::intersects(World &world) const { std::vector<Intersection> all_intersections; for (auto sphere : world.objects()) { auto curr_intersections = this->intersets(sphere); for (auto intersection : curr_intersections.items()) { all_intersections.push_back(intersection); } } std::sort(all_intersections.begin(), all_intersections.end()); return Intersections(all_intersections); } Ray Ray::transform(dito::util::Matrix m) const { auto transformed_direction = m * this->direction(); auto transformed_direction_vector = transformed_direction.to_vector(); auto transformed_origin = m * this->origin(); auto transformd_origin_point = transformed_origin.to_point(); return Ray(transformd_origin_point, transformed_direction_vector); } Computations Ray::prepare_computations(Intersection intersection) const { auto t = intersection.t(); auto object = intersection.object(); auto point = position(t); auto eye_vector = direction().negate().to_vector(); auto normal_vector = object->normal_at(point); bool inside = false; if (normal_vector.dot(eye_vector) < 0) { inside = true; normal_vector = normal_vector.negate().to_vector(); } return Computations( object, point, eye_vector, normal_vector, t, inside ); } Color Ray::color_at(dito::physics::World &world) const { Color c(0, 0, 0); auto intersections = this->intersects(world); auto hit = intersections.hit(); if (!hit.has_value()) { return c; } auto comps = this->prepare_computations(*hit); return world.shade_hit(comps); }
d53bbad07262d86bc6f7f684e99348c0bdb87063
bb0e580e3fd528ea5212f74eaab797116ff42ab9
/microbit_cpp_code/source/main.cc
259331590273734c514f1b49c0f4e2d13d51c3e9
[]
no_license
8n8/realbikenav
0676f41664ca56fe12fbe42b1ebeefe45dab3b8f
e493e2247b7e026c9aee3f2ed2c1cd8be6ce7d0f
refs/heads/master
2023-07-31T02:16:03.832891
2018-06-30T12:02:33
2018-06-30T12:02:33
405,713,661
0
0
null
null
null
null
UTF-8
C++
false
false
6,306
cc
main.cc
// It runs on the microbit. It receives information about what to // display on the LEDs from the parent computer via a USB serial port. // It reads the sensors and sends the readings to the parent computer. // It runs continuously. #include "MicroBit.h" MicroBit uBit; struct leds { bool new_destination; int direction; int recording_state; bool error_state; }; struct accel { int x; int y; int z; }; // It represents the data for sending to the output struct State { leds display; int compass; accel acceleration; int buttonAcounter; int buttonBcounter; }; // It represents all the input readings after parsing. struct InputData { leds display; int compass; accel acceleration; bool buttonA; bool buttonB; }; // It converts the display byte received from the serial port into // the led struct. void parse_display(const char &raw_display, leds &display) { display.new_destination = raw_display & 1; display.direction = (raw_display >> 1) & 15; display.recording_state = (raw_display >> 5) & 3; display.error_state = (raw_display >> 7) & 1; } // It reads all the inputs. void read_input(InputData &input_data) { parse_display( uBit.serial.read(1).charAt(0), input_data.display); input_data.compass = uBit.compass.heading(); input_data.acceleration.x = uBit.accelerometer.getX(); input_data.acceleration.y = uBit.accelerometer.getY(); input_data.acceleration.z = uBit.accelerometer.getZ(); input_data.buttonA = uBit.buttonA.isPressed(); input_data.buttonB = uBit.buttonB.isPressed(); } // It updates the state, given the new input data from the sensors // and the parent computer. void update_state(State &state, const InputData &input_data) { state.display = input_data.display; state.compass = input_data.compass; state.acceleration = input_data.acceleration; state.buttonAcounter = (state.buttonAcounter < 10000) * (state.buttonAcounter + input_data.buttonA); state.buttonBcounter = (state.buttonBcounter < 10000) * (state.buttonBcounter + input_data.buttonB); } // It sends an int to the parent computer. void sendInt(const int &the_int) { uBit.serial.sendChar(the_int & 0xff); uBit.serial.sendChar((the_int >> 8) & 0xff); uBit.serial.sendChar((the_int >> 16) & 0xff); uBit.serial.sendChar((the_int >> 24) & 0xff); } // It sends the message to the parent computer. void send_message_to_laptop(const State &state) { ManagedString compass(state.compass); ManagedString accelx(state.acceleration.x); ManagedString accely(state.acceleration.y); ManagedString accelz(state.acceleration.z); ManagedString buttonAcounter(state.buttonAcounter); ManagedString buttonBcounter(state.buttonBcounter); ManagedString space(" "); ManagedString line_end("\n"); ManagedString message = compass + space + accelx + space + accely + space + accelz + space + buttonAcounter + space + buttonBcounter + line_end; uBit.serial.send(message); } // It calculates the led number (0 - 24) from the direction code // (0 - 15). // // The direction codes are: // 14 15 0 1 2 // 13 3 // 12 4 // 11 5 // 10 9 8 7 6 // // The led codes are: // 0 1 2 3 4 // 5 6 7 8 9 // 10 11 12 13 14 // 15 16 17 18 19 // 20 21 22 23 24 int direction2led_num(const int &direction) { switch(direction) { case 0: return 2; case 1: return 3; case 2: return 4; case 3: return 9; case 4: return 14; case 5: return 19; case 6: return 24; case 7: return 23; case 8: return 22; case 9: return 21; case 10: return 20; case 11: return 15; case 12: return 10; case 13: return 5; case 14: return 0; case 15: return 1; } } // It lights up the leds, given the display information. void light_up_leds(const leds &display) { bool led_on_off[25] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; led_on_off[13] = display.new_destination; led_on_off[direction2led_num(display.direction)] = 1; switch(display.recording_state) { case 0: break; case 1: led_on_off[11] = 1; break; case 2: led_on_off[0] = 1; led_on_off[1] = 1; led_on_off[2] = 1; led_on_off[3] = 1; led_on_off[4] = 1; led_on_off[5] = 1; led_on_off[6] = 1; led_on_off[7] = 1; led_on_off[8] = 1; led_on_off[9] = 1; led_on_off[10] = 1; led_on_off[11] = 1; led_on_off[12] = 1; led_on_off[13] = 1; led_on_off[14] = 1; led_on_off[15] = 1; } if (display.error_state) { for (int i = 0; i < 25; i++) { led_on_off[i] = 1; } } MicroBitImage image(5, 5); int x, y; for (int i = 0; i < 25; i++) { x = i % 5; y = i / 5; image.setPixelValue(x, y, led_on_off[i] * 255); } uBit.display.print(image); } // It sends all the outputs. It sends the message to the parent computer // down the serial port, and updates the LED display. void send_output(const State &state) { send_message_to_laptop(state); light_up_leds(state.display); } int main() { // Initialise the micro:bit runtime. uBit.init(); // Insert your code here! // uBit.display.scroll("HELLO WORLD! :)"); uBit.compass.calibrate(); State state; state.display = {false, 0, 0, false}; state.compass = 0; state.acceleration = {0, 0, 0}; state.buttonAcounter = 0; state.buttonBcounter = 0; InputData input_data; while(true) { send_output(state); read_input(input_data); update_state(state, input_data); } // If main exits, there may still be other fibers running or // registered event handlers etc. // Simply release this fiber, which will mean we enter the scheduler. // Worse case, we then sit in the idle task forever, in a power // efficient sleep. release_fiber(); }
46fb3870ca1de7fb7ef45ee27f814829dfeb2b24
bbeaadef08cccb872c9a1bb32ebac7335d196318
/Fontes/Redegraf/VTRedegraf.h
033a976f0532ec5bc1f5a99119c8be7a6d6320f0
[]
no_license
danilodesouzapereira/plataformasinap_exportaopendss
d0e529b493f280aefe91b37e893359a373557ef8
c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f
refs/heads/master
2023-03-20T20:37:21.948550
2021-03-12T17:53:12
2021-03-12T17:53:12
347,150,304
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,936
h
VTRedegraf.h
//--------------------------------------------------------------------------- #ifndef VTRedegraf_H #define VTRedegraf_H //--------------------------------------------------------------------------- #include <Classes.hpp> #include "VTCoordenada.h" #include "..\Editor\Marca\VTMarca.h" #include "..\Rede\VTArea.h" #include "..\Rede\VTBarra.h" #include "..\Rede\VTEqbar.h" #include "..\Rede\VTLigacao.h" #include "..\Rede\VTMutua.h" #include "..\Rede\VTTrafo.h" #include "..\Rede\VTTrafo3E.h" #include "..\Rede\VTTrecho.h" #include "..\Rede\VTRedes.h" #include "..\Rede\VTRede.h" //--------------------------------------------------------------------------- enum modoGRAFICO {modoGEOREFERENCIADO=1, modoESQUEMATICO, modoESQ_FUNCIONAL}; //--------------------------------------------------------------------------- class VTApl; class VTArea; class VTCelula; class VTFiguraComentario; class VTLink; class VTRetangulo; //--------------------------------------------------------------------------- class VTRedegraf : public TObject { public: //property __property VTCoordenada* CoordBarra[VTEqpto*] = {read=PM_GetCoordLine}; __property VTCoordenada* CoordEqbar[VTEqpto*] = {read=PM_GetCoordLine}; __property VTCoordenada* CoordEqpto[VTEqpto*] = {read=PM_GetCoordEqpto}; __property VTCoordenada* CoordLigacao[VTEqpto*] = {read=PM_GetCoordEqpto}; __property VTCoordenada* CoordMutua[VTMutua*] = {read=PM_GetCoordMutua}; __property VTCoordenada* CoordMarca[VTMarca*] = {read=PM_GetCoordMarca}; __property VTCoordenada* CoordTrafo[VTEqpto*] = {read=PM_GetCoordLine}; __property VTCoordenada* CoordTrafo3E[VTTrafo3E*] = {read=PM_GetCoordTrafo3E}; __property VTCoordenada* CoordTrecho[VTTrecho*] = {read=PM_GetCoordTrecho}; __property TColor CorFundo = {read=PM_GetCorFundo, write=PM_SetCorFundo}; __property int ModoGrafico = {read=PM_GetModoGrafico, write=PM_SetModoGrafico}; public: __fastcall VTRedegraf(void) {}; virtual __fastcall ~VTRedegraf(void) {}; virtual bool __fastcall Area(TList *lisBAR, VTArea *area) = 0; virtual VTArea* __fastcall Area(VTCelula *celula) = 0; virtual VTArea* __fastcall Area(VTRede *rede) = 0; virtual VTArea* __fastcall Area(VTRedes *redes) = 0; virtual bool __fastcall CoordFigComentario(VTFiguraComentario *comentario, double escala, int &x1, int &y1, int &x2, int &y2) = 0; virtual bool __fastcall CoordFigLink(VTLink *link, double escala, int &x1, int &y1, int &x2, int &y2) = 0; virtual bool __fastcall CoordFigRetangulo(VTRetangulo *retangulo, double escala, int &x1, int &y1, int &x2, int &y2) = 0; protected: //métodos acessados via property virtual VTCoordenada* __fastcall PM_GetCoordEqpto(VTEqpto *eqpto) = 0; virtual VTCoordenada* __fastcall PM_GetCoordLine(VTEqpto *eqpto) = 0; virtual VTCoordenada* __fastcall PM_GetCoordMarca(VTMarca *marca) = 0; virtual VTCoordenada* __fastcall PM_GetCoordMutua(VTMutua *mutua) = 0; virtual VTCoordenada* __fastcall PM_GetCoordTrafo3E(VTTrafo3E *trafo3e) = 0; virtual VTCoordenada* __fastcall PM_GetCoordTrecho(VTTrecho *trecho) = 0; virtual TColor __fastcall PM_GetCorFundo(void) = 0; virtual int __fastcall PM_GetModoGrafico(void) = 0; virtual void __fastcall PM_SetCorFundo(TColor color) = 0; virtual void __fastcall PM_SetModoGrafico(int modo) = 0; }; //--------------------------------------------------------------------------- //protótipo de função para criar objetos VTRedegraf //--------------------------------------------------------------------------- VTRedegraf* __fastcall NewObjRedegraf(VTApl *apl); #endif //----------------------------------------------------------------------------- // eof
7bee9635c375497a4879a1e0bb96f7096069ad5b
416e31ae351bee33108e67a47bb558312d66b147
/ProiectTDMRC/ElementalDust.h
494b4b2d9f2d244060c61a3c73f5ac6967f318cf
[]
no_license
ZaharescuMihai/TDMRC-2015
a9b782b40128fde4b497dfa52938027128cd3faf
0f30e6b20f586ae34506d51aec2585a6c7289bd6
refs/heads/master
2020-05-18T13:23:54.040876
2015-04-29T02:22:19
2015-04-29T02:22:19
32,980,429
1
4
null
2015-03-31T08:29:09
2015-03-27T10:32:24
C++
UTF-8
C++
false
false
617
h
ElementalDust.h
#include "Direct_Access_Image.h" #include "stdafx.h" #include "particle.h" #include "fixed_float.h" class ElementalDust { int nr_particles_int; particle *partiles_prt; public: ElementalDust(); ~ElementalDust(); void import(KImage *import, float multiplicator); void import(char *file_name); void import(void *file_contents, size_t size); void SaveAs(char *file_name); void SaveAs(KImage *import, float multiplicator); ElementalDust& operator= (ElementalDust b_flt); bool operator==(ElementalDust &b_flt); bool operator!=(ElementalDust &b_flt); void sortParticles(); private: void clear(); };
ab2f685d607990d6a71c407979d05f4ab2d63c7c
2340859cdfd21ecf9bf5dd3d4dc3304b89ebf115
/dogpack-mapped/lib/2d/cart/ApplyPosLimiter.cpp
5449e6988e573e2caa4abcf75ef859063c72a05d
[]
no_license
smoe1/ThesisCode
56c97c440f7f8182f5be7dba76848741dcf9a9d6
bd535bc99d0add16787524bd2ac5c4a53f2d86ee
refs/heads/master
2021-01-24T07:18:55.455846
2017-06-07T02:15:40
2017-06-07T02:15:40
93,338,238
0
1
null
null
null
null
UTF-8
C++
false
false
7,191
cpp
ApplyPosLimiter.cpp
#include<cmath> #include "DogParams.h" #include "dogdefs.h" #include "dog_math.h" #include "Legendre2d.h" void ApplyPosLimiter(const dTensorBC4& aux, dTensorBC4& q) { double Min(double, double); const int mx = q.getsize(1); const int my = q.getsize(2); const int meqn = q.getsize(3); const int kmax = q.getsize(4); const int mbc = q.getmbc(); const int maux = aux.getsize(2); const int space_order = dogParams.get_space_order(); // ------------------------------------------------ // // number of points where we want to check solution // // ------------------------------------------------ // const int mpoints_on_corners = 4; const int mpoints_on_edges = 4*space_order; const int mpoints_L2Proj = (space_order)*(space_order); ///////////// Change this quantity if needed to check more points ///////////// // const int mpoints = mpoints_on_corners + mpoints_on_edges + mpoints_L2Proj; const int mpoints = mpoints_L2Proj; /////////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------- // // sample basis at all points where we want to check solution // // ---------------------------------------------------------- // dTensor2 spts(mpoints,2); void SetPositivePoints(const int& space_order, dTensor2& spts); SetPositivePoints(space_order,spts); void SamplePhiAtPositivePoints(const int& space_order, const dTensor2& spts, dTensor2& phi); dTensor2 phi(mpoints,kmax); SamplePhiAtPositivePoints(space_order,spts,phi); // -------------------------------------------------------------- // // q_limited = Q1 + \theta ( q(xi,eta) - Q1 ) // // where theta = min(1, |Q1| / |Q1-m|; m = min_{i} q(xi_i, eta_i) // // -------------------------------------------------------------- // #pragma omp parallel for for(int i=1-mbc; i <= mx+mbc; i++) for(int j=1-mbc; j <= my+mbc; j++) for(int me=1; me <= meqn; me++) { double m = 0.0; for(int mp=1; mp <= mpoints; mp++) { // evaluate q at spts(mp) // double qnow = 0.0; for( int k=1; k <= kmax; k++ ) { qnow += q.get(i,j,me,k) * phi.get(mp,k); } m = Min(m, qnow); } double theta = 0.0; double Q1 = q.get(i,j,me,1); if( fabs( Q1 - m ) < 1.0e-14 ){ theta = 1.0; } else{ theta = Min( 1.0, fabs( Q1 / (Q1 - m) ) ); } // limit q // for( int k=2; k <= kmax; k++ ) { q.set(i,j,me,k, q.get(i,j,me,k) * theta ); } } } void SetPositivePoints(const int& space_order, dTensor2& spts) { dTensor1 s1d(space_order); // 1D Gaussian quadrature points switch ( space_order ) { case 1: s1d.set(1, 0.0e0 ); break; case 2: s1d.set(1, -1.0/sq3 ); s1d.set(2, 1.0/sq3 ); break; case 3: s1d.set(1, -sq3/sq5 ); s1d.set(2, 0.0e0 ); s1d.set(3, sq3/sq5 ); break; case 4: s1d.set(1, -sqrt(3.0+sqrt(4.8))/sq7 ); s1d.set(2, -sqrt(3.0-sqrt(4.8))/sq7 ); s1d.set(3, sqrt(3.0-sqrt(4.8))/sq7 ); s1d.set(4, sqrt(3.0+sqrt(4.8))/sq7 ); break; case 5: s1d.set(1, -sqrt(5.0 + sqrt(40.0/7.0))/3.0 ); s1d.set(2, -sqrt(5.0 - sqrt(40.0/7.0))/3.0 ); s1d.set(3, 0.0 ); s1d.set(4, sqrt(5.0 - sqrt(40.0/7.0))/3.0 ); s1d.set(5, sqrt(5.0 + sqrt(40.0/7.0))/3.0 ); break; } // This region has been commented out because we are no longer applying // the limiter at the corner points // 2D points -- corners // spts.set(1,1, -1.0e0 ); // spts.set(1,2, -1.0e0 ); // spts.set(2,1, 1.0e0 ); // spts.set(2,2, -1.0e0 ); // spts.set(3,1, -1.0e0 ); // spts.set(3,2, 1.0e0 ); // spts.set(4,1, 1.0e0 ); // spts.set(4,2, 1.0e0 ); // 2D points -- left, right, bottom and top edges // for (int m=1; m<=space_order; m++) // { // double s = s1d.get(m); // // left edge // spts.set(4+m,1, -1.0e0 ); // spts.set(4+m,2, s ); // // right edge // spts.set(4+space_order+m,1, 1.0e0 ); // spts.set(4+space_order+m,2, s ); // // bottom edge // spts.set(4+2*space_order+m,1, s ); // spts.set(4+2*space_order+m,2, -1.0e0 ); // // top edge // spts.set(4+3*space_order+m,1, s ); // spts.set(4+3*space_order+m,2, 1.0e0 ); // } // 2D points -- all interior points int z = 4+4*space_order; z = 0; for (int m=1; m<=space_order; m++) for (int k=1; k<=space_order; k++) { double s1 = s1d.get(m); double s2 = s1d.get(k); z = z+1; spts.set(z,1, s1d.get(m) ); spts.set(z,2, s1d.get(k) ); } } void SamplePhiAtPositivePoints(const int& space_order, const dTensor2& spts, dTensor2& phi) { const int mpoints = spts.getsize(1); for (int m=1; m<=mpoints; m++) { // grid point (x,y) const double xi = spts.get(m,1); const double eta = spts.get(m,2); const double xi2 = xi*xi; const double xi3 = xi*xi2; const double xi4 = xi*xi3; const double eta2 = eta*eta; const double eta3 = eta*eta2; const double eta4 = eta*eta3; // Legendre basis functions at each gaussian quadrature point in the // interval [-1,1]x[-1,1]. switch( space_order ) { case 5: // fifth order phi.set( m,15, 105.0/8.0*eta4 - 45.0/4.0*eta2 + 9.0/8.0 ); phi.set( m,14, 105.0/8.0*xi4 - 45.0/4.0*xi2 + 9.0/8.0 ); phi.set( m,13, 5.0/4.0*(3.0*xi2 - 1.0)*(3.0*eta2 - 1.0) ); phi.set( m,12, sq3*sq7*(2.5*eta3 - 1.5*eta)*xi ); phi.set( m,11, sq3*sq7*(2.5*xi3 - 1.5*xi)*eta ); case 4: // fourth order phi.set( m,10, sq7*(2.5*eta3 - 1.5*eta) ); phi.set( m,9, sq7*(2.5*xi3 - 1.5*xi) ); phi.set( m,8, sq3*sq5*xi*(1.5*eta2 - 0.5) ); phi.set( m,7, sq3*sq5*eta*(1.5*xi2 - 0.5) ); case 3: // third order phi.set( m,6, sq5*(1.5*eta2 - 0.5) ); phi.set( m,5, sq5*(1.5*xi2 - 0.5) ); phi.set( m,4, 3.0*xi*eta ); case 2: // second order phi.set( m,3, sq3*eta ); phi.set( m,2, sq3*xi ); case 1: // first order phi.set( m,1, 1.0 ); break; default: unsupported_value_error(space_order); } } }
f67173ab10b346086348df0e76bc4047680c41ae
48e5c5039435deb0ac0e64ce8bc00ddc5e9c83b2
/The Road/The Road/VertexBuffer2D.cpp
773dc5f55deb3ccdaa236b025374f92e131b064a
[]
no_license
ThimbleFire/CPP-DirectX-June-2010
b70e2613604facd7c9dea850774c511f175aaa9f
52884a90a5932e5199a030605d14616fd9d4b2ba
refs/heads/main
2022-12-26T03:30:44.673542
2020-10-14T09:01:55
2020-10-14T09:01:55
303,959,387
0
0
null
null
null
null
UTF-8
C++
false
false
6,090
cpp
VertexBuffer2D.cpp
#include "VertexBuffer2D.h" VertexBuffer2D::VertexBuffer2D() { m_vertexBuffer = nullptr; m_indexBuffer = nullptr; Translate(0.0f, 0.0f, 0.0f); Rotate(0.0f); } VertexBuffer2D::~VertexBuffer2D() { } bool VertexBuffer2D::Initialize(ID3D11Device* device, unsigned int screenWidth, unsigned int screenHeight) { bool result; screenWidth_ = screenWidth; screenHeight_ = screenHeight; oldX = -1; oldY = -1; result = InitializeBuffers(device); if(!result) return false; return true; } void VertexBuffer2D::Shutdown() { if(m_indexBuffer) { m_indexBuffer->Release(); m_indexBuffer = nullptr; } if(m_vertexBuffer) { m_vertexBuffer->Release(); m_vertexBuffer = nullptr; } } int VertexBuffer2D::GetIndexCount() { return m_indexCount; } bool VertexBuffer2D::InitializeBuffers(ID3D11Device* device) { VertexType* vertices; unsigned long* indices; D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc; D3D11_SUBRESOURCE_DATA vertexData, indexData; HRESULT result; m_vertexCount = 6; m_indexCount = 6; vertices = new VertexType[m_vertexCount]; if(!vertices) return false; indices = new unsigned long[m_indexCount]; if(!indices) return false; memset(vertices, 0, (sizeof(VertexType) * m_vertexCount)); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 4; //altern indices[5] = 5; vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; vertexData.pSysMem = vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer); if(FAILED(result)) return false; indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; indexData.pSysMem = indices; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer); if(FAILED(result)) return false; delete[] vertices; vertices = nullptr; delete[] indices; indices = nullptr; return true; } bool VertexBuffer2D::UpdateBuffers(ID3D11DeviceContext* deviceContext, float positionOnScreenX, float positionOnScreenY, SourceRectangle sourceRectangle, float textureWidth, float textureHeight) { if(oldX == positionOnScreenX && oldY == positionOnScreenY) return true; oldX = positionOnScreenX; oldY = positionOnScreenY; VertexType* vertices; unsigned long* indices; D3D11_MAPPED_SUBRESOURCE mappedResource; vertices = nullptr; vertices = new VertexType[m_vertexCount]; indices = nullptr; indices = new unsigned long[m_indexCount]; positionOnScreenX = (float)(((float)screenWidth_ / 2) * (-1) + positionOnScreenX); positionOnScreenY = -(float)(((float)screenHeight_ / 2) * (-1) + positionOnScreenY); //in future, try to find a way to manually get these numbers //as we'll need to render a UI and not all objects will be of this resolution. float left = positionOnScreenX; float right = positionOnScreenX + ((sourceRectangle.W * textureWidth)); float top = positionOnScreenY; float bot = positionOnScreenY - ((sourceRectangle.H * textureHeight)); vertices[0].position = D3DXVECTOR3( left, top, 0.0f); vertices[1].position = D3DXVECTOR3( right, bot, 0.0f); vertices[2].position = D3DXVECTOR3( left, bot, 0.0f); vertices[3].position = D3DXVECTOR3( left, top, 0.0f); vertices[4].position = D3DXVECTOR3( right, top, 0.0f); vertices[5].position = D3DXVECTOR3( right, bot, 0.0f); //TOP LEFT vertices[0].texture = D3DXVECTOR2(sourceRectangle.X, sourceRectangle.Y); //BOTTOM RIGHT vertices[1].texture = D3DXVECTOR2(sourceRectangle.X + sourceRectangle.W, sourceRectangle.Y + sourceRectangle.H); //BOTTOM LEFT vertices[2].texture = D3DXVECTOR2(sourceRectangle.X, sourceRectangle.Y + sourceRectangle.H); //TOP LEFT vertices[3].texture = D3DXVECTOR2(sourceRectangle.X, sourceRectangle.Y); //TOP RIGHT vertices[4].texture = D3DXVECTOR2(sourceRectangle.X + sourceRectangle.W, sourceRectangle.Y); //BOTTOM LEFT vertices[5].texture = D3DXVECTOR2(sourceRectangle.X + sourceRectangle.W, sourceRectangle.Y + sourceRectangle.H); //lock vertex buffer so it can be written to. HRESULT result = deviceContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) return false; VertexType* src = nullptr; src = (VertexType*)mappedResource.pData; memcpy(src, (void*)vertices, (sizeof(VertexType) * m_vertexCount)); deviceContext->Unmap(m_vertexBuffer, 0); delete [] vertices; vertices = nullptr; delete [] indices; indices = nullptr; return true; } void VertexBuffer2D::Translate(float x, float y, float z) { D3DXMatrixTranslation(&matrix_translation_, x, y, z); } void VertexBuffer2D::Rotate(float angle) { D3DXMatrixRotationY(&matrix_rotation_, angle); } bool VertexBuffer2D::Render(ID3D11DeviceContext* deviceContext, float positionOnScreenX, float positionOnScreenY, Texture2D* texture, SourceRectangle sourceRectangle, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, D3DXVECTOR4 colour) { unsigned int stride, offset; stride= sizeof(VertexType); offset = 0; UpdateBuffers(deviceContext, positionOnScreenX, positionOnScreenY, sourceRectangle, texture->GetWidth(), texture->GetHeight()); worldMatrix *= matrix_translation_ * matrix_rotation_; deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset); deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return true; }
497b09a5d06a0b0a66137164cdb4137a52a1f6f0
6cb2d86ef616ac145baee0670a89f05c49921d99
/include/JustMath/Beta.hpp
f93ca9947d3b1054401a4ea83b26b5475ab275ee
[ "MIT" ]
permissive
alexander-valov/IncompleteBeta
9503aae6e810aaceebb9b6bbdcfe58b4bac27396
4b3cc7f7eb1d07dfe0a921173695efe88d0206dc
refs/heads/master
2023-08-06T01:39:52.614427
2021-09-12T09:10:27
2021-09-12T09:10:27
405,302,766
0
0
null
null
null
null
UTF-8
C++
false
false
9,394
hpp
Beta.hpp
/* IncompleteBeta https://github.com/alexander-valov/IncompleteBeta MIT License Copyright (c) 2021 Alexander Valov <https://github.com/alexander-valov> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <cmath> #include <limits> #include <stdexcept> #include <type_traits> namespace JustMath { /************************************************************************ * @brief Utility structures to promote floating point types. ************************************************************************/ namespace detail { template<class T, bool = std::is_integral<T>::value> struct promote_fp { typedef double type; }; template<class T> struct promote_fp<T, false> {}; template<> struct promote_fp<long double> { typedef long double type; }; template<> struct promote_fp<double> { typedef double type; }; template<> struct promote_fp<float> { typedef float type; }; template< class T1, class T2, class TP1 = typename promote_fp<T1>::type, class TP2 = typename promote_fp<T2>::type > struct promote_fp_2 { typedef std::remove_reference_t<decltype(TP1() + TP2())> type; }; template< class T1, class T2, class T3, class TP1 = typename promote_fp<T1>::type, class TP2 = typename promote_fp<T2>::type, class TP3 = typename promote_fp<T3>::type > struct promote_fp_3 { typedef std::remove_reference_t<decltype(TP1() + TP2() + TP3())> type; }; /******************************************************************** * @brief Implementation of beta function. * @param[in] a Argument a > 0 * @param[in] b Argument b > 0 * @return beta(a, b) ******************************************************************** */ template<class T> T beta_impl(const T& a, const T& b) { return std::exp(std::lgamma(a) + std::lgamma(b) - std::lgamma(a + b)); } /******************************************************************** * @brief Implementation of incomplete beta function. * @param[in, out] x Argument 0 <= x <= 1 * @param[in] a Argument a > 0 * @param[in] b Argument b > 0 * @param[in] TOL Continued fraction approximation tolerance * @param[in] MAX_ITER Continued fraction approximation max iterations * @return Approximation of B(x, a, b) ******************************************************************** */ template<class T> T incbeta_impl( const T& x, const T& a, const T& b, const T& TOL = T(1e-8), unsigned MAX_ITER = 200 ) { if (x < 0 || x > 1) { throw std::domain_error("incbeta(x, a, b): The argument 'x' must be inside [0, 1] interval"); } if (a <= 0) { throw std::domain_error("incbeta(x, a, b): The argument 'a' must be greater than zero"); } if (b <= 0) { throw std::domain_error("incbeta(x, a, b): The argument 'b' must be greater than zero"); } // ----------------------------------------------------------- // Limiting cases // ----------------------------------------------------------- if (x == T(0)) { return T(0); } if (x == T(1)) { return beta_impl(a, b); } // ----------------------------------------------------------- // The continued fraction converges rapidly for // x < (a + 1) / (a + b + 2) // In other cases is used symmetry relation // B(x, a, b) = beta(a, b) - B(1 - x, b, a) // ----------------------------------------------------------- if (x - (a + 1) / (a + b + 2) > std::numeric_limits<T>::epsilon()) { return (beta_impl(a, b) - incbeta_impl(1 - x, b, a, TOL, MAX_ITER)); } // ----------------------------------------------------------- // Calculate the front part of incomplete beta function // ----------------------------------------------------------- T front = std::exp(a * std::log(x) + b * std::log(1 - x)) / a; // ----------------------------------------------------------- // Calculate continued fraction part using Lentz's algorithm // ----------------------------------------------------------- T D = 0; T C = 1; T F = 1; T CD = 0; T THRESHOLD = T(1e-30); for (unsigned i = 0; i < MAX_ITER; i++) { // ----------------------------------------------------------- // Calculate numerator of continued fraction // ----------------------------------------------------------- T numerator; unsigned m = i / 2; if (i == 0) { numerator = 1; } else if (i % 2 == 0) { numerator = (m * (b - m) * x) / ((a + 2 * m - 1) * (a + 2 * m)); } else { numerator = -((a + m) * (a + b + m) * x) / ((a + 2 * m) * (a + 2 * m + 1)); } // ----------------------------------------------------------- // Iteration of Lentz's algorithm // ----------------------------------------------------------- D = 1 + numerator * D; if (std::abs(D) < THRESHOLD) { D = THRESHOLD; } D = 1 / D; C = 1 + numerator / C; if (std::abs(C) < THRESHOLD) { C = THRESHOLD; } CD = C * D; F *= CD; // ----------------------------------------------------------- // Check for convergence // ----------------------------------------------------------- if (std::abs(1 - CD) < TOL) { return front * (F - 1); } } throw std::logic_error("incbeta(x, a, b): no convergence for given TOL and MAX_ITER"); } } // detail namespace /******************************************************************** * @brief Beta function. * * @see https://en.wikipedia.org/wiki/Beta_function * * @param[in] a Argument a > 0 * @param[in] b Argument b > 0 * @return beta(a, b) ******************************************************************** */ template<class Ta, class Tb> typename detail::promote_fp_2<Ta, Tb>::type beta( const Ta& a, const Tb& b ) { typedef typename detail::promote_fp_2<Ta, Tb>::type type; return detail::beta_impl<type>(a, b); } /******************************************************************** * @brief Incomplete beta function. * * Incomplete beta function symmetry: * B(x, a, b) = beta(a, b) - B(1 - x, b, a) * * @see https://codeplea.com/incomplete-beta-function-c * @see https://dlmf.nist.gov/8.17#SS5.p1 * * @param[in, out] x Argument 0 <= x <= 1 * @param[in] a Argument a > 0 * @param[in] b Argument b > 0 * @param[in] TOL Continued fraction approximation tolerance * @param[in] MAX_ITER Continued fraction approximation max iterations * @return Approximation of B(x, a, b) ******************************************************************** */ template<class Tx, class Ta, class Tb> typename detail::promote_fp_3<Tx, Ta, Tb>::type incbeta( const Tx& x, const Ta& a, const Tb& b, const typename detail::promote_fp_3<Tx, Ta, Tb>::type& TOL = typename detail::promote_fp_3<Tx, Ta, Tb>::type(1e-8), unsigned MAX_ITER = 200 ) { typedef typename detail::promote_fp_3<Tx, Ta, Tb>::type type; return detail::incbeta_impl<type>(x, a, b, TOL, MAX_ITER); } /******************************************************************** * @brief Regularized incomplete beta function: * I(x, a, b) = B(x, a, b) / B(a, b) * @param[in, out] x Argument 0 <= x <= 1 * @param[in] a Argument a > 0 * @param[in] b Argument b > 0 * @param[in] TOL Continued fraction approximation tolerance * @param[in] MAX_ITER Continued fraction approximation max iterations * @return Approximation of I(x, a, b) ******************************************************************** */ template<class Tx, class Ta, class Tb> typename detail::promote_fp_3<Tx, Ta, Tb>::type incbeta_reg( const Tx& x, const Ta& a, const Tb& b, const typename detail::promote_fp_3<Tx, Ta, Tb>::type& TOL = typename detail::promote_fp_3<Tx, Ta, Tb>::type(1e-8), unsigned MAX_ITER = 200 ) { return incbeta(x, a, b, TOL, MAX_ITER) / beta(a, b); } } // JustMath namespace
4e3e0f304430aa5d4b78283100a80a2d2a59b36d
49e1bc7edabeb7c1f2d9c8d6ae8c4bc1f8a3ec4b
/BambooCC/Geometry/Polygon.h
873c8bee77a9be55542e31d88b1dcd80e1661ea0
[]
no_license
ngoaho91/bamboocc
8ff38dd28f8493716bad63368b77bd9177c31bbe
e3800af23f97b099cd40e2f2e94265da1c2262a7
refs/heads/master
2021-01-01T05:49:05.729457
2014-04-07T16:48:27
2014-04-07T16:48:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
606
h
Polygon.h
#ifndef Polygon_h #define Polygon_h #include "Rectangle.h" #include "QuadTree.h" #include "Node.h" #define QOT_POLYGON 1 namespace Geometry { class Polygon :public QuadObject, public Nodes { public: Polygon(); ~Polygon(); void CalculateAABB(); bool PointInsideBB(Node* node); Polygon::iterator GetNext(Polygon::iterator it); Polygon::iterator GetPrevious(Polygon::iterator it); }; typedef vector<Polygon*> Polygons; class ConvexHull :public Polygon { public: ConvexHull(); ConvexHull(Polygon* polygon); ~ConvexHull(); }; typedef vector<ConvexHull*> ConvexHulls; } #endif
9fa4751f7644ec4b74aade79e1f7290a9250bf69
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/C/C/E/D/ACCED.h
e9c0901f546f8da394fffac490b3d994b0b75ddf
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
65
h
ACCED.h
#ifndef ACCED_H namespace ACCED { std::string run(); } #endif
c487ba21326e3adc472b75300f04d4245e17441b
c1f89beed3118eed786415e2a6d378c28ecbf6bb
/src/md/compiler/newmerger.cpp
9ae8ab6753cfd01f7d9f0b19d8eba956fd5b867c
[ "MIT" ]
permissive
mono/coreclr
0d85c616ffc8db17f9a588e0448f6b8547324015
90f7060935732bb624e1f325d23f63072433725f
refs/heads/mono
2023-08-23T10:17:23.811021
2019-03-05T18:50:49
2019-03-05T18:50:49
45,067,402
10
4
NOASSERTION
2019-03-05T18:50:51
2015-10-27T20:15:09
C#
UTF-8
C++
false
false
262,939
cpp
newmerger.cpp
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // //***************************************************************************** // NewMerger.cpp // // // contains utility code to MD directory // // This file provides Compiler Support functionality in metadata. //***************************************************************************** #include "stdafx.h" #include "newmerger.h" #include "regmeta.h" #include "importhelper.h" #include "rwutil.h" #include "mdlog.h" #include <posterror.h> #include <sstring.h> #include "ndpversion.h" #ifdef FEATURE_METADATA_EMIT_ALL #define MODULEDEFTOKEN TokenFromRid(1, mdtModule) #define COR_MSCORLIB_NAME "mscorlib" #define COR_MSCORLIB_TYPEREF {0xb7, 0x7a, 0x5c, 0x56,0x19,0x34,0xe0,0x89} #define COR_CONSTRUCTOR_METADATA_IDENTIFIER W(".ctor") #define COR_COMPILERSERVICE_NAMESPACE "System.Runtime.CompilerServices" #define COR_EXCEPTIONSERVICE_NAMESPACE "System.Runtime.ExceptionServices" #define COR_SUPPRESS_MERGE_CHECK_ATTRIBUTE "SuppressMergeCheckAttribute" #define COR_HANDLE_PROCESS_CORRUPTED_STATE_EXCEPTION_ATTRIBUTE "HandleProcessCorruptedStateExceptionsAttribute" #define COR_MISCBITS_NAMESPACE "Microsoft.VisualC" #define COR_MISCBITS_ATTRIBUTE "Microsoft.VisualC.MiscellaneousBitsAttribute" #define COR_NATIVECPPCLASS_ATTRIBUTE "System.Runtime.CompilerServices.NativeCppClassAttribute" // MODULE_CA_LOCATION W("System.Runtime.CompilerServices.AssemblyAttributesGoHere") #define MODULE_CA_TYPENAME "AssemblyAttributesGoHere" // fake assembly type-ref for hanging Assembly-level CAs off of //***************************************************************************** // BEGIN: Security Critical Attributes and Enumeration //***************************************************************************** #define COR_SECURITYCRITICALSCOPE_ENUM_W W("System.Security.SecurityCriticalScope") #define COR_SECURITYCRITICAL_ATTRIBUTE_FULL "System.Security.SecurityCriticalAttribute" #define COR_SECURITYTRANSPARENT_ATTRIBUTE_FULL "System.Security.SecurityTransparentAttribute" #define COR_SECURITYTREATASSAFE_ATTRIBUTE_FULL "System.Security.SecurityTreatAsSafeAttribute" #define COR_SECURITYCRITICAL_ATTRIBUTE_FULL_W W("System.Security.SecurityCriticalAttribute") #define COR_SECURITYTRANSPARENT_ATTRIBUTE_FULL_W W("System.Security.SecurityTransparentAttribute") #define COR_SECURITYTREATASSAFE_ATTRIBUTE_FULL_W W("System.Security.SecurityTreatAsSafeAttribute") #define COR_SECURITYSAFECRITICAL_ATTRIBUTE_FULL_W W("System.Security.SecuritySafeCriticalAttribute") // definitions of enumeration for System.Security.SecurityCriticalScope (Explicit or Everything) #define COR_SECURITYCRITICAL_CTOR_ARGCOUNT_NO_SCOPE 0 #define COR_SECURITYCRITICAL_CTOR_ARGCOUNT_SCOPE_EVERYTHING 1 #define COR_SECURITYCRITICAL_CTOR_NO_SCOPE_SIG_MAX_SIZE (3) #define COR_SECURITYCRITICAL_CTOR_SCOPE_SIG_MAX_SIZE (5 + sizeof(mdTypeRef) * 1) #define COR_SECURITYCRITICAL_ATTRIBUTE_NAMESPACE "System.Security" #define COR_SECURITYCRITICAL_ATTRIBUTE "SecurityCriticalAttribute" #define COR_SECURITYTRANSPARENT_ATTRIBUTE_NAMESPACE "System.Security" #define COR_SECURITYTRANSPARENT_ATTRIBUTE "SecurityTransparentAttribute" #define COR_SECURITYTREATASSAFE_ATTRIBUTE_NAMESPACE "System.Security" #define COR_SECURITYTREATASSAFE_ATTRIBUTE "SecurityTreatAsSafeAttribute" #define COR_SECURITYSAFECRITICAL_ATTRIBUTE "SecuritySafeCriticalAttribute" #define COR_SECURITYCRITICAL_ATTRIBUTE_VALUE_EVERYTHING { 0x01, 0x00 ,0x01, 0x00, 0x00, 0x00 ,0x00, 0x00 } #define COR_SECURITYCRITICAL_ATTRIBUTE_VALUE_EXPLICIT {0x01, 0x00, 0x00 ,0x00} #define COR_SECURITYTREATASSAFE_ATTRIBUTE_VALUE {0x01, 0x00, 0x00 ,0x00} // if true, then registry has been read for enabling or disabling SecurityCritical support static BOOL g_fRefShouldMergeCriticalChecked = FALSE; // by default, security critical attributes will be merged (e.g. unmarked CRT marked Critical/TAS) // - unless registry config explicitly disables merging static BOOL g_fRefShouldMergeCritical = TRUE; //***************************************************************************** // END: Security Critical Attributes and Enumeration //***************************************************************************** //***************************************************************************** // Checks to see if the given type is managed or native. We'll key off of the // Custom Attribute "Microsoft.VisualC.MiscellaneousBitsAttribute". If the third // byte has the 01000000 bit set then it is an unmanaged type. // If we can't find the attribute, we will also check for the presence of the // "System.Runtime.CompilerServices.NativeCppClassAttribute" Custom Attribute // since the CPP compiler stopped emitting MiscellaneousBitsAttribute in Dev11. //***************************************************************************** HRESULT IsManagedType(CMiniMdRW* pMiniMd, mdTypeDef td, BOOL *fIsManagedType) { // First look for the custom attribute HENUMInternal hEnum; HRESULT hr = S_OK; IfFailRet(pMiniMd->CommonEnumCustomAttributeByName(td, COR_MISCBITS_ATTRIBUTE, false, &hEnum)); // If there aren't any custom attributes here, then this must be a managed type if (hEnum.m_ulCount > 0) { // Let's loop through these, and see if any of them have that magical bit set. mdCustomAttribute ca; CustomAttributeRec *pRec; ULONG cbData = 0; while(HENUMInternal::EnumNext(&hEnum, &ca)) { const BYTE* pData = NULL; IfFailGo(pMiniMd->GetCustomAttributeRecord(RidFromToken(ca), &pRec)); IfFailGo(pMiniMd->getValueOfCustomAttribute(pRec, &pData, &cbData)); if (pData != NULL && cbData >=3) { // See if the magical bit is set to make this an unmanaged type if ((*(pData+2)&0x40) > 0) { // Yes, this is an unmanaged type HENUMInternal::ClearEnum(&hEnum); *fIsManagedType = FALSE; return S_OK; } } } } HENUMInternal::ClearEnum(&hEnum); // If this was emitted by a Dev11+ CPP compiler, we only have NativeCppClassAttribute // so let's check for that before calling this a managed class. IfFailRet(pMiniMd->CommonEnumCustomAttributeByName(td, COR_NATIVECPPCLASS_ATTRIBUTE, false, &hEnum)); if (hEnum.m_ulCount > 0) { // Yes, this is an unmanaged type HENUMInternal::ClearEnum(&hEnum); *fIsManagedType = FALSE; return S_OK; } // Nope, this isn't an unmanaged type.... must be managed HENUMInternal::ClearEnum(&hEnum); *fIsManagedType = TRUE; hr = S_OK; ErrExit: return hr; }// IsManagedType //***************************************************************************** // "Is CustomAttribute from certain namespace and assembly" check helper // Returns S_OK and fills **ppTypeRefRec. // Returns error code or S_FALSE otherwise as not found and fills **ppTypeRefRec with NULL. //***************************************************************************** HRESULT IsAttributeFromNamespace( CMiniMdRW *pMiniMd, mdToken tk, LPCSTR szNamespace, LPCSTR szAssembly, TypeRefRec **ppTypeRefRec) { HRESULT hr = S_OK; if(TypeFromToken(tk) == mdtMemberRef) { MemberRefRec *pMemRefRec; IfFailGo(pMiniMd->GetMemberRefRecord(RidFromToken(tk), &pMemRefRec)); tk = pMiniMd->getClassOfMemberRef(pMemRefRec); } if(TypeFromToken(tk) == mdtTypeRef) { TypeRefRec *pTypeRefRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tk), &pTypeRefRec)); LPCSTR szTypeRefNamespace; IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szTypeRefNamespace)); if (strcmp(szTypeRefNamespace, szNamespace) == 0) { mdToken tkResTmp = pMiniMd->getResolutionScopeOfTypeRef(pTypeRefRec); if (TypeFromToken(tkResTmp) == mdtAssemblyRef) { AssemblyRefRec *pAsmRefRec; IfFailGo(pMiniMd->GetAssemblyRefRecord(RidFromToken(tkResTmp), &pAsmRefRec)); LPCSTR szAssemblyRefName; IfFailGo(pMiniMd->getNameOfAssemblyRef(pAsmRefRec, &szAssemblyRefName)); if(SString::_stricmp(szAssemblyRefName, szAssembly) == 0) { *ppTypeRefRec = pTypeRefRec; return S_OK; } } } } // Record not found hr = S_FALSE; ErrExit: *ppTypeRefRec = NULL; return hr; } //***************************************************************************** // constructor //***************************************************************************** NEWMERGER::NEWMERGER() : m_pRegMetaEmit(0), m_pImportDataList(NULL), m_optimizeRefToDef(MDRefToDefDefault), m_isscsSecurityCritical(ISSCS_Unknown), m_isscsSecurityCriticalAllScopes(~ISSCS_Unknown) { m_pImportDataTail = &(m_pImportDataList); #if _DEBUG m_iImport = 0; #endif // _DEBUG } // NEWMERGER::NEWMERGER() //***************************************************************************** // initializer //***************************************************************************** HRESULT NEWMERGER::Init(RegMeta *pRegMeta) { HRESULT hr = NOERROR; MergeTypeData * pMTD; m_pRegMetaEmit = pRegMeta; // burn an entry so that the RID matches the array index IfNullGo(pMTD = m_rMTDs.Append()); pMTD->m_bSuppressMergeCheck = false; pMTD->m_cMethods = 0; pMTD->m_cFields = 0; pMTD->m_cEvents = 0; pMTD->m_cProperties = 0; ErrExit: return hr; } // NEWMERGER::Init //***************************************************************************** // destructor //***************************************************************************** NEWMERGER::~NEWMERGER() { if (m_pImportDataList) { // delete this list and release all AddRef'ed interfaces! MergeImportData *pNext; for (pNext = m_pImportDataList; pNext != NULL; ) { pNext = m_pImportDataList->m_pNextImportData; if (m_pImportDataList->m_pHandler) m_pImportDataList->m_pHandler->Release(); if (m_pImportDataList->m_pHostMapToken) m_pImportDataList->m_pHostMapToken->Release(); if (m_pImportDataList->m_pMDTokenMap) delete m_pImportDataList->m_pMDTokenMap; m_pImportDataList->m_pRegMetaImport->Release(); delete m_pImportDataList; m_pImportDataList = pNext; } } } // NEWMERGER::~NEWMERGER //***************************************************************************** CMiniMdRW *NEWMERGER::GetMiniMdEmit() { return &(m_pRegMetaEmit->m_pStgdb->m_MiniMd); } // CMiniMdRW *NEWMERGER::GetMiniMdEmit() //***************************************************************************** // Adding a new import //***************************************************************************** HRESULT NEWMERGER::AddImport( IMetaDataImport2 *pImport, // [IN] The scope to be merged. IMapToken *pHostMapToken, // [IN] Host IMapToken interface to receive token remap notification IUnknown *pHandler) // [IN] An object to receive error notification. { HRESULT hr = NOERROR; MergeImportData *pData; RegMeta *pRM = static_cast<RegMeta*>(pImport); // Add a MergeImportData to track the information for this import scope pData = new (nothrow) MergeImportData; IfNullGo( pData ); pData->m_pRegMetaImport = pRM; pData->m_pRegMetaImport->AddRef(); pData->m_pHostMapToken = pHostMapToken; if (pData->m_pHostMapToken) pData->m_pHostMapToken->AddRef(); if (pHandler) { pData->m_pHandler = pHandler; pData->m_pHandler->AddRef(); } else { pData->m_pHandler = NULL; } pData->m_pMDTokenMap = NULL; pData->m_pNextImportData = NULL; #if _DEBUG pData->m_iImport = ++m_iImport; #endif // _DEBUG pData->m_tkHandleProcessCorruptedStateCtor = mdTokenNil; // add the newly create node to the tail of the list *m_pImportDataTail = pData; m_pImportDataTail = &(pData->m_pNextImportData); ErrExit: return hr; } // HRESULT NEWMERGER::AddImport() HRESULT NEWMERGER::InitMergeTypeData() { CMiniMdRW *pMiniMdEmit; ULONG cTypeDefRecs; ULONG i, j; bool bSuppressMergeCheck; ULONG ridStart, ridEnd; RID ridMap; mdToken tkSuppressMergeCheckCtor = mdTokenNil; mdToken tkCA; mdMethodDef mdEmit; mdFieldDef fdEmit; mdEvent evEmit; mdProperty prEmit; TypeDefRec *pTypeDefRec; EventMapRec *pEventMapRec; PropertyMapRec *pPropertyMapRec; MergeTypeData *pMTD; HRESULT hr = NOERROR; pMiniMdEmit = GetMiniMdEmit(); // cache the SuppressMergeCheckAttribute.ctor token ImportHelper::FindCustomAttributeCtorByName( pMiniMdEmit, COR_MSCORLIB_NAME, COR_COMPILERSERVICE_NAMESPACE, COR_SUPPRESS_MERGE_CHECK_ATTRIBUTE, &tkSuppressMergeCheckCtor); cTypeDefRecs = pMiniMdEmit->getCountTypeDefs(); _ASSERTE(m_rMTDs.Count() > 0); for (i = m_rMTDs.Count(); i <= cTypeDefRecs; i++) { IfNullGo(pMTD = m_rMTDs.Append()); pMTD->m_cMethods = 0; pMTD->m_cFields = 0; pMTD->m_cEvents = 0; pMTD->m_cProperties = 0; pMTD->m_bSuppressMergeCheck = (tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdEmit, TokenFromRid(i, mdtTypeDef), tkSuppressMergeCheckCtor, NULL, 0, &tkCA)); IfFailGo(pMiniMdEmit->GetTypeDefRecord(i, &pTypeDefRec)); // Count the number methods ridStart = pMiniMdEmit->getMethodListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdEmit->getEndMethodListOfTypeDef(i, &ridEnd)); for (j = ridStart; j < ridEnd; j++) { IfFailGo(pMiniMdEmit->GetMethodRid(j, (ULONG *)&mdEmit)); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdEmit, mdEmit, tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cMethods++; } } // Count the number fields ridStart = pMiniMdEmit->getFieldListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdEmit->getEndFieldListOfTypeDef(i, &ridEnd)); for (j = ridStart; j < ridEnd; j++) { IfFailGo(pMiniMdEmit->GetFieldRid(j, (ULONG *)&fdEmit)); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdEmit, fdEmit, tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cFields++; } } // Count the number of events IfFailGo(pMiniMdEmit->FindEventMapFor(i, &ridMap)); if (!InvalidRid(ridMap)) { IfFailGo(pMiniMdEmit->GetEventMapRecord(ridMap, &pEventMapRec)); ridStart = pMiniMdEmit->getEventListOfEventMap(pEventMapRec); IfFailGo(pMiniMdEmit->getEndEventListOfEventMap(ridMap, &ridEnd)); for (j = ridStart; j < ridEnd; j++) { IfFailGo(pMiniMdEmit->GetEventRid(j, (ULONG *)&evEmit)); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdEmit, evEmit, tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cEvents++; } } } // Count the number of properties IfFailGo(pMiniMdEmit->FindPropertyMapFor(i, &ridMap)); if (!InvalidRid(ridMap)) { IfFailGo(pMiniMdEmit->GetPropertyMapRecord(ridMap, &pPropertyMapRec)); ridStart = pMiniMdEmit->getPropertyListOfPropertyMap(pPropertyMapRec); IfFailGo(pMiniMdEmit->getEndPropertyListOfPropertyMap(ridMap, &ridEnd)); for (j = ridStart; j < ridEnd; j++) { IfFailGo(pMiniMdEmit->GetPropertyRid(j, (ULONG *)&prEmit)); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdEmit, prEmit, tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cProperties++; } } } } ErrExit: return hr; } //***************************************************************************** // Merge now //***************************************************************************** HRESULT NEWMERGER::Merge(MergeFlags dwMergeFlags, CorRefToDefCheck optimizeRefToDef) { MergeImportData *pImportData = m_pImportDataList; MDTOKENMAP **pPrevMap = NULL; MDTOKENMAP *pMDTokenMap; HRESULT hr = NOERROR; MDTOKENMAP *pCurTKMap; int i; #if _DEBUG { LOG((LOGMD, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); LOG((LOGMD, "Merge scope list\n")); i = 0; for (MergeImportData *pID = m_pImportDataList; pID != NULL; pID = pID->m_pNextImportData) { WCHAR szScope[1024], szGuid[40]; GUID mvid; ULONG cchScope; pID->m_pRegMetaImport->GetScopeProps(szScope, 1024, &cchScope, &mvid); szScope[1023] = 0; GuidToLPWSTR(mvid, szGuid, 40); ++i; // Counter is 1-based. LOG((LOGMD, "%3d: %ls : %ls\n", i, szGuid, szScope)); } LOG((LOGMD, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); } #endif // _DEBUG m_dwMergeFlags = dwMergeFlags; m_optimizeRefToDef = optimizeRefToDef; // check to see if we need to do dup check m_fDupCheck = ((m_dwMergeFlags & NoDupCheck) != NoDupCheck); while (pImportData) { // Verify that we have a filter for each import scope. IfNullGo( pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd.GetFilterTable() ); // cache the SuppressMergeCheckAttribute.ctor token for each import scope ImportHelper::FindCustomAttributeCtorByName( &pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd, COR_MSCORLIB_NAME, COR_COMPILERSERVICE_NAMESPACE, COR_SUPPRESS_MERGE_CHECK_ATTRIBUTE, &pImportData->m_tkSuppressMergeCheckCtor); // cache the HandleProcessCorruptedStateExceptionsAttribute.ctor token for each import scope ImportHelper::FindCustomAttributeCtorByName( &pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd, COR_MSCORLIB_NAME, COR_EXCEPTIONSERVICE_NAMESPACE, COR_HANDLE_PROCESS_CORRUPTED_STATE_EXCEPTION_ATTRIBUTE, &pImportData->m_tkHandleProcessCorruptedStateCtor); // check for security critical attribute in the assembly (i.e. explicit annotations) InputScopeSecurityCriticalStatus isscsTemp = CheckInputScopeIsCritical(pImportData, hr); IfFailGo(hr); // clear the unset flag bits (e.g. if critical, clear transparent bit) // whatever bits remain are bits that have been set in all scopes if (ISSCS_Unknown == (isscsTemp & ISSCS_SECURITYCRITICAL_FLAGS)) m_isscsSecurityCriticalAllScopes &= ISSCS_SECURITYCRITICAL_LEGACY; else m_isscsSecurityCriticalAllScopes &= isscsTemp; // set the flag bits (essentially, this allows us to see if _any_ scopes requested a bit) m_isscsSecurityCritical |= isscsTemp; // create the tokenmap class to track metadata token remap for each import scope pMDTokenMap = new (nothrow) MDTOKENMAP; IfNullGo(pMDTokenMap); IfFailGo(pMDTokenMap->Init((IMetaDataImport2*)pImportData->m_pRegMetaImport)); pImportData->m_pMDTokenMap = pMDTokenMap; pImportData->m_pMDTokenMap->m_pMap = pImportData->m_pHostMapToken; if (pImportData->m_pHostMapToken) pImportData->m_pHostMapToken->AddRef(); pImportData->m_pMDTokenMap->m_pNextMap = NULL; if (pPrevMap) *pPrevMap = pImportData->m_pMDTokenMap; pPrevMap = &(pImportData->m_pMDTokenMap->m_pNextMap); pImportData = pImportData->m_pNextImportData; } // Populate the m_rMTDs with the type info already defined in the emit scope IfFailGo( InitMergeTypeData() ); // 1. Merge Module IfFailGo( MergeModule( ) ); // 2. Merge TypeDef partially (i.e. only name) IfFailGo( MergeTypeDefNamesOnly() ); // 3. Merge ModuleRef property and do ModuleRef to ModuleDef optimization IfFailGo( MergeModuleRefs() ); // 4. Merge AssemblyRef. IfFailGo( MergeAssemblyRefs() ); // 5. Merge TypeRef with TypeRef to TypeDef optimization IfFailGo( MergeTypeRefs() ); // 6. Merge TypeSpec & MethodSpec IfFailGo( MergeTypeSpecs() ); // 7. Now Merge the remaining of TypeDef records IfFailGo( CompleteMergeTypeDefs() ); // 8. Merge Methods and Fields. Such that Signature translation is respecting the TypeRef to TypeDef optimization. IfFailGo( MergeTypeDefChildren() ); // 9. Merge MemberRef with MemberRef to MethodDef/FieldDef optimization IfFailGo( MergeMemberRefs( ) ); // 10. Merge InterfaceImpl IfFailGo( MergeInterfaceImpls( ) ); // merge all of the remaining in metadata .... // 11. constant has dependency on property, field, param IfFailGo( MergeConstants() ); // 12. field marshal has dependency on param and field IfFailGo( MergeFieldMarshals() ); // 13. in ClassLayout, move over the FieldLayout and deal with FieldLayout as well IfFailGo( MergeClassLayouts() ); // 14. FieldLayout has dependency on FieldDef. IfFailGo( MergeFieldLayouts() ); // 15. FieldRVA has dependency on FieldDef. IfFailGo( MergeFieldRVAs() ); // 16. MethodImpl has dependency on MemberRef, MethodDef, TypeRef and TypeDef. IfFailGo( MergeMethodImpls() ); // 17. pinvoke depends on MethodDef and ModuleRef IfFailGo( MergePinvoke() ); IfFailGo( MergeStandAloneSigs() ); IfFailGo( MergeMethodSpecs() ); IfFailGo( MergeStrings() ); if (m_dwMergeFlags & MergeManifest) { // keep the manifest!! IfFailGo( MergeAssembly() ); IfFailGo( MergeFiles() ); IfFailGo( MergeExportedTypes() ); IfFailGo( MergeManifestResources() ); } else if (m_dwMergeFlags & ::MergeExportedTypes) { IfFailGo( MergeFiles() ); IfFailGo( MergeExportedTypes() ); } IfFailGo( MergeCustomAttributes() ); IfFailGo( MergeDeclSecuritys() ); // Please don't add any MergeXxx() below here. CustomAttributess must be // very late, because custom values are various other types. // Fixup list cannot be merged. Linker will need to re-emit them. // Now call back to host for the result of token remap // for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // Send token remap information for each import scope pCurTKMap = pImportData->m_pMDTokenMap; TOKENREC *pRec; if (pImportData->m_pHostMapToken) { for (i = 0; i < pCurTKMap->Count(); i++) { pRec = pCurTKMap->Get(i); if (!pRec->IsEmpty()) pImportData->m_pHostMapToken->Map(pRec->m_tkFrom, pRec->m_tkTo); } } } // And last, but not least, let's do Security critical module-level attribute consolidation // and metadata fixups. IfFailGo( MergeSecurityCriticalAttributes() ); #if _DEBUG for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // dump the mapping LOG((LOGMD, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); LOG((LOGMD, "Dumping token remap for one import scope!\n")); LOG((LOGMD, "This is the %d import scope for merge!\n", pImportData->m_iImport)); pCurTKMap = pImportData->m_pMDTokenMap; TOKENREC *pRec; for (i = 0; i < pCurTKMap->Count(); i++) { pRec = pCurTKMap->Get(i); if (!pRec->IsEmpty()) { LOG((LOGMD, " Token 0x%08x ====>>>> Token 0x%08x\n", pRec->m_tkFrom, pRec->m_tkTo)); } } LOG((LOGMD, "End dumping token remap!\n")); LOG((LOGMD, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); } #endif // _DEBUG ErrExit: return hr; } // HRESULT NEWMERGER::Merge() //***************************************************************************** // Merge ModuleDef //***************************************************************************** HRESULT NEWMERGER::MergeModule() { MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; HRESULT hr = NOERROR; TOKENREC *pTokenRec; // we don't really merge Module information but we create a one to one mapping for each module token into the TokenMap for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo( pCurTkMap->InsertNotFound(MODULEDEFTOKEN, true, MODULEDEFTOKEN, &pTokenRec) ); } ErrExit: return hr; } // HRESULT NEWMERGER::MergeModule() //***************************************************************************** // Merge TypeDef but only Names. This is a partial merge to support TypeRef to TypeDef optimization //***************************************************************************** HRESULT NEWMERGER::MergeTypeDefNamesOnly() { HRESULT hr = NOERROR; TypeDefRec *pRecImport = NULL; TypeDefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdTypeDef tdEmit; mdTypeDef tdImport; bool bDuplicate; DWORD dwFlags; DWORD dwExportFlags; NestedClassRec *pNestedRec; RID iNestedRec; mdTypeDef tdNester; TOKENREC *pTokenRec; LPCUTF8 szNameImp; LPCUTF8 szNamespaceImp; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountTypeDefs(); // Merge the typedefs for (i = 1; i <= iCount; i++) { // only merge those TypeDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeDefMarked(TokenFromRid(i, mdtTypeDef)) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetTypeDefRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfTypeDef(pRecImport, &szNameImp)); IfFailGo(pMiniMdImport->getNamespaceOfTypeDef(pRecImport, &szNamespaceImp)); // If the class is a Nested class, get the parent token. dwFlags = pMiniMdImport->getFlagsOfTypeDef(pRecImport); if (IsTdNested(dwFlags)) { IfFailGo(pMiniMdImport->FindNestedClassHelper(TokenFromRid(i, mdtTypeDef), &iNestedRec)); if (InvalidRid(iNestedRec)) { _ASSERTE(!"Bad state!"); IfFailGo(META_E_BADMETADATA); } else { IfFailGo(pMiniMdImport->GetNestedClassRecord(iNestedRec, &pNestedRec)); tdNester = pMiniMdImport->getEnclosingClassOfNestedClass(pNestedRec); _ASSERTE(!IsNilToken(tdNester)); IfFailGo(pCurTkMap->Remap(tdNester, &tdNester)); } } else tdNester = mdTokenNil; bSuppressMergeCheck = (pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, TokenFromRid(i, mdtTypeDef), pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA)); // does this TypeDef already exist in the emit scope? if ( ImportHelper::FindTypeDefByName( pMiniMdEmit, szNamespaceImp, szNameImp, tdNester, &tdEmit) == S_OK ) { // Yes, it does bDuplicate = true; // Let's look at their accessiblities. IfFailGo(pMiniMdEmit->GetTypeDefRecord(RidFromToken(tdEmit), &pRecEmit)); dwExportFlags = pMiniMdEmit->getFlagsOfTypeDef(pRecEmit); // Managed types need to have the same accessiblity BOOL fManagedType = FALSE; IfFailGo(IsManagedType(pMiniMdImport, TokenFromRid(i, mdtTypeDef), &fManagedType)); if (fManagedType) { if ((dwFlags&tdVisibilityMask) != (dwExportFlags&tdVisibilityMask)) { CheckContinuableErrorEx(META_E_MISMATCHED_VISIBLITY, pImportData, TokenFromRid(i, mdtTypeDef)); } } pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); if (pMTD->m_bSuppressMergeCheck != bSuppressMergeCheck) { CheckContinuableErrorEx(META_E_MD_INCONSISTENCY, pImportData, TokenFromRid(i, mdtTypeDef)); } } else { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddTypeDefRecord(&pRecEmit, (RID *)&tdEmit)); // make sure the index matches _ASSERTE(((mdTypeDef)m_rMTDs.Count()) == tdEmit); IfNullGo(pMTD = m_rMTDs.Append()); pMTD->m_cMethods = 0; pMTD->m_cFields = 0; pMTD->m_cEvents = 0; pMTD->m_cProperties = 0; pMTD->m_bSuppressMergeCheck = bSuppressMergeCheck; tdEmit = TokenFromRid( tdEmit, mdtTypeDef ); // Set Full Qualified Name. IfFailGo( CopyTypeDefPartially( pRecEmit, pMiniMdImport, pRecImport) ); // Create a NestedClass record if the class is a Nested class. if (! IsNilToken(tdNester)) { IfFailGo(pMiniMdEmit->AddNestedClassRecord(&pNestedRec, &iNestedRec)); // copy over the information IfFailGo( pMiniMdEmit->PutToken(TBL_NestedClass, NestedClassRec::COL_NestedClass, pNestedRec, tdEmit)); // tdNester has already been remapped above to the Emit scope. IfFailGo( pMiniMdEmit->PutToken(TBL_NestedClass, NestedClassRec::COL_EnclosingClass, pNestedRec, tdNester)); IfFailGo( pMiniMdEmit->AddNestedClassToHash(iNestedRec) ); } } // record the token movement tdImport = TokenFromRid(i, mdtTypeDef); IfFailGo( pCurTkMap->InsertNotFound(tdImport, bDuplicate, tdEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeTypeDefNamesOnly() //***************************************************************************** // Merge EnclosingType tables //***************************************************************************** HRESULT NEWMERGER::CopyTypeDefPartially( TypeDefRec *pRecEmit, // [IN] the emit record to fill CMiniMdRW *pMiniMdImport, // [IN] the importing scope TypeDefRec *pRecImp) // [IN] the record to import { HRESULT hr; LPCUTF8 szNameImp; LPCUTF8 szNamespaceImp; CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); IfFailGo(pMiniMdImport->getNameOfTypeDef(pRecImp, &szNameImp)); IfFailGo(pMiniMdImport->getNamespaceOfTypeDef(pRecImp, &szNamespaceImp)); IfFailGo( pMiniMdEmit->PutString( TBL_TypeDef, TypeDefRec::COL_Name, pRecEmit, szNameImp) ); IfFailGo( pMiniMdEmit->PutString( TBL_TypeDef, TypeDefRec::COL_Namespace, pRecEmit, szNamespaceImp) ); pRecEmit->SetFlags(pRecImp->GetFlags()); // Don't copy over the extends until TypeRef's remap is calculated ErrExit: return hr; } // HRESULT NEWMERGER::CopyTypeDefPartially() //***************************************************************************** // Merge ModuleRef tables including ModuleRef to ModuleDef optimization //***************************************************************************** HRESULT NEWMERGER::MergeModuleRefs() { HRESULT hr = NOERROR; ModuleRefRec *pRecImport = NULL; ModuleRefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdModuleRef mrEmit; bool bDuplicate = false; TOKENREC *pTokenRec; LPCUTF8 szNameImp; bool isModuleDef; MergeImportData *pImportData; MergeImportData *pData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountModuleRefs(); // loop through all ModuleRef for (i = 1; i <= iCount; i++) { // only merge those ModuleRefs that are marked if ( pMiniMdImport->GetFilterTable()->IsModuleRefMarked(TokenFromRid(i, mdtModuleRef)) == false) continue; isModuleDef = false; // compare it with the emit scope IfFailGo(pMiniMdImport->GetModuleRefRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfModuleRef(pRecImport, &szNameImp)); // Only do the ModuleRef to ModuleDef optimization if ModuleRef's name is meaningful! if ( szNameImp && szNameImp[0] != '\0') { // Check to see if this ModuleRef has become the ModuleDef token for (pData = m_pImportDataList; pData != NULL; pData = pData->m_pNextImportData) { CMiniMdRW *pMiniMd = &(pData->m_pRegMetaImport->m_pStgdb->m_MiniMd); ModuleRec *pRec; LPCUTF8 szName; IfFailGo(pMiniMd->GetModuleRecord(MODULEDEFTOKEN, &pRec)); IfFailGo(pMiniMd->getNameOfModule(pRec, &szName)); if (szName && szName[0] != '\0' && strcmp(szNameImp, szName) == 0) { // We found an import Module for merging that has the same name as the ModuleRef isModuleDef = true; bDuplicate = true; mrEmit = MODULEDEFTOKEN; // set the resulting token to ModuleDef Token break; } } } if (isModuleDef == false) { // does this ModuleRef already exist in the emit scope? hr = ImportHelper::FindModuleRef(pMiniMdEmit, szNameImp, &mrEmit); if (hr == S_OK) { // Yes, it does bDuplicate = true; } else if (hr == CLDB_E_RECORD_NOTFOUND) { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddModuleRefRecord(&pRecEmit, (RID*)&mrEmit)); mrEmit = TokenFromRid(mrEmit, mdtModuleRef); // Set ModuleRef Name. IfFailGo( pMiniMdEmit->PutString(TBL_ModuleRef, ModuleRefRec::COL_Name, pRecEmit, szNameImp) ); } else IfFailGo(hr); } // record the token movement IfFailGo( pCurTkMap->InsertNotFound( TokenFromRid(i, mdtModuleRef), bDuplicate, mrEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeModuleRefs() //***************************************************************************** // Merge AssemblyRef tables //***************************************************************************** HRESULT NEWMERGER::MergeAssemblyRefs() { HRESULT hr = NOERROR; AssemblyRefRec *pRecImport = NULL; AssemblyRefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; mdAssemblyRef arEmit; bool bDuplicate = false; LPCUTF8 szTmp; const void *pbTmp; ULONG cbTmp; ULONG iCount; ULONG i; ULONG iRecord; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountAssemblyRefs(); // loope through all the AssemblyRefs. for (i = 1; i <= iCount; i++) { // Compare with the emit scope. IfFailGo(pMiniMdImport->GetAssemblyRefRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getPublicKeyOrTokenOfAssemblyRef(pRecImport, (const BYTE **)&pbTmp, &cbTmp)); hr = CLDB_E_RECORD_NOTFOUND; if (m_fDupCheck) { LPCSTR szAssemblyRefName; LPCSTR szAssemblyRefLocale; IfFailGo(pMiniMdImport->getNameOfAssemblyRef(pRecImport, &szAssemblyRefName)); IfFailGo(pMiniMdImport->getLocaleOfAssemblyRef(pRecImport, &szAssemblyRefLocale)); hr = ImportHelper::FindAssemblyRef( pMiniMdEmit, szAssemblyRefName, szAssemblyRefLocale, pbTmp, cbTmp, pRecImport->GetMajorVersion(), pRecImport->GetMinorVersion(), pRecImport->GetBuildNumber(), pRecImport->GetRevisionNumber(), pRecImport->GetFlags(), &arEmit); } if (hr == S_OK) { // Yes, it does bDuplicate = true; // <TODO>@FUTURE: more verification?</TODO> } else if (hr == CLDB_E_RECORD_NOTFOUND) { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddAssemblyRefRecord(&pRecEmit, &iRecord)); arEmit = TokenFromRid(iRecord, mdtAssemblyRef); pRecEmit->Copy(pRecImport); IfFailGo(pMiniMdImport->getPublicKeyOrTokenOfAssemblyRef(pRecImport, (const BYTE **)&pbTmp, &cbTmp)); IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_PublicKeyOrToken, pRecEmit, pbTmp, cbTmp)); IfFailGo(pMiniMdImport->getNameOfAssemblyRef(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Name, pRecEmit, szTmp)); IfFailGo(pMiniMdImport->getLocaleOfAssemblyRef(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_AssemblyRef, AssemblyRefRec::COL_Locale, pRecEmit, szTmp)); IfFailGo(pMiniMdImport->getHashValueOfAssemblyRef(pRecImport, (const BYTE **)&pbTmp, &cbTmp)); IfFailGo(pMiniMdEmit->PutBlob(TBL_AssemblyRef, AssemblyRefRec::COL_HashValue, pRecEmit, pbTmp, cbTmp)); } else IfFailGo(hr); // record the token movement. IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(i, mdtAssemblyRef), bDuplicate, arEmit, &pTokenRec)); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeAssemblyRefs() //***************************************************************************** // Merge TypeRef tables also performing TypeRef to TypeDef opitimization. ie. // we will not introduce a TypeRef record if we can optimize it to a TypeDef. //***************************************************************************** HRESULT NEWMERGER::MergeTypeRefs() { HRESULT hr = NOERROR; TypeRefRec *pRecImport = NULL; TypeRefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdTypeRef trEmit; bool bDuplicate = false; TOKENREC *pTokenRec; bool isTypeDef; mdToken tkResImp; mdToken tkResEmit; LPCUTF8 szNameImp; LPCUTF8 szNamespaceImp; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountTypeRefs(); // loop through all TypeRef for (i = 1; i <= iCount; i++) { // only merge those TypeRefs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeRefMarked(TokenFromRid(i, mdtTypeRef)) == false) continue; isTypeDef = false; // compare it with the emit scope IfFailGo(pMiniMdImport->GetTypeRefRecord(i, &pRecImport)); tkResImp = pMiniMdImport->getResolutionScopeOfTypeRef(pRecImport); IfFailGo(pMiniMdImport->getNamespaceOfTypeRef(pRecImport, &szNamespaceImp)); IfFailGo(pMiniMdImport->getNameOfTypeRef(pRecImport, &szNameImp)); if (!IsNilToken(tkResImp)) { IfFailGo(pCurTkMap->Remap(tkResImp, &tkResEmit)); } else { tkResEmit = tkResImp; } // There are some interesting cases to consider here. // 1) If the TypeRef's ResolutionScope is a nil token, or is the MODULEDEFTOKEN (current module), // then the TypeRef refers to a type in the current scope, so we should find a corresponding // TypeDef in the output scope. If we find the TypeDef, we'll remap this TypeRef token // to that TypeDef token. // If we don't find that TypeDef, or if "TypeRef to TypeDef" optimization is turned off, we'll // create the TypeRef in the output scope. // 2) If the TypeRef's ResolutionScope has been resolved to a TypeDef, then this TypeRef was part // of a nested type definition. In that case, we'd better find a corresponding TypeDef // or we have an error. if (IsNilToken(tkResEmit) || tkResEmit == MODULEDEFTOKEN || TypeFromToken(tkResEmit) == mdtTypeDef) { hr = ImportHelper::FindTypeDefByName( pMiniMdEmit, szNamespaceImp, szNameImp, (TypeFromToken(tkResEmit) == mdtTypeDef) ? tkResEmit : mdTokenNil, &trEmit); if (hr == S_OK) { isTypeDef = true; // it really does not matter if we set the duplicate to true or false. bDuplicate = true; } } // If the ResolutionScope was merged as a TypeDef, and this token wasn't found as TypeDef, send the error. if (TypeFromToken(tkResEmit) == mdtTypeDef && !isTypeDef) { // Send the error notification. Use the "continuable error" callback, but even if linker says it is // ok, don't continue. CheckContinuableErrorEx(META_E_TYPEDEF_MISSING, pImportData, TokenFromRid(i, mdtTypeRef)); IfFailGo(META_E_TYPEDEF_MISSING); } // If this TypeRef cannot be optmized to a TypeDef or the Ref to Def optimization is turned off, do the following. if (!isTypeDef || !((m_optimizeRefToDef & MDTypeRefToDef) == MDTypeRefToDef)) { // does this TypeRef already exist in the emit scope? if ( m_fDupCheck && ImportHelper::FindTypeRefByName( pMiniMdEmit, tkResEmit, szNamespaceImp, szNameImp, &trEmit) == S_OK ) { // Yes, it does bDuplicate = true; } else { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddTypeRefRecord(&pRecEmit, (RID*)&trEmit)); trEmit = TokenFromRid(trEmit, mdtTypeRef); // Set ResolutionScope. tkResEmit has already been re-mapped. IfFailGo(pMiniMdEmit->PutToken(TBL_TypeRef, TypeRefRec::COL_ResolutionScope, pRecEmit, tkResEmit)); // Set Name. IfFailGo(pMiniMdEmit->PutString(TBL_TypeRef, TypeRefRec::COL_Name, pRecEmit, szNameImp)); IfFailGo(pMiniMdEmit->AddNamedItemToHash(TBL_TypeRef, trEmit, szNameImp, 0)); // Set Namespace. IfFailGo(pMiniMdEmit->PutString(TBL_TypeRef, TypeRefRec::COL_Namespace, pRecEmit, szNamespaceImp)); } } // record the token movement IfFailGo( pCurTkMap->InsertNotFound( TokenFromRid(i, mdtTypeRef), bDuplicate, trEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeTypeRefs() //***************************************************************************** // copy over the remaining information of partially merged TypeDef records. Right now only // extends field is delayed to here. The reason that we delay extends field is because we want // to optimize TypeRef to TypeDef if possible. //***************************************************************************** HRESULT NEWMERGER::CompleteMergeTypeDefs() { HRESULT hr = NOERROR; TypeDefRec *pRecImport = NULL; TypeDefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; TOKENREC *pTokenRec; mdToken tkExtendsImp; mdToken tkExtendsEmit; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountTypeDefs(); // Merge the typedefs for (i = 1; i <= iCount; i++) { // only merge those TypeDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeDefMarked(TokenFromRid(i, mdtTypeDef)) == false) continue; if ( !pCurTkMap->Find(TokenFromRid(i, mdtTypeDef), &pTokenRec) ) { _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } if (pTokenRec->m_isDuplicate == false) { // get the extends token from the import IfFailGo(pMiniMdImport->GetTypeDefRecord(i, &pRecImport)); tkExtendsImp = pMiniMdImport->getExtendsOfTypeDef(pRecImport); // map the extends token to an merged token IfFailGo( pCurTkMap->Remap(tkExtendsImp, &tkExtendsEmit) ); // set the extends to the merged TypeDef records. IfFailGo(pMiniMdEmit->GetTypeDefRecord(RidFromToken(pTokenRec->m_tkTo), &pRecEmit)); IfFailGo(pMiniMdEmit->PutToken(TBL_TypeDef, TypeDefRec::COL_Extends, pRecEmit, tkExtendsEmit)); } else { // <TODO>@FUTURE: we can check to make sure the import extends maps to the one that is set to the emit scope. // Otherwise, it is a error to report to linker.</TODO> } } } ErrExit: return hr; } // HRESULT NEWMERGER::CompleteMergeTypeDefs() //***************************************************************************** // merging TypeSpecs //***************************************************************************** HRESULT NEWMERGER::MergeTypeSpecs() { HRESULT hr = NOERROR; TypeSpecRec *pRecImport = NULL; TypeSpecRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; TOKENREC *pTokenRec; mdTypeSpec tsImp; mdTypeSpec tsEmit; bool fDuplicate; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountTypeSpecs(); // loop through all TypeSpec for (i = 1; i <= iCount; i++) { // only merge those TypeSpecs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeSpecMarked(TokenFromRid(i, mdtTypeSpec)) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetTypeSpecRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getSignatureOfTypeSpec(pRecImport, &pbSig, &cbSig)); // convert tokens contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInFieldSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly information. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit hr = CLDB_E_RECORD_NOTFOUND; if (m_fDupCheck) hr = ImportHelper::FindTypeSpec( pMiniMdEmit, (PCOR_SIGNATURE) qbSig.Ptr(), cbEmit, &tsEmit ); if ( hr == S_OK ) { // find a duplicate fDuplicate = true; } else { // copy over fDuplicate = false; IfFailGo(pMiniMdEmit->AddTypeSpecRecord(&pRecEmit, (ULONG *)&tsEmit)); tsEmit = TokenFromRid(tsEmit, mdtTypeSpec); IfFailGo( pMiniMdEmit->PutBlob( TBL_TypeSpec, TypeSpecRec::COL_Signature, pRecEmit, (PCOR_SIGNATURE)qbSig.Ptr(), cbEmit)); } tsImp = TokenFromRid(i, mdtTypeSpec); // Record the token movement IfFailGo( pCurTkMap->InsertNotFound(tsImp, fDuplicate, tsEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeTypeSpecs() //***************************************************************************** // merging Children of TypeDefs. This includes field, method, parameter, property, event //***************************************************************************** HRESULT NEWMERGER::MergeTypeDefChildren() { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdTypeDef tdEmit; mdTypeDef tdImport; TOKENREC *pTokenRec; #if _DEBUG TypeDefRec *pRecImport = NULL; LPCUTF8 szNameImp; LPCUTF8 szNamespaceImp; #endif // _DEBUG MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountTypeDefs(); // loop through all TypeDef again to merge/copy Methods, fields, events, and properties // for (i = 1; i <= iCount; i++) { // only merge those TypeDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeDefMarked(TokenFromRid(i, mdtTypeDef)) == false) continue; #if _DEBUG IfFailGo(pMiniMdImport->GetTypeDefRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfTypeDef(pRecImport, &szNameImp)); IfFailGo(pMiniMdImport->getNamespaceOfTypeDef(pRecImport, &szNamespaceImp)); #endif // _DEBUG // check to see if the typedef is duplicate or not tdImport = TokenFromRid(i, mdtTypeDef); if ( pCurTkMap->Find( tdImport, &pTokenRec) == false) { _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } tdEmit = pTokenRec->m_tkTo; if (pTokenRec->m_isDuplicate == false) { // now move all of the children records over IfFailGo( CopyMethods(pImportData, tdImport, tdEmit) ); IfFailGo( CopyFields(pImportData, tdImport, tdEmit) ); IfFailGo( CopyEvents(pImportData, tdImport, tdEmit) ); // Property has dependency on events IfFailGo( CopyProperties(pImportData, tdImport, tdEmit) ); // Generic Params. IfFailGo( CopyGenericParams(pImportData, tdImport, tdEmit) ); } else { // verify the children records IfFailGo( VerifyMethods(pImportData, tdImport, tdEmit) ); IfFailGo( VerifyFields(pImportData, tdImport, tdEmit) ); IfFailGo( VerifyEvents(pImportData, tdImport, tdEmit) ); // property has dependency on events IfFailGo( VerifyProperties(pImportData, tdImport, tdEmit) ); IfFailGo( VerifyGenericParams(pImportData, tdImport, tdEmit) ); } } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeTypeDefChildren() //******************************************************************************* // Helper to copy an Method record //******************************************************************************* HRESULT NEWMERGER::CopyMethod( MergeImportData *pImportData, // [IN] import scope MethodRec *pRecImp, // [IN] the record to import MethodRec *pRecEmit) // [IN] the emit record to fill { HRESULT hr; CMiniMdRW *pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; MDTOKENMAP *pCurTkMap; pCurTkMap = pImportData->m_pMDTokenMap; // copy over the fix part of the record pRecEmit->Copy(pRecImp); // copy over the name IfFailGo(pMiniMdImp->getNameOfMethod(pRecImp, &szName)); IfFailGo(pMiniMdEmit->PutString(TBL_Method, MethodRec::COL_Name, pRecEmit, szName)); // copy over the signature IfFailGo(pMiniMdImp->getSignatureOfMethod(pRecImp, &pbSig, &cbSig)); // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImp, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit IfFailGo(pMiniMdEmit->PutBlob(TBL_Method, MethodRec::COL_Signature, pRecEmit, qbSig.Ptr(), cbEmit)); ErrExit: return hr; } // HRESULT NEWMERGER::CopyMethod() //******************************************************************************* // Helper to copy an field record //******************************************************************************* HRESULT NEWMERGER::CopyField( MergeImportData *pImportData, // [IN] import scope FieldRec *pRecImp, // [IN] the record to import FieldRec *pRecEmit) // [IN] the emit record to fill { HRESULT hr; CMiniMdRW *pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; MDTOKENMAP *pCurTkMap; pCurTkMap = pImportData->m_pMDTokenMap; // copy over the fix part of the record pRecEmit->SetFlags(pRecImp->GetFlags()); // copy over the name IfFailGo(pMiniMdImp->getNameOfField(pRecImp, &szName)); IfFailGo(pMiniMdEmit->PutString(TBL_Field, FieldRec::COL_Name, pRecEmit, szName)); // copy over the signature IfFailGo(pMiniMdImp->getSignatureOfField(pRecImp, &pbSig, &cbSig)); // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Emit assembly scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImp, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit IfFailGo(pMiniMdEmit->PutBlob(TBL_Field, FieldRec::COL_Signature, pRecEmit, qbSig.Ptr(), cbEmit)); ErrExit: return hr; } // HRESULT NEWMERGER::CopyField() //******************************************************************************* // Helper to copy an field record //******************************************************************************* HRESULT NEWMERGER::CopyParam( MergeImportData *pImportData, // [IN] import scope ParamRec *pRecImp, // [IN] the record to import ParamRec *pRecEmit) // [IN] the emit record to fill { HRESULT hr; CMiniMdRW *pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); LPCUTF8 szName; MDTOKENMAP *pCurTkMap; pCurTkMap = pImportData->m_pMDTokenMap; // copy over the fix part of the record pRecEmit->Copy(pRecImp); // copy over the name IfFailGo(pMiniMdImp->getNameOfParam(pRecImp, &szName)); IfFailGo(pMiniMdEmit->PutString(TBL_Param, ParamRec::COL_Name, pRecEmit, szName)); ErrExit: return hr; } // HRESULT NEWMERGER::CopyParam() //******************************************************************************* // Helper to copy an Event record //******************************************************************************* HRESULT NEWMERGER::CopyEvent( MergeImportData *pImportData, // [IN] import scope EventRec *pRecImp, // [IN] the record to import EventRec *pRecEmit) // [IN] the emit record to fill { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); mdToken tkEventTypeImp; mdToken tkEventTypeEmit; // could be TypeDef or TypeRef LPCUTF8 szName; MDTOKENMAP *pCurTkMap; pCurTkMap = pImportData->m_pMDTokenMap; pRecEmit->SetEventFlags(pRecImp->GetEventFlags()); //move over the event name IfFailGo(pMiniMdImp->getNameOfEvent(pRecImp, &szName)); IfFailGo( pMiniMdEmit->PutString(TBL_Event, EventRec::COL_Name, pRecEmit, szName) ); // move over the EventType tkEventTypeImp = pMiniMdImp->getEventTypeOfEvent(pRecImp); if ( !IsNilToken(tkEventTypeImp) ) { IfFailGo( pCurTkMap->Remap(tkEventTypeImp, &tkEventTypeEmit) ); IfFailGo(pMiniMdEmit->PutToken(TBL_Event, EventRec::COL_EventType, pRecEmit, tkEventTypeEmit)); } ErrExit: return hr; } // HRESULT NEWMERGER::CopyEvent() //******************************************************************************* // Helper to copy a property record //******************************************************************************* HRESULT NEWMERGER::CopyProperty( MergeImportData *pImportData, // [IN] import scope PropertyRec *pRecImp, // [IN] the record to import PropertyRec *pRecEmit) // [IN] the emit record to fill { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; MDTOKENMAP *pCurTkMap; pCurTkMap = pImportData->m_pMDTokenMap; // move over the flag value pRecEmit->SetPropFlags(pRecImp->GetPropFlags()); //move over the property name IfFailGo(pMiniMdImp->getNameOfProperty(pRecImp, &szName)); IfFailGo( pMiniMdEmit->PutString(TBL_Property, PropertyRec::COL_Name, pRecEmit, szName) ); // move over the type of the property IfFailGo(pMiniMdImp->getTypeOfProperty(pRecImp, &pbSig, &cbSig)); // convert rid contained in signature to new scope IfFailGo( ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImp, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit) ); // number of bytes write to cbEmit IfFailGo(pMiniMdEmit->PutBlob(TBL_Property, PropertyRec::COL_Type, pRecEmit, qbSig.Ptr(), cbEmit)); ErrExit: return hr; } // HRESULT NEWMERGER::CopyProperty() //***************************************************************************** // Copy MethodSemantics for an event or a property //***************************************************************************** HRESULT NEWMERGER::CopyMethodSemantics( MergeImportData *pImportData, mdToken tkImport, // Event or property in the import scope mdToken tkEmit) // corresponding event or property in the emitting scope { HRESULT hr = NOERROR; MethodSemanticsRec *pRecImport = NULL; MethodSemanticsRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); ULONG i; ULONG msEmit; // MethodSemantics are just index not tokens mdToken tkMethodImp; mdToken tkMethodEmit; MDTOKENMAP *pCurTkMap; HENUMInternal hEnum; pCurTkMap = pImportData->m_pMDTokenMap; // copy over the associates IfFailGo( pMiniMdImport->FindMethodSemanticsHelper(tkImport, &hEnum) ); while (HENUMInternal::EnumNext(&hEnum, (mdToken *) &i)) { IfFailGo(pMiniMdImport->GetMethodSemanticsRecord(i, &pRecImport)); IfFailGo(pMiniMdEmit->AddMethodSemanticsRecord(&pRecEmit, &msEmit)); pRecEmit->SetSemantic(pRecImport->GetSemantic()); // set the MethodSemantics tkMethodImp = pMiniMdImport->getMethodOfMethodSemantics(pRecImport); IfFailGo( pCurTkMap->Remap(tkMethodImp, &tkMethodEmit) ); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodSemantics, MethodSemanticsRec::COL_Method, pRecEmit, tkMethodEmit)); // set the associate _ASSERTE( pMiniMdImport->getAssociationOfMethodSemantics(pRecImport) == tkImport ); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodSemantics, MethodSemanticsRec::COL_Association, pRecEmit, tkEmit)); // no need to record the movement since it is not a token IfFailGo( pMiniMdEmit->AddMethodSemanticsToHash(msEmit) ); } ErrExit: HENUMInternal::ClearEnum(&hEnum); return hr; } // HRESULT NEWMERGER::CopyMethodSemantics() //***************************************************************************** // Copy Methods given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyMethods( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; MethodRec *pRecImport = NULL; MethodRec *pRecEmit = NULL; TypeDefRec *pTypeDefRec; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG ridStart, ridEnd; ULONG i; mdMethodDef mdEmit; mdMethodDef mdImp; TOKENREC *pTokenRec; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo(pMiniMdImport->GetTypeDefRecord(RidFromToken(tdImport), &pTypeDefRec)); ridStart = pMiniMdImport->getMethodListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdImport->getEndMethodListOfTypeDef(RidFromToken(tdImport), &ridEnd)); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // make sure we didn't count the methods yet _ASSERTE(pMTD->m_cMethods == 0); // loop through all Methods for (i = ridStart; i < ridEnd; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetMethodRid(i, (ULONG *)&mdImp)); // only merge those MethodDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsMethodMarked(TokenFromRid(mdImp, mdtMethodDef)) == false) continue; IfFailGo(pMiniMdImport->GetMethodRecord(mdImp, &pRecImport)); IfFailGo(pMiniMdEmit->AddMethodRecord(&pRecEmit, (RID *)&mdEmit)); // copy the method content over IfFailGo( CopyMethod(pImportData, pRecImport, pRecEmit) ); IfFailGo( pMiniMdEmit->AddMethodToTypeDef(RidFromToken(tdEmit), mdEmit)); // record the token movement mdImp = TokenFromRid(mdImp, mdtMethodDef); mdEmit = TokenFromRid(mdEmit, mdtMethodDef); IfFailGo( pMiniMdEmit->AddMemberDefToHash( mdEmit, tdEmit) ); IfFailGo( pCurTkMap->InsertNotFound(mdImp, false, mdEmit, &pTokenRec) ); // copy over the children IfFailGo( CopyParams(pImportData, mdImp, mdEmit) ); IfFailGo( CopyGenericParams(pImportData, mdImp, mdEmit) ); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, mdImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cMethods++; } } // make sure we don't count any methods if merge check is suppressed on the type _ASSERTE(pMTD->m_cMethods == 0 || !pMTD->m_bSuppressMergeCheck); ErrExit: return hr; } // HRESULT NEWMERGER::CopyMethods() //***************************************************************************** // Copy Fields given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyFields( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; FieldRec *pRecImport = NULL; FieldRec *pRecEmit = NULL; TypeDefRec *pTypeDefRec; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG ridStart, ridEnd; ULONG i; mdFieldDef fdEmit; mdFieldDef fdImp; bool bDuplicate; TOKENREC *pTokenRec; PCCOR_SIGNATURE pvSigBlob; ULONG cbSigBlob; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo(pMiniMdImport->GetTypeDefRecord(RidFromToken(tdImport), &pTypeDefRec)); ridStart = pMiniMdImport->getFieldListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdImport->getEndFieldListOfTypeDef(RidFromToken(tdImport), &ridEnd)); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // make sure we didn't count the methods yet _ASSERTE(pMTD->m_cFields == 0); // loop through all FieldDef of a TypeDef for (i = ridStart; i < ridEnd; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetFieldRid(i, (ULONG *)&fdImp)); // only merge those FieldDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(TokenFromRid(fdImp, mdtFieldDef)) == false) continue; IfFailGo(pMiniMdImport->GetFieldRecord(fdImp, &pRecImport)); bDuplicate = false; IfFailGo(pMiniMdEmit->AddFieldRecord(&pRecEmit, (RID *)&fdEmit)); // copy the field content over IfFailGo( CopyField(pImportData, pRecImport, pRecEmit) ); IfFailGo( pMiniMdEmit->AddFieldToTypeDef(RidFromToken(tdEmit), fdEmit)); // record the token movement fdImp = TokenFromRid(fdImp, mdtFieldDef); fdEmit = TokenFromRid(fdEmit, mdtFieldDef); IfFailGo(pMiniMdEmit->getSignatureOfField(pRecEmit, &pvSigBlob, &cbSigBlob)); IfFailGo( pMiniMdEmit->AddMemberDefToHash( fdEmit, tdEmit) ); IfFailGo( pCurTkMap->InsertNotFound(fdImp, false, fdEmit, &pTokenRec) ); // count the number of fields that didn't suppress merge check // non-static fields doesn't inherite the suppress merge check attribute from the type bSuppressMergeCheck = (IsFdStatic(pRecEmit->GetFlags()) && pMTD->m_bSuppressMergeCheck) || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, fdImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cFields++; } } ErrExit: return hr; } // HRESULT NEWMERGER::CopyFields() //***************************************************************************** // Copy Events given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyEvents( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); RID ridEventMap; EventMapRec *pEventMapRec; EventRec *pRecImport; EventRec *pRecEmit; ULONG ridStart; ULONG ridEnd; ULONG i; mdEvent evImp; mdEvent evEmit; TOKENREC *pTokenRec; ULONG iEventMap; EventMapRec *pEventMap; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; mdCustomAttribute tkCA; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); pCurTkMap = pImportData->m_pMDTokenMap; pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // make sure we didn't count the events yet _ASSERTE(pMTD->m_cEvents == 0); IfFailGo(pMiniMdImport->FindEventMapFor(RidFromToken(tdImport), &ridEventMap)); if (!InvalidRid(ridEventMap)) { IfFailGo(pMiniMdImport->GetEventMapRecord(ridEventMap, &pEventMapRec)); ridStart = pMiniMdImport->getEventListOfEventMap(pEventMapRec); IfFailGo(pMiniMdImport->getEndEventListOfEventMap(ridEventMap, &ridEnd)); if (ridEnd > ridStart) { // If there is any event, create the eventmap record in the emit scope // Create new record. IfFailGo(pMiniMdEmit->AddEventMapRecord(&pEventMap, &iEventMap)); // Set parent. IfFailGo(pMiniMdEmit->PutToken(TBL_EventMap, EventMapRec::COL_Parent, pEventMap, tdEmit)); } for (i = ridStart; i < ridEnd; i++) { // get the real event rid IfFailGo(pMiniMdImport->GetEventRid(i, (ULONG *)&evImp)); // only merge those Events that are marked if ( pMiniMdImport->GetFilterTable()->IsEventMarked(TokenFromRid(evImp, mdtEvent)) == false) continue; IfFailGo(pMiniMdImport->GetEventRecord(evImp, &pRecImport)); IfFailGo(pMiniMdEmit->AddEventRecord(&pRecEmit, (RID *)&evEmit)); // copy the event record over IfFailGo( CopyEvent(pImportData, pRecImport, pRecEmit) ); // Add Event to the EventMap. IfFailGo( pMiniMdEmit->AddEventToEventMap(iEventMap, evEmit) ); // record the token movement evImp = TokenFromRid(evImp, mdtEvent); evEmit = TokenFromRid(evEmit, mdtEvent); IfFailGo( pCurTkMap->InsertNotFound(evImp, false, evEmit, &pTokenRec) ); // copy over the method semantics IfFailGo( CopyMethodSemantics(pImportData, evImp, evEmit) ); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, evImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cEvents++; } } } // make sure we don't count any events if merge check is suppressed on the type _ASSERTE(pMTD->m_cEvents == 0 || !pMTD->m_bSuppressMergeCheck); ErrExit: return hr; } // HRESULT NEWMERGER::CopyEvents() //***************************************************************************** // Copy Properties given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyProperties( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); RID ridPropertyMap; PropertyMapRec *pPropertyMapRec; PropertyRec *pRecImport; PropertyRec *pRecEmit; ULONG ridStart; ULONG ridEnd; ULONG i; mdProperty prImp; mdProperty prEmit; TOKENREC *pTokenRec; ULONG iPropertyMap; PropertyMapRec *pPropertyMap; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; mdCustomAttribute tkCA; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); pCurTkMap = pImportData->m_pMDTokenMap; pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // make sure we didn't count the properties yet _ASSERTE(pMTD->m_cProperties == 0); IfFailGo(pMiniMdImport->FindPropertyMapFor(RidFromToken(tdImport), &ridPropertyMap)); if (!InvalidRid(ridPropertyMap)) { IfFailGo(pMiniMdImport->GetPropertyMapRecord(ridPropertyMap, &pPropertyMapRec)); ridStart = pMiniMdImport->getPropertyListOfPropertyMap(pPropertyMapRec); IfFailGo(pMiniMdImport->getEndPropertyListOfPropertyMap(ridPropertyMap, &ridEnd)); if (ridEnd > ridStart) { // If there is any event, create the PropertyMap record in the emit scope // Create new record. IfFailGo(pMiniMdEmit->AddPropertyMapRecord(&pPropertyMap, &iPropertyMap)); // Set parent. IfFailGo(pMiniMdEmit->PutToken(TBL_PropertyMap, PropertyMapRec::COL_Parent, pPropertyMap, tdEmit)); } for (i = ridStart; i < ridEnd; i++) { // get the property rid IfFailGo(pMiniMdImport->GetPropertyRid(i, (ULONG *)&prImp)); // only merge those Properties that are marked if ( pMiniMdImport->GetFilterTable()->IsPropertyMarked(TokenFromRid(prImp, mdtProperty)) == false) continue; IfFailGo(pMiniMdImport->GetPropertyRecord(prImp, &pRecImport)); IfFailGo(pMiniMdEmit->AddPropertyRecord(&pRecEmit, (RID *)&prEmit)); // copy the property record over IfFailGo( CopyProperty(pImportData, pRecImport, pRecEmit) ); // Add Property to the PropertyMap. IfFailGo( pMiniMdEmit->AddPropertyToPropertyMap(iPropertyMap, prEmit) ); // record the token movement prImp = TokenFromRid(prImp, mdtProperty); prEmit = TokenFromRid(prEmit, mdtProperty); IfFailGo( pCurTkMap->InsertNotFound(prImp, false, prEmit, &pTokenRec) ); // copy over the method semantics IfFailGo( CopyMethodSemantics(pImportData, prImp, prEmit) ); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, prImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (!bSuppressMergeCheck) { pMTD->m_cProperties++; } } } // make sure we don't count any properties if merge check is suppressed on the type _ASSERTE(pMTD->m_cProperties == 0 || !pMTD->m_bSuppressMergeCheck); ErrExit: return hr; } // HRESULT NEWMERGER::CopyProperties() //***************************************************************************** // Copy Parameters given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyParams( MergeImportData *pImportData, mdMethodDef mdImport, mdMethodDef mdEmit) { HRESULT hr = NOERROR; ParamRec *pRecImport = NULL; ParamRec *pRecEmit = NULL; MethodRec *pMethodRec; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG ridStart, ridEnd; ULONG i; mdParamDef pdEmit; mdParamDef pdImp; TOKENREC *pTokenRec; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo(pMiniMdImport->GetMethodRecord(RidFromToken(mdImport), &pMethodRec)); ridStart = pMiniMdImport->getParamListOfMethod(pMethodRec); IfFailGo(pMiniMdImport->getEndParamListOfMethod(RidFromToken(mdImport), &ridEnd)); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // loop through all InterfaceImpl for (i = ridStart; i < ridEnd; i++) { // Get the param rid IfFailGo(pMiniMdImport->GetParamRid(i, (ULONG *)&pdImp)); // only merge those Params that are marked if ( pMiniMdImport->GetFilterTable()->IsParamMarked(TokenFromRid(pdImp, mdtParamDef)) == false) continue; IfFailGo(pMiniMdImport->GetParamRecord(pdImp, &pRecImport)); IfFailGo(pMiniMdEmit->AddParamRecord(&pRecEmit, (RID *)&pdEmit)); // copy the Parameter record over IfFailGo( CopyParam(pImportData, pRecImport, pRecEmit) ); // warning!! warning!! // We cannot add paramRec to method list until it is fully set. // AddParamToMethod will use the ulSequence in the record IfFailGo( pMiniMdEmit->AddParamToMethod(RidFromToken(mdEmit), pdEmit)); // record the token movement pdImp = TokenFromRid(pdImp, mdtParamDef); pdEmit = TokenFromRid(pdEmit, mdtParamDef); IfFailGo( pCurTkMap->InsertNotFound(pdImp, false, pdEmit, &pTokenRec) ); } ErrExit: return hr; } // HRESULT NEWMERGER::CopyParams() //***************************************************************************** // Copy GenericParams given a TypeDef //***************************************************************************** HRESULT NEWMERGER::CopyGenericParams( MergeImportData *pImportData, mdToken tkImport, mdToken tkEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; TOKENREC *pTokenRec; GenericParamRec *pRecImport = NULL; GenericParamRec *pRecEmit = NULL; MDTOKENMAP *pCurTkMap; HENUMInternal hEnum; mdGenericParam gpImport; mdGenericParam gpEmit; LPCSTR szGenericParamName; pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pMiniMdEmit = GetMiniMdEmit(); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo( pMiniMdImport->FindGenericParamHelper(tkImport, &hEnum) ); while (HENUMInternal::EnumNext(&hEnum, (mdToken *) &gpImport)) { // Get the import GenericParam record _ASSERTE(TypeFromToken(gpImport) == mdtGenericParam); IfFailGo(pMiniMdImport->GetGenericParamRecord(RidFromToken(gpImport), &pRecImport)); // Create new emit record. IfFailGo(pMiniMdEmit->AddGenericParamRecord(&pRecEmit, (RID *)&gpEmit)); // copy the GenericParam content pRecEmit->SetNumber( pRecImport->GetNumber()); pRecEmit->SetFlags( pRecImport->GetFlags()); IfFailGo( pMiniMdEmit->PutToken(TBL_GenericParam, GenericParamRec::COL_Owner, pRecEmit, tkEmit)); IfFailGo(pMiniMdImport->getNameOfGenericParam(pRecImport, &szGenericParamName)); IfFailGo( pMiniMdEmit->PutString(TBL_GenericParam, GenericParamRec::COL_Name, pRecEmit, szGenericParamName)); // record the token movement gpImport = TokenFromRid(gpImport, mdtGenericParam); gpEmit = TokenFromRid(gpEmit, mdtGenericParam); IfFailGo( pCurTkMap->InsertNotFound(gpImport, false, gpEmit, &pTokenRec) ); // copy over any constraints IfFailGo( CopyGenericParamConstraints(pImportData, gpImport, gpEmit) ); } ErrExit: return hr; } // HRESULT NEWMERGER::CopyGenericParams() //***************************************************************************** // Copy GenericParamConstraints given a GenericParam //***************************************************************************** HRESULT NEWMERGER::CopyGenericParamConstraints( MergeImportData *pImportData, mdGenericParamConstraint tkImport, mdGenericParamConstraint tkEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; TOKENREC *pTokenRec; GenericParamConstraintRec *pRecImport = NULL; GenericParamConstraintRec *pRecEmit = NULL; MDTOKENMAP *pCurTkMap; HENUMInternal hEnum; mdGenericParamConstraint gpImport; mdGenericParamConstraint gpEmit; mdToken tkConstraint; pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pMiniMdEmit = GetMiniMdEmit(); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo( pMiniMdImport->FindGenericParamConstraintHelper(tkImport, &hEnum) ); while (HENUMInternal::EnumNext(&hEnum, (mdToken *) &gpImport)) { // Get the import GenericParam record _ASSERTE(TypeFromToken(gpImport) == mdtGenericParamConstraint); IfFailGo(pMiniMdImport->GetGenericParamConstraintRecord(RidFromToken(gpImport), &pRecImport)); // Translate the constraint before creating new record. tkConstraint = pMiniMdImport->getConstraintOfGenericParamConstraint(pRecImport); if (pCurTkMap->Find(tkConstraint, &pTokenRec) == false) { // This should never fire unless the TypeDefs/Refs weren't merged // before this code runs. _ASSERTE(!"GenericParamConstraint Constraint not found in MERGER::CopyGenericParamConstraints. Bad state!"); IfFailGo( META_E_BADMETADATA ); } tkConstraint = pTokenRec->m_tkTo; // Create new emit record. IfFailGo(pMiniMdEmit->AddGenericParamConstraintRecord(&pRecEmit, (RID *)&gpEmit)); // copy the GenericParamConstraint content IfFailGo( pMiniMdEmit->PutToken(TBL_GenericParamConstraint, GenericParamConstraintRec::COL_Owner, pRecEmit, tkEmit)); IfFailGo( pMiniMdEmit->PutToken(TBL_GenericParamConstraint, GenericParamConstraintRec::COL_Constraint, pRecEmit, tkConstraint)); } ErrExit: return hr; } // HRESULT NEWMERGER::CopyGenericParamConstraints() //***************************************************************************** // Verify GenericParams given a TypeDef //***************************************************************************** HRESULT NEWMERGER::VerifyGenericParams( MergeImportData *pImportData, mdToken tkImport, mdToken tkEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; TOKENREC *pTokenRec; MDTOKENMAP *pCurTkMap; HENUMInternal hEnumImport; // Enumerator for import scope. HENUMInternal hEnumEmit; // Enumerator for emit scope. ULONG cImport, cEmit; // Count of import & emit records. ULONG i; // Enumerating records in import scope. ULONG iEmit; // Tracking records in emit scope. mdGenericParam gpImport; // Import scope GenericParam token. mdGenericParam gpEmit; // Emit scope GenericParam token. GenericParamRec *pRecImport = NULL; GenericParamRec *pRecEmit = NULL; LPCSTR szNameImport; // Name of param in import scope. LPCSTR szNameEmit; // Name of param in emit scope. pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pMiniMdEmit = GetMiniMdEmit(); pCurTkMap = pImportData->m_pMDTokenMap; // Get enumerators for the input and output scopes. IfFailGo(pMiniMdImport->FindGenericParamHelper(tkImport, &hEnumImport)); IfFailGo(pMiniMdEmit->FindGenericParamHelper(tkEmit, &hEnumEmit)); // The counts should be the same. IfFailGo(HENUMInternal::GetCount(&hEnumImport, &cImport)); IfFailGo(HENUMInternal::GetCount(&hEnumEmit, &cEmit)); if (cImport != cEmit) { CheckContinuableErrorEx(META_E_GENERICPARAM_INCONSISTENT, pImportData, tkImport); // If we are here, the linker says this error is OK. } for (i=iEmit=0; i<cImport; ++i) { // Get the import GenericParam record IfFailGo(HENUMInternal::GetElement(&hEnumImport, i, &gpImport)); _ASSERTE(TypeFromToken(gpImport) == mdtGenericParam); IfFailGo(pMiniMdImport->GetGenericParamRecord(RidFromToken(gpImport), &pRecImport)); // Find the emit record. If the import and emit scopes are ordered the same // this is easy; otherwise go looking for it. // Get the "next" emit record. if (iEmit < cEmit) { IfFailGo(HENUMInternal::GetElement(&hEnumEmit, iEmit, &gpEmit)); _ASSERTE(TypeFromToken(gpEmit) == mdtGenericParam); IfFailGo(pMiniMdEmit->GetGenericParamRecord(RidFromToken(gpEmit), &pRecEmit)); } // If the import and emit sequence numbers don't match, go looking. // Also, if we would have walked off end of array, go looking. if (iEmit >= cEmit || pRecImport->GetNumber() != pRecEmit->GetNumber()) { for (iEmit=0; iEmit<cEmit; ++iEmit) { IfFailGo( HENUMInternal::GetElement(&hEnumEmit, iEmit, &gpEmit)); _ASSERTE(TypeFromToken(gpEmit) == mdtGenericParam); IfFailGo(pMiniMdEmit->GetGenericParamRecord(RidFromToken(gpEmit), &pRecEmit)); // The one we want? if (pRecImport->GetNumber() == pRecEmit->GetNumber()) break; } if (iEmit >= cEmit) goto Error; // Didn't find it } // Check that these "n'th" GenericParam records match. // Flags. if (pRecImport->GetFlags() != pRecEmit->GetFlags()) goto Error; // Name. IfFailGo(pMiniMdImport->getNameOfGenericParam(pRecImport, &szNameImport)); IfFailGo(pMiniMdEmit->getNameOfGenericParam(pRecEmit, &szNameEmit)); if (strcmp(szNameImport, szNameEmit) != 0) goto Error; // Verify any constraints. gpImport = TokenFromRid(gpImport, mdtGenericParam); gpEmit = TokenFromRid(gpEmit, mdtGenericParam); hr = VerifyGenericParamConstraints(pImportData, gpImport, gpEmit); if (SUCCEEDED(hr)) { // record the token movement IfFailGo( pCurTkMap->InsertNotFound(gpImport, true, gpEmit, &pTokenRec) ); } else { Error: // inconsistent in GenericParams hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_E_GENERICPARAM_INCONSISTENT, pImportData, tkImport); } } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyGenericParams() //***************************************************************************** // Verify GenericParamConstraints given a GenericParam //***************************************************************************** HRESULT NEWMERGER::VerifyGenericParamConstraints( MergeImportData *pImportData, // The import scope. mdGenericParam gpImport, // Import GenericParam. mdGenericParam gpEmit) // Emit GenericParam. { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; TOKENREC *pTokenRec; HENUMInternal hEnumImport; // Enumerator for import scope. HENUMInternal hEnumEmit; // Enumerator for emit scope. ULONG cImport, cEmit; // Count of import & emit records. ULONG i; // Enumerating records in import scope. ULONG iEmit; // Tracking records in emit scope. GenericParamConstraintRec *pRecImport = NULL; GenericParamConstraintRec *pRecEmit = NULL; MDTOKENMAP *pCurTkMap; mdToken tkConstraintImport = mdTokenNil; mdToken tkConstraintEmit = mdTokenNil; pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pMiniMdEmit = GetMiniMdEmit(); pCurTkMap = pImportData->m_pMDTokenMap; // Get enumerators for the input and output scopes. IfFailGo(pMiniMdImport->FindGenericParamConstraintHelper(gpImport, &hEnumImport)); IfFailGo(pMiniMdEmit->FindGenericParamConstraintHelper(gpEmit, &hEnumEmit)); // The counts should be the same. IfFailGo(HENUMInternal::GetCount(&hEnumImport, &cImport)); IfFailGo(HENUMInternal::GetCount(&hEnumEmit, &cEmit)); if (cImport != cEmit) IfFailGo(META_E_GENERICPARAM_INCONSISTENT); // Different numbers of constraints. for (i=iEmit=0; i<cImport; ++i) { // Get the import GenericParam record IfFailGo( HENUMInternal::GetElement(&hEnumImport, i, &gpImport)); _ASSERTE(TypeFromToken(gpImport) == mdtGenericParamConstraint); IfFailGo(pMiniMdImport->GetGenericParamConstraintRecord(RidFromToken(gpImport), &pRecImport)); // Get the constraint. tkConstraintImport = pMiniMdImport->getConstraintOfGenericParamConstraint(pRecImport); if (pCurTkMap->Find(tkConstraintImport, &pTokenRec) == false) { // This should never fire unless the TypeDefs/Refs weren't merged // before this code runs. _ASSERTE(!"GenericParamConstraint Constraint not found in MERGER::VerifyGenericParamConstraints. Bad state!"); IfFailGo( META_E_BADMETADATA ); } tkConstraintImport = pTokenRec->m_tkTo; // Find the emit record. If the import and emit scopes are ordered the same // this is easy; otherwise go looking for it. // Get the "next" emit record. if (iEmit < cEmit) { IfFailGo( HENUMInternal::GetElement(&hEnumEmit, iEmit, &gpEmit)); _ASSERTE(TypeFromToken(gpEmit) == mdtGenericParamConstraint); IfFailGo(pMiniMdEmit->GetGenericParamConstraintRecord(RidFromToken(gpEmit), &pRecEmit)); tkConstraintEmit = pMiniMdEmit->getConstraintOfGenericParamConstraint(pRecEmit); } // If the import and emit constraints don't match, go looking. if (iEmit >= cEmit || tkConstraintEmit != tkConstraintImport) { for (iEmit=0; iEmit<cEmit; ++iEmit) { IfFailGo( HENUMInternal::GetElement(&hEnumEmit, iEmit, &gpEmit)); _ASSERTE(TypeFromToken(gpEmit) == mdtGenericParamConstraint); IfFailGo(pMiniMdEmit->GetGenericParamConstraintRecord(RidFromToken(gpEmit), &pRecEmit)); tkConstraintEmit = pMiniMdEmit->getConstraintOfGenericParamConstraint(pRecEmit); // The one we want? if (tkConstraintEmit == tkConstraintImport) break; } if (iEmit >= cEmit) { IfFailGo(META_E_GENERICPARAM_INCONSISTENT); // Didn't find the constraint } } } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyGenericParamConstraints() //***************************************************************************** // Verify Methods //***************************************************************************** HRESULT NEWMERGER::VerifyMethods( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; MethodRec *pRecImp; MethodRec *pRecEmit; ULONG ridStart; ULONG ridEnd; ULONG i; TypeDefRec *pTypeDefRec; LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; TOKENREC *pTokenRec; mdMethodDef mdImp; mdMethodDef mdEmit; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; ULONG cImport = 0; // count of non-merge check suppressed methods mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // Get a count of records in the import scope; prepare to enumerate them. IfFailGo(pMiniMdImport->GetTypeDefRecord(RidFromToken(tdImport), &pTypeDefRec)); ridStart = pMiniMdImport->getMethodListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdImport->getEndMethodListOfTypeDef(RidFromToken(tdImport), &ridEnd)); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // loop through all Methods of the TypeDef for (i = ridStart; i < ridEnd; i++) { IfFailGo(pMiniMdImport->GetMethodRid(i, (ULONG *)&mdImp)); // only verify those Methods that are marked if ( pMiniMdImport->GetFilterTable()->IsMethodMarked(TokenFromRid(mdImp, mdtMethodDef)) == false) continue; IfFailGo(pMiniMdImport->GetMethodRecord(mdImp, &pRecImp)); if (m_fDupCheck == FALSE && tdImport == pImportData->m_pRegMetaImport->m_tdModule) // TokenFromRid(1, mdtTypeDef)) { // No dup check. This is the scenario that we only have one import scope. Just copy over the // globals. goto CopyMethodLabel; } IfFailGo(pMiniMdImport->getNameOfMethod(pRecImp, &szName)); IfFailGo(pMiniMdImport->getSignatureOfMethod(pRecImp, &pbSig, &cbSig)); mdImp = TokenFromRid(mdImp, mdtMethodDef); if ( IsMdPrivateScope( pRecImp->GetFlags() ) ) { // Trigger additive merge goto CopyMethodLabel; } // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit hr = ImportHelper::FindMethod( pMiniMdEmit, tdEmit, szName, (const COR_SIGNATURE *)qbSig.Ptr(), cbEmit, &mdEmit); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, mdImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (bSuppressMergeCheck || (tdImport == pImportData->m_pRegMetaImport->m_tdModule)) { // global functions! Make sure that we move over the non-duplicate global function // declaration // if (hr == S_OK) { // found the duplicate IfFailGo( VerifyMethod(pImportData, mdImp, mdEmit) ); } else { CopyMethodLabel: // not a duplicate! Copy over the IfFailGo(pMiniMdEmit->AddMethodRecord(&pRecEmit, (RID *)&mdEmit)); // copy the method content over IfFailGo( CopyMethod(pImportData, pRecImp, pRecEmit) ); IfFailGo( pMiniMdEmit->AddMethodToTypeDef(RidFromToken(tdEmit), mdEmit)); // record the token movement mdEmit = TokenFromRid(mdEmit, mdtMethodDef); IfFailGo( pMiniMdEmit->AddMemberDefToHash( mdEmit, tdEmit) ); mdImp = TokenFromRid(mdImp, mdtMethodDef); IfFailGo( pCurTkMap->InsertNotFound(mdImp, false, mdEmit, &pTokenRec) ); // copy over the children IfFailGo( CopyParams(pImportData, mdImp, mdEmit) ); IfFailGo( CopyGenericParams(pImportData, mdImp, mdEmit) ); } } else { if (hr == S_OK) { // Good! We are supposed to find a duplicate IfFailGo( VerifyMethod(pImportData, mdImp, mdEmit) ); } else { // Oops! The typedef is duplicated but the method is not!! hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_E_METHD_NOT_FOUND, pImportData, mdImp); } cImport++; } } // The counts should be the same, unless this is <module> if (cImport != pMTD->m_cMethods && tdImport != pImportData->m_pRegMetaImport->m_tdModule) { CheckContinuableErrorEx(META_E_METHOD_COUNTS, pImportData, tdImport); // If we are here, the linker says this error is OK. } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyMethods() //***************************************************************************** // verify a duplicated method //***************************************************************************** HRESULT NEWMERGER::VerifyMethod( MergeImportData *pImportData, mdMethodDef mdImp, // [IN] the emit record to fill mdMethodDef mdEmit) // [IN] the record to import { HRESULT hr; MethodRec *pRecImp; MethodRec *pRecEmit; TOKENREC *pTokenRec; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; IfFailGo( pCurTkMap->InsertNotFound(mdImp, true, mdEmit, &pTokenRec) ); IfFailGo(pMiniMdImport->GetMethodRecord(RidFromToken(mdImp), &pRecImp)); // We need to make sure that the impl flags are propagated . // Rules are: if the first method has miForwardRef flag set but the new method does not, // we want to disable the miForwardRef flag. If the one found in the emit scope does not have // miForwardRef set and the second one doesn't either, we want to make sure that the rest of // impl flags are the same. // if ( !IsMiForwardRef( pRecImp->GetImplFlags() ) ) { IfFailGo(pMiniMdEmit->GetMethodRecord(RidFromToken(mdEmit), &pRecEmit)); if (!IsMiForwardRef(pRecEmit->GetImplFlags())) { // make sure the rest of ImplFlags are the same if (pRecEmit->GetImplFlags() != pRecImp->GetImplFlags()) { // inconsistent in implflags CheckContinuableErrorEx(META_E_METHDIMPL_INCONSISTENT, pImportData, mdImp); } } else { // propagate the importing ImplFlags pRecEmit->SetImplFlags(pRecImp->GetImplFlags()); } } // verify the children IfFailGo( VerifyParams(pImportData, mdImp, mdEmit) ); IfFailGo( VerifyGenericParams(pImportData, mdImp, mdEmit) ); ErrExit: return hr; } // HRESULT NEWMERGER::VerifyMethod() //***************************************************************************** // Verify Fields //***************************************************************************** HRESULT NEWMERGER::VerifyFields( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; FieldRec *pRecImp; FieldRec *pRecEmit; mdFieldDef fdImp; mdFieldDef fdEmit; ULONG ridStart; ULONG ridEnd; ULONG i; TypeDefRec *pTypeDefRec; LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; TOKENREC *pTokenRec; MDTOKENMAP *pCurTkMap; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; ULONG cImport = 0; // count of non-merge check suppressed fields mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // Get a count of records in the import scope; prepare to enumerate them. IfFailGo(pMiniMdImport->GetTypeDefRecord(RidFromToken(tdImport), &pTypeDefRec)); ridStart = pMiniMdImport->getFieldListOfTypeDef(pTypeDefRec); IfFailGo(pMiniMdImport->getEndFieldListOfTypeDef(RidFromToken(tdImport), &ridEnd)); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); // loop through all fields of the TypeDef for (i = ridStart; i < ridEnd; i++) { IfFailGo(pMiniMdImport->GetFieldRid(i, (ULONG *)&fdImp)); // only verify those fields that are marked if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(TokenFromRid(fdImp, mdtFieldDef)) == false) continue; IfFailGo(pMiniMdImport->GetFieldRecord(fdImp, &pRecImp)); if (m_fDupCheck == FALSE && tdImport == pImportData->m_pRegMetaImport->m_tdModule) { // No dup check. This is the scenario that we only have one import scope. Just copy over the // globals. goto CopyFieldLabel; } IfFailGo(pMiniMdImport->getNameOfField(pRecImp, &szName)); IfFailGo(pMiniMdImport->getSignatureOfField(pRecImp, &pbSig, &cbSig)); if ( IsFdPrivateScope(pRecImp->GetFlags())) { // Trigger additive merge fdImp = TokenFromRid(fdImp, mdtFieldDef); goto CopyFieldLabel; } // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit hr = ImportHelper::FindField( pMiniMdEmit, tdEmit, szName, (const COR_SIGNATURE *)qbSig.Ptr(), cbEmit, &fdEmit); fdImp = TokenFromRid(fdImp, mdtFieldDef); bSuppressMergeCheck = (IsFdStatic(pRecImp->GetFlags()) && pMTD->m_bSuppressMergeCheck) || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, fdImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (bSuppressMergeCheck || (tdImport == pImportData->m_pRegMetaImport->m_tdModule)) { // global data! Make sure that we move over the non-duplicate global function // declaration // if (hr == S_OK) { // found the duplicate IfFailGo( pCurTkMap->InsertNotFound(fdImp, true, fdEmit, &pTokenRec) ); } else { CopyFieldLabel: // not a duplicate! Copy over the IfFailGo(pMiniMdEmit->AddFieldRecord(&pRecEmit, (RID *)&fdEmit)); // copy the field record over IfFailGo( CopyField(pImportData, pRecImp, pRecEmit) ); IfFailGo( pMiniMdEmit->AddFieldToTypeDef(RidFromToken(tdEmit), fdEmit)); // record the token movement fdEmit = TokenFromRid(fdEmit, mdtFieldDef); IfFailGo( pMiniMdEmit->AddMemberDefToHash( fdEmit, tdEmit) ); fdImp = TokenFromRid(fdImp, mdtFieldDef); IfFailGo( pCurTkMap->InsertNotFound(fdImp, false, fdEmit, &pTokenRec) ); } } else { if (hr == S_OK) { // Good! We are supposed to find a duplicate IfFailGo( pCurTkMap->InsertNotFound(fdImp, true, fdEmit, &pTokenRec) ); } else { // Oops! The typedef is duplicated but the field is not!! hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_E_FIELD_NOT_FOUND, pImportData, fdImp); } cImport++; } } // The counts should be the same, unless this is <module> if (cImport != pMTD->m_cFields && tdImport != pImportData->m_pRegMetaImport->m_tdModule) { CheckContinuableErrorEx(META_E_FIELD_COUNTS, pImportData, tdImport); // If we are here, the linker says this error is OK. } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyFields() //***************************************************************************** // Verify Events //***************************************************************************** HRESULT NEWMERGER::VerifyEvents( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; RID ridEventMap, ridEventMapEmit; EventMapRec *pEventMapRec; EventRec *pRecImport; ULONG ridStart; ULONG ridEnd; ULONG i; mdEvent evImport; mdEvent evEmit; TOKENREC *pTokenRec; LPCUTF8 szName; mdToken tkType; MDTOKENMAP *pCurTkMap; EventMapRec *pEventMapEmit; EventRec *pRecEmit; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; ULONG cImport = 0; // count of non-merge check suppressed events mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); IfFailGo(pMiniMdImport->FindEventMapFor(RidFromToken(tdImport), &ridEventMap)); if (!InvalidRid(ridEventMap)) { // Get a count of records already in emit scope. IfFailGo(pMiniMdEmit->FindEventMapFor(RidFromToken(tdEmit), &ridEventMapEmit)); if (InvalidRid(ridEventMapEmit)) { // If there is any event, create the eventmap record in the emit scope // Create new record. IfFailGo(pMiniMdEmit->AddEventMapRecord(&pEventMapEmit, &ridEventMapEmit)); // Set parent. IfFailGo(pMiniMdEmit->PutToken(TBL_EventMap, EventMapRec::COL_Parent, pEventMapEmit, tdEmit)); } // Get a count of records in the import scope; prepare to enumerate them. IfFailGo(pMiniMdImport->GetEventMapRecord(ridEventMap, &pEventMapRec)); ridStart = pMiniMdImport->getEventListOfEventMap(pEventMapRec); IfFailGo(pMiniMdImport->getEndEventListOfEventMap(ridEventMap, &ridEnd)); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); for (i = ridStart; i < ridEnd; i++) { // get the property rid IfFailGo(pMiniMdImport->GetEventRid(i, (ULONG *)&evImport)); // only verify those Events that are marked if ( pMiniMdImport->GetFilterTable()->IsEventMarked(TokenFromRid(evImport, mdtEvent)) == false) continue; IfFailGo(pMiniMdImport->GetEventRecord(evImport, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfEvent(pRecImport, &szName)); tkType = pMiniMdImport->getEventTypeOfEvent( pRecImport ); IfFailGo( pCurTkMap->Remap(tkType, &tkType) ); evImport = TokenFromRid( evImport, mdtEvent); hr = ImportHelper::FindEvent( pMiniMdEmit, tdEmit, szName, &evEmit); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, evImport, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (bSuppressMergeCheck) { if (hr == S_OK ) { // Good. We found the matching event when we have a duplicate typedef IfFailGo( pCurTkMap->InsertNotFound(evImport, true, evEmit, &pTokenRec) ); } else { // not a duplicate! Copy over the IfFailGo(pMiniMdEmit->AddEventRecord(&pRecEmit, (RID *)&evEmit)); // copy the event record over IfFailGo( CopyEvent(pImportData, pRecImport, pRecEmit) ); // Add Event to the EventMap. IfFailGo( pMiniMdEmit->AddEventToEventMap(ridEventMapEmit, evEmit) ); // record the token movement evEmit = TokenFromRid(evEmit, mdtEvent); IfFailGo( pCurTkMap->InsertNotFound(evImport, false, evEmit, &pTokenRec) ); // copy over the method semantics IfFailGo( CopyMethodSemantics(pImportData, evImport, evEmit) ); } } else { if (hr == S_OK ) { // Good. We found the matching event when we have a duplicate typedef IfFailGo( pCurTkMap->InsertNotFound(evImport, true, evEmit, &pTokenRec) ); } else { // Oops! The typedef is duplicated but the event is not!! hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_E_EVENT_NOT_FOUND, pImportData, evImport); } cImport++; } } // The counts should be the same, unless this is <module> if (cImport != pMTD->m_cEvents && tdImport != pImportData->m_pRegMetaImport->m_tdModule) { CheckContinuableErrorEx(META_E_EVENT_COUNTS, pImportData, tdImport); // If we are here, the linker says this error is OK. } } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyEvents() //***************************************************************************** // Verify Properties //***************************************************************************** HRESULT NEWMERGER::VerifyProperties( MergeImportData *pImportData, mdTypeDef tdImport, mdTypeDef tdEmit) { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; RID ridPropertyMap, ridPropertyMapEmit; PropertyMapRec *pPropertyMapRec; PropertyRec *pRecImport; ULONG ridStart; ULONG ridEnd; ULONG i; mdProperty prImp; mdProperty prEmit; TOKENREC *pTokenRec; LPCUTF8 szName; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; MDTOKENMAP *pCurTkMap; PropertyMapRec *pPropertyMapEmit; PropertyRec *pRecEmit; MergeTypeData *pMTD; BOOL bSuppressMergeCheck; ULONG cImport = 0; // count of non-merge check suppressed properties mdCustomAttribute tkCA; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); IfFailGo(pMiniMdImport->FindPropertyMapFor(RidFromToken(tdImport), &ridPropertyMap)); if (!InvalidRid(ridPropertyMap)) { // Get a count of records already in emit scope. IfFailGo(pMiniMdEmit->FindPropertyMapFor(RidFromToken(tdEmit), &ridPropertyMapEmit)); if (InvalidRid(ridPropertyMapEmit)) { // If there is any event, create the PropertyMap record in the emit scope // Create new record. IfFailGo(pMiniMdEmit->AddPropertyMapRecord(&pPropertyMapEmit, &ridPropertyMapEmit)); // Set parent. IfFailGo(pMiniMdEmit->PutToken(TBL_PropertyMap, PropertyMapRec::COL_Parent, pPropertyMapEmit, tdEmit)); } // Get a count of records in the import scope; prepare to enumerate them. IfFailGo(pMiniMdImport->GetPropertyMapRecord(ridPropertyMap, &pPropertyMapRec)); ridStart = pMiniMdImport->getPropertyListOfPropertyMap(pPropertyMapRec); IfFailGo(pMiniMdImport->getEndPropertyListOfPropertyMap(ridPropertyMap, &ridEnd)); pMTD = m_rMTDs.Get(RidFromToken(tdEmit)); for (i = ridStart; i < ridEnd; i++) { // get the property rid IfFailGo(pMiniMdImport->GetPropertyRid(i, (ULONG *)&prImp)); // only verify those Properties that are marked if ( pMiniMdImport->GetFilterTable()->IsPropertyMarked(TokenFromRid(prImp, mdtProperty)) == false) continue; IfFailGo(pMiniMdImport->GetPropertyRecord(prImp, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfProperty(pRecImport, &szName)); IfFailGo(pMiniMdImport->getTypeOfProperty(pRecImport, &pbSig, &cbSig)); prImp = TokenFromRid( prImp, mdtProperty); // convert rid contained in signature to new scope IfFailGo( ImportHelper::MergeUpdateTokenInSig( NULL, // Emit assembly. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit) ); // number of bytes write to cbEmit hr = ImportHelper::FindProperty( pMiniMdEmit, tdEmit, szName, (PCCOR_SIGNATURE) qbSig.Ptr(), cbEmit, &prEmit); bSuppressMergeCheck = pMTD->m_bSuppressMergeCheck || ((pImportData->m_tkSuppressMergeCheckCtor != mdTokenNil) && (S_OK == ImportHelper::FindCustomAttributeByToken(pMiniMdImport, prImp, pImportData->m_tkSuppressMergeCheckCtor, NULL, 0, &tkCA))); if (bSuppressMergeCheck) { if (hr == S_OK) { // Good. We found the matching property when we have a duplicate typedef IfFailGo( pCurTkMap->InsertNotFound(prImp, true, prEmit, &pTokenRec) ); } else { IfFailGo(pMiniMdEmit->AddPropertyRecord(&pRecEmit, (RID *)&prEmit)); // copy the property record over IfFailGo( CopyProperty(pImportData, pRecImport, pRecEmit) ); // Add Property to the PropertyMap. IfFailGo( pMiniMdEmit->AddPropertyToPropertyMap(ridPropertyMapEmit, prEmit) ); // record the token movement prEmit = TokenFromRid(prEmit, mdtProperty); IfFailGo( pCurTkMap->InsertNotFound(prImp, false, prEmit, &pTokenRec) ); // copy over the method semantics IfFailGo( CopyMethodSemantics(pImportData, prImp, prEmit) ); } } else { if (hr == S_OK) { // Good. We found the matching property when we have a duplicate typedef IfFailGo( pCurTkMap->InsertNotFound(prImp, true, prEmit, &pTokenRec) ); } else { hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_E_PROP_NOT_FOUND, pImportData, prImp); } cImport++; } } // The counts should be the same, unless this is <module> if (cImport != pMTD->m_cProperties && tdImport != pImportData->m_pRegMetaImport->m_tdModule) { CheckContinuableErrorEx(META_E_PROPERTY_COUNTS, pImportData, tdImport); // If we are here, the linker says this error is OK. } } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyProperties() //***************************************************************************** // Verify Parameters given a Method //***************************************************************************** HRESULT NEWMERGER::VerifyParams( MergeImportData *pImportData, mdMethodDef mdImport, mdMethodDef mdEmit) { HRESULT hr = NOERROR; ParamRec *pRecImport = NULL; ParamRec *pRecEmit = NULL; MethodRec *pMethodRec; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG ridStart, ridEnd; ULONG ridStartEmit, ridEndEmit; ULONG cImport, cEmit; ULONG i, j; mdParamDef pdEmit = 0; mdParamDef pdImp; TOKENREC *pTokenRec; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); pCurTkMap = pImportData->m_pMDTokenMap; // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // Get count of params in import scope; prepare to enumerate. IfFailGo(pMiniMdImport->GetMethodRecord(RidFromToken(mdImport), &pMethodRec)); ridStart = pMiniMdImport->getParamListOfMethod(pMethodRec); IfFailGo(pMiniMdImport->getEndParamListOfMethod(RidFromToken(mdImport), &ridEnd)); cImport = ridEnd - ridStart; // Get count of params in emit scope; prepare to enumerate. IfFailGo(pMiniMdEmit->GetMethodRecord(RidFromToken(mdEmit), &pMethodRec)); ridStartEmit = pMiniMdEmit->getParamListOfMethod(pMethodRec); IfFailGo(pMiniMdEmit->getEndParamListOfMethod(RidFromToken(mdEmit), &ridEndEmit)); cEmit = ridEndEmit - ridStartEmit; // The counts should be the same. if (cImport != cEmit) { // That is, unless this is <module>, so get the method's parent. mdTypeDef tdImport; IfFailGo(pMiniMdImport->FindParentOfMethodHelper(mdImport, &tdImport)); if (tdImport != pImportData->m_pRegMetaImport->m_tdModule) CheckContinuableErrorEx(META_E_PARAM_COUNTS, pImportData, mdImport); // If we are here, the linker says this error is OK. } // loop through all Parameters for (i = ridStart; i < ridEnd; i++) { // Get the importing param row IfFailGo(pMiniMdImport->GetParamRid(i, (ULONG *)&pdImp)); // only verify those Params that are marked if ( pMiniMdImport->GetFilterTable()->IsParamMarked(TokenFromRid(pdImp, mdtParamDef)) == false) continue; IfFailGo(pMiniMdImport->GetParamRecord(pdImp, &pRecImport)); pdImp = TokenFromRid(pdImp, mdtParamDef); // It turns out when we merge a typelib with itself, the emit and import scope // has different sequence of parameter // // find the corresponding emit param row for (j = ridStartEmit; j < ridEndEmit; j++) { IfFailGo(pMiniMdEmit->GetParamRid(j, (ULONG *)&pdEmit)); IfFailGo(pMiniMdEmit->GetParamRecord(pdEmit, &pRecEmit)); if (pRecEmit->GetSequence() == pRecImport->GetSequence()) break; } if (j == ridEndEmit) { // did not find the corresponding parameter in the emiting scope hr = S_OK; // discard old error; new error will be returned from CheckContinuableError CheckContinuableErrorEx(META_S_PARAM_MISMATCH, pImportData, pdImp); } else { _ASSERTE( pRecEmit->GetSequence() == pRecImport->GetSequence() ); pdEmit = TokenFromRid(pdEmit, mdtParamDef); // record the token movement #ifdef WE_DONT_NEED_TO_CHECK_NAMES__THEY_DONT_AFFECT_ANYTHING LPCUTF8 szNameImp; LPCUTF8 szNameEmit; IfFailGo(pMiniMdImport->getNameOfParam(pRecImport, &szNameImp)); IfFailGo(pMiniMdEmit->getNameOfParam(pRecEmit, &szNameEmit)); if (szNameImp && szNameEmit && strcmp(szNameImp, szNameEmit) != 0) { // parameter name doesn't match CheckContinuableErrorEx(META_S_PARAM_MISMATCH, pImportData, pdImp); } #endif if (pRecEmit->GetFlags() != pRecImport->GetFlags()) { // flags doesn't match CheckContinuableErrorEx(META_S_PARAM_MISMATCH, pImportData, pdImp); } // record token movement. This is a duplicate. IfFailGo( pCurTkMap->InsertNotFound(pdImp, true, pdEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::VerifyParams() //***************************************************************************** // merging MemberRef //***************************************************************************** HRESULT NEWMERGER::MergeMemberRefs( ) { HRESULT hr = NOERROR; MemberRefRec *pRecImport = NULL; MemberRefRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdMemberRef mrEmit; mdMemberRef mrImp; bool bDuplicate = false; TOKENREC *pTokenRec; mdToken tkParentImp; mdToken tkParentEmit; LPCUTF8 szNameImp; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; bool isRefOptimizedToDef; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountMemberRefs(); // loop through all MemberRef for (i = 1; i <= iCount; i++) { // only merge those MemberRefs that are marked if ( pMiniMdImport->GetFilterTable()->IsMemberRefMarked(TokenFromRid(i, mdtMemberRef)) == false) continue; isRefOptimizedToDef = false; // compare it with the emit scope IfFailGo(pMiniMdImport->GetMemberRefRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getNameOfMemberRef(pRecImport, &szNameImp)); IfFailGo(pMiniMdImport->getSignatureOfMemberRef(pRecImport, &pbSig, &cbSig)); tkParentImp = pMiniMdImport->getClassOfMemberRef(pRecImport); IfFailGo( pCurTkMap->Remap(tkParentImp, &tkParentEmit) ); // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly information. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit // We want to know if we can optimize this MemberRef to a FieldDef or MethodDef if (TypeFromToken(tkParentEmit) == mdtTypeDef && RidFromToken(tkParentEmit) != 0) { // The parent of this MemberRef has been successfully optimized to a TypeDef. Then this MemberRef should be // be able to optimized to a MethodDef or FieldDef unless one of the parent in the inheritance hierachy // is through TypeRef. Then this MemberRef stay as MemberRef. If This is a VarArg calling convention, then // we will remap the MemberRef's parent to a MethodDef or stay as TypeRef. // mdToken tkParent = tkParentEmit; mdToken tkMethDefOrFieldDef; PCCOR_SIGNATURE pbSigTmp = (const COR_SIGNATURE *) qbSig.Ptr(); while (TypeFromToken(tkParent) == mdtTypeDef && RidFromToken(tkParent) != 0) { TypeDefRec *pRec; hr = ImportHelper::FindMember(pMiniMdEmit, tkParent, szNameImp, pbSigTmp, cbEmit, &tkMethDefOrFieldDef); if (hr == S_OK) { // We have found a match!! if (isCallConv(CorSigUncompressCallingConv(pbSigTmp), IMAGE_CEE_CS_CALLCONV_VARARG)) { // The found MethodDef token will replace this MemberRef's parent token _ASSERTE(TypeFromToken(tkMethDefOrFieldDef) == mdtMethodDef); tkParentEmit = tkMethDefOrFieldDef; break; } else { // The found MethodDef/FieldDef token will replace this MemberRef token and we won't introduce a MemberRef // record. // mrEmit = tkMethDefOrFieldDef; isRefOptimizedToDef = true; bDuplicate = true; break; } } // now walk up to the parent class of tkParent and try to resolve this MemberRef IfFailGo(pMiniMdEmit->GetTypeDefRecord(RidFromToken(tkParent), &pRec)); tkParent = pMiniMdEmit->getExtendsOfTypeDef(pRec); } // When we exit the loop, there are several possibilities: // 1. We found a MethodDef/FieldDef to replace the MemberRef // 2. We found a MethodDef matches the MemberRef but the MemberRef is VarArg, thus we want to use the MethodDef in the // parent column but not replacing it. // 3. We exit because we run out the TypeDef on the parent chain. If it is because we encounter a TypeRef, this TypeRef will // replace the parent column of the MemberRef. Or we encounter nil token! (This can be unresolved global MemberRef or // compiler error to put an undefined MemberRef. In this case, we should just use the old tkParentEmit // on the parent column for the MemberRef. if (TypeFromToken(tkParent) == mdtTypeRef && RidFromToken(tkParent) != 0) { // we had walked up the parent's chain to resolve it but we have not been successful and got stopped by a TypeRef. // Then we will use this TypeRef as the parent of the emit MemberRef record // tkParentEmit = tkParent; } } else if ((TypeFromToken(tkParentEmit) == mdtMethodDef && !isCallConv(CorSigUncompressCallingConv(pbSig), IMAGE_CEE_CS_CALLCONV_VARARG)) || (TypeFromToken(tkParentEmit) == mdtFieldDef)) { // If the MemberRef's parent is already a non-vararg MethodDef or FieldDef, we can also // safely drop the MemberRef mrEmit = tkParentEmit; isRefOptimizedToDef = true; bDuplicate = true; } // If the Ref cannot be optimized to a Def or MemberRef to Def optmization is turned off, do the following. if (isRefOptimizedToDef == false || !((m_optimizeRefToDef & MDMemberRefToDef) == MDMemberRefToDef)) { // does this MemberRef already exist in the emit scope? if ( m_fDupCheck && ImportHelper::FindMemberRef( pMiniMdEmit, tkParentEmit, szNameImp, (const COR_SIGNATURE *) qbSig.Ptr(), cbEmit, &mrEmit) == S_OK ) { // Yes, it does bDuplicate = true; } else { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddMemberRefRecord(&pRecEmit, (RID *)&mrEmit)); mrEmit = TokenFromRid( mrEmit, mdtMemberRef ); // Copy over the MemberRef context IfFailGo(pMiniMdEmit->PutString(TBL_MemberRef, MemberRefRec::COL_Name, pRecEmit, szNameImp)); IfFailGo(pMiniMdEmit->PutToken(TBL_MemberRef, MemberRefRec::COL_Class, pRecEmit, tkParentEmit)); IfFailGo(pMiniMdEmit->PutBlob(TBL_MemberRef, MemberRefRec::COL_Signature, pRecEmit, qbSig.Ptr(), cbEmit)); IfFailGo(pMiniMdEmit->AddMemberRefToHash(mrEmit) ); } } // record the token movement mrImp = TokenFromRid(i, mdtMemberRef); IfFailGo( pCurTkMap->InsertNotFound(mrImp, bDuplicate, mrEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeMemberRefs() //***************************************************************************** // merge interface impl //***************************************************************************** HRESULT NEWMERGER::MergeInterfaceImpls( ) { HRESULT hr = NOERROR; InterfaceImplRec *pRecImport = NULL; InterfaceImplRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdTypeDef tkParent; mdInterfaceImpl iiEmit; bool bDuplicate; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountInterfaceImpls(); // loop through all InterfaceImpl for (i = 1; i <= iCount; i++) { // only merge those InterfaceImpls that are marked if ( pMiniMdImport->GetFilterTable()->IsInterfaceImplMarked(TokenFromRid(i, mdtInterfaceImpl)) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetInterfaceImplRecord(i, &pRecImport)); tkParent = pMiniMdImport->getClassOfInterfaceImpl(pRecImport); // does this TypeRef already exist in the emit scope? if ( pCurTkMap->Find(tkParent, &pTokenRec) ) { if ( pTokenRec->m_isDuplicate ) { // parent in the emit scope mdToken tkParentEmit; mdToken tkInterface; // remap the typedef token tkParentEmit = pTokenRec->m_tkTo; // remap the implemented interface token tkInterface = pMiniMdImport->getInterfaceOfInterfaceImpl(pRecImport); IfFailGo( pCurTkMap->Remap( tkInterface, &tkInterface) ); // Set duplicate flag bDuplicate = true; // find the corresponding interfaceimpl in the emit scope if ( ImportHelper::FindInterfaceImpl(pMiniMdEmit, tkParentEmit, tkInterface, &iiEmit) != S_OK ) { // bad state!! We have a duplicate typedef but the interface impl is not the same!! // continuable error CheckContinuableErrorEx( META_E_INTFCEIMPL_NOT_FOUND, pImportData, TokenFromRid(i, mdtInterfaceImpl)); iiEmit = mdTokenNil; } } else { // No, it doesn't. Copy it over. bDuplicate = false; IfFailGo(pMiniMdEmit->AddInterfaceImplRecord(&pRecEmit, (RID *)&iiEmit)); // copy the interfaceimp record over IfFailGo( CopyInterfaceImpl( pRecEmit, pImportData, pRecImport) ); } } else { _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } // record the token movement IfFailGo( pCurTkMap->InsertNotFound( TokenFromRid(i, mdtInterfaceImpl), bDuplicate, TokenFromRid( iiEmit, mdtInterfaceImpl ), &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeInterfaceImpls() //***************************************************************************** // merge all of the constant for field, property, and parameter //***************************************************************************** HRESULT NEWMERGER::MergeConstants() { HRESULT hr = NOERROR; ConstantRec *pRecImport = NULL; ConstantRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; ULONG csEmit; // constant value is not a token mdToken tkParentImp; TOKENREC *pTokenRec; void const *pValue; ULONG cbBlob; #if _DEBUG ULONG typeParent; #endif // _DEBUG MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountConstants(); // loop through all Constants for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetConstantRecord(i, &pRecImport)); tkParentImp = pMiniMdImport->getParentOfConstant(pRecImport); // only move those constant over if their parents are marked // If MDTOKENMAP::Find returns false, we don't need to copy the constant value over if ( pCurTkMap->Find(tkParentImp, &pTokenRec) ) { // If the parent is duplicated, no need to move over the constant value if ( !pTokenRec->m_isDuplicate ) { IfFailGo(pMiniMdEmit->AddConstantRecord(&pRecEmit, &csEmit)); pRecEmit->SetType(pRecImport->GetType()); // set the parent IfFailGo( pMiniMdEmit->PutToken(TBL_Constant, ConstantRec::COL_Parent, pRecEmit, pTokenRec->m_tkTo) ); // move over the constant blob value IfFailGo(pMiniMdImport->getValueOfConstant(pRecImport, (const BYTE **)&pValue, &cbBlob)); IfFailGo( pMiniMdEmit->PutBlob(TBL_Constant, ConstantRec::COL_Value, pRecEmit, pValue, cbBlob) ); IfFailGo( pMiniMdEmit->AddConstantToHash(csEmit) ); } else { // <TODO>@FUTURE: more verification on the duplicate??</TODO> } } #if _DEBUG // Include this block only under Debug build. The reason is that // the linker chooses all the errors that we report (such as unmatched MethodDef or FieldDef) // as a continuable error. It is likely to hit this else while the tkparentImp is marked if there // is any error reported earlier!! else { typeParent = TypeFromToken(tkParentImp); if (typeParent == mdtFieldDef) { // FieldDef should not be marked. if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(tkParentImp) == false) continue; } else if (typeParent == mdtParamDef) { // ParamDef should not be marked. if ( pMiniMdImport->GetFilterTable()->IsParamMarked(tkParentImp) == false) continue; } else { _ASSERTE(typeParent == mdtProperty); // Property should not be marked. if ( pMiniMdImport->GetFilterTable()->IsPropertyMarked(tkParentImp) == false) continue; } // If we come to here, we have a constant whose parent is marked but we could not // find it in the map!! Bad state. _ASSERTE(!"Ignore this error if you have seen error reported earlier! Otherwise bad token map or bad metadata!"); } #endif // _DEBUG // Note that we don't need to record the token movement since constant is not a valid token kind. } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeConstants() //***************************************************************************** // Merge field marshal information //***************************************************************************** HRESULT NEWMERGER::MergeFieldMarshals() { HRESULT hr = NOERROR; FieldMarshalRec *pRecImport = NULL; FieldMarshalRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; ULONG fmEmit; // FieldMarhsal is not a token mdToken tkParentImp; TOKENREC *pTokenRec; void const *pValue; ULONG cbBlob; #if _DEBUG ULONG typeParent; #endif // _DEBUG MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountFieldMarshals(); // loop through all TypeRef for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetFieldMarshalRecord(i, &pRecImport)); tkParentImp = pMiniMdImport->getParentOfFieldMarshal(pRecImport); // We want to merge only those field marshals that parents are marked. // Find will return false if the parent is not marked // if ( pCurTkMap->Find(tkParentImp, &pTokenRec) ) { // If the parent is duplicated, no need to move over the constant value if ( !pTokenRec->m_isDuplicate ) { IfFailGo(pMiniMdEmit->AddFieldMarshalRecord(&pRecEmit, &fmEmit)); // set the parent IfFailGo( pMiniMdEmit->PutToken( TBL_FieldMarshal, FieldMarshalRec::COL_Parent, pRecEmit, pTokenRec->m_tkTo) ); // move over the constant blob value IfFailGo(pMiniMdImport->getNativeTypeOfFieldMarshal(pRecImport, (const BYTE **)&pValue, &cbBlob)); IfFailGo( pMiniMdEmit->PutBlob(TBL_FieldMarshal, FieldMarshalRec::COL_NativeType, pRecEmit, pValue, cbBlob) ); IfFailGo( pMiniMdEmit->AddFieldMarshalToHash(fmEmit) ); } else { // <TODO>@FUTURE: more verification on the duplicate??</TODO> } } #if _DEBUG else { typeParent = TypeFromToken(tkParentImp); if (typeParent == mdtFieldDef) { // FieldDefs should not be marked if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(tkParentImp) == false) continue; } else { _ASSERTE(typeParent == mdtParamDef); // ParamDefs should not be marked if ( pMiniMdImport->GetFilterTable()->IsParamMarked(tkParentImp) == false) continue; } // If we come to here, that is we have a FieldMarshal whose parent is marked and we don't find it // in the map!!! // either bad lookup map or bad metadata _ASSERTE(!"Ignore this assert if you have seen error reported earlier. Otherwise, it is bad state!"); } #endif // _DEBUG } // Note that we don't need to record the token movement since FieldMarshal is not a valid token kind. } ErrExit: return hr; } // HRESULT NEWMERGER::MergeFieldMarshals() //***************************************************************************** // Merge class layout information //***************************************************************************** HRESULT NEWMERGER::MergeClassLayouts() { HRESULT hr = NOERROR; ClassLayoutRec *pRecImport = NULL; ClassLayoutRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; ULONG iRecord; // class layout is not a token mdToken tkParentImp; TOKENREC *pTokenRec; RID ridClassLayout; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountClassLayouts(); // loop through all TypeRef for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetClassLayoutRecord(i, &pRecImport)); tkParentImp = pMiniMdImport->getParentOfClassLayout(pRecImport); // only merge those TypeDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsTypeDefMarked(tkParentImp) == false) continue; if ( pCurTkMap->Find(tkParentImp, &pTokenRec) ) { if ( !pTokenRec->m_isDuplicate ) { // If the parent is not duplicated, just copy over the classlayout information IfFailGo(pMiniMdEmit->AddClassLayoutRecord(&pRecEmit, &iRecord)); // copy over the fix part information pRecEmit->Copy(pRecImport); IfFailGo( pMiniMdEmit->PutToken(TBL_ClassLayout, ClassLayoutRec::COL_Parent, pRecEmit, pTokenRec->m_tkTo)); IfFailGo( pMiniMdEmit->AddClassLayoutToHash(iRecord) ); } else { IfFailGo(pMiniMdEmit->FindClassLayoutHelper(pTokenRec->m_tkTo, &ridClassLayout)); if (InvalidRid(ridClassLayout)) { // class is duplicated but not class layout info CheckContinuableErrorEx(META_E_CLASS_LAYOUT_INCONSISTENT, pImportData, tkParentImp); } else { IfFailGo(pMiniMdEmit->GetClassLayoutRecord(RidFromToken(ridClassLayout), &pRecEmit)); if (pMiniMdImport->getPackingSizeOfClassLayout(pRecImport) != pMiniMdEmit->getPackingSizeOfClassLayout(pRecEmit) || pMiniMdImport->getClassSizeOfClassLayout(pRecImport) != pMiniMdEmit->getClassSizeOfClassLayout(pRecEmit) ) { CheckContinuableErrorEx(META_E_CLASS_LAYOUT_INCONSISTENT, pImportData, tkParentImp); } } } } else { // bad lookup map _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } // no need to record the index movement. Classlayout is not a token. } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeClassLayouts() //***************************************************************************** // Merge field layout information //***************************************************************************** HRESULT NEWMERGER::MergeFieldLayouts() { HRESULT hr = NOERROR; FieldLayoutRec *pRecImport = NULL; FieldLayoutRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; ULONG iRecord; // field layout2 is not a token. mdToken tkFieldImp; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountFieldLayouts(); // loop through all FieldLayout records. for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetFieldLayoutRecord(i, &pRecImport)); tkFieldImp = pMiniMdImport->getFieldOfFieldLayout(pRecImport); // only merge those FieldDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(tkFieldImp) == false) continue; if ( pCurTkMap->Find(tkFieldImp, &pTokenRec) ) { if ( !pTokenRec->m_isDuplicate ) { // If the Field is not duplicated, just copy over the FieldLayout information IfFailGo(pMiniMdEmit->AddFieldLayoutRecord(&pRecEmit, &iRecord)); // copy over the fix part information pRecEmit->Copy(pRecImport); IfFailGo( pMiniMdEmit->PutToken(TBL_FieldLayout, FieldLayoutRec::COL_Field, pRecEmit, pTokenRec->m_tkTo)); IfFailGo( pMiniMdEmit->AddFieldLayoutToHash(iRecord) ); } else { // <TODO>@FUTURE: more verification??</TODO> } } else { // bad lookup map _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } // no need to record the index movement. fieldlayout2 is not a token. } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeFieldLayouts() //***************************************************************************** // Merge field RVAs //***************************************************************************** HRESULT NEWMERGER::MergeFieldRVAs() { HRESULT hr = NOERROR; FieldRVARec *pRecImport = NULL; FieldRVARec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; ULONG iRecord; // FieldRVA is not a token. mdToken tkFieldImp; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountFieldRVAs(); // loop through all FieldRVA records. for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetFieldRVARecord(i, &pRecImport)); tkFieldImp = pMiniMdImport->getFieldOfFieldRVA(pRecImport); // only merge those FieldDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsFieldMarked(TokenFromRid(tkFieldImp, mdtFieldDef)) == false) continue; if ( pCurTkMap->Find(tkFieldImp, &pTokenRec) ) { if ( !pTokenRec->m_isDuplicate ) { // If the Field is not duplicated, just copy over the FieldRVA information IfFailGo(pMiniMdEmit->AddFieldRVARecord(&pRecEmit, &iRecord)); // copy over the fix part information pRecEmit->Copy(pRecImport); IfFailGo( pMiniMdEmit->PutToken(TBL_FieldRVA, FieldRVARec::COL_Field, pRecEmit, pTokenRec->m_tkTo)); IfFailGo( pMiniMdEmit->AddFieldRVAToHash(iRecord) ); } else { // <TODO>@FUTURE: more verification??</TODO> } } else { // bad lookup map _ASSERTE( !"bad state!"); IfFailGo( META_E_BADMETADATA ); } // no need to record the index movement. FieldRVA is not a token. } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeFieldRVAs() //***************************************************************************** // Merge MethodImpl information //***************************************************************************** HRESULT NEWMERGER::MergeMethodImpls() { HRESULT hr = NOERROR; MethodImplRec *pRecImport = NULL; MethodImplRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; RID iRecord; mdTypeDef tkClassImp; mdToken tkBodyImp; mdToken tkDeclImp; TOKENREC *pTokenRecClass; mdToken tkBodyEmit; mdToken tkDeclEmit; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountMethodImpls(); // loop through all the MethodImpls. for (i = 1; i <= iCount; i++) { // only merge those MethodImpls that are marked. if ( pMiniMdImport->GetFilterTable()->IsMethodImplMarked(i) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetMethodImplRecord(i, &pRecImport)); tkClassImp = pMiniMdImport->getClassOfMethodImpl(pRecImport); tkBodyImp = pMiniMdImport->getMethodBodyOfMethodImpl(pRecImport); tkDeclImp = pMiniMdImport->getMethodDeclarationOfMethodImpl(pRecImport); if ( pCurTkMap->Find(tkClassImp, &pTokenRecClass)) { // If the TypeDef is duplicated, no need to move over the MethodImpl record. if ( !pTokenRecClass->m_isDuplicate ) { // Create a new record and set the data. // <TODO>@FUTURE: We might want to consider changing the error for the remap into a continuable error. // Because we probably can continue merging for more data...</TODO> IfFailGo( pCurTkMap->Remap(tkBodyImp, &tkBodyEmit) ); IfFailGo( pCurTkMap->Remap(tkDeclImp, &tkDeclEmit) ); IfFailGo(pMiniMdEmit->AddMethodImplRecord(&pRecEmit, &iRecord)); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodImpl, MethodImplRec::COL_Class, pRecEmit, pTokenRecClass->m_tkTo) ); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodImpl, MethodImplRec::COL_MethodBody, pRecEmit, tkBodyEmit) ); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodImpl, MethodImplRec::COL_MethodDeclaration, pRecEmit, tkDeclEmit) ); IfFailGo( pMiniMdEmit->AddMethodImplToHash(iRecord) ); } else { // <TODO>@FUTURE: more verification on the duplicate??</TODO> } // No need to record the token movement, MethodImpl is not a token. } else { // either bad lookup map or bad metadata _ASSERTE(!"bad state"); IfFailGo( META_E_BADMETADATA ); } } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeMethodImpls() //***************************************************************************** // Merge PInvoke //***************************************************************************** HRESULT NEWMERGER::MergePinvoke() { HRESULT hr = NOERROR; ImplMapRec *pRecImport = NULL; ImplMapRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdModuleRef mrImp; mdModuleRef mrEmit; mdMethodDef mdImp; RID mdImplMap; TOKENREC *pTokenRecMR; TOKENREC *pTokenRecMD; USHORT usMappingFlags; LPCUTF8 szImportName; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountImplMaps(); // loop through all ImplMaps for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetImplMapRecord(i, &pRecImport)); // Get the MethodDef token in the new space. mdImp = pMiniMdImport->getMemberForwardedOfImplMap(pRecImport); // only merge those MethodDefs that are marked if ( pMiniMdImport->GetFilterTable()->IsMethodMarked(mdImp) == false) continue; // Get the ModuleRef token in the new space. mrImp = pMiniMdImport->getImportScopeOfImplMap(pRecImport); // map the token to the new scope if (pCurTkMap->Find(mrImp, &pTokenRecMR) == false) { // This should never fire unless the module refs weren't merged // before this code ran. _ASSERTE(!"Parent ModuleRef not found in MERGER::MergePinvoke. Bad state!"); IfFailGo( META_E_BADMETADATA ); } // If the ModuleRef has been remapped to the "module token", we need to undo that // for the pinvokeimpl. A pinvoke can only have a ModuleRef for the ImportScope. mrEmit = pTokenRecMR->m_tkTo; if (mrEmit == MODULEDEFTOKEN) { // Yes, the ModuleRef has been remapped to the module token. So, // find the ModuleRef in the output scope; if it is not found, add // it. ModuleRefRec *pModRefImport; LPCUTF8 szNameImp; IfFailGo(pMiniMdImport->GetModuleRefRecord(RidFromToken(mrImp), &pModRefImport)); IfFailGo(pMiniMdImport->getNameOfModuleRef(pModRefImport, &szNameImp)); // does this ModuleRef already exist in the emit scope? hr = ImportHelper::FindModuleRef(pMiniMdEmit, szNameImp, &mrEmit); if (hr == CLDB_E_RECORD_NOTFOUND) { // No, it doesn't. Copy it over. ModuleRefRec *pModRefEmit; IfFailGo(pMiniMdEmit->AddModuleRefRecord(&pModRefEmit, (RID*)&mrEmit)); mrEmit = TokenFromRid(mrEmit, mdtModuleRef); // Set ModuleRef Name. IfFailGo( pMiniMdEmit->PutString(TBL_ModuleRef, ModuleRefRec::COL_Name, pModRefEmit, szNameImp) ); } else IfFailGo(hr); } if (pCurTkMap->Find(mdImp, &pTokenRecMD) == false) { // This should never fire unless the method defs weren't merged // before this code ran. _ASSERTE(!"Parent MethodDef not found in MERGER::MergePinvoke. Bad state!"); IfFailGo( META_E_BADMETADATA ); } // Get copy of rest of data. usMappingFlags = pMiniMdImport->getMappingFlagsOfImplMap(pRecImport); IfFailGo(pMiniMdImport->getImportNameOfImplMap(pRecImport, &szImportName)); // If the method associated with PInvokeMap is not duplicated, then don't bother to look up the // duplicated PInvokeMap information. if (pTokenRecMD->m_isDuplicate == true) { // Does the correct ImplMap entry exist in the emit scope? IfFailGo(pMiniMdEmit->FindImplMapHelper(pTokenRecMD->m_tkTo, &mdImplMap)); } else { mdImplMap = mdTokenNil; } if (!InvalidRid(mdImplMap)) { // Verify that the rest of the data is identical, else it's an error. IfFailGo(pMiniMdEmit->GetImplMapRecord(mdImplMap, &pRecEmit)); _ASSERTE(pMiniMdEmit->getMemberForwardedOfImplMap(pRecEmit) == pTokenRecMD->m_tkTo); LPCSTR szImplMapImportName; IfFailGo(pMiniMdEmit->getImportNameOfImplMap(pRecEmit, &szImplMapImportName)); if (pMiniMdEmit->getImportScopeOfImplMap(pRecEmit) != mrEmit || pMiniMdEmit->getMappingFlagsOfImplMap(pRecEmit) != usMappingFlags || strcmp(szImplMapImportName, szImportName)) { // Mismatched p-invoke entries are found. _ASSERTE(!"Mismatched P-invoke entries during merge. Bad State!"); IfFailGo(E_FAIL); } } else { IfFailGo(pMiniMdEmit->AddImplMapRecord(&pRecEmit, &mdImplMap)); // Copy rest of data. IfFailGo( pMiniMdEmit->PutToken(TBL_ImplMap, ImplMapRec::COL_MemberForwarded, pRecEmit, pTokenRecMD->m_tkTo) ); IfFailGo( pMiniMdEmit->PutToken(TBL_ImplMap, ImplMapRec::COL_ImportScope, pRecEmit, mrEmit) ); IfFailGo( pMiniMdEmit->PutString(TBL_ImplMap, ImplMapRec::COL_ImportName, pRecEmit, szImportName) ); pRecEmit->SetMappingFlags(usMappingFlags); IfFailGo( pMiniMdEmit->AddImplMapToHash(mdImplMap) ); } } } ErrExit: return hr; } // HRESULT NEWMERGER::MergePinvoke() //***************************************************************************** // Merge StandAloneSigs //***************************************************************************** HRESULT NEWMERGER::MergeStandAloneSigs() { HRESULT hr = NOERROR; StandAloneSigRec *pRecImport = NULL; StandAloneSigRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; TOKENREC *pTokenRec; mdSignature saImp; mdSignature saEmit; bool fDuplicate; PCCOR_SIGNATURE pbSig; ULONG cbSig; ULONG cbEmit; CQuickBytes qbSig; PCOR_SIGNATURE rgSig; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountStandAloneSigs(); // loop through all Signatures for (i = 1; i <= iCount; i++) { // only merge those Signatures that are marked if ( pMiniMdImport->GetFilterTable()->IsSignatureMarked(TokenFromRid(i, mdtSignature)) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetStandAloneSigRecord(i, &pRecImport)); IfFailGo(pMiniMdImport->getSignatureOfStandAloneSig(pRecImport, &pbSig, &cbSig)); // This is a signature containing the return type after count of args // convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Assembly import scope info. pMiniMdImport, // The scope to merge into the emit scope. pbSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit rgSig = ( PCOR_SIGNATURE ) qbSig.Ptr(); hr = ImportHelper::FindStandAloneSig( pMiniMdEmit, rgSig, cbEmit, &saEmit ); if ( hr == S_OK ) { // find a duplicate fDuplicate = true; } else { // copy over fDuplicate = false; IfFailGo(pMiniMdEmit->AddStandAloneSigRecord(&pRecEmit, (ULONG *)&saEmit)); saEmit = TokenFromRid(saEmit, mdtSignature); IfFailGo( pMiniMdEmit->PutBlob(TBL_StandAloneSig, StandAloneSigRec::COL_Signature, pRecEmit, rgSig, cbEmit)); } saImp = TokenFromRid(i, mdtSignature); // Record the token movement IfFailGo( pCurTkMap->InsertNotFound(saImp, fDuplicate, saEmit, &pTokenRec) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeStandAloneSigs() //***************************************************************************** // Merge MethodSpecs //***************************************************************************** HRESULT NEWMERGER::MergeMethodSpecs() { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdToken tk; ULONG iRecord; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; // Loop through all MethodSpec iCount = pMiniMdImport->getCountMethodSpecs(); for (i=1; i<=iCount; ++i) { MethodSpecRec *pRecImport; MethodSpecRec *pRecEmit; TOKENREC *pTokenRecMethod; TOKENREC *pTokenRecMethodNew; PCCOR_SIGNATURE pvSig; ULONG cbSig; CQuickBytes qbSig; ULONG cbEmit; // Only copy marked records. if (!pMiniMdImport->GetFilterTable()->IsMethodSpecMarked(i)) continue; IfFailGo(pMiniMdImport->GetMethodSpecRecord(i, &pRecImport)); tk = pMiniMdImport->getMethodOfMethodSpec(pRecImport); // Map the token to the new scope. if (pCurTkMap->Find(tk, &pTokenRecMethod) == false) { // This should never fire unless the TypeDefs/Refs weren't merged // before this code runs. _ASSERTE(!"MethodSpec method not found in MERGER::MergeGenericsInfo. Bad state!"); IfFailGo( META_E_BADMETADATA ); } // Copy to output scope. IfFailGo(pMiniMdEmit->AddMethodSpecRecord(&pRecEmit, &iRecord)); IfFailGo( pMiniMdEmit->PutToken(TBL_MethodSpec, MethodSpecRec::COL_Method, pRecEmit, pTokenRecMethod->m_tkTo)); // Copy the signature, translating any embedded tokens. IfFailGo(pMiniMdImport->getInstantiationOfMethodSpec(pRecImport, &pvSig, &cbSig)); // ...convert rid contained in signature to new scope IfFailGo(ImportHelper::MergeUpdateTokenInSig( NULL, // Assembly emit scope. pMiniMdEmit, // The emit scope. NULL, NULL, 0, // Import assembly scope information. pMiniMdImport, // The scope to merge into the emit scope. pvSig, // signature from the imported scope pCurTkMap, // Internal token mapping structure. &qbSig, // [OUT] translated signature 0, // start from first byte of the signature 0, // don't care how many bytes consumed &cbEmit)); // number of bytes write to cbEmit // ...persist the converted signature IfFailGo( pMiniMdEmit->PutBlob(TBL_MethodSpec, MethodSpecRec::COL_Instantiation, pRecEmit, qbSig.Ptr(), cbEmit) ); IfFailGo( pCurTkMap->InsertNotFound(TokenFromRid(i, mdtMethodSpec), false, TokenFromRid(iRecord, mdtMethodSpec), &pTokenRecMethodNew) ); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeMethodSpecs() //***************************************************************************** // Merge DeclSecuritys //***************************************************************************** HRESULT NEWMERGER::MergeDeclSecuritys() { HRESULT hr = NOERROR; DeclSecurityRec *pRecImport = NULL; DeclSecurityRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdToken tkParentImp; TOKENREC *pTokenRec; void const *pValue; ULONG cbBlob; mdPermission pmImp; mdPermission pmEmit; bool fDuplicate; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountDeclSecuritys(); // loop through all DeclSecurity for (i = 1; i <= iCount; i++) { // only merge those DeclSecurities that are marked if ( pMiniMdImport->GetFilterTable()->IsDeclSecurityMarked(TokenFromRid(i, mdtPermission)) == false) continue; // compare it with the emit scope IfFailGo(pMiniMdImport->GetDeclSecurityRecord(i, &pRecImport)); tkParentImp = pMiniMdImport->getParentOfDeclSecurity(pRecImport); if ( pCurTkMap->Find(tkParentImp, &pTokenRec) ) { if ( !pTokenRec->m_isDuplicate ) { // If the parent is not duplicated, just copy over the custom value goto CopyPermission; } else { // Try to see if the Permission is there in the emit scope or not. // If not, move it over still if ( ImportHelper::FindPermission( pMiniMdEmit, pTokenRec->m_tkTo, pRecImport->GetAction(), &pmEmit) == S_OK ) { // found a match // <TODO>@FUTURE: more verification??</TODO> fDuplicate = true; } else { // Parent is duplicated but the Permission is not. Still copy over the // Permission. CopyPermission: fDuplicate = false; IfFailGo(pMiniMdEmit->AddDeclSecurityRecord(&pRecEmit, (ULONG *)&pmEmit)); pmEmit = TokenFromRid(pmEmit, mdtPermission); pRecEmit->Copy(pRecImport); // set the parent IfFailGo( pMiniMdEmit->PutToken( TBL_DeclSecurity, DeclSecurityRec::COL_Parent, pRecEmit, pTokenRec->m_tkTo) ); // move over the CustomAttribute blob value IfFailGo(pMiniMdImport->getPermissionSetOfDeclSecurity(pRecImport, (const BYTE **)&pValue, &cbBlob)); IfFailGo(pMiniMdEmit->PutBlob( TBL_DeclSecurity, DeclSecurityRec::COL_PermissionSet, pRecEmit, pValue, cbBlob)); } } pmEmit = TokenFromRid(pmEmit, mdtPermission); pmImp = TokenFromRid(i, mdtPermission); // Record the token movement IfFailGo( pCurTkMap->InsertNotFound(pmImp, fDuplicate, pmEmit, &pTokenRec) ); } else { // bad lookup map _ASSERTE(!"bad state"); IfFailGo( META_E_BADMETADATA ); } } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeDeclSecuritys() //***************************************************************************** // Merge Strings //***************************************************************************** HRESULT NEWMERGER::MergeStrings() { HRESULT hr = NOERROR; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; for (UINT32 nIndex = 0; ;) { MetaData::DataBlob userString; UINT32 nNextIndex; UINT32 nEmitIndex; hr = pMiniMdImport->GetUserStringAndNextIndex( nIndex, &userString, &nNextIndex); IfFailGo(hr); if (hr == S_FALSE) { // We reached the last user string hr = S_OK; break; } _ASSERTE(hr == S_OK); // Skip empty strings if (userString.IsEmpty()) { nIndex = nNextIndex; continue; } if (pMiniMdImport->GetFilterTable()->IsUserStringMarked(TokenFromRid(nIndex, mdtString)) == false) { // Process next user string in the heap nIndex = nNextIndex; continue; } IfFailGo(pMiniMdEmit->PutUserString( userString, &nEmitIndex)); IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(nIndex, mdtString), false, TokenFromRid(nEmitIndex, mdtString), &pTokenRec)); // Process next user string in the heap nIndex = nNextIndex; } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeStrings() // Helper method to merge the module-level security critical attributes // Strips all module-level security critical attribute [that won't be ultimately needed] // Returns: // FAILED(hr): Failure occurred retrieving metadata or parsing scopes // S_OK: Attribute should be merged into final output scope // S_FALSE: Attribute should be ignored/dropped from output scope HRESULT NEWMERGER::MergeSecurityCriticalModuleLevelAttributes( MergeImportData* pImportData, // import scope mdToken tkParentImp, // parent token with attribute TOKENREC* pTypeRec, // token record of attribute ctor mdToken mrSecurityTreatAsSafeAttributeCtor, // 'generic' TAS attribute token mdToken mrSecurityTransparentAttributeCtor, // 'generic' Transparent attribute token mdToken mrSecurityCriticalExplicitAttributeCtor, // 'generic' Critical attribute token mdToken mrSecurityCriticalEverythingAttributeCtor) { HRESULT hr = S_OK; // if ANY assembly-level critical attributes were specified, then we'll output // one assembly-level Critical(Explicit) attribute only // AND if this scope has tags if (ISSCS_Unknown != pImportData->m_isscsSecurityCriticalStatus) { _ASSERTE(ISSCS_Unknown != m_isscsSecurityCritical); // drop only assembly-level attributes TypeRefRec* pTypeRefRec; // metadata emitter CMiniMdRW* pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // if compiler is generating a module - then this will be a module token LPCSTR szTypeRefName; if (tkParentImp == MODULEDEFTOKEN || // otherwise, if merging assemblies, we have a fake type ref called MODULE_CA_LOCATION (TypeFromToken(tkParentImp) == mdtTypeRef && (IsAttributeFromNamespace(pMiniMdImport, tkParentImp, COR_COMPILERSERVICE_NAMESPACE, COR_MSCORLIB_NAME, &pTypeRefRec) == S_OK) && (pMiniMdImport->getNameOfTypeRef(pTypeRefRec, &szTypeRefName) == S_OK) && (strcmp(MODULE_CA_TYPENAME, szTypeRefName) == 0))) { // drop the TAS attribute (unless all scopes have TAS) if ( pTypeRec->m_tkTo == mrSecurityTreatAsSafeAttributeCtor ) { if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityTreatAsSafe) == ISSCS_SecurityTreatAsSafe) { _ASSERTE((pImportData->m_isscsSecurityCriticalStatus & ISSCS_SecurityTreatAsSafe) == ISSCS_SecurityTreatAsSafe); return S_OK; } return S_FALSE; } // drop the Transparent attribute (unless all scopes have Transparent) else if (pTypeRec->m_tkTo == mrSecurityTransparentAttributeCtor) { if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityTransparent) == ISSCS_SecurityTransparent) { _ASSERTE((pImportData->m_isscsSecurityCriticalStatus & ISSCS_SecurityTransparent) == ISSCS_SecurityTransparent); return S_OK; } return S_FALSE; } else if (pTypeRec->m_tkTo == mrSecurityCriticalExplicitAttributeCtor) { // if NOT Critical Everything, then leave the Critical.Explicit attribute // the Critical.Explicit attribute will be used as the final global attribute if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityCriticalEverything) != ISSCS_SecurityCriticalEverything) { _ASSERTE((pImportData->m_isscsSecurityCriticalStatus & ISSCS_SecurityCriticalExplicit) == ISSCS_SecurityCriticalExplicit); return S_OK; } else { // drop this attribute return S_FALSE; } } else if (pTypeRec->m_tkTo == mrSecurityCriticalEverythingAttributeCtor) { // OPTIMIZATION: if all attributes are Critical.Everything, // then leave the global Critical attribute if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityCriticalEverything) == ISSCS_SecurityCriticalEverything) { _ASSERTE((pImportData->m_isscsSecurityCriticalStatus & ISSCS_SecurityCriticalEverything) == ISSCS_SecurityCriticalEverything); return S_OK; } else { // drop this attribute return S_FALSE; } } } } return hr; } // NEWMERGER::MergeSecurityCriticalModuleLevelAttributes // HELPER: Retrieve the meta-data info related to SecurityCritical HRESULT NEWMERGER::RetrieveStandardSecurityCriticalMetaData( mdAssemblyRef& tkMscorlib, mdTypeRef& securityEnum, BYTE*& rgSigBytesSecurityCriticalEverythingCtor, DWORD& dwSigEverythingSize, BYTE*& rgSigBytesSecurityCriticalExplicitCtor, DWORD& dwSigExplicitSize) { HRESULT hr = S_OK; CMiniMdRW* emit = GetMiniMdEmit(); // get typeref for mscorlib BYTE pbMscorlibToken[] = COR_MSCORLIB_TYPEREF; BYTE* pCurr = rgSigBytesSecurityCriticalEverythingCtor; IfFailGo(ImportHelper::FindAssemblyRef(emit, COR_MSCORLIB_NAME, NULL, pbMscorlibToken, sizeof(pbMscorlibToken), asm_rmj, asm_rmm, asm_rup, asm_rpt, 0, &tkMscorlib)); IfFailGo(m_pRegMetaEmit->DefineTypeRefByName(tkMscorlib, COR_SECURITYCRITICALSCOPE_ENUM_W, &securityEnum)); // build the constructor sig that takes SecurityCriticalScope argument if (rgSigBytesSecurityCriticalEverythingCtor) { *pCurr++ = IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS; *pCurr++ = COR_SECURITYCRITICAL_CTOR_ARGCOUNT_SCOPE_EVERYTHING; // one argument to constructor *pCurr++ = ELEMENT_TYPE_VOID; *pCurr++ = ELEMENT_TYPE_VALUETYPE; pCurr += CorSigCompressToken(securityEnum, pCurr); dwSigEverythingSize = (DWORD)(pCurr - rgSigBytesSecurityCriticalEverythingCtor); _ASSERTE(dwSigEverythingSize <= COR_SECURITYCRITICAL_CTOR_SCOPE_SIG_MAX_SIZE); } // if Explicit ctor is requested if (rgSigBytesSecurityCriticalExplicitCtor) { // build the constructor sig that has NO arguments pCurr = rgSigBytesSecurityCriticalExplicitCtor; *pCurr++ = IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS; *pCurr++ = COR_SECURITYCRITICAL_CTOR_ARGCOUNT_NO_SCOPE; // no arguments to constructor *pCurr++ = ELEMENT_TYPE_VOID; dwSigExplicitSize = (DWORD)(pCurr - rgSigBytesSecurityCriticalExplicitCtor); _ASSERTE(dwSigExplicitSize <= COR_SECURITYCRITICAL_CTOR_NO_SCOPE_SIG_MAX_SIZE); } ErrExit: return hr; } // NEWMERGER::RetrieveStandardSecurityCriticalMetaData //***************************************************************************** // Merge CustomAttributes //***************************************************************************** HRESULT NEWMERGER::MergeCustomAttributes() { HRESULT hr = NOERROR; CustomAttributeRec *pRecImport = NULL; CustomAttributeRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; ULONG iCount; ULONG i; mdToken tkParentImp; // Token of attributed object (parent). TOKENREC *pTokenRec; // Parent's remap. mdToken tkType; // Token of attribute's type. TOKENREC *pTypeRec; // Type's remap. void const *pValue; // The actual value. ULONG cbBlob; // Size of the value. mdToken cvImp; mdToken cvEmit; bool fDuplicate; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; TypeRefRec *pTypeRefRec; ULONG cTypeRefRecs; mdToken mrSuppressMergeCheckAttributeCtor = mdTokenNil; mdToken mrSecurityCriticalExplicitAttributeCtor = mdTokenNil; mdToken mrSecurityCriticalEverythingAttributeCtor = mdTokenNil; mdToken mrSecurityTransparentAttributeCtor = mdTokenNil; mdToken mrSecurityTreatAsSafeAttributeCtor = mdTokenNil; pMiniMdEmit = GetMiniMdEmit(); // Find out the TypeRef referring to our library's System.CompilerServices.SuppressMergeCheckAttribute, // System.Security.SecurityCriticalAttribute, System.Security.SecurityTransparentAttribute, and // System.Security.SecurityTreatAsSafeAttibute cTypeRefRecs = pMiniMdEmit->getCountTypeRefs(); { // retrieve global attribute TypeRefs mdAssemblyRef tkMscorlib = mdTokenNil; mdTypeRef securityEnum = mdTokenNil; NewArrayHolder<BYTE> rgSigBytesSecurityCriticalEverythingCtor(new (nothrow)BYTE[COR_SECURITYCRITICAL_CTOR_SCOPE_SIG_MAX_SIZE]); BYTE* pSigBytesSecurityCriticalEverythingCtor = rgSigBytesSecurityCriticalEverythingCtor.GetValue(); IfFailGo((pSigBytesSecurityCriticalEverythingCtor == NULL)?E_OUTOFMEMORY:S_OK); DWORD dwSigEverythingSize = 0; NewArrayHolder<BYTE> rgSigBytesSecurityCriticalExplicitCtor(new (nothrow)BYTE[COR_SECURITYCRITICAL_CTOR_NO_SCOPE_SIG_MAX_SIZE]); BYTE* pSigBytesSecurityCriticalExplicitCtor = rgSigBytesSecurityCriticalExplicitCtor.GetValue(); IfFailGo((pSigBytesSecurityCriticalExplicitCtor == NULL)?E_OUTOFMEMORY:S_OK); DWORD dwSigExplicitSize = 0; // retrieve security critical metadata info if necessary if(ISSCS_Unknown != m_isscsSecurityCritical) { hr = RetrieveStandardSecurityCriticalMetaData( tkMscorlib, securityEnum, pSigBytesSecurityCriticalEverythingCtor, dwSigEverythingSize, pSigBytesSecurityCriticalExplicitCtor, dwSigExplicitSize); } // Search for the TypeRef. for (i = 1; i <= cTypeRefRecs; i++) { mdToken tkTmp = TokenFromRid(i,mdtTypeRef); if (IsAttributeFromNamespace(pMiniMdEmit, tkTmp, COR_COMPILERSERVICE_NAMESPACE, COR_MSCORLIB_NAME, &pTypeRefRec) == S_OK) { LPCSTR szNameOfTypeRef; IfFailGo(pMiniMdEmit->getNameOfTypeRef(pTypeRefRec, &szNameOfTypeRef)); if (strcmp(szNameOfTypeRef, COR_SUPPRESS_MERGE_CHECK_ATTRIBUTE) == 0) { hr = ImportHelper::FindMemberRef( pMiniMdEmit, tkTmp, COR_CTOR_METHOD_NAME, NULL, 0, &mrSuppressMergeCheckAttributeCtor); if (S_OK == hr) continue; } } else // if we are merging security critical attributes, then look for transparent-related attributes if ((ISSCS_Unknown != m_isscsSecurityCritical) && (IsAttributeFromNamespace(pMiniMdEmit, tkTmp, COR_SECURITYCRITICAL_ATTRIBUTE_NAMESPACE, COR_MSCORLIB_NAME, &pTypeRefRec) == S_OK)) { LPCSTR szNameOfTypeRef; IfFailGo(pMiniMdEmit->getNameOfTypeRef(pTypeRefRec, &szNameOfTypeRef)); // look for the SecurityCritical attribute if (strcmp(szNameOfTypeRef, COR_SECURITYCRITICAL_ATTRIBUTE) == 0) { // since the SecurityCritical attribute can be either // parameterless constructor or SecurityCriticalScope constructor, we // look for both hr = ImportHelper::FindMemberRef( pMiniMdEmit, tkTmp, COR_CTOR_METHOD_NAME, rgSigBytesSecurityCriticalEverythingCtor.GetValue(), dwSigEverythingSize, &mrSecurityCriticalEverythingAttributeCtor); if (S_OK == hr) continue; hr = ImportHelper::FindMemberRef( pMiniMdEmit, tkTmp, COR_CTOR_METHOD_NAME, rgSigBytesSecurityCriticalExplicitCtor.GetValue(), dwSigExplicitSize, &mrSecurityCriticalExplicitAttributeCtor); if (S_OK == hr) continue; } else // look for the SecurityTransparent attribute if (strcmp(szNameOfTypeRef, COR_SECURITYTRANSPARENT_ATTRIBUTE) == 0) { hr = ImportHelper::FindMemberRef( pMiniMdEmit, tkTmp, COR_CTOR_METHOD_NAME, NULL, 0, &mrSecurityTransparentAttributeCtor); if (S_OK == hr) continue; } else // look for the SecurityTreatAsSafe attribute if (strcmp(szNameOfTypeRef, COR_SECURITYTREATASSAFE_ATTRIBUTE) == 0) { hr = ImportHelper::FindMemberRef( pMiniMdEmit, tkTmp, COR_CTOR_METHOD_NAME, NULL, 0, &mrSecurityTreatAsSafeAttributeCtor); if (S_OK == hr) continue; } } hr = S_OK; // ignore failures since the attribute may not be used } } // Loop over every module scope for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // We know that the filter table is not null here. Tell PREFIX that we know it. PREFIX_ASSUME( pMiniMdImport->GetFilterTable() != NULL ); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountCustomAttributes(); // loop through all CustomAttribute for (i = 1; i <= iCount; i++) { // compare it with the emit scope IfFailGo(pMiniMdImport->GetCustomAttributeRecord(i, &pRecImport)); tkParentImp = pMiniMdImport->getParentOfCustomAttribute(pRecImport); tkType = pMiniMdImport->getTypeOfCustomAttribute(pRecImport); IfFailGo(pMiniMdImport->getValueOfCustomAttribute(pRecImport, (const BYTE **)&pValue, &cbBlob)); // only merge those CustomAttributes that are marked if ( pMiniMdImport->GetFilterTable()->IsCustomAttributeMarked(TokenFromRid(i, mdtCustomAttribute)) == false) continue; // Check the type of the CustomAttribute. If it is not marked, then we don't need to move over the CustomAttributes. // This will only occur for compiler defined discardable CAs during linking. // if ( pMiniMdImport->GetFilterTable()->IsTokenMarked(tkType) == false) continue; if ( pCurTkMap->Find(tkParentImp, &pTokenRec) ) { // If the From token type is different from the To token's type, we have optimized the ref to def. // In this case, we are dropping the CA associated with the Ref tokens. // if (TypeFromToken(tkParentImp) == TypeFromToken(pTokenRec->m_tkTo)) { // If tkParentImp is a MemberRef and it is also mapped to a MemberRef in the merged scope with a MethodDef // parent, then it is a MemberRef optimized to a MethodDef. We are keeping the MemberRef because it is a // vararg call. So we can drop CAs on this MemberRef. if (TypeFromToken(tkParentImp) == mdtMemberRef) { MemberRefRec *pTempRec; IfFailGo(pMiniMdEmit->GetMemberRefRecord(RidFromToken(pTokenRec->m_tkTo), &pTempRec)); if (TypeFromToken(pMiniMdEmit->getClassOfMemberRef(pTempRec)) == mdtMethodDef) continue; } if (! pCurTkMap->Find(tkType, &pTypeRec) ) { _ASSERTE(!"CustomAttribute Type not found in output scope"); IfFailGo(META_E_BADMETADATA); } // Determine if we need to copy or ignore security-critical-related attributes hr = MergeSecurityCriticalModuleLevelAttributes( pImportData, tkParentImp, pTypeRec, mrSecurityTreatAsSafeAttributeCtor, mrSecurityTransparentAttributeCtor, mrSecurityCriticalExplicitAttributeCtor, mrSecurityCriticalEverythingAttributeCtor); IfFailGo(hr); // S_FALSE means skip attribute if (hr == S_FALSE) continue; // S_OK means consider copying attribute // if it's the SuppressMergeCheckAttribute, don't copy it if ( pTypeRec->m_tkTo == mrSuppressMergeCheckAttributeCtor ) { continue; } if ( pTokenRec->m_isDuplicate) { // Try to see if the custom value is there in the emit scope or not. // If not, move it over still hr = ImportHelper::FindCustomAttributeByToken( pMiniMdEmit, pTokenRec->m_tkTo, pTypeRec->m_tkTo, pValue, cbBlob, &cvEmit); if ( hr == S_OK ) { // found a match // <TODO>@FUTURE: more verification??</TODO> fDuplicate = true; } else { TypeRefRec *pAttributeTypeRefRec; // We need to allow additive merge on TypeRef for CustomAttributes because compiler // could build module but not assembly. They are hanging of Assembly level CAs on a bogus // TypeRef. // Also allow additive merge for CAs from CompilerServices and Microsoft.VisualC if (tkParentImp == MODULEDEFTOKEN || TypeFromToken(tkParentImp) == mdtTypeRef || (IsAttributeFromNamespace(pMiniMdImport, tkType, COR_COMPILERSERVICE_NAMESPACE, COR_MSCORLIB_NAME, &pAttributeTypeRefRec) == S_OK) || (IsAttributeFromNamespace(pMiniMdImport, tkType, COR_MISCBITS_NAMESPACE, COR_MISCBITS_NAMESPACE, &pAttributeTypeRefRec) == S_OK)) { // clear the error hr = NOERROR; // custom value of module token! Copy over the custom value goto CopyCustomAttribute; } // another case to support additive merge if the CA on MehtodDef is // HandleProcessCorruptedStateExceptionsAttribute if ( TypeFromToken(tkParentImp) == mdtMethodDef && tkType == pImportData->m_tkHandleProcessCorruptedStateCtor) { // clear the error hr = NOERROR; // custom value of module token! Copy over the custom value goto CopyCustomAttribute; } CheckContinuableErrorEx(META_E_MD_INCONSISTENCY, pImportData, TokenFromRid(i, mdtCustomAttribute)); } } else { CopyCustomAttribute: if ((m_dwMergeFlags & DropMemberRefCAs) && TypeFromToken(pTokenRec->m_tkTo) == mdtMemberRef) { // CustomAttributes associated with MemberRef. If the parent of MemberRef is a MethodDef or FieldDef, drop // the custom attribute. MemberRefRec *pMemberRefRec; IfFailGo(pMiniMdEmit->GetMemberRefRecord(RidFromToken(pTokenRec->m_tkTo), &pMemberRefRec)); mdToken mrParent = pMiniMdEmit->getClassOfMemberRef(pMemberRefRec); if (TypeFromToken(mrParent) == mdtMethodDef || TypeFromToken(mrParent) == mdtFieldDef) { // Don't bother to copy over continue; } } // Parent is duplicated but the custom value is not. Still copy over the // custom value. fDuplicate = false; IfFailGo(pMiniMdEmit->AddCustomAttributeRecord(&pRecEmit, (ULONG *)&cvEmit)); cvEmit = TokenFromRid(cvEmit, mdtCustomAttribute); // set the parent IfFailGo( pMiniMdEmit->PutToken(TBL_CustomAttribute, CustomAttributeRec::COL_Parent, pRecEmit, pTokenRec->m_tkTo) ); // set the type IfFailGo( pMiniMdEmit->PutToken(TBL_CustomAttribute, CustomAttributeRec::COL_Type, pRecEmit, pTypeRec->m_tkTo)); // move over the CustomAttribute blob value IfFailGo(pMiniMdImport->getValueOfCustomAttribute(pRecImport, (const BYTE **)&pValue, &cbBlob)); IfFailGo( pMiniMdEmit->PutBlob(TBL_CustomAttribute, CustomAttributeRec::COL_Value, pRecEmit, pValue, cbBlob)); IfFailGo( pMiniMdEmit->AddCustomAttributesToHash(cvEmit) ); } cvEmit = TokenFromRid(cvEmit, mdtCustomAttribute); cvImp = TokenFromRid(i, mdtCustomAttribute); // Record the token movement IfFailGo( pCurTkMap->InsertNotFound(cvImp, pTokenRec->m_isDuplicate, cvEmit, &pTokenRec) ); } } else { // either bad lookup map or bad metadata _ASSERTE(!"Bad state"); IfFailGo( META_E_BADMETADATA ); } } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeCustomAttributes() //******************************************************************************* // Helper to check if input scope has assembly-level security transparent awareness (either SecurityTransparent or SecurityCritical) // SIDE EFFECT: pImportData->m_isscsSecurityCriticalStatus will be explicitly set [same value as return value] // SecurityCritical.Explicit attribute injection occurs for all scopes that have tags (e.g. NOT ISSCS_Unknown) // If the tagged scopes are all SecurityCritical.Everything, then the final attribute should be SecurityCritical.Everything // anyway. Otherwise, at least one SecurityCritical.Explicit tag will be used/injected //******************************************************************************* InputScopeSecurityCriticalStatus NEWMERGER::CheckInputScopeIsCritical(MergeImportData* pImportData, HRESULT& hr) { hr = S_OK; // the attribute should be in a known state no matter how we return from this function // default to no attribute explicitly specified pImportData->m_isscsSecurityCriticalStatus = ISSCS_Unknown; mdTypeRef fakeModuleTypeRef = mdTokenNil; mdAssemblyRef tkMscorlib = mdTokenNil; // TODO: Should we remove the ability to disable merging critical attributes? if (g_fRefShouldMergeCriticalChecked == FALSE) { // shouldn't require thread safety lock g_fRefShouldMergeCritical = (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_MergeCriticalAttributes) != 0); g_fRefShouldMergeCriticalChecked = TRUE; } // return no merge needed, if the merge critical attribute setting is not enabled. if (!g_fRefShouldMergeCritical) return ISSCS_Unknown; // get typeref for mscorlib BYTE pbMscorlibToken[] = COR_MSCORLIB_TYPEREF; CMiniMdRW* pImportedMiniMd = &pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd; if (S_OK != ImportHelper::FindAssemblyRef(pImportedMiniMd, COR_MSCORLIB_NAME, NULL, pbMscorlibToken, sizeof(pbMscorlibToken), asm_rmj, asm_rmm, asm_rup, asm_rpt, 0, &tkMscorlib)) { // there isn't an mscorlib ref here... we can't have the security critical attribute return ISSCS_Unknown; } if (S_OK != ImportHelper::FindTypeRefByName(pImportedMiniMd, tkMscorlib, COR_COMPILERSERVICE_NAMESPACE, MODULE_CA_TYPENAME, &fakeModuleTypeRef)) { // for now let use the fake module ref as the assembly def fakeModuleTypeRef = 0x000001; } // Check the input scope for TreatAsSafe if (S_OK == ImportHelper::GetCustomAttributeByName(pImportedMiniMd, fakeModuleTypeRef, // This is the assembly def token COR_SECURITYTREATASSAFE_ATTRIBUTE_FULL, NULL, NULL)) { pImportData->m_isscsSecurityCriticalStatus |= ISSCS_SecurityTreatAsSafe; } // Check the input scope for security transparency awareness // For example, the assembly is marked SecurityTransparent, SecurityCritical(Explicit), or SecurityCritical(Everything) const void *pbData = NULL; // [OUT] Put pointer to data here. ULONG cbData = 0; // number of bytes in pbData // Check if the SecurityTransparent attribute is present if (S_OK == ImportHelper::GetCustomAttributeByName(pImportedMiniMd, fakeModuleTypeRef, // This is the assembly def token COR_SECURITYTRANSPARENT_ATTRIBUTE_FULL, NULL, NULL)) { pImportData->m_isscsSecurityCriticalStatus |= ISSCS_SecurityTransparent; } else // Check if the SecurityCritical attribute is present if (S_OK == ImportHelper::GetCustomAttributeByName(pImportedMiniMd, fakeModuleTypeRef, // This is the assembly def token COR_SECURITYCRITICAL_ATTRIBUTE_FULL, &pbData, &cbData)) { // find out if critical everything or explicit // default to critical pImportData->m_isscsSecurityCriticalStatus = ISSCS_SecurityCritical; BYTE rgSecurityCriticalEverythingCtorValue[] = COR_SECURITYCRITICAL_ATTRIBUTE_VALUE_EVERYTHING; // if value is non-0 (i.e. 1), then mark as SecurityCritical everything, otherwise, explicit if (NULL != pbData && cbData == 8 && memcmp(rgSecurityCriticalEverythingCtorValue, pbData, cbData) == 0) { pImportData->m_isscsSecurityCriticalStatus |= ISSCS_SecurityCriticalEverything; } else { pImportData->m_isscsSecurityCriticalStatus |= ISSCS_SecurityCriticalExplicit; } } return pImportData->m_isscsSecurityCriticalStatus; } // HRESULT NEWMERGER::CheckInputScopeIsCritical() //******************************************************************************* // Helper to merge security critical annotations across assemblies and types //******************************************************************************* HRESULT NEWMERGER::MergeSecurityCriticalAttributes() { // if no assembly-level critical attributes were specified, then none are needed, // and no need to do special attribute merging if (ISSCS_Unknown == m_isscsSecurityCritical) { return S_OK; } // or if the global-scope already has TAS/Critical.Everything, then ignore individual type fixes else if ((ISSCS_SECURITYCRITICAL_LEGACY & m_isscsSecurityCriticalAllScopes) == ISSCS_SECURITYCRITICAL_LEGACY) { return S_OK; } HRESULT hr = S_OK; CMiniMdRW* emit = GetMiniMdEmit(); // The attribute we want to decorate all of the types with has not been defined. mdMemberRef tkSecurityCriticalEverythingAttribute = mdTokenNil; mdMemberRef tkSecurityTreatAsSafeAttribute = mdTokenNil; mdMemberRef tkSecuritySafeCriticalAttribute = mdTokenNil; mdAssemblyRef tkMscorlib = mdTokenNil; mdTypeRef fakeModuleTypeRef = mdTokenNil; mdTypeRef securityEnum = mdTokenNil; DWORD dwSigSize; BYTE* rgSigBytesSecurityCriticalExplicitCtor = 0; DWORD dwSigSize_TEMP; BYTE rgSigBytesTreatAsSafeCtor[] = {IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS, 0x00, ELEMENT_TYPE_VOID}; BYTE rgSecurityCriticalEverythingCtorValue[] = COR_SECURITYCRITICAL_ATTRIBUTE_VALUE_EVERYTHING; mdTypeRef tkSecurityCriticalEverythingAttributeType = mdTokenNil; mdTypeRef tkSecurityTreatAsSafeAttributeType = mdTokenNil; NewArrayHolder<BYTE> rgSigBytesSecurityCriticalEverythingCtor(new (nothrow)BYTE[COR_SECURITYCRITICAL_CTOR_SCOPE_SIG_MAX_SIZE]); BYTE* pSigBytesSecurityCriticalEverythingCtor = rgSigBytesSecurityCriticalEverythingCtor.GetValue(); IfFailGo((pSigBytesSecurityCriticalEverythingCtor == NULL)?E_OUTOFMEMORY:S_OK); IfFailGo(RetrieveStandardSecurityCriticalMetaData( tkMscorlib, securityEnum, pSigBytesSecurityCriticalEverythingCtor, dwSigSize, rgSigBytesSecurityCriticalExplicitCtor, dwSigSize_TEMP)); if (S_OK != ImportHelper::FindTypeRefByName(emit, tkMscorlib, COR_COMPILERSERVICE_NAMESPACE, MODULE_CA_TYPENAME, &fakeModuleTypeRef)) { // for now let use the fake module ref as the assembly def fakeModuleTypeRef = 0x000001; } IfFailGo(m_pRegMetaEmit->DefineTypeRefByName( tkMscorlib, COR_SECURITYCRITICAL_ATTRIBUTE_FULL_W, &tkSecurityCriticalEverythingAttributeType)); IfFailGo(m_pRegMetaEmit->DefineMemberRef(tkSecurityCriticalEverythingAttributeType, COR_CONSTRUCTOR_METADATA_IDENTIFIER, rgSigBytesSecurityCriticalEverythingCtor.GetValue(), dwSigSize, &tkSecurityCriticalEverythingAttribute)); IfFailGo(m_pRegMetaEmit->DefineTypeRefByName( tkMscorlib, COR_SECURITYTREATASSAFE_ATTRIBUTE_FULL_W, &tkSecurityTreatAsSafeAttributeType)); IfFailGo(m_pRegMetaEmit->DefineMemberRef(tkSecurityTreatAsSafeAttributeType, COR_CONSTRUCTOR_METADATA_IDENTIFIER, rgSigBytesTreatAsSafeCtor, sizeof(rgSigBytesTreatAsSafeCtor), &tkSecurityTreatAsSafeAttribute)); // place this block in a new scope so that we can safely goto past it { mdTypeRef tkSecuritySafeCriticalAttributeType = mdTokenNil; if (FAILED (hr = m_pRegMetaEmit->DefineTypeRefByName(tkMscorlib, COR_SECURITYSAFECRITICAL_ATTRIBUTE_FULL_W, &tkSecuritySafeCriticalAttributeType))) { _ASSERTE(!"Couldn't Emit a Typeref for SafeCritical attribute"); return hr; } BYTE rgSigBytesSafeCriticalCtor[] = {IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS, 0x00, ELEMENT_TYPE_VOID}; if (FAILED(hr = m_pRegMetaEmit->DefineMemberRef(tkSecuritySafeCriticalAttributeType, W(".ctor"), rgSigBytesSafeCriticalCtor, sizeof(rgSigBytesSafeCriticalCtor), &tkSecuritySafeCriticalAttribute))) { _ASSERTE(!"Couldn't Emit a MemberRef for SafeCritical attribute .ctor"); return hr; } } for (MergeImportData* pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // if the import is marked TAS, then we need to explicitly mark each type as TAS // if the import is marked Crit/Everything, then we need to explicitly mark each type as Crit // if the import is not marked at all, then we need to explicitly mark each type TAS/Crit // if the import is marked ONLY Crit/Explicit or ONLY Transparent then we can ignore it if (ISSCS_SecurityTransparent == pImportData->m_isscsSecurityCriticalStatus || ISSCS_SecurityCriticalExplicit == pImportData->m_isscsSecurityCriticalStatus) continue; // Run through the scopes that need to have their types decorated with this attribute MDTOKENMAP*pCurTKMap = pImportData->m_pMDTokenMap; BYTE rgTreatAsSafeCtorValue[] = COR_SECURITYTREATASSAFE_ATTRIBUTE_VALUE; BOOL fMarkEachTokenAsCritical = FALSE; // if the import is unmarked or marked Crit/Everything, // then we need to explicitly mark each token as Crit // Unless the the global scope already has SecurityCritical.Everything if (((ISSCS_SecurityCriticalEverything & m_isscsSecurityCriticalAllScopes) != ISSCS_SecurityCriticalEverything) && (((ISSCS_SecurityCriticalEverything & pImportData->m_isscsSecurityCriticalStatus) == ISSCS_SecurityCriticalEverything ) || // OR this scope is NOT transparent or critical-explicit (ISSCS_SecurityTransparent & pImportData->m_isscsSecurityCriticalStatus) == 0 || (ISSCS_SecurityCritical & pImportData->m_isscsSecurityCriticalStatus) == 0 || // OR this scope is UNKNOWN (ISSCS_Unknown == (ISSCS_SECURITYCRITICAL_FLAGS & pImportData->m_isscsSecurityCriticalStatus)))) { fMarkEachTokenAsCritical = TRUE; } BOOL fMarkEachTokenAsSafe = FALSE; // if the import is unmarked or marked TAS, // then we need to explicitly mark each token as TAS // Unless the the global scope already has SecurityTreatAsSafe if (((ISSCS_SecurityTreatAsSafe & m_isscsSecurityCriticalAllScopes) != ISSCS_SecurityTreatAsSafe) && ((ISSCS_SecurityTreatAsSafe & pImportData->m_isscsSecurityCriticalStatus) || ISSCS_Unknown == (pImportData->m_isscsSecurityCriticalStatus & ISSCS_SECURITYCRITICAL_FLAGS))) { fMarkEachTokenAsSafe = TRUE; } BYTE rgSafeCriticalCtorValue[] = {0x01, 0x00, 0x00 ,0x00}; for (int i = 0; i < pCurTKMap->Count(); i++) { TOKENREC* pRec = pCurTKMap->Get(i); BOOL fInjectSecurityAttributes = FALSE; // skip empty records if (pRec->IsEmpty()) continue; // If this scope contained a typeref that was resolved to a typedef, let's not mark it. We'll let the owner // of the actual typedef decide if that type should be marked. if ((TypeFromToken(pRec->m_tkFrom) == mdtTypeRef) && (TypeFromToken(pRec->m_tkTo) == mdtTypeDef)) continue; // Same for method refs/method defs if ((TypeFromToken(pRec->m_tkFrom) == mdtMemberRef) && (TypeFromToken(pRec->m_tkTo) == mdtMethodDef)) continue; // check for typedefs, but don't put this on the global typedef if ((TypeFromToken(pRec->m_tkTo) == mdtTypeDef) && (pRec->m_tkTo != TokenFromRid(1, mdtTypeDef))) { // by default we will inject fInjectSecurityAttributes = TRUE; // except for Enums DWORD dwClassAttrs = 0; mdTypeRef crExtends = mdTokenNil; if (FAILED(hr = m_pRegMetaEmit->GetTypeDefProps(pRec->m_tkTo, NULL, NULL, 0 , &dwClassAttrs, &crExtends))) { // TODO: should we fail ?? } // check for Enum types if (!IsNilToken(crExtends) && (TypeFromToken(crExtends)==mdtTypeRef)) { // get the namespace and the name for this token CMiniMdRW *pMiniMd = GetMiniMdEmit(); TypeRefRec *pTypeRefRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(crExtends), &pTypeRefRec)); LPCSTR szNamespace; LPCSTR szName; IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szNamespace));; IfFailGo(pMiniMd->getNameOfTypeRef(pTypeRefRec, &szName)); // check for System.Enum BOOL bIsEnum = (!strcmp(szNamespace,"System"))&&(!strcmp(szName,"Enum")); if (bIsEnum) { fInjectSecurityAttributes = FALSE; } } } else // check for global method defs if (TypeFromToken(pRec->m_tkTo) == mdtMethodDef) { int isGlobal = 0; if (!FAILED(m_pRegMetaEmit->IsGlobal(pRec->m_tkTo, &isGlobal))) { // check for global methods if (isGlobal != 0) { fInjectSecurityAttributes = TRUE; } } } if (fInjectSecurityAttributes) { // check to see if the token already has a custom attribute const void *pbData = NULL; // [OUT] Put pointer to data here. ULONG cbData = 0; if (fMarkEachTokenAsCritical) { // Check if the Type already has SecurityCritical BOOL fInjectSecurityCriticalEverything = TRUE; if (S_OK == m_pRegMetaEmit->GetCustomAttributeByName(pRec->m_tkTo, COR_SECURITYCRITICAL_ATTRIBUTE_FULL_W, &pbData, &cbData)) { // if value is non-0 (i.e. 1), then it is SecurityCritical.Everything - so do not inject another fInjectSecurityCriticalEverything = !(NULL != pbData && cbData == 8 && memcmp(rgSecurityCriticalEverythingCtorValue, pbData, cbData) == 0); } // either inject or overwrite SecurityCritical.Everything if (fInjectSecurityCriticalEverything) { IfFailGo(m_pRegMetaEmit->DefineCustomAttribute( pRec->m_tkTo, tkSecurityCriticalEverythingAttribute, rgSecurityCriticalEverythingCtorValue, // Use this if you need specific custom attribute data (presence of the attribute isn't enough) sizeof(rgSecurityCriticalEverythingCtorValue), // Length of your custom attribute data NULL)); } } // If the Type does NOT already have TAS then add it if (fMarkEachTokenAsSafe && S_OK != m_pRegMetaEmit->GetCustomAttributeByName(pRec->m_tkTo, COR_SECURITYTREATASSAFE_ATTRIBUTE_FULL_W, &pbData, &cbData)) { IfFailGo(m_pRegMetaEmit->DefineCustomAttribute( pRec->m_tkTo, tkSecurityTreatAsSafeAttribute, rgTreatAsSafeCtorValue, // Use this if you need specific custom attribute data (presence of the attribute isn't enough) sizeof(rgTreatAsSafeCtorValue), // Length of your custom attribute data NULL)); } hr = m_pRegMetaEmit->DefineCustomAttribute(pRec->m_tkTo, tkSecuritySafeCriticalAttribute, rgSafeCriticalCtorValue, // Use this if you need specific custom attribute data (presence of the attribute isn't enough) sizeof(rgSafeCriticalCtorValue), // Length of your custom attribute data NULL); } } } // If the global scope is not Transparent, we should emit SecurityCritical.Explicit || Everything if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityTransparent) != ISSCS_SecurityTransparent && (m_isscsSecurityCritical & ISSCS_SecurityCriticalEverything) != ISSCS_SecurityCriticalExplicit) { BOOL fEmitSecurityEverything = FALSE; // in the case of Unmarked and TAS/Unmarked, we need to emit the SecurityCritical.Everything attribute // if it hasn't already been emitted if ((m_isscsSecurityCriticalAllScopes & ISSCS_SecurityCriticalEverything) == ISSCS_SecurityCriticalEverything) { fEmitSecurityEverything = TRUE; } // otherwise, emit the SecurityCritical.Explicit attribute BOOL fSecurityCriticalExists = FALSE; // check to see if the assembly already has the appropriate SecurityCritical attribute // [from one of the input scopes] const void *pbData = NULL; ULONG cbData = 0; if (S_OK == ImportHelper::GetCustomAttributeByName(emit, fakeModuleTypeRef, // This is the assembly def token COR_SECURITYCRITICAL_ATTRIBUTE_FULL, &pbData, &cbData)) { // find out if critical everything or explicit // default to critical // if value is non-0 (i.e. 1), then mark as SecurityCritical everything, otherwise, explicit if (NULL != pbData && cbData == 8 && memcmp(rgSecurityCriticalEverythingCtorValue, pbData, cbData) == 0) { if (!fEmitSecurityEverything) { _ASSERTE(!"Unexpected SecurityCritical.Everything attribute detected"); IfFailGo(META_E_BADMETADATA); } } else { if (fEmitSecurityEverything) { _ASSERTE(!"Unexpected SecurityCritical.Explicit attribute detected"); IfFailGo(META_E_BADMETADATA); } } fSecurityCriticalExists = TRUE; } if (!fSecurityCriticalExists) { // retrieve the type and CustomAttribute mdCustomAttribute tkSecurityCriticalAttributeExplicit; mdTypeRef tkSecurityCriticalExplicitAttributeType = mdTokenNil; IfFailGo(m_pRegMetaEmit->DefineTypeRefByName( tkMscorlib, COR_SECURITYCRITICAL_ATTRIBUTE_FULL_W, &tkSecurityCriticalExplicitAttributeType)); BYTE rgSigBytesSecurityCriticalExplicitCtorLocal[] = {IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS, 0x00, ELEMENT_TYPE_VOID}; BYTE rgSecurityCriticalExplicitCtorValue[] = COR_SECURITYCRITICAL_ATTRIBUTE_VALUE_EXPLICIT; IfFailGo(m_pRegMetaEmit->DefineMemberRef(tkSecurityCriticalExplicitAttributeType, COR_CONSTRUCTOR_METADATA_IDENTIFIER, rgSigBytesSecurityCriticalExplicitCtorLocal, sizeof(rgSigBytesSecurityCriticalExplicitCtorLocal), &tkSecurityCriticalAttributeExplicit)); IfFailGo(m_pRegMetaEmit->DefineCustomAttribute( fakeModuleTypeRef, fEmitSecurityEverything?tkSecurityCriticalEverythingAttribute:tkSecurityCriticalAttributeExplicit, fEmitSecurityEverything?rgSecurityCriticalEverythingCtorValue:rgSecurityCriticalExplicitCtorValue, fEmitSecurityEverything?sizeof(rgSecurityCriticalEverythingCtorValue):sizeof(rgSecurityCriticalExplicitCtorValue), NULL)); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeSecurityCriticalAttributes() //******************************************************************************* // Helper to copy an InterfaceImpl record //******************************************************************************* HRESULT NEWMERGER::CopyInterfaceImpl( InterfaceImplRec *pRecEmit, // [IN] the emit record to fill MergeImportData *pImportData, // [IN] the importing context InterfaceImplRec *pRecImp) // [IN] the record to import { HRESULT hr; mdToken tkParent; mdToken tkInterface; CMiniMdRW *pMiniMdEmit = GetMiniMdEmit(); CMiniMdRW *pMiniMdImp; MDTOKENMAP *pCurTkMap; pMiniMdImp = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; tkParent = pMiniMdImp->getClassOfInterfaceImpl(pRecImp); tkInterface = pMiniMdImp->getInterfaceOfInterfaceImpl(pRecImp); IfFailGo( pCurTkMap->Remap(tkParent, &tkParent) ); IfFailGo( pCurTkMap->Remap(tkInterface, &tkInterface) ); IfFailGo( pMiniMdEmit->PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Class, pRecEmit, tkParent) ); IfFailGo( pMiniMdEmit->PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Interface, pRecEmit, tkInterface) ); ErrExit: return hr; } // HRESULT NEWMERGER::CopyInterfaceImpl() //***************************************************************************** // Merge Assembly table //***************************************************************************** HRESULT NEWMERGER::MergeAssembly() { HRESULT hr = NOERROR; AssemblyRec *pRecImport = NULL; AssemblyRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; LPCUTF8 szTmp; const BYTE *pbTmp; ULONG cbTmp; ULONG iRecord; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; if (!pMiniMdImport->getCountAssemblys()) goto ErrExit; // There is no Assembly in the import scope to merge. // Copy the Assembly map record to the Emit scope and send a token remap notifcation // to the client. No duplicate checking needed since the Assembly can be present in // only one scope and there can be atmost one entry. IfFailGo(pMiniMdImport->GetAssemblyRecord(1, &pRecImport)); IfFailGo(pMiniMdEmit->AddAssemblyRecord(&pRecEmit, &iRecord)); pRecEmit->Copy(pRecImport); IfFailGo(pMiniMdImport->getPublicKeyOfAssembly(pRecImport, &pbTmp, &cbTmp)); IfFailGo(pMiniMdEmit->PutBlob(TBL_Assembly, AssemblyRec::COL_PublicKey, pRecEmit, pbTmp, cbTmp)); IfFailGo(pMiniMdImport->getNameOfAssembly(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_Assembly, AssemblyRec::COL_Name, pRecEmit, szTmp)); IfFailGo(pMiniMdImport->getLocaleOfAssembly(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_Assembly, AssemblyRec::COL_Locale, pRecEmit, szTmp)); // record the token movement. IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(1, mdtAssembly), false, TokenFromRid(iRecord, mdtAssembly), &pTokenRec)); } ErrExit: return hr; } // HRESULT NEWMERGER::MergeAssembly() //***************************************************************************** // Merge File table //***************************************************************************** HRESULT NEWMERGER::MergeFiles() { HRESULT hr = NOERROR; FileRec *pRecImport = NULL; FileRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; LPCUTF8 szTmp; const void *pbTmp; ULONG cbTmp; ULONG iCount; ULONG i; ULONG iRecord; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountFiles(); // Loop through all File records and copy them to the Emit scope. // Since there can only be one File table in all the scopes combined, // there isn't any duplicate checking that needs to be done. for (i = 1; i <= iCount; i++) { IfFailGo(pMiniMdImport->GetFileRecord(i, &pRecImport)); IfFailGo(pMiniMdEmit->AddFileRecord(&pRecEmit, &iRecord)); pRecEmit->Copy(pRecImport); IfFailGo(pMiniMdImport->getNameOfFile(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_File, FileRec::COL_Name, pRecEmit, szTmp)); IfFailGo(pMiniMdImport->getHashValueOfFile(pRecImport, (const BYTE **)&pbTmp, &cbTmp)); IfFailGo(pMiniMdEmit->PutBlob(TBL_File, FileRec::COL_HashValue, pRecEmit, pbTmp, cbTmp)); // record the token movement. IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(i, mdtFile), false, TokenFromRid(iRecord, mdtFile), &pTokenRec)); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeFiles() //***************************************************************************** // Merge ExportedType table //***************************************************************************** HRESULT NEWMERGER::MergeExportedTypes() { HRESULT hr = NOERROR; ExportedTypeRec *pRecImport = NULL; ExportedTypeRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; LPCUTF8 szTmp; mdToken tkTmp; ULONG iCount; ULONG i; ULONG iRecord; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountExportedTypes(); // Loop through all ExportedType records and copy them to the Emit scope. // Since there can only be one ExportedType table in all the scopes combined, // there isn't any duplicate checking that needs to be done. for (i = 1; i <= iCount; i++) { IfFailGo(pMiniMdImport->GetExportedTypeRecord(i, &pRecImport)); IfFailGo(pMiniMdEmit->AddExportedTypeRecord(&pRecEmit, &iRecord)); pRecEmit->Copy(pRecImport); IfFailGo(pMiniMdImport->getTypeNameOfExportedType(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_ExportedType, ExportedTypeRec::COL_TypeName, pRecEmit, szTmp)); IfFailGo(pMiniMdImport->getTypeNamespaceOfExportedType(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_ExportedType, ExportedTypeRec::COL_TypeNamespace, pRecEmit, szTmp)); tkTmp = pMiniMdImport->getImplementationOfExportedType(pRecImport); IfFailGo(pCurTkMap->Remap(tkTmp, &tkTmp)); IfFailGo(pMiniMdEmit->PutToken(TBL_ExportedType, ExportedTypeRec::COL_Implementation, pRecEmit, tkTmp)); // record the token movement. IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(i, mdtExportedType), false, TokenFromRid(iRecord, mdtExportedType), &pTokenRec)); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeExportedTypes() //***************************************************************************** // Merge ManifestResource table //***************************************************************************** HRESULT NEWMERGER::MergeManifestResources() { HRESULT hr = NOERROR; ManifestResourceRec *pRecImport = NULL; ManifestResourceRec *pRecEmit = NULL; CMiniMdRW *pMiniMdImport; CMiniMdRW *pMiniMdEmit; LPCUTF8 szTmp; mdToken tkTmp; ULONG iCount; ULONG i; ULONG iRecord; TOKENREC *pTokenRec; MergeImportData *pImportData; MDTOKENMAP *pCurTkMap; pMiniMdEmit = GetMiniMdEmit(); for (pImportData = m_pImportDataList; pImportData != NULL; pImportData = pImportData->m_pNextImportData) { // for each import scope pMiniMdImport = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); // set the current MDTokenMap pCurTkMap = pImportData->m_pMDTokenMap; iCount = pMiniMdImport->getCountManifestResources(); // Loop through all ManifestResource records and copy them to the Emit scope. // Since there can only be one ManifestResource table in all the scopes combined, // there isn't any duplicate checking that needs to be done. for (i = 1; i <= iCount; i++) { IfFailGo(pMiniMdImport->GetManifestResourceRecord(i, &pRecImport)); IfFailGo(pMiniMdEmit->AddManifestResourceRecord(&pRecEmit, &iRecord)); pRecEmit->Copy(pRecImport); IfFailGo(pMiniMdImport->getNameOfManifestResource(pRecImport, &szTmp)); IfFailGo(pMiniMdEmit->PutString(TBL_ManifestResource, ManifestResourceRec::COL_Name, pRecEmit, szTmp)); tkTmp = pMiniMdImport->getImplementationOfManifestResource(pRecImport); IfFailGo(pCurTkMap->Remap(tkTmp, &tkTmp)); IfFailGo(pMiniMdEmit->PutToken(TBL_ManifestResource, ManifestResourceRec::COL_Implementation, pRecEmit, tkTmp)); // record the token movement. IfFailGo(pCurTkMap->InsertNotFound( TokenFromRid(i, mdtManifestResource), false, TokenFromRid(iRecord, mdtManifestResource), &pTokenRec)); } } ErrExit: return hr; } // HRESULT NEWMERGER::MergeManifestResources() //***************************************************************************** // Error handling. Call back to host to see what they want to do. //***************************************************************************** HRESULT NEWMERGER::OnError( HRESULT hrIn, // The error HR we're reporting. MergeImportData *pImportData, // The input scope with the error. mdToken token) // The token with the error. { // This function does a QI and a Release on every call. However, it should be // called very infrequently, and lets the scope just keep a generic handler. IMetaDataError *pIErr = NULL; IUnknown *pHandler = pImportData->m_pHandler; CMiniMdRW *pMiniMd = &(pImportData->m_pRegMetaImport->m_pStgdb->m_MiniMd); CQuickArray<WCHAR> rName; // Name of the TypeDef in unicode. LPCUTF8 szTypeName; LPCUTF8 szNSName; TypeDefRec *pTypeRec; int iLen; // Length of a name. mdToken tkParent; HRESULT hr = NOERROR; if (pHandler && pHandler->QueryInterface(IID_IMetaDataError, (void**)&pIErr)==S_OK) { switch (hrIn) { case META_E_PARAM_COUNTS: case META_E_METHD_NOT_FOUND: case META_E_METHDIMPL_INCONSISTENT: { LPCUTF8 szMethodName; MethodRec *pMethodRec; // Method name. _ASSERTE(TypeFromToken(token) == mdtMethodDef); IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(token), &pMethodRec)); IfFailGo(pMiniMd->getNameOfMethod(pMethodRec, &szMethodName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzMethodName, szMethodName); IfNullGo(wzMethodName); // Type and its name. IfFailGo( pMiniMd->FindParentOfMethodHelper(token, &tkParent) ); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), wzMethodName, token); break; } case META_E_FIELD_NOT_FOUND: { LPCUTF8 szFieldName; FieldRec *pFieldRec; // Field name. _ASSERTE(TypeFromToken(token) == mdtFieldDef); IfFailGo(pMiniMd->GetFieldRecord(RidFromToken(token), &pFieldRec)); IfFailGo(pMiniMd->getNameOfField(pFieldRec, &szFieldName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzFieldName, szFieldName); IfNullGo(wzFieldName); // Type and its name. IfFailGo( pMiniMd->FindParentOfFieldHelper(token, &tkParent) ); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), wzFieldName, token); break; } case META_E_EVENT_NOT_FOUND: { LPCUTF8 szEventName; EventRec *pEventRec; // Event name. _ASSERTE(TypeFromToken(token) == mdtEvent); IfFailGo(pMiniMd->GetEventRecord(RidFromToken(token), &pEventRec)); IfFailGo(pMiniMd->getNameOfEvent(pEventRec, &szEventName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzEventName, szEventName); IfNullGo(wzEventName); // Type and its name. IfFailGo( pMiniMd->FindParentOfEventHelper(token, &tkParent) ); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), wzEventName, token); break; } case META_E_PROP_NOT_FOUND: { LPCUTF8 szPropertyName; PropertyRec *pPropertyRec; // Property name. _ASSERTE(TypeFromToken(token) == mdtProperty); IfFailGo(pMiniMd->GetPropertyRecord(RidFromToken(token), &pPropertyRec)); IfFailGo(pMiniMd->getNameOfProperty(pPropertyRec, &szPropertyName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzPropertyName, szPropertyName); IfNullGo(wzPropertyName); // Type and its name. IfFailGo( pMiniMd->FindParentOfPropertyHelper(token, &tkParent) ); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), wzPropertyName, token); break; } case META_S_PARAM_MISMATCH: { LPCUTF8 szMethodName; MethodRec *pMethodRec; mdToken tkMethod; // Method name. _ASSERTE(TypeFromToken(token) == mdtParamDef); IfFailGo( pMiniMd->FindParentOfParamHelper(token, &tkMethod) ); IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(tkMethod), &pMethodRec)); IfFailGo(pMiniMd->getNameOfMethod(pMethodRec, &szMethodName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzMethodName, szMethodName); IfNullGo(wzMethodName); // Type and its name. IfFailGo( pMiniMd->FindParentOfMethodHelper(token, &tkParent) ); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); // use the error hresult so that we can post the correct error. PostError(META_E_PARAM_MISMATCH, wzMethodName, (LPWSTR) rName.Ptr(), token); break; } case META_E_INTFCEIMPL_NOT_FOUND: { InterfaceImplRec *pRec; // The InterfaceImpl mdToken tkIface; // Token of the implemented interface. CQuickArray<WCHAR> rIface; // Name of the Implemented Interface in unicode. TypeRefRec *pRef; // TypeRef record when II is a typeref. InterfaceImplRec *pInterfaceImplRec; // Get the record. _ASSERTE(TypeFromToken(token) == mdtInterfaceImpl); IfFailGo(pMiniMd->GetInterfaceImplRecord(RidFromToken(token), &pRec)); // Get the name of the class. tkParent = pMiniMd->getClassOfInterfaceImpl(pRec); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); // Get the name of the implemented interface. IfFailGo(pMiniMd->GetInterfaceImplRecord(RidFromToken(token), &pInterfaceImplRec)); tkIface = pMiniMd->getInterfaceOfInterfaceImpl(pInterfaceImplRec); if (TypeFromToken(tkIface) == mdtTypeDef) { // If it is a typedef... IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkIface), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); } else { // If it is a typeref... _ASSERTE(TypeFromToken(tkIface) == mdtTypeRef); IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tkIface), &pRef)); IfFailGo(pMiniMd->getNameOfTypeRef(pRef, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pRef, &szNSName)); } // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rIface.ReSizeNoThrow(iLen+1)); ns::MakePath(rIface.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), (LPWSTR)rIface.Ptr(), token); break; } case META_E_CLASS_LAYOUT_INCONSISTENT: case META_E_METHOD_COUNTS: case META_E_FIELD_COUNTS: case META_E_EVENT_COUNTS: case META_E_PROPERTY_COUNTS: { // get the type name. _ASSERTE(TypeFromToken(token) == mdtTypeDef); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(token), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), token); break; } case META_E_GENERICPARAM_INCONSISTENT: { // If token is type, get type name; if method, get method name. LPWSTR wzName; LPCUTF8 szMethodName; MethodRec *pMethodRec; if ((TypeFromToken(token) == mdtMethodDef)) { // Get the method name. IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(token), &pMethodRec)); IfFailGo(pMiniMd->getNameOfMethod(pMethodRec, &szMethodName)); MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzMethodName, szMethodName); IfNullGo(wzMethodName); wzName = wzMethodName; } else { // Get the type name. _ASSERTE(TypeFromToken(token) == mdtTypeDef); IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(token), &pTypeRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTypeRec, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTypeRec, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); wzName = (LPWSTR)rName.Ptr(); } PostError(hrIn, wzName, token); break; } case META_E_TYPEDEF_MISSING: { TypeRefRec *pRef; // TypeRef record when II is a typeref. // Get the record. _ASSERTE(TypeFromToken(token) == mdtTypeRef); IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(token), &pRef)); IfFailGo(pMiniMd->getNameOfTypeRef(pRef, &szTypeName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pRef, &szNSName)); // Put namespace + name together. iLen = ns::GetFullLength(szNSName, szTypeName); IfFailGo(rName.ReSizeNoThrow(iLen+1)); ns::MakePath(rName.Ptr(), iLen+1, szNSName, szTypeName); PostError(hrIn, (LPWSTR) rName.Ptr(), token); break; } default: { PostError(hrIn, token); break; } } hr = pIErr->OnError(hrIn, token); } else hr = S_FALSE; ErrExit: if (pIErr) pIErr->Release(); return (hr); } // NEWMERGER::OnError #endif //FEATURE_METADATA_EMIT_ALL
8fab901b36a92947f156ac53eff295d83f3e3b45
afa59b7b69f09b924061eade6ecfd77bed61ebac
/controllers/ros44/include/webots_ros/motor_set_control_pid.h
207fea2415aa7e88621ac33ade166fc491efe8d3
[]
no_license
ekuo1/rovey2
a8ead58269be266a7f880c6cac2da7dbc5fc5270
db883dd7ae6b96465a16c83a57394cc2acb9b139
refs/heads/master
2020-04-13T14:25:15.274334
2019-01-05T07:29:52
2019-01-05T07:29:52
163,262,441
0
0
null
null
null
null
UTF-8
C++
false
false
2,303
h
motor_set_control_pid.h
#ifndef WEBOTS_ROS_MESSAGE_MOTOR_SET_CONTROL_PID_H #define WEBOTS_ROS_MESSAGE_MOTOR_SET_CONTROL_PID_H #include "ros/service_traits.h" #include "motor_set_control_pidRequest.h" #include "motor_set_control_pidResponse.h" namespace webots_ros { struct motor_set_control_pid { typedef motor_set_control_pidRequest Request; typedef motor_set_control_pidResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; } // namespace webots_ros namespace ros { namespace service_traits { template<> struct MD5Sum< ::webots_ros::motor_set_control_pid > { static const char* value() { return "712b4e401e3c9cbb098cd0435a9a13d3"; } static const char* value(const ::webots_ros::motor_set_control_pid&) { return value(); } }; template<> struct DataType< ::webots_ros::motor_set_control_pid > { static const char* value() { return "webots_ros/motor_set_control_pid"; } static const char* value(const ::webots_ros::motor_set_control_pid&) { return value(); } }; template<> struct MD5Sum< ::webots_ros::motor_set_control_pidRequest> { static const char* value() { return MD5Sum< ::webots_ros::motor_set_control_pid >::value(); } static const char* value(const ::webots_ros::motor_set_control_pidRequest&) { return value(); } }; template<> struct DataType< ::webots_ros::motor_set_control_pidRequest> { static const char* value() { return DataType< ::webots_ros::motor_set_control_pid >::value(); } static const char* value(const ::webots_ros::motor_set_control_pidRequest&) { return value(); } }; template<> struct MD5Sum< ::webots_ros::motor_set_control_pidResponse> { static const char* value() { return MD5Sum< ::webots_ros::motor_set_control_pid >::value(); } static const char* value(const ::webots_ros::motor_set_control_pidResponse&) { return value(); } }; template<> struct DataType< ::webots_ros::motor_set_control_pidResponse> { static const char* value() { return DataType< ::webots_ros::motor_set_control_pid >::value(); } static const char* value(const ::webots_ros::motor_set_control_pidResponse&) { return value(); } }; } // namespace service_traits } // namespace ros #endif // WEBOTS_ROS_MESSAGE_MOTOR_SET_CONTROL_PID_H
de2e0a48b766eefe9230d939433e6c35d3ee8259
e654d5c80e216de7378aabd937f47dcbd474c333
/Submitted/800/263A-Beautiful_Matrix.cpp
5535f6340c19995c96c02e6a2c8de7cc100928cb
[]
no_license
AgustinMDominguez/Codeforces
ccf685a293d777bfbddd84b316d666b3bed6d685
bedfe8d3ef9fd91fb2aa3b61c0912327acdcd001
refs/heads/master
2023-01-22T22:45:16.655989
2020-11-19T15:21:59
2020-11-19T15:21:59
314,286,604
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
263A-Beautiful_Matrix.cpp
#include <bits/stdc++.h> using namespace std; #define DBG(x) cout << #x << " = " << (x) << "\n" #define END(e) {cout << (e) << "\n"; return EXIT_SUCCESS;} int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int v; for(int r=1; r<6; ++r) { for(int c=1; c<6; ++c) { cin >> v; if(v==1)END(abs(r-3)+abs(c-3)) } } }
732b7fcee848204b5c279a5aac21b378a06e18bc
cbed91fe314a3ad6c1058953fb50176f66bc63c1
/Opencv_exercise/canny_edge_detection/canny_edge_detection.cpp
6bf8a2436302025cbb686fd29c9e61aa79f60948
[]
no_license
Atsushi-Kobayashi/mic_programming_exercise
716a8f3a6a2672631e89e7df77d9688fb9c05a66
6a692d6f310c519f60956bd4c363ac59d4075e6e
refs/heads/master
2020-04-30T14:06:12.134966
2019-04-16T08:43:28
2019-04-16T08:43:28
176,879,407
0
1
null
2019-03-24T17:24:58
2019-03-21T05:57:42
C++
UTF-8
C++
false
false
1,165
cpp
canny_edge_detection.cpp
#include <opencv2/opencv.hpp> #include"filters.h" #include<iostream> #include<vector> #include<cmath> void cannyEdgeDetection(cv::Mat &img) { int high_threshold=35; int low_threshold=30; /*std::cout << "Gaussian filter\n";*/ gaussianFilter(img); cv::imshow("Gaussian", img); cv::waitKey(0); cv::Mat img_edge = GrayConvertedFromBGR(img); std::vector<uchar> sobel_edge_normal_direction = {}; sobelFilter(img_edge,sobel_edge_normal_direction); cv::imshow("Fused sobel", img_edge); cv::waitKey(0); nonMaximumSuppression(img_edge, sobel_edge_normal_direction); cv::imshow("Non Maximum Suppression", img_edge); cv::waitKey(0); /* std::cout << "Hysteresis threshold\n"; while (true) { std::cout << "Input high threshold (0,255): \n"; std::cin >> high_threshold; std::cout << "Input low threshold (0,255): \n"; std::cin >> low_threshold; if (high_threshold > 0 && high_threshold < 255 && low_threshold>0 && low_threshold < 255 && high_threshold>low_threshold) { break; } std::cout << "Error\n"; }*/ hysteresisThreshold(img_edge, (uchar)high_threshold, (uchar)low_threshold); cv::imshow("Result", img_edge); cv::waitKey(0); }
e06528560c72287a967c40e283d88a83bb7a508a
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/xgboost/xgboost-gumtree/dmlc_xgboost_new_hunk_884.cpp
c5f6195e6dfc7c18af43e2ddb4e7ed033316fcb4
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
dmlc_xgboost_new_hunk_884.cpp
} public: /*! * \brief step 1: initialize the number of rows in the data, not necessary exact * \nrows number of rows in the matrix, can be smaller than expected */ inline void InitBudget( size_t nrows = 0 ){ if( !UseAcList ){ rptr.clear(); rptr.resize( nrows + 1, 0 ); }else{ Assert( nrows + 1 == rptr.size(), "rptr must be initialized already" ); this->Cleanup();
a526b8d9a9700f55e193364be011d8f38b3780b1
c20c21fe3bde17040c8f1367eaa697258479798e
/raygame/Sprite.h
1975d39a5168083caf47ff66e2579ad853f91312
[ "MIT" ]
permissive
DynashEtvala/TurfTanks
6c92d6b4d85bf277d3e8a5187c718c75871d770a
5aa6a346b485c36c3ac74473c3a2a26ccd40cfb1
refs/heads/master
2020-04-07T01:26:32.673737
2018-12-07T01:48:10
2018-12-07T01:48:10
157,941,105
0
0
null
null
null
null
UTF-8
C++
false
false
726
h
Sprite.h
#pragma once #include "raylib.h" #include "Helpers.h" class Sprite { public: Texture2D* tex; Point frame; Point frameCount; Point frameSize; Vector2 pos; Vector2 orig; Color tint; float scale; float rot; float spf; float ftime = 0; Sprite(); Sprite(Texture2D* _tex, Point _frame, Point _frameSize, Vector2 _pos, float _scale, Color tint); Sprite(Texture2D* _tex, Point _frame, Point _frameSize, Vector2 _pos, float _scale, Color tint, Point _frameCount, float _spf); Sprite(Texture2D* _tex, Point _frame, Point _frameSize, Vector2 _pos, float _scale, Color tint, Point _frameCount, float _spf, Vector2 _orig, float _rot); ~Sprite(); virtual void Update(float delta_t); virtual void Draw(float delta_t); };
447b3e43f79abeea27272a38186796f77f9445ea
81c74937fd4586b264b9ff3242be616292d06bdf
/trunk/src/c++/markerinfo/markerinfo.cpp
6a68337a29b1e6acdd381349c26cf165413bf2f8
[]
no_license
rahulkr007/sageCore
be877ff6bb2ee5825e5cc9b9d71e03ac32f4e29f
b1b19b95d80637b48fca789a09a8de16cdaad3ab
refs/heads/master
2021-06-01T12:41:41.374258
2016-09-02T19:14:02
2016-09-02T19:14:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,499
cpp
markerinfo.cpp
//================================================================== // File: markerinfo.cpp // // Author: Yeunjoo Song // // History: Initial implementation. Mar. 2002 // // Copyright (c) 2002 R. C. Elston //================================================================== #include <string> #include <cassert> #include <functional> #include <vector> #include <iomanip> #include "LSF/LSFinit.h" #include "error/bufferederrorstream.h" #include "gelim/geno_eliminate.h" #include "gelim/pedigree_region.h" #include "markerinfo/markerinfo.h" #include "markerinfo/input.h" using namespace SAGE; MARKERINFO::MARKERINFO(int argc, char **argv) : APP::SAGEapp(APP::APP_MARKERINFO, true, argc, argv), my_consistent_out(false), my_pedigree_out(false), my_summary_file(NULL), my_pedigree_file(NULL), my_table_file(NULL) { LSFInit(); } MARKERINFO::~MARKERINFO() {} int MARKERINFO::main() { // Create input data. // markerinfo_data mdata(name, debug()); print_title(mdata.info()); // Get the error stream and make it available locally // cerrorstream& errors = mdata.errors(); mdata.input(argc, argv); // Start markerinfo analysis. // cout << endl << "MARKERINFO analysis......." << endl << endl << flush; if( mdata.analysis().size() ) parse_analyses(mdata.analysis()[0], mdata.pedigrees(), errors); boost::scoped_ptr<ofstream> s_file; boost::scoped_ptr<ofstream> p1_file; boost::scoped_ptr<ofstream> p2_file; boost::scoped_ptr<ofstream> t_file; string sum_filename; string ped_filename; string par_filename; string tab_filename; ofstream sum_file; ofstream ped_file; ofstream par_file; ofstream tab_file; if( my_outfile_name.size() ) { sum_filename = my_outfile_name + ".out"; sum_file.open( sum_filename.c_str() ); if(sum_file) print_title(sum_file); my_summary_file = &sum_file; if( my_pedigree_out ) { ped_filename = my_outfile_name + "_clean.ped"; ped_file.open( ped_filename.c_str() ); my_pedigree_file = &ped_file; par_filename = my_outfile_name + "_clean.par"; par_file.open( par_filename.c_str() ); my_parameter_file = &par_file; //tab_filename = my_outfile_name + ".tab"; //tab_file.open( tab_filename.c_str() ); //if(tab_file) // print_title(tab_file); //my_table_file = &tab_file; } } else { sum_filename = "markerinfo.out"; if( s_file.get() == NULL ) { s_file.reset( new ofstream(sum_filename.c_str()) ); if(*s_file) print_title(*s_file); } my_summary_file = s_file.get(); if( my_pedigree_out ) { ped_filename = "markerinfo_clean.ped"; if( p1_file.get() == NULL ) { p1_file.reset( new ofstream(ped_filename.c_str()) ); } my_pedigree_file = p1_file.get(); par_filename = "markerinfo_clean.par"; if( p2_file.get() == NULL ) { p2_file.reset( new ofstream(par_filename.c_str()) ); } my_parameter_file = p2_file.get(); //tab_filename = "markerinfo.tab"; //if( t_file.get() == NULL ) //{ // t_file.reset( new ofstream(tab_filename.c_str()) ); // if(*t_file) // print_title(*t_file); //} //my_table_file = t_file.get(); } } run_analyses(mdata); cout << endl << "Analysis complete!" << endl << endl; print_inf_banner(cout); return EXIT_SUCCESS; } void MARKERINFO::parse_analyses(LSFBase* params, const RPED::RefMultiPedigree& mp, cerrorstream& errors) { AttrVal v = attr_value(params, "out"); if( !v.has_value() || !v.String().size() ) v = attr_value(params, "output"); if( v.has_value() && v.String().size() ) my_outfile_name = v.String(); if( !params->List() ) return; LSFList::const_iterator i; AttrVal a; for( i = params->List()->begin(); i != params->List()->end(); ++i) { if( !*i || !((*i)->name().size()) ) continue; string name = toUpper( (*i)->name() ); if( name == "SAMPLE_ID" ) { a = attr_value(*i, "SAMPLE_ID", 0); if( a.has_value() ) { size_t string_index = mp.info().string_find(a.String()); if( string_index == (size_t) - 1 ) errors << priority(information) << "Invalid sample_id name : " << a.String() << "\n Skipped... " << endl; else my_sample_ids.push_back(string_index); } } else if( name == "CONSISTENT_OUT" ) { a = attr_value(*i, "CONSISTENT_OUT", 0); if( a.has_value() ) { if( toUpper(a.String()) == "TRUE" || toUpper(a.String()) == "YES" ) my_consistent_out = true; } } else if( name == "PEDIGREE_SKIP" ) { a = attr_value(*i, "PEDIGREE_SKIP", 0); if( a.has_value() ) { if( mp.pedigree_find(a.String() ) ) { size_t pedigree_index = mp.pedigree_find(a.String())->index(); my_pedigree_skips.insert(pedigree_index); } else errors << priority(information) << "Invalid pedigree name : " << a.String() << "\n Skipped... " << endl; } } else if( name == "PEDIGREE_OUT" ) { a = attr_value(*i, "PEDIGREE_OUT", 0); if( a.has_value() ) { if( toUpper(a.String()) == "TRUE" || toUpper(a.String()) == "YES" ) my_pedigree_out = true; } } else errors << priority(information) << "Unknown option : " << name << "\n Skipped... " << endl; } return; } void MARKERINFO::run_analyses(const markerinfo_data& mdata) { genotype_eliminator gelim; const RPED::RefMultiPedigree& ref_mp = mdata.pedigrees(); FPED::Multipedigree fped(ref_mp); FPED::MPFilterer::add_multipedigree(fped, ref_mp); fped.construct(); FPED::PedigreeConstIterator ped = fped.pedigree_begin(); vector< string > ped_name_sorted; for( ; ped != fped.pedigree_end(); ++ped ) { const FPED::Pedigree& pedigree = *ped; ped_name_sorted.push_back(pedigree.name()); } sort(ped_name_sorted.begin(), ped_name_sorted.end()); for( size_t ped_name = 0; ped_name < ped_name_sorted.size(); ++ped_name ) { const FPED::Pedigree& pedigree = *fped.pedigree_find(ped_name_sorted[ped_name]); char old_fill = cout.fill('.'); string s = "'" + pedigree.name() + "'"; if( my_pedigree_skips.find(pedigree.index()) != my_pedigree_skips.end() ) { cout << "Skipping pedigree " << s << "........." << endl << flush; continue; } cout << "Processing pedigree " << s << flush; #if 0 cout << "member in mped : " << endl; RPED::filtered_multipedigree::pedigree_type::member_const_iterator m_i = pedigree.member_begin(); for( ; m_i != pedigree.member_end(); ++m_i ) cout << "name = " << m_i->name() << ", index = " << m_i->index() << endl; cout << endl; #endif FPED::SubpedigreeConstIterator subped = pedigree.subpedigree_begin(); FPED::SubpedigreeConstIterator subped_end = pedigree.subpedigree_end(); for( ; subped != subped_end; ++subped) { //string c; //cin >> c; pedigree_region ped_r(*subped, mdata.get_region(), mdata.errors(), false, false); gelim.set_subpedigree(*subped); for( size_t i = 0; i < ped_r.inheritance_model_count(); ++i ) { MLOCUS::inheritance_model& i_model = ped_r[i]; if( !i_model.penetrance_informative() ) { gelim.mark_uninformative(i_model, i); continue; } // Generate errors // - only family errors first. FPED::FamilyConstIterator f = subped->family_begin(); FPED::FamilyConstIterator fam_end = subped->family_end(); for( ; f != fam_end; ++f ) { gelim.process_family(i_model, i, *f, inconsistency_handler::nuclear_family, genotype_eliminator::none, false); } // - mendelian errors. gelim.process(i_model, i); } } cout << left << setw(22-s.size()) << "" << "done."<< endl; cout.fill(old_fill); } // Produce output ostream& analysis_out = *my_summary_file; analysis_out << endl << "=====================================================================" << endl << " Markerinfo Analysis Output" << endl << "=====================================================================" << endl << endl; if(gelim.get_errors().family_begin() != gelim.get_errors().family_end()) { inconsistency_table_printer printer(analysis_out); //Not yet! //printer.set_columns(); analysis_out << "---------------------------------------------------------------------" << endl << " Part 1.1: Number of Inconsistencies per pedigree" << endl << "---------------------------------------------------------------------" << endl << endl; printer.print_pedigree_table(gelim.get_errors()); analysis_out << endl; analysis_out << "---------------------------------------------------------------------" << endl << " Part 1.2: Number of Inconsistencies per marker" << endl << "---------------------------------------------------------------------" << endl << endl; printer.print_marker_table(gelim.get_errors(), fped.info().markers()); analysis_out << endl << endl; analysis_out << "---------------------------------------------------------------------" << endl << " Part 2: Inconsistencies" << endl << "---------------------------------------------------------------------" << endl << endl; // find the name for missing allele. const MLOCUS::inheritance_model_map& imap = fped.info().markers(); string mv = imap[0].missing_allele_name(); if( mv == "*missing" ) mv = "?"; analysis_out << " missing allele code = " << mv << endl << endl; printer.print_inconsistency_table(gelim.get_errors(), fped.info().markers(), my_sample_ids, my_consistent_out); if( my_pedigree_out ) { print_resetted_pedigree(gelim.get_errors(), fped); //print_marker_pedigree_table(gelim.get_errors(), fped); } } else { inconsistency_table_printer printer(analysis_out); analysis_out << "---------------------------------------------------------------------" << endl << " Part 1.1: Number of Inconsistencies per pedigree" << endl << "---------------------------------------------------------------------" << endl << endl; printer.print_pedigree_table(gelim.get_errors(), false); analysis_out << endl; analysis_out << "---------------------------------------------------------------------" << endl << " Part 1.2: Number of Inconsistencies per marker" << endl << "---------------------------------------------------------------------" << endl << endl; printer.print_marker_table(gelim.get_errors(), fped.info().markers(), false); analysis_out << endl << endl; analysis_out << " No inconsistencies detected!" << endl; } return; } void MARKERINFO::print_resetted_pedigree(const inconsistency_handler& h, const FPED::Multipedigree& fped) { const MLOCUS::inheritance_model_map& imap = fped.info().markers(); // Construct subpedigree inconsistency map. // map< const FPED::SubpedigreeConstPointer, vector<bool> > sped_incon_map; inconsistency_handler::incon_family_iterator fi = h.family_begin(); for( ; fi != h.family_end(); ++fi ) { const FPED::FamilyConstPointer fam_id = fi->first; const FPED::SubpedigreeConstPointer sped_id = fam_id->subpedigree(); if( !sped_incon_map[sped_id].size() ) sped_incon_map[sped_id].resize(imap.size(), false); const inconsistency_handler::family_error_type& fam = fi->second; inconsistency_handler::family_error_type::const_iterator fam_member = fam.begin(); for( ; fam_member != fam.end(); ++fam_member ) { if( fam_member->second.size() ) { inconsistency_handler::error_map::const_iterator e = fam_member->second.begin(); for( ; e != fam_member->second.end(); ++e ) { size_t m = e->first; sped_incon_map[sped_id][m] = true; } } } } #if 0 cout << "Dump sped_incon_map:" << endl; map< FPED::SubpedigreeConstPointer, vector<bool> >::const_iterator sp = sped_incon_map.begin(); for( ; sp != sped_incon_map.end(); ++sp ) { cout << "sped " << sp->first->pedigree()->name() << "-s" << sp->first->name(); for( size_t m = 0; m < sp->second.size(); ++m ) { cout << ", " << sp->second[m]; } cout << endl; } #endif // Print out cleaned pedigree file & parameter file. // ostream& out = *my_pedigree_file; ostream& par = *my_parameter_file; // id fields // out << "pedid\tindid\tdad\tmom\tsex"; par << "pedigree\n" << "{\n" << " delimiters = \"\\t\"\n" << " delimiter_mode = single\n" << " individual_missing_value = \"" << fped.info().individual_missing_code() << "\"\n\n" << " sex_code, male = \"" << fped.info().sex_code_male() << "\"" << ", female = \"" << fped.info().sex_code_female() << "\"" << ", missing = \"" << fped.info().sex_code_unknown() << "\"\n\n" << " pedigree_id = pedid\n" << " individual_id = indid\n" << " parent_id = dad\n" << " parent_id = mom\n" << " sex_field = sex\n\n"; // trait field // for( size_t t = 0; t < fped.info().trait_count(); ++t ) { const RPED::RefTraitInfo& t_info = fped.info().trait_info(t); if( t_info.name() == "SEX_CODE" || t_info.name() == "FAMILIAL_INDICATOR" || t_info.name() == "FOUNDER_INDICATOR" || t_info.name() == "PEDIGREE_SIZE" ) continue; out << "\t" << t_info.name(); par << " trait = \"" << t_info.name() << "\""; if( t_info.type() == RPED::RefTraitInfo::binary_trait ) par << ", binary, affected = \"" << t_info.string_affected_code() << "\"" << ", unaffected = \"" << t_info.string_unaffected_code() << "\""; par << ", missing = \"" << t_info.string_missing_code() << "\"\n"; } par << "\n"; // string field // for( size_t s = 0; s < fped.info().string_count(); ++s ) { out << "\t" << fped.info().string_info(s).name(); par << " string = " << fped.info().string_info(s).name() << "\n"; } par << "\n"; // marker field // // check first to see autosomal, sex-linked, or mixed set<MLOCUS::GenotypeModelType> m_type; set<string> m_miss; for( size_t m = 0; m < imap.size(); ++m ) { const MLOCUS::inheritance_model& model = imap[m]; out << "\t" << model.name(); m_type.insert(model.get_model_type()); m_miss.insert(model.missing_allele_name()); } out << "\n"; if( m_type.size() > 1 || m_miss.size() > 1 ) { for( size_t m = 0; m < imap.size(); ++m ) { const MLOCUS::inheritance_model& model = imap[m]; par << " marker = \"" << model.name() << "\""; if( m_miss.size() > 1 ) par << ", missing = \"" << model.missing_allele_name() << "\""; if( model.get_model_type() == MLOCUS::X_LINKED ) par << ", x_linked"; else if( model.get_model_type() == MLOCUS::Y_LINKED ) par << ", y_linked"; par << "\n"; } par << "}\n\n" << "marker\n" << "{\n"; if( m_miss.size() == 1 ) par << " allele_missing = \"" << imap[0].missing_allele_name() << "\"\n"; par << " allele_delimiter = \"/\"\n" << "}\n"; } else { par << " marker_list, start = \"" << imap[0].name() << "\""; par << ", end = \"" << imap[imap.size()-1].name() << "\""; if( imap[0].get_model_type() == MLOCUS::X_LINKED ) par << ", x_linked"; else if( imap[0].get_model_type() == MLOCUS::Y_LINKED ) par << ", y_linked"; par << "\n}\n\n" << "marker\n" << "{\n" << " allele_missing = \"" << imap[0].missing_allele_name() << "\"\n" << " allele_delimiter = \"/\"\n" << "}\n"; } // pedigree data // FPED::PedigreeConstIterator ped = fped.pedigree_begin(); for( ; ped != fped.pedigree_end(); ++ped ) { const FPED::FilteredPedigreeInfo& ped_info = ped->info(); FPED::MemberConstIterator mem = ped->member_begin(); for( ; mem != ped->member_end(); ++mem ) { const FPED::SubpedigreeConstPointer sped = mem->subpedigree(); out << ped->name() << "\t" << mem->name(); if( mem->get_father() != NULL ) out << "\t" << mem->get_father()->name(); else out << "\t" << fped.info().individual_missing_code(); if( mem->get_mother() != NULL ) out << "\t" << mem->get_mother()->name(); else out << "\t" << fped.info().individual_missing_code(); if( mem->is_male() ) out << "\t" << fped.info().sex_code_male(); else if( mem->is_female() ) out << "\t" << fped.info().sex_code_female(); else out << "\t" << fped.info().sex_code_unknown(); for( size_t t = 0; t < fped.info().trait_count(); ++t ) { const RPED::RefTraitInfo& t_info = fped.info().trait_info(t); if( t_info.name() == "SEX_CODE" || t_info.name() == "FAMILIAL_INDICATOR" || t_info.name() == "FOUNDER_INDICATOR" || t_info.name() == "PEDIGREE_SIZE" ) continue; if( ped_info.trait_missing(mem->index(), t) ) out << "\t" << fped.info().trait_info(t).string_missing_code(); else { if( t_info.type() == RPED::RefTraitInfo::binary_trait ) { if( ped_info.trait(mem->index(), t) == 1.0 ) out << "\t" << t_info.string_affected_code(); else out << "\t" << t_info.string_unaffected_code(); } else out << "\t" << ped_info.trait(mem->index(), t); } } for( size_t s = 0; s < fped.info().string_count(); ++s ) { out << "\t" << ped_info.get_string(mem->index(), s); } bool print_asis = false; if( sped_incon_map.find(sped) == sped_incon_map.end() ) print_asis = true; #if 0 cout << ped->name() << ",s"; if( sped != NULL ) cout << setw(4) << sped->name(); else cout << " "; cout << ",m" << mem->name(); if( print_asis ) cout << " no incon"; else cout << " incon"; #endif for( size_t m = 0; m < imap.size(); ++m ) { const MLOCUS::inheritance_model& model = imap[m]; size_t p = ped_info.phenotype(mem->index(), m); if( !print_asis ) { bool men_error = sped_incon_map[sped][m]; if( men_error ) p = model.get_missing_phenotype_id(); } string pheno = get_pheno_string(p, model); out << "\t" << pheno; #if 0 cout << "\t" << p << "," << pheno; #endif } out << endl; #if 0 cout << endl; #endif } } } void MARKERINFO::print_marker_pedigree_table(const inconsistency_handler& h, const FPED::Multipedigree& fped) { } string MARKERINFO::get_pheno_string(size_t p, const MLOCUS::inheritance_model& model) const { string pheno_name = model.get_phenotype(p).name(); if( p == model.get_missing_phenotype_id() ) { string a = model.missing_allele_name(); if( a == "*missing" ) a = "?"; pheno_name = a + "/" + a; } else { string al1, al2; MLOCUS::Ordering order; string geno_name = model.unphased_penetrance_begin(p).unphased_geno().name(); model.gmodel().parse_genotype_name(geno_name, al1, al2, order); if( !al1.size() || al1.substr(0,1) == "~" ) al1 = model.missing_allele_name(); if( !al2.size() || al2.substr(0,1) == "~" ) al2 = model.missing_allele_name(); if( al1 == "*missing" ) al1 = "?"; if( al2 == "*missing" ) al2 = "?"; pheno_name = al1 + "/" + al2; } return pheno_name; } int main(int argc, char **argv) { free(malloc(1)); MARKERINFO *markerinfo = new MARKERINFO(argc,argv); assert(markerinfo != NULL); int r = markerinfo->main(); delete markerinfo; return r; }
bde89b943f25791b9e8baba9e5786e35a2be79a1
c10c56fd3be1500dc19c63ab8ce93da26b2235b6
/robot.h
748d605e5a856e2548980548c6c5e160d65cc790
[]
no_license
Susta79/RF210001
f64ae60b8a00eea40fc79e65628adaf1465378ff
73721046a4ba290d2316bd914397be95549052c9
refs/heads/main
2023-08-16T01:29:38.103006
2021-10-04T19:44:25
2021-10-04T19:44:25
412,329,214
2
0
null
null
null
null
UTF-8
C++
false
false
573
h
robot.h
#ifndef ROBOT_H #define ROBOT_H #include "pose.h" #include "joint.h" enum Brand { IR, ABB, KUKA }; class Robot { private: double a1z; double a2x; double a2z; double a3z; double a4x; double a4z; double a5x; double a6x; Brand brand; public: Robot(); void setdimensions(double a1z, double a2x, double a2z, double a3z, double a4x, double a4z, double a5x, double a6x); void setdimensionsIR(void); void setdimensionsABB(void); Pose FK(Joint j); Joint IK(Pose p, Joint jAct, bool bFrontBack, bool bUpDown); }; #endif
fa39ce02209d304ceddea462a6f9fac0808708c1
b1aa9ad6733efcb53d465809d5109e9174dabf04
/CCode/PluginCode/C4EditorManipulators.cpp
ad71c7658869893727aefdd24ff9601e34867872
[]
no_license
dumpinfo/GameMatrixTest
d21545dbef9ade76fe092343a8362da4c8b142ca
9e4a73ad17555ddb90020c47e2486698b90e4d0d
refs/heads/master
2023-02-04T01:52:05.342214
2020-12-23T17:22:36
2020-12-23T17:22:36
323,961,033
2
0
null
null
null
null
UTF-8
C++
false
false
48,594
cpp
C4EditorManipulators.cpp
//============================================================= // // C4 Engine version 4.5 // Copyright 1999-2015, by Terathon Software LLC // // This file is part of the C4 Engine and is provided under the // terms of the license agreement entered by the registed user. // // Unauthorized redistribution of source code is strictly // prohibited. Violators will be prosecuted. // //============================================================= #include "C4EditorManipulators.h" #include "C4GeometryManipulators.h" #include "C4CameraManipulators.h" #include "C4LightManipulators.h" #include "C4SourceManipulators.h" #include "C4ZoneManipulators.h" #include "C4PortalManipulators.h" #include "C4SpaceManipulators.h" #include "C4MarkerManipulators.h" #include "C4TriggerManipulators.h" #include "C4EffectManipulators.h" #include "C4EmitterManipulators.h" #include "C4InstanceManipulators.h" #include "C4ModelManipulators.h" #include "C4PhysicsManipulators.h" #include "C4TerrainTools.h" #include "C4WaterTools.h" #include "C4WorldEditor.h" #include "C4EditorSupport.h" #include "C4EditorGizmo.h" using namespace C4; namespace { const ConstColorRGBA kUnselectedMarkerColor = {0.5F, 0.5F, 0.5F, 1.0F}; } SharedVertexBuffer EditorManipulator::markerVertexBuffer(kVertexBufferAttribute | kVertexBufferStatic); SharedVertexBuffer EditorManipulator::boxVertexBuffer(kVertexBufferAttribute | kVertexBufferStatic); SharedVertexBuffer EditorManipulator::boxIndexBuffer(kVertexBufferIndex | kVertexBufferStatic); const ConstPoint3D EditorManipulator::manipulatorBoxPickEdge[12][2] = { {{0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}}, {{1.0F, 0.0F, 0.0F}, {1.0F, 1.0F, 0.0F}}, {{1.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}}, {{0.0F, 1.0F, 0.0F}, {0.0F, 0.0F, 0.0F}}, {{0.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}}, {{1.0F, 0.0F, 1.0F}, {1.0F, 1.0F, 1.0F}}, {{1.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}}, {{0.0F, 1.0F, 1.0F}, {0.0F, 0.0F, 1.0F}}, {{0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 1.0F}}, {{1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 1.0F}}, {{1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 1.0F}}, {{0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 1.0F}} }; const ConstPoint3D EditorManipulator::manipulatorBoxPosition[kManipulatorBoxVertexCount] = { {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {1.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 1.0F, 0.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {0.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 0.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F}, {0.0F, 1.0F, 1.0F} }; const ConstVector3D EditorManipulator::manipulatorBoxOffset[kManipulatorBoxVertexCount] = { {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F}, {-1.0F, -1.0F, -1.0F}, {1.0F, -1.0F, -1.0F}, {1.0F, 1.0F, -1.0F}, {-1.0F, 1.0F, -1.0F}, {-1.0F, -1.0F, 1.0F}, {1.0F, -1.0F, 1.0F}, {1.0F, 1.0F, 1.0F}, {-1.0F, 1.0F, 1.0F} }; const Triangle EditorManipulator::manipulatorBoxTriangle[kManipulatorBoxTriangleCount] = { {{ 1, 8, 5}}, {{ 5, 8, 12}}, {{ 5, 12, 6}}, {{ 6, 12, 15}}, {{ 6, 15, 2}}, {{ 2, 15, 11}}, {{ 2, 11, 1}}, {{ 1, 11, 8}}, {{10, 17, 14}}, {{14, 17, 21}}, {{14, 21, 15}}, {{15, 21, 20}}, {{15, 20, 11}}, {{11, 20, 16}}, {{11, 16, 10}}, {{10, 16, 17}}, {{19, 26, 23}}, {{23, 26, 30}}, {{23, 30, 20}}, {{20, 30, 29}}, {{20, 29, 16}}, {{16, 29, 25}}, {{16, 25, 19}}, {{19, 25, 26}}, {{24, 3, 28}}, {{28, 3, 7}}, {{28, 7, 29}}, {{29, 7, 6}}, {{29, 6, 25}}, {{25, 6, 2}}, {{25, 2, 24}}, {{24, 2, 3}}, {{33, 40, 37}}, {{37, 40, 44}}, {{37, 44, 38}}, {{38, 44, 47}}, {{38, 47, 34}}, {{34, 47, 43}}, {{34, 43, 33}}, {{33, 43, 40}}, {{42, 49, 46}}, {{46, 49, 53}}, {{46, 53, 47}}, {{47, 53, 52}}, {{47, 52, 43}}, {{43, 52, 48}}, {{43, 48, 42}}, {{42, 48, 49}}, {{51, 58, 55}}, {{55, 58, 62}}, {{55, 62, 52}}, {{52, 62, 61}}, {{52, 61, 48}}, {{48, 61, 57}}, {{48, 57, 51}}, {{51, 57, 58}}, {{56, 35, 60}}, {{60, 35, 39}}, {{60, 39, 61}}, {{61, 39, 38}}, {{61, 38, 57}}, {{57, 38, 34}}, {{57, 34, 56}}, {{56, 34, 35}}, {{ 6, 34, 5}}, {{ 5, 34, 33}}, {{ 5, 33, 4}}, {{ 4, 33, 32}}, {{ 4, 32, 7}}, {{ 7, 32, 35}}, {{ 7, 35, 6}}, {{ 6, 35, 34}}, {{14, 42, 13}}, {{13, 42, 41}}, {{13, 41, 12}}, {{12, 41, 40}}, {{12, 40, 15}}, {{15, 40, 43}}, {{15, 43, 14}}, {{14, 43, 42}}, {{22, 50, 21}}, {{21, 50, 49}}, {{21, 49, 20}}, {{20, 49, 48}}, {{20, 48, 23}}, {{23, 48, 51}}, {{23, 51, 22}}, {{22, 51, 50}}, {{30, 58, 29}}, {{29, 58, 57}}, {{29, 57, 28}}, {{28, 57, 56}}, {{28, 56, 31}}, {{31, 56, 59}}, {{31, 59, 30}}, {{30, 59, 58}}, {{ 0, 1, 4}}, {{ 1, 5, 4}}, {{ 3, 2, 0}}, {{ 2, 1, 0}}, {{ 3, 0, 7}}, {{ 0, 4, 7}}, {{ 9, 10, 13}}, {{10, 14, 13}}, {{ 8, 11, 9}}, {{11, 10, 9}}, {{ 8, 9, 12}}, {{ 9, 13, 12}}, {{18, 19, 22}}, {{19, 23, 22}}, {{17, 16, 18}}, {{16, 19, 18}}, {{17, 18, 21}}, {{18, 22, 21}}, {{27, 24, 31}}, {{24, 28, 31}}, {{26, 25, 27}}, {{25, 24, 27}}, {{26, 27, 30}}, {{27, 31, 30}}, {{32, 33, 36}}, {{33, 37, 36}}, {{39, 36, 38}}, {{38, 36, 37}}, {{35, 32, 39}}, {{32, 36, 39}}, {{41, 42, 45}}, {{42, 46, 45}}, {{44, 45, 47}}, {{47, 45, 46}}, {{40, 41, 44}}, {{41, 45, 44}}, {{50, 51, 54}}, {{51, 55, 54}}, {{53, 54, 52}}, {{52, 54, 55}}, {{49, 50, 53}}, {{50, 54, 53}}, {{59, 56, 63}}, {{56, 60, 63}}, {{62, 63, 61}}, {{61, 63, 60}}, {{58, 59, 62}}, {{59, 63, 62}} }; const TextureHeader EditorManipulator::outlineTextureHeader = { kTexture2D, kTextureForceHighQuality, kTextureSemanticEmission, kTextureSemanticTransparency, kTextureI8, 8, 1, 1, {kTextureClampBorder, kTextureRepeat, kTextureRepeat}, 4 }; const unsigned_int8 EditorManipulator::outlineTextureImage[15] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF }; ManipulatorWidget::ManipulatorWidget(EditorManipulator *manipulator) : RenderableWidget(kWidgetManipulator, kRenderQuads, Vector2D(kGraphBoxWidth, kGraphBoxHeight)), vertexBuffer(kVertexBufferAttribute | kVertexBufferDynamic), diffuseAttribute(K::black) { editorManipulator = manipulator; viewportScale = 1.0F; } ManipulatorWidget::~ManipulatorWidget() { } void ManipulatorWidget::Preprocess(void) { RenderableWidget::Preprocess(); SetVertexBuffer(kVertexBufferAttributeArray, &vertexBuffer, sizeof(Point2D)); SetVertexAttributeArray(kArrayPosition, 0, 2); vertexBuffer.Establish(sizeof(Point2D) * 28); attributeList.Append(&diffuseAttribute); SetMaterialAttributeList(&attributeList); } void ManipulatorWidget::Build(void) { volatile Point2D *restrict vertex = vertexBuffer.BeginUpdate<Point2D>(); float scale = viewportScale; vertex[0].Set(-scale, -scale); vertex[1].Set(-scale, 0.0F); vertex[2].Set(kGraphBoxWidth + scale, 0.0F); vertex[3].Set(kGraphBoxWidth + scale, -scale); vertex[4].Set(-scale, kGraphBoxHeight); vertex[5].Set(-scale, kGraphBoxHeight + scale); vertex[6].Set(kGraphBoxWidth + scale, kGraphBoxHeight + scale); vertex[7].Set(kGraphBoxWidth + scale, kGraphBoxHeight); vertex[8].Set(-scale, 0.0F); vertex[9].Set(-scale, kGraphBoxHeight); vertex[10].Set(0.0F, kGraphBoxHeight); vertex[11].Set(0.0F, 0.0F); vertex[12].Set(kGraphBoxWidth, 0.0F); vertex[13].Set(kGraphBoxWidth, kGraphBoxHeight); vertex[14].Set(kGraphBoxWidth + scale, kGraphBoxHeight); vertex[15].Set(kGraphBoxWidth + scale, 0.0F); int32 count = 16; const Node *node = editorManipulator->GetTargetNode(); if (node->GetFirstSubnode()) { count = 20; vertex[16].Set(kGraphBoxWidth + 1.0F, 7.0F); vertex[17].Set(kGraphBoxWidth + 1.0F, 7.0F + scale); vertex[18].Set(kGraphBoxWidth + 10.0F, 7.0F + scale); vertex[19].Set(kGraphBoxWidth + 10.0F, 7.0F); } if (node->GetSuperNode()) { const Node *previous = node->Previous(); if (previous) { vertex[count].Set(-14.0F, 7.0F); vertex[count + 1].Set(-14.0F, 7.0F + scale); vertex[count + 2].Set(-1.0F, 7.0F + scale); vertex[count + 3].Set(-1.0F, 7.0F); float h = static_cast<EditorManipulator *>(previous->GetManipulator())->GetGraphHeight(); float y = (previous->Previous()) ? 8.0F - h : 13.0F - h; vertex[count + 4].Set(-15.0F, y); vertex[count + 5].Set(-15.0F, 8.0F); vertex[count + 6].Set(scale - 15.0F, 8.0F); vertex[count + 7].Set(scale - 15.0F, y); count += 8; } else { vertex[count].Set(-9.0F, 7.0F); vertex[count + 1].Set(-9.0F, 7.0F + scale); vertex[count + 2].Set(-1.0F, 7.0F + scale); vertex[count + 3].Set(-1.0F, 7.0F); count += 4; } } SetVertexCount(count); vertexBuffer.EndUpdate(); } EditorManipulator::EditorManipulator(Node *node, const char *iconName) : Manipulator(node), markerColorAttribute(kUnselectedMarkerColor, kAttributeMutable), markerTextureAttribute("WorldEditor/marker"), markerRenderable(kRenderTriangleStrip, kRenderDepthTest | kRenderDepthInhibit), iconTextureAttribute(iconName), iconRenderable(kRenderTriangleStrip, kRenderDepthTest | kRenderDepthInhibit), handleVertexBuffer(kVertexBufferAttribute | kVertexBufferDynamic), handleRenderable(kRenderQuads), graphBackground(Vector2D(kGraphBoxWidth + 8.0F, kGraphBoxHeight + 8.0F), "WorldEditor/graph"), graphImage(Vector2D(16.0F, 16.0F)), graphText(Vector2D(kGraphBoxWidth - 21.0F, kGraphBoxHeight), nullptr, "font/Normal"), graphBorder(this), graphCollapseButton(Vector2D(13.0F, 13.0F), Point2D(0.5625F, 0.6875F), Point2D(0.6875F, 0.8125F)), graphCollapseObserver(this, &EditorManipulator::HandleGraphCollapseEvent) { manipulatorFlags = 0; worldEditor = nullptr; editorGizmo = nullptr; selectionType = kEditorSelectionObject; nodeSpherePointer = nullptr; treeSpherePointer = nullptr; handleCount = 0; connectorCount = 0; connectorStorage = nullptr; if (markerVertexBuffer.Retain() == 1) { static const MarkerVertex markerVertex[8] = { {Point2D(0.0F, 0.0F), Vector2D(-36.0F, -36.0F), Point2D(0.0F, 1.0F)}, {Point2D(0.0F, 0.0F), Vector2D(-36.0F, 12.0F), Point2D(0.0F, 0.0F)}, {Point2D(0.0F, 0.0F), Vector2D(12.0F, -36.0F), Point2D(1.0F, 1.0F)}, {Point2D(0.0F, 0.0F), Vector2D(12.0F, 12.0F), Point2D(1.0F, 0.0F)}, {Point2D(0.0F, 0.0F), Vector2D(-34.5F, -34.5F), Point2D(0.0F, 1.0F)}, {Point2D(0.0F, 0.0F), Vector2D(-34.5F, -13.5F), Point2D(0.0F, 0.0F)}, {Point2D(0.0F, 0.0F), Vector2D(-13.5F, -34.5F), Point2D(1.0F, 1.0F)}, {Point2D(0.0F, 0.0F), Vector2D(-13.5F, -13.5F), Point2D(1.0F, 0.0F)} }; markerVertexBuffer.Establish(sizeof(MarkerVertex) * 8, markerVertex); } markerRenderable.SetAmbientBlendState(kBlendInterpolate); markerRenderable.SetShaderFlags(kShaderAmbientEffect | kShaderVertexBillboard | kShaderScaleVertex); markerRenderable.SetRenderParameterPointer(&manipulatorScaleVector); markerRenderable.SetTransformable(node); markerRenderable.SetVertexCount(4); markerRenderable.SetVertexBuffer(kVertexBufferAttributeArray, &markerVertexBuffer, sizeof(MarkerVertex)); markerRenderable.SetVertexAttributeArray(kArrayPosition, 0, 2); markerRenderable.SetVertexAttributeArray(kArrayBillboard, sizeof(Point2D), 2); markerRenderable.SetVertexAttributeArray(kArrayTexcoord, sizeof(Point2D) * 2, 2); markerAttributeList.Append(&markerColorAttribute); markerAttributeList.Append(&markerTextureAttribute); markerRenderable.SetMaterialAttributeList(&markerAttributeList); iconRenderable.SetAmbientBlendState(kBlendInterpolate); iconRenderable.SetShaderFlags(kShaderAmbientEffect | kShaderVertexBillboard | kShaderScaleVertex); iconRenderable.SetRenderParameterPointer(&manipulatorScaleVector); iconRenderable.SetTransformable(node); iconRenderable.SetVertexCount(4); iconRenderable.SetVertexBuffer(kVertexBufferAttributeArray, &markerVertexBuffer, sizeof(MarkerVertex)); iconRenderable.SetVertexAttributeArray(kArrayPosition, sizeof(MarkerVertex) * 4, 2); iconRenderable.SetVertexAttributeArray(kArrayBillboard, sizeof(MarkerVertex) * 4 + sizeof(Point2D), 2); iconRenderable.SetVertexAttributeArray(kArrayTexcoord, sizeof(MarkerVertex) * 4 + sizeof(Point2D) * 2, 2); iconAttributeList.Append(&iconTextureAttribute); iconRenderable.SetMaterialAttributeList(&iconAttributeList); handleRenderable.SetAmbientBlendState(kBlendInterpolate); handleRenderable.SetShaderFlags(kShaderAmbientEffect | kShaderVertexBillboard | kShaderScaleVertex); handleRenderable.SetRenderParameterPointer(&manipulatorScaleVector); handleRenderable.SetTransformable(node); handleRenderable.SetVertexBuffer(kVertexBufferAttributeArray, &handleVertexBuffer, sizeof(HandleVertex)); handleRenderable.SetVertexAttributeArray(kArrayPosition, 0, 3); handleRenderable.SetVertexAttributeArray(kArrayBillboard, sizeof(Point3D), 2); graphBackground.SetQuadOffset(Vector2D(-4.0F, -1.0F)); graphText.SetWidgetPosition(Point3D(21.0F, 2.0F, 0.0F)); graphText.SetTextFlags(kTextUnformatted | kTextClipped); graphCollapseButton.SetWidgetPosition(Point3D(120.0F, 2.0F, 0.0F)); graphCollapseButton.SetWidgetColor(ColorRGBA(1.0F, 1.0F, 0.5F, 1.0F)); graphCollapseButton.SetObserver(&graphCollapseObserver); graphBackground.AppendSubnode(&graphImage); graphBackground.AppendSubnode(&graphText); graphBackground.AppendSubnode(&graphBorder); graphBackground.AppendSubnode(&graphCollapseButton); graphBackground.Preprocess(); } EditorManipulator::~EditorManipulator() { ReleaseConnectorStorage(); delete editorGizmo; markerVertexBuffer.Release(); } Manipulator *EditorManipulator::Create(Node *node, unsigned_int32 flags) { switch (node->GetNodeType()) { case kNodeGeneric: return (new GroupManipulator(node)); case kNodeCamera: return (CameraManipulator::Create(static_cast<Camera *>(node))); case kNodeLight: return (LightManipulator::Create(static_cast<Light *>(node))); case kNodeSource: return (SourceManipulator::Create(static_cast<Source *>(node))); case kNodeGeometry: return (GeometryManipulator::Create(static_cast<Geometry *>(node))); case kNodeInstance: return (new InstanceManipulator(static_cast<Instance *>(node))); case kNodeModel: return (new ModelManipulator(static_cast<Model *>(node))); case kNodeBone: return (new BoneManipulator(static_cast<Bone *>(node))); case kNodeMarker: return (MarkerManipulator::Create(static_cast<Marker *>(node))); case kNodeTrigger: return (TriggerManipulator::Create(static_cast<Trigger *>(node))); case kNodeEffect: return (EffectManipulator::Create(static_cast<Effect *>(node))); case kNodeEmitter: return (EmitterManipulator::Create(static_cast<Emitter *>(node))); case kNodeSpace: return (SpaceManipulator::Create(static_cast<Space *>(node))); case kNodePortal: return (PortalManipulator::Create(static_cast<Portal *>(node))); case kNodeZone: return (ZoneManipulator::Create(static_cast<Zone *>(node))); case kNodeShape: return (ShapeManipulator::Create(static_cast<Shape *>(node))); case kNodeJoint: return (JointManipulator::Create(static_cast<Joint *>(node))); case kNodeField: return (FieldManipulator::Create(static_cast<Field *>(node))); case kNodeBlocker: return (BlockerManipulator::Create(static_cast<Blocker *>(node))); case kNodePhysics: return (new PhysicsNodeManipulator(static_cast<PhysicsNode *>(node))); case kNodeSkybox: return (new SkyboxManipulator(static_cast<Skybox *>(node))); case kNodeImpostor: return (new ImpostorManipulator(static_cast<Impostor *>(node))); case kNodeTerrainBlock: return (new TerrainBlockManipulator(static_cast<TerrainBlock *>(node))); case kNodeWaterBlock: return (new WaterBlockManipulator(static_cast<WaterBlock *>(node))); } return (nullptr); } void EditorManipulator::Pack(Packer& data, unsigned_int32 packFlags) const { Manipulator::Pack(data, packFlags); if (graphCollapseButton.GetWidgetState() & kWidgetCollapsed) { data << ChunkHeader('CLPS', 0); } data << TerminatorChunk; } void EditorManipulator::Unpack(Unpacker& data, unsigned_int32 unpackFlags) { Manipulator::Unpack(data, unpackFlags); UnpackChunkList<EditorManipulator>(data, unpackFlags); } bool EditorManipulator::UnpackChunk(const ChunkHeader *chunkHeader, Unpacker& data, unsigned_int32 unpackFlags) { switch (chunkHeader->chunkType) { case 'CLPS': graphCollapseButton.SetWidgetState(graphCollapseButton.GetWidgetState() | kWidgetCollapsed); return (true); } return (false); } const char *EditorManipulator::GetDefaultNodeName(void) const { return (TheWorldEditor->GetStringTable()->GetString(StringID('NAME', 'NODE'))); } void EditorManipulator::Preprocess(void) { Manipulator::Preprocess(); AllocateConnectorStorage(); UpdateGraphColor(); graphImage.SetTexture(0, GetIconName()); if (GetTargetNode()->GetNodeFlags() & kNodeNonpersistent) { SetManipulatorState(GetManipulatorState() & ~kManipulatorShowIcon); } } void EditorManipulator::Invalidate(void) { EditorManipulator *manipulator = this; for (;;) { manipulator->SetManipulatorState(manipulator->GetManipulatorState() & ~kManipulatorUpdated); Node *super = manipulator->GetTargetNode()->GetSuperNode(); if (!super) { break; } manipulator = static_cast<EditorManipulator *>(super->GetManipulator()); if ((!manipulator) || (!(manipulator->GetManipulatorState() & kManipulatorUpdated))) { break; } } if (GetManipulatorState() & kManipulatorShowGizmo) { worldEditor->PostEvent(GizmoEditorEvent(kEditorEventGizmoTargetInvalidated, GetTargetNode())); } } void EditorManipulator::InvalidateGraph(void) { unsigned_int32 state = GetManipulatorState(); if (state & kManipulatorGraphValid) { SetManipulatorState(state & ~kManipulatorGraphValid); InvalidateGraphTree(); } Node *node = GetTargetNode(); for (;;) { Node *previous = node->Previous(); if (previous) { EditorManipulator *manipulator = static_cast<EditorManipulator *>(previous->GetManipulator()); state = manipulator->GetManipulatorState(); if (state & kManipulatorGraphValid) { manipulator->SetManipulatorState(state & ~kManipulatorGraphValid); manipulator->InvalidateGraphTree(); } } Node *next = node->Next(); while (next) { EditorManipulator *manipulator = static_cast<EditorManipulator *>(next->GetManipulator()); state = manipulator->GetManipulatorState(); if (!(state & kManipulatorGraphValid)) { break; } manipulator->SetManipulatorState(state & ~kManipulatorGraphValid); manipulator->InvalidateGraphTree(); next = next->Next(); } node = node->GetSuperNode(); if (!node) { break; } EditorManipulator *manipulator = static_cast<EditorManipulator *>(node->GetManipulator()); manipulator->SetManipulatorState(manipulator->GetManipulatorState() & ~kManipulatorGraphValid); manipulator->graphBackground.Invalidate(); } } void EditorManipulator::InvalidateGraphTree(void) { graphBackground.Invalidate(); Node *subnode = GetTargetNode()->GetFirstSubnode(); while (subnode) { EditorManipulator *manipulator = static_cast<EditorManipulator *>(subnode->GetManipulator()); unsigned_int32 state = manipulator->GetManipulatorState(); if (state & kManipulatorGraphValid) { manipulator->SetManipulatorState(state & ~kManipulatorGraphValid); manipulator->InvalidateGraphTree(); } subnode = subnode->Next(); } } void EditorManipulator::InvalidateNode(void) { GetTargetNode()->Invalidate(); } void EditorManipulator::EnableGizmo(void) { SetManipulatorState(GetManipulatorState() | kManipulatorShowGizmo); if (!editorGizmo) { editorGizmo = new EditorGizmo(worldEditor, this); } } void EditorManipulator::DisableGizmo(void) { SetManipulatorState(GetManipulatorState() & ~kManipulatorShowGizmo); delete editorGizmo; editorGizmo = nullptr; } void EditorManipulator::Update(void) { unsigned_int32 state = GetManipulatorState(); if (!(state & kManipulatorUpdated)) { SetManipulatorState(state | kManipulatorUpdated); const Node *node = GetTargetNode(); const Node *subnode = node->GetFirstSubnode(); while (subnode) { EditorManipulator *manipulator = static_cast<EditorManipulator *>(subnode->GetManipulator()); manipulator->Update(); subnode = subnode->Next(); } nodeSpherePointer = nullptr; treeSpherePointer = nullptr; bool icon = ((state & kManipulatorShowIcon) != 0); if (CalculateNodeSphere(&nodeSphere)) { nodeSphere.SetCenter(node->GetWorldTransform() * nodeSphere.GetCenter()); nodeSpherePointer = &nodeSphere; if (icon) { BoundingSphere sphere(node->GetWorldPosition(), Editor::kFrustumRenderScale * 12.0F); nodeSphere.Union(&sphere); } treeSphere = nodeSphere; treeSpherePointer = &treeSphere; } else if (icon) { nodeSphere.SetCenter(node->GetWorldPosition()); nodeSphere.SetRadius(Editor::kFrustumRenderScale * 12.0F); nodeSpherePointer = &nodeSphere; treeSphere = nodeSphere; treeSpherePointer = &treeSphere; } else { nodeSphere.SetCenter(node->GetWorldPosition()); nodeSphere.SetRadius(Editor::kFrustumRenderScale); nodeSpherePointer = &nodeSphere; treeSphere = nodeSphere; treeSpherePointer = &treeSphere; } int32 count = GetHandleTable(handlePosition); handleCount = count; handleRenderable.InvalidateVertexData(); handleRenderable.SetVertexCount(count * 4); handleVertexBuffer.Establish(count * (sizeof(HandleVertex) * 4)); if (count != 0) { volatile HandleVertex *restrict vertex = handleVertexBuffer.BeginUpdate<HandleVertex>(); for (machine a = 0; a < count; a++) { const Point3D& p = handlePosition[a]; vertex[0].position = p; vertex[0].billboard.Set(-3.0F, -3.0F); vertex[1].position = p; vertex[1].billboard.Set(-3.0F, 3.0F); vertex[2].position = p; vertex[2].billboard.Set(3.0F, 3.0F); vertex[3].position = p; vertex[3].billboard.Set(3.0F, -3.0F); vertex += 4; } handleVertexBuffer.EndUpdate(); } subnode = GetTargetNode()->GetFirstSubnode(); while (subnode) { EditorManipulator *manipulator = static_cast<EditorManipulator *>(subnode->GetManipulator()); const BoundingSphere *sphere = manipulator->GetTreeSphere(); if (sphere) { if (treeSpherePointer) { treeSphere.Union(sphere); } else { treeSphere = *sphere; nodeSpherePointer = &treeSphere; treeSpherePointer = &treeSphere; } } subnode = subnode->Next(); } } } void EditorManipulator::UpdateGraph(void) { unsigned_int32 state = GetManipulatorState(); if (!(state & kManipulatorGraphValid)) { SetManipulatorState(state | kManipulatorGraphValid); const Node *node = GetTargetNode(); const Node *previous = node->Previous(); if (previous) { const EditorManipulator *manipulator = static_cast<EditorManipulator *>(previous->GetManipulator()); const Point3D& position = manipulator->GetGraphPosition(); graphBackground.SetWidgetPosition(Point3D(position.x, position.y + manipulator->GetGraphHeight(), 0.0F)); } else { const Node *super = node->GetSuperNode(); if (super) { const EditorManipulator *manipulator = static_cast<EditorManipulator *>(super->GetManipulator()); const Point3D& position = manipulator->GetGraphPosition(); graphBackground.SetWidgetPosition(Point3D(position.x + kGraphBoxWidth + 29.0F, position.y, 0.0F)); } else { graphBackground.SetWidgetPosition(Point3D(0.0F, 0.0F, 0.0F)); } } const char *name = node->GetNodeName(); graphText.SetText((name) ? name : GetDefaultNodeName()); const Node *subnode = node->GetFirstSubnode(); if (subnode) { float width = 0.0F; float height = 0.0F; do { EditorManipulator *manipulator = static_cast<EditorManipulator *>(subnode->GetManipulator()); manipulator->UpdateGraph(); width = Fmax(width, manipulator->GetGraphWidth()); height += manipulator->GetGraphHeight(); subnode = subnode->Next(); } while (subnode); if (!(graphCollapseButton.GetWidgetState() & kWidgetCollapsed)) { graphWidth = width + kGraphBoxWidth + 29.0F; graphHeight = height; } else { graphWidth = kGraphBoxWidth + 29.0F; graphHeight = kGraphBoxHeight + 12.0F; } graphCollapseButton.Show(); } else { graphWidth = kGraphBoxWidth; const Node *next = node->Next(); if ((next) && (!next->GetFirstSubnode())) { graphHeight = kGraphBoxHeight + 8.0F; } else { graphHeight = kGraphBoxHeight + 12.0F; } graphCollapseButton.Hide(); } graphBackground.Update(); } } void EditorManipulator::UpdateGraphColor(void) { if (!(GetTargetNode()->GetNodeFlags() & kNodeNonpersistent)) { if (!Selected()) { if (!Hidden()) { graphBackground.SetWidgetColor(ColorRGBA(1.0F, 1.0F, 1.0F, 1.0F)); } else { graphBackground.SetWidgetColor(ColorRGBA(0.5F, 0.5F, 0.5F, 1.0F)); } } else { graphBackground.SetWidgetColor(TheInterfaceMgr->GetInterfaceColor(kInterfaceColorHilite)); } } else { graphBackground.SetWidgetColor(ColorRGBA(1.0F, 0.5F, 0.5F, 1.0F)); } } void EditorManipulator::HandleGraphCollapseEvent(Widget *widget, const WidgetEventData *eventData) { if (eventData->eventType == kEventWidgetActivate) { InvalidateGraph(); widget->SetWidgetState(widget->GetWidgetState() ^ kWidgetCollapsed); } } bool EditorManipulator::CalculateNodeSphere(BoundingSphere *sphere) const { if (!GetTargetNode()->CalculateBoundingSphere(sphere)) { sphere->SetCenter(Zero3D); sphere->SetRadius(0.0F); } return (true); } bool EditorManipulator::PickLineSegment(const Ray *ray, const Point3D& p1, const Point3D& p2, float r2, float *param) { float u1, u2; Vector3D dp = p2 - p1; if (Math::CalculateNearestParameters(ray->origin, ray->direction, p1, dp, &u1, &u2)) { if ((u1 > ray->tmin) && (u1 < ray->tmax) && (u2 > 0.0F) && (u2 < 1.0F)) { if (SquaredMag(ray->origin + ray->direction * u1 - p1 - dp * u2) < r2) { *param = u1; return (true); } } } return (false); } bool EditorManipulator::RegionPickLineSegment(const VisibilityRegion *region, const Point3D& p1, const Point3D& p2) const { const Transform4D& worldTransform = GetTargetNode()->GetWorldTransform(); return (region->CylinderVisible(worldTransform * p1, worldTransform * p2, 0.0F)); } void EditorManipulator::Show(void) { SetManipulatorState(GetManipulatorState() & ~kManipulatorHidden); UpdateGraphColor(); } void EditorManipulator::Hide(void) { SetManipulatorState(GetManipulatorState() | kManipulatorHidden); UpdateGraphColor(); } bool EditorManipulator::PredecessorSelected(void) const { const Node *node = GetTargetNode(); for (;;) { node = node->GetSuperNode(); if (!node) { break; } if (node->GetManipulator()->Selected()) { return (true); } } return (false); } void EditorManipulator::Select(void) { SetManipulatorState(GetManipulatorState() | kManipulatorSelected); selectionType = kEditorSelectionObject; markerColorAttribute.SetDiffuseColor(K::white); Show(); } void EditorManipulator::Unselect(void) { SetManipulatorState(GetManipulatorState() & ~(kManipulatorSelected | kManipulatorTempSelected)); selectionType = kEditorSelectionObject; markerColorAttribute.SetDiffuseColor(kUnselectedMarkerColor); UpdateGraphColor(); } void EditorManipulator::Hilite(void) { SetManipulatorState(GetManipulatorState() | kManipulatorHilited); } void EditorManipulator::Unhilite(void) { SetManipulatorState(GetManipulatorState() & ~kManipulatorHilited); } void EditorManipulator::HandleDelete(bool undoable) { SetManipulatorState(GetManipulatorState() | kManipulatorDeleted); UnselectConnector(); } void EditorManipulator::HandleUndelete(void) { SetManipulatorState(GetManipulatorState() & ~kManipulatorDeleted); } void EditorManipulator::HandleSizeUpdate(int32 count, const float *size) { Node *node = GetTargetNode(); Object *object = node->GetObject(); if (object) { float objectSize[kMaxObjectSizeCount]; for (machine a = 0; a < count; a++) { objectSize[a] = Fmax(size[a], kSizeEpsilon); } object->SetObjectSize(objectSize); worldEditor->InvalidateNode(node); } } void EditorManipulator::HandleSettingsUpdate(void) { GetTargetNode()->Invalidate(); InvalidateGraph(); } void EditorManipulator::HandleConnectorUpdate(void) { GetTargetNode()->ProcessInternalConnectors(); } bool EditorManipulator::MaterialSettable(void) const { return (false); } bool EditorManipulator::MaterialRemovable(void) const { return (false); } int32 EditorManipulator::GetMaterialCount(void) const { return (0); } MaterialObject *EditorManipulator::GetMaterial(int32 index) const { return (nullptr); } void EditorManipulator::SetMaterial(MaterialObject *material) { } void EditorManipulator::ReplaceMaterial(MaterialObject *oldMaterial, MaterialObject *newMaterial) { } void EditorManipulator::RemoveMaterial(void) { } void EditorManipulator::InvalidateShaderData(void) { } bool EditorManipulator::ReparentedSubnodesAllowed(void) const { return ((GetTargetNode()->GetNodeFlags() & kNodeNonpersistent) == 0); } Box3D EditorManipulator::CalculateNodeBoundingBox(void) const { return (Box3D(Zero3D, Zero3D)); } Box3D EditorManipulator::CalculateWorldBoundingBox(void) const { return (Transform(CalculateNodeBoundingBox(), GetTargetNode()->GetWorldTransform())); } void EditorManipulator::AdjustBoundingBox(Box3D *box) { Vector3D size = box->GetSize(); if (size.x < 0.25F) { float x = (box->min.x + box->max.x) * 0.5F; box->min.x = x - 0.125F; box->max.x = x + 0.125F; } if (size.y < 0.25F) { float y = (box->min.y + box->max.y) * 0.5F; box->min.y = y - 0.125F; box->max.y = y + 0.125F; } if (size.z < 0.25F) { float z = (box->min.z + box->max.z) * 0.5F; box->min.z = z - 0.125F; box->max.z = z + 0.125F; } float expand = Fmax(size.x, size.y, size.z) * 0.03125F; box->min -= Vector3D(expand, expand, expand); box->max += Vector3D(expand, expand, expand); } bool EditorManipulator::Pick(const Ray *ray, PickData *data) const { if (GetManipulatorState() & kManipulatorShowIcon) { float t2; float r = ray->radius * 11.0F; if (r == 0.0F) { r = Editor::kFrustumRenderScale * 12.0F; } return (Math::IntersectRayAndSphere(ray, Zero3D, r, &data->rayParam, &t2)); } return (false); } bool EditorManipulator::RegionPick(const VisibilityRegion *region) const { return (region->SphereVisible(GetTargetNode()->GetWorldPosition(), 0.0F)); } void EditorManipulator::BeginTransform(void) { } void EditorManipulator::EndTransform(void) { } int32 EditorManipulator::GetHandleTable(Point3D *handle) const { return (0); } void EditorManipulator::GetHandleData(int32 index, ManipulatorHandleData *handleData) const { handleData->handleFlags = 0; handleData->oppositeIndex = kHandleOrigin; } void EditorManipulator::BeginResize(const ManipulatorResizeData *resizeData) { const Node *node = GetTargetNode(); const Object *object = node->GetObject(); if (object) { object->GetObjectSize(originalSize); } originalPosition = node->GetNodePosition(); } void EditorManipulator::EndResize(const ManipulatorResizeData *resizeData) { } bool EditorManipulator::Resize(const ManipulatorResizeData *resizeData) { return (false); } SharedVertexBuffer *EditorManipulator::RetainBoxVertexBuffer(void) { if (boxVertexBuffer.Retain() == 1) { boxVertexBuffer.Establish(sizeof(BoxVertex) * kManipulatorBoxVertexCount); volatile BoxVertex *restrict vertex = boxVertexBuffer.BeginUpdate<BoxVertex>(); const Point3D *position = &manipulatorBoxPosition[0]; const Vector3D *offset = &manipulatorBoxOffset[0]; for (machine a = 0; a < kManipulatorBoxVertexCount; a++) { vertex[a].position = position[a]; vertex[a].offset = offset[a]; } boxVertexBuffer.EndUpdate(); } return (&boxVertexBuffer); } SharedVertexBuffer *EditorManipulator::RetainBoxIndexBuffer(void) { if (boxIndexBuffer.Retain() == 1) { boxIndexBuffer.Establish(sizeof(Triangle) * kManipulatorBoxTriangleCount, manipulatorBoxTriangle); } return (&boxIndexBuffer); } void EditorManipulator::ReleaseBoxVertexBuffer(void) { boxVertexBuffer.Release(); } void EditorManipulator::ReleaseBoxIndexBuffer(void) { boxIndexBuffer.Release(); } void EditorManipulator::AllocateConnectorStorage(void) { ReleaseConnectorStorage(); connectorCount = 0; const Hub *hub = GetTargetNode()->GetHub(); if (hub) { int32 count = hub->GetOutgoingEdgeCount(); connectorCount = count; if (count != 0) { connectorStorage = new char[sizeof(EditorConnector) * count]; editorConnector = reinterpret_cast<EditorConnector *>(connectorStorage); Connector *connector = hub->GetFirstOutgoingEdge(); for (machine a = 0; a < count; a++) { new(&editorConnector[a]) EditorConnector(this, connector, a); connector = connector->GetNextOutgoingEdge(); } } } } void EditorManipulator::ReleaseConnectorStorage(void) { if (connectorStorage) { for (machine index = connectorCount - 1; index >= 0; index--) { editorConnector[index].~EditorConnector(); } delete[] connectorStorage; connectorStorage = nullptr; } } void EditorManipulator::UpdateConnectors(void) { AllocateConnectorStorage(); SetManipulatorState(GetManipulatorState() & ~kManipulatorConnectorSelected); Detach(); } void EditorManipulator::SelectConnector(int32 index, bool toggle) { unsigned_int32 state = GetManipulatorState(); if (state & kManipulatorConnectorSelected) { if (connectorSelection == index) { if (toggle) { editorConnector[index].Unselect(); SetManipulatorState(state & ~kManipulatorConnectorSelected); } return; } editorConnector[connectorSelection].Unselect(); } else { SetManipulatorState(state | kManipulatorConnectorSelected); } connectorSelection = index; editorConnector[index].Select(); } void EditorManipulator::UnselectConnector(void) { unsigned_int32 state = GetManipulatorState(); if (state & kManipulatorConnectorSelected) { SetManipulatorState(state & ~kManipulatorConnectorSelected); editorConnector[connectorSelection].Unselect(); Detach(); } } bool EditorManipulator::SetConnectorTarget(int32 index, Node *target, const ConnectorKey **key) { Node *node = GetTargetNode(); const Hub *hub = node->GetHub(); if (hub) { Connector *connector = hub->GetOutgoingEdge(index); if (connector) { const ConnectorKey& connectorKey = connector->GetConnectorKey(); if (target) { if (node->ValidConnectedNode(connectorKey, target)) { connector->SetConnectorTarget(target); if (key) { *key = &connectorKey; } HandleConnectorUpdate(); return (true); } } else { connector->SetConnectorTarget(nullptr); if (key) { *key = &connectorKey; } HandleConnectorUpdate(); return (true); } } } return (false); } bool EditorManipulator::PickConnector(const ManipulatorViewportData *viewportData, const Ray *ray, PickData *pickData) const { int32 count = connectorCount; for (machine a = count - 1; a >= 0; a--) { if (editorConnector[a].Pick(viewportData, ray)) { pickData->pickIndex[0] = a; return (true); } } return (false); } Box2D EditorManipulator::GetGraphBox(void) const { const Point2D& p = GetGraphPosition().GetPoint2D(); return (Box2D(p, Point2D(p.x + kGraphBoxWidth, p.y + 16.0F))); } void EditorManipulator::ExpandSubgraph(void) { unsigned_int32 state = graphCollapseButton.GetWidgetState(); if (state & kWidgetCollapsed) { InvalidateGraph(); graphCollapseButton.SetWidgetState(state & ~kWidgetCollapsed); } } void EditorManipulator::CollapseSubgraph(void) { unsigned_int32 state = graphCollapseButton.GetWidgetState(); if (!(state & kWidgetCollapsed)) { InvalidateGraph(); graphCollapseButton.SetWidgetState(state | kWidgetCollapsed); } } Node *EditorManipulator::PickGraphNode(const ManipulatorViewportData *viewportData, const Ray *ray, Widget **widget) { const Point3D& position = GetGraphPosition(); float x = ray->origin.x - position.x; float y = ray->origin.y - position.y; if ((y > -1.0F) && (y < graphHeight) && (x > -1.0F) && (x < graphWidth + 29.0F)) { Node *node = GetTargetNode(); if ((x > -1.0F) && (x < kGraphBoxWidth + 1.0F) && (y < 17.0F)) { while (node->GetNodeFlags() & kNodeNonpersistent) { node = node->GetSuperNode(); } return (node); } if (widget) { if ((graphCollapseButton.Visible()) && (graphCollapseButton.GetBoundingBox()->Contains(ray->origin.GetPoint2D()))) { *widget = &graphCollapseButton; return (nullptr); } } const Node *subnode = node->GetFirstSubnode(); while (subnode) { Node *pick = static_cast<EditorManipulator *>(subnode->GetManipulator())->PickGraphNode(viewportData, ray, widget); if (pick) { return (pick); } subnode = subnode->Next(); } } return (nullptr); } void EditorManipulator::SelectGraphNodes(float left, float right, float top, float bottom, bool temp) { const Point3D& position = GetGraphPosition(); if ((position.y < bottom) && (position.y + graphHeight > top) && (position.x < right) && (position.x + graphWidth > left)) { Node *node = GetTargetNode(); if ((position.x + kGraphBoxWidth > left) && (position.y + 16.0F > top)) { if (!Selected()) { worldEditor->SelectNode(node); if (temp) { SetManipulatorState(GetManipulatorState() | kManipulatorTempSelected); } } } unsigned_int32 state = graphCollapseButton.GetWidgetState(); if (!(state & kWidgetCollapsed)) { const Node *subnode = node->GetFirstSubnode(); while (subnode) { static_cast<EditorManipulator *>(subnode->GetManipulator())->SelectGraphNodes(left, right, top, bottom, temp); subnode = subnode->Next(); } } } } void EditorManipulator::HiliteSubtree(void) { Node *root = GetTargetNode(); Node *node = root->GetFirstSubnode(); while (node) { Editor::GetManipulator(node)->Hilite(); node = root->GetNextNode(node); } } void EditorManipulator::UnhiliteSubtree(void) { Node *root = GetTargetNode(); Node *node = root->GetFirstSubnode(); while (node) { Editor::GetManipulator(node)->Unhilite(); node = root->GetNextNode(node); } } void EditorManipulator::Render(const ManipulatorRenderData *renderData) { float scale = renderData->viewportScale; manipulatorScaleVector.Set(scale, scale, scale, scale); unsigned_int32 state = GetManipulatorState(); bool showConnectors = ((renderData->connectorList) && (state & (kManipulatorSelected | kManipulatorConnectorSelected)) && (connectorCount != 0)); if ((state & kManipulatorShowIcon) || (showConnectors)) { List<Renderable> *renderList = renderData->manipulatorList; if (renderList) { renderList->Append(&markerRenderable); renderList->Append(&iconRenderable); } } if (state & kManipulatorSelected) { List<Renderable> *renderList = renderData->handleList; if ((renderList) && (handleCount != 0)) { renderList->Append(&handleRenderable); } } if (showConnectors) { List<Renderable> *renderList = renderData->connectorList; for (machine a = 0; a < connectorCount; a++) { editorConnector[a].RenderLine(renderData, renderList); } for (machine a = 0; a < connectorCount; a++) { editorConnector[a].RenderBox(renderData, renderList); } } } void EditorManipulator::RenderGraph(const ManipulatorViewportData *viewportData, List<Renderable> *renderList) { const Node *node = GetTargetNode(); const Node *previous = node->Previous(); const Point3D& cameraPosition = viewportData->viewportCamera->GetNodePosition(); const Vector3D& position = GetGraphPosition() - cameraPosition; float left = position.x - 29.0F; float right = position.x + graphWidth; float top = (previous) ? Editor::GetManipulator(previous)->GetGraphPosition().y - cameraPosition.y : position.y - 1.0F; float bottom = position.y + graphHeight; const OrthoCameraObject *cameraObject = static_cast<OrthoCamera *>(viewportData->viewportCamera)->GetObject(); if ((top < cameraObject->GetOrthoRectBottom()) && (bottom > cameraObject->GetOrthoRectTop()) && (left < cameraObject->GetOrthoRectRight()) && (right > cameraObject->GetOrthoRectLeft())) { graphBorder.SetViewportScale(viewportData->viewportScale); graphBackground.RenderTree(renderList); if (!(graphCollapseButton.GetWidgetState() & kWidgetCollapsed)) { const Node *subnode = node->GetFirstSubnode(); while (subnode) { static_cast<EditorManipulator *>(subnode->GetManipulator())->RenderGraph(viewportData, renderList); subnode = subnode->Next(); } } } } void EditorManipulator::Install(Editor *editor, Node *root, bool recursive) { EditorManipulator *manipulator = Editor::GetManipulator(root); if (!manipulator) { manipulator = static_cast<EditorManipulator *>(Manipulator::Create(root)); if (!manipulator) { manipulator = new EditorManipulator(root, "WorldEditor/node/Node"); } root->SetManipulator(manipulator); manipulator->Invalidate(); } else { manipulator->SetManipulatorState(manipulator->GetManipulatorState() & ~kManipulatorSelected); } manipulator->worldEditor = editor; if (recursive) { Node *node = root->GetFirstSubnode(); while (node) { Install(editor, node); node = node->Next(); } } } GroupManipulator::GroupManipulator(Node *node) : EditorManipulator(node, "WorldEditor/node/Group") { } GroupManipulator::~GroupManipulator() { } const char *GroupManipulator::GetDefaultNodeName(void) const { return (TheWorldEditor->GetStringTable()->GetString(StringID('NAME', kNodeGeneric))); } void GroupManipulator::Preprocess(void) { SetManipulatorState(GetManipulatorState() | kManipulatorShowIcon); EditorManipulator::Preprocess(); } SkyboxManipulator::SkyboxManipulator(Skybox *skybox) : EditorManipulator(skybox, "WorldEditor/atmosphere/Skybox") { } SkyboxManipulator::~SkyboxManipulator() { } const char *SkyboxManipulator::GetDefaultNodeName(void) const { return (TheWorldEditor->GetStringTable()->GetString(StringID('NAME', kNodeSkybox))); } void SkyboxManipulator::Preprocess(void) { SetManipulatorState(GetManipulatorState() | kManipulatorShowIcon); EditorManipulator::Preprocess(); GetEditor()->SetProcessPropertiesFlag(); } void SkyboxManipulator::HandleDelete(bool undoable) { EditorManipulator::HandleDelete(undoable); GetEditor()->SetProcessPropertiesFlag(); } void SkyboxManipulator::HandleUndelete(void) { EditorManipulator::HandleUndelete(); GetEditor()->SetProcessPropertiesFlag(); } void SkyboxManipulator::HandleSettingsUpdate(void) { EditorManipulator::HandleSettingsUpdate(); GetTargetNode()->InvalidateShaderData(); } bool SkyboxManipulator::MaterialSettable(void) const { return (true); } bool SkyboxManipulator::MaterialRemovable(void) const { return (true); } int32 SkyboxManipulator::GetMaterialCount(void) const { return (1); } MaterialObject *SkyboxManipulator::GetMaterial(int32 index) const { return (GetTargetNode()->GetMaterialObject()); } void SkyboxManipulator::SetMaterial(MaterialObject *material) { Skybox *skybox = GetTargetNode(); skybox->SetMaterialObject(material); skybox->InvalidateShaderData(); } void SkyboxManipulator::ReplaceMaterial(MaterialObject *oldMaterial, MaterialObject *newMaterial) { Skybox *skybox = GetTargetNode(); if (skybox->GetMaterialObject() == oldMaterial) { skybox->SetMaterialObject(newMaterial); skybox->InvalidateShaderData(); } } void SkyboxManipulator::RemoveMaterial(void) { Skybox *skybox = GetTargetNode(); skybox->SetMaterialObject(nullptr); skybox->InvalidateShaderData(); } void SkyboxManipulator::InvalidateShaderData(void) { GetTargetNode()->InvalidateShaderData(); } ImpostorManipulator::ImpostorManipulator(Impostor *impostor) : EditorManipulator(impostor, "WorldEditor/impostor/Impostor") { } ImpostorManipulator::~ImpostorManipulator() { } const char *ImpostorManipulator::GetDefaultNodeName(void) const { return (TheWorldEditor->GetStringTable()->GetString(StringID('NAME', kNodeImpostor))); } void ImpostorManipulator::Preprocess(void) { SetManipulatorState(GetManipulatorState() | kManipulatorShowIcon); EditorManipulator::Preprocess(); } bool ImpostorManipulator::MaterialSettable(void) const { return (true); } int32 ImpostorManipulator::GetMaterialCount(void) const { return (1); } MaterialObject *ImpostorManipulator::GetMaterial(int32 index) const { return (GetTargetNode()->GetMaterialObject()); } void ImpostorManipulator::SetMaterial(MaterialObject *material) { Impostor *impostor = GetTargetNode(); impostor->SetMaterialObject(material); } void ImpostorManipulator::ReplaceMaterial(MaterialObject *oldMaterial, MaterialObject *newMaterial) { Impostor *impostor = GetTargetNode(); if (impostor->GetMaterialObject() == oldMaterial) { impostor->SetMaterialObject(newMaterial); } } // ZYUQURM
bdb06b004f4a4d491f3fa3eced7e8c3a3c6cc8bc
9144ea02a3bf4197f45f6034f2b0ee8efa7da200
/src/interface/ipmCamCalibParamParser.cpp
7f643e8adfa2fb027f5fe1c35ee96075c1f563e9
[ "MIT" ]
permissive
fengtanshou/Easy-Ipm-Client
adbe78d566309f5e198d65c2e3bb7b8c802ddced
ca8039a67423d5119704bb01a58e43491f92ddfb
refs/heads/master
2021-03-15T15:15:42.663067
2019-11-26T14:04:47
2019-11-26T14:04:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
ipmCamCalibParamParser.cpp
/************************************************ * Copyright 2018 Baidu Inc. All Rights Reserved. * Author: Luo Yao * File: ipmCamCalibParamParser.cpp * Date: 18-12-26 下午2:23 ************************************************/ #include "ipmCamCalibParamParser.h" IpmCamCalibParamParser::IpmCamCalibParamParser(const IpmCamCalibParamParser &parser) { this->_m_image_size = parser._m_image_size; this->_m_board_size = parser._m_board_size; this->_m_square_size = parser._m_square_size; this->_m_calib_para_save_path = parser._m_calib_para_save_path; } IpmCamCalibParamParser& IpmCamCalibParamParser::operator=(const IpmCamCalibParamParser &parser) { if (this == &parser) { return *this; } this->_m_image_size = parser._m_image_size; this->_m_board_size = parser._m_board_size; this->_m_square_size = parser._m_square_size; this->_m_calib_para_save_path = parser._m_calib_para_save_path; return *this; }
1ea1c4489f834e03a2a7328265ad413f7f11c49b
b6ef93e8c4c3b78dc28a77d6d43fa83f8cfeea5e
/Plugins/RuntimeQuVRTransformAxis/Source/RuntimeQuVRTransformAxis/Public/RuntimeQuVRAssetContainer.h
3d6564def11b9f62222fe8775411dddff69995f5
[]
no_license
sines/QRTIMeshComponent
36a695cf4525762f104691b0df1d9507b1946f0c
90b08aba1a8b36fc3601c76d312f17fc3a5e3e68
refs/heads/master
2018-09-10T08:26:01.695867
2018-06-05T09:26:12
2018-06-05T09:26:12
114,124,539
0
0
null
null
null
null
UTF-8
C++
false
false
2,449
h
RuntimeQuVRAssetContainer.h
// Copyright 2018 Louis. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Engine/DataAsset.h" #include "RuntimeQuVRAssetContainer.generated.h" // Forward declarations class UMaterialInterface; class USoundBase; class UStaticMesh; /** * Asset container for Render. */ UCLASS(Blueprintable) class RUNTIMEQUVRTRANSFORMAXIS_API URuntimeQuVRAssetContainer : public UDataAsset { GENERATED_BODY() public: static const FString AssetContainerPath; // // Sound // UPROPERTY(EditAnywhere, Category = Sound) USoundBase* GizmoHandleSelectedSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* GizmoHandleDropSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* SelectionChangeSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* SelectionDropSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* SelectionStartDragSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* GridSnapSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* ActorSnapSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* UndoSound; UPROPERTY(EditAnywhere, Category = Sound) USoundBase* RedoSound; // // Meshes // UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* GridMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* TranslationHandleMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* UniformScaleHandleMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* ScaleHandleMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* PlaneTranslationHandleMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* RotationHandleMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* RotationHandleSelectedMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* StartRotationIndicatorMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* CurrentRotationIndicatorMesh; UPROPERTY(EditAnywhere, Category = Mesh) UStaticMesh* FreeRotationHandleMesh; // // Materials // UPROPERTY(EditAnywhere, Category = Material) UMaterialInterface* GridMaterial; UPROPERTY(EditAnywhere, Category = Material) UMaterialInterface* TransformGizmoMaterial; UPROPERTY(EditAnywhere, Category = Material) UMaterialInterface* TranslucentTransformGizmoMaterial; public: /** Static function to load the asset container */ static const class URuntimeQuVRAssetContainer& LoadAssetContainer(); };
01067a59cd8d1325a32ba6b19b10fccb82f61a66
766996d84cc71493deaf100f2493ee42ed0d4243
/src/ifc/ifc4/IfcEvent.h
64bd208b3e7914a984469b3906a62ae15024e88c
[]
no_license
andreasniggl/ifclite
6040cd72460d401a364c4c7554f2fe3f44ee6df8
aacc8a9f0add7036c4c04eeaed7938e731726ead
refs/heads/master
2020-03-09T05:13:57.641923
2018-08-06T21:42:27
2018-08-06T21:42:27
128,607,886
3
1
null
null
null
null
UTF-8
C++
false
false
1,613
h
IfcEvent.h
// Automatically generated by ifclite express parser from ifc4 express file - do not modify #pragma once #include "IfcTypeDefinitions.h" #include "IfcProcess.h" #include "IfcEventTime.h" namespace ifc4 { class IfcEvent : public IfcProcess { public: virtual ~IfcEvent(){} explicit IfcEvent() = default; explicit IfcEvent(const IfcGloballyUniqueId& _GlobalId) : IfcProcess(_GlobalId) {} virtual std::string className() const { return "IfcEvent"; } boost::optional<IfcEventTypeEnum> PredefinedType; // optional parameter boost::optional<IfcEventTriggerTypeEnum> EventTriggerType; // optional parameter boost::optional<IfcLabel> UserDefinedEventTriggerType; // optional parameter IfcEventTime* EventOccurenceTime; // optional parameter protected: virtual void serialize(ifc::StepWriter& w) const { w.beginEntity(this); w.writeAttributeValue(GlobalId); w.writeAttributeInstance(OwnerHistory); w.writeAttributeValue(Name); w.writeAttributeValue(Description); w.writeAttributeValue(ObjectType); w.writeAttributeValue(Identification); w.writeAttributeValue(LongDescription); w.writeAttributeValue(IfcEventTypeEnumStringMap, PredefinedType); w.writeAttributeValue(IfcEventTriggerTypeEnumStringMap, EventTriggerType); w.writeAttributeValue(UserDefinedEventTriggerType); w.writeAttributeInstance(EventOccurenceTime); w.endEntity(); } }; } // namespace ifc4
ade8940a723b28a0f1c4ec4a3ec71d9d800c4ef4
e2206c5b0555dddb2b440bd48a9df0fac8f3c356
/Seasonal/bts18p4.cpp
dcfdc2268ae1db4318b58ce19d57f91944444cf5
[]
no_license
stevenbai0724/DMOJ-Solutions
e802bdfcf496861ebb34179bead2207233eb483e
965998d2f958f726458958208e8e0613ea2a63ef
refs/heads/main
2023-07-15T05:19:49.296694
2021-08-30T14:32:43
2021-08-30T14:32:43
315,147,794
0
0
null
null
null
null
UTF-8
C++
false
false
1,757
cpp
bts18p4.cpp
//https://dmoj.ca/problem/bts18p4 #include <bits/stdc++.h> using namespace std; #define int long long int n, nd; int mx = 0, cnt = 0, ans = 0; vector<int>colour; vector<vector<int>>adj; vector<int>dis; vector<bool>vis; vector<int>comp; void dfs(int v){ colour[v] = 1; for(int u: adj[v]){ if(colour[u]==0){ dis[u] = dis[v] + 1; if(dis[u]>mx){ nd = u; mx = dis[u]; } dfs(u); } } colour[v] = 2; } void dfsComp(int v){ colour[v] = 1; for(int u: adj[v]){ if(colour[u] ==0){ dfsComp(u); } } colour[v] = 2; } void find_comp(){ for(int i=1;i<=n;i++){ if(vis[i] && colour[i]==0){ comp[cnt]=i; dfsComp(i); cnt++; } } } signed main(){ cin.tie(nullptr)->sync_with_stdio(false); cin>>n; colour.resize(n+1); adj.resize(n+1); dis.resize(n+1); vis.resize(n+1); comp.resize(n+1); fill(vis.begin(), vis.end(), true); for(int i=1;i<=n;i++){ int y;cin>>y; int x = (sqrt(y)); if((x*x +x) !=y)vis[i] = false; } for(int i=1;i<n;i++){ int x, y; cin>>x>>y; if(!vis[x] || !vis[y])continue; adj[x].push_back(y); adj[y].push_back(x); } find_comp(); fill(colour.begin(), colour.end(), 0); for(auto x: comp){ if(x==0)break; dfs(x); fill(colour.begin(), colour.end(), 0); fill(dis.begin(), dis.end(), 0); mx = 0; dfs(nd); ans = max(ans, mx+1); mx = 0; } cout<<ans; return 0; }
c24d6bd1ad79ddfbfa592df966d01e158603ae16
cb45c5824504b2c3010d54efdecff1c564ad6051
/MatteEngine/Music.h
2548a92208d09eeab54dd5d31997b19a481e9e20
[]
no_license
tarsir/MatteEngine
7129f28b7a4b2cb2a47dc98bbcaded1d90a1b115
0b57ed46ff3986e1d293094c1cc096bb450b0bed
refs/heads/master
2021-09-25T13:29:40.289215
2018-10-09T08:57:09
2018-10-09T08:57:09
113,271,502
0
0
null
null
null
null
UTF-8
C++
false
false
1,068
h
Music.h
#pragma once #include <SDL.h> #include <SDL_mixer.h> #include "Entity.h" #include "Util.h" #include "spdlog\spdlog.h" auto music_logger = spdlog::stdout_color_mt("Music.h"); namespace SMusic { int current_music_volume = 32; Mix_Music* current_bgm; void load_music(std::string filename) { Mix_FadeOutMusic(2000); current_bgm = Mix_LoadMUS(filename.c_str()); if (!current_bgm) { music_logger->error("Couldn't load bgm with error: {}", Mix_GetError()); die(); } Mix_FadeInMusic(current_bgm, 0, 2000); } void update(EntityManager* e_mgr, const SDL_Event& e) { bool is_change = false; switch (e.type) { case SDL_KEYDOWN: switch (e.key.keysym.sym) { case SDLK_KP_PLUS: ++current_music_volume; Mix_VolumeMusic(current_music_volume); is_change = true; break; case SDLK_KP_MINUS: --current_music_volume; Mix_VolumeMusic(current_music_volume); is_change = true; break; } if (is_change) { music_logger->info("new music volume: {}", current_music_volume); } } } }
9314cbaa2fba0945d04ef535e5c640a2be6f2628
5e52e2b2742efe15a84b501554986ca6643bcc82
/ParseIdl/env/NoConnection.h
35fe667846717c9fcdde4b157aad56ddbed2de62
[]
no_license
hogoww/ParseIdl
a271d2207f8b51d67b4457e246c1370268e86b12
3cb06253a38f3aedac877dd7a25840d8a13e1525
refs/heads/master
2021-03-24T13:30:15.646219
2018-10-10T16:25:52
2018-10-10T16:25:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
NoConnection.h
#ifndef __NO_CONNECTION_H__ #define __NO_CONNECTION_H__ #include <string> #include <exception> #include "Component.h" /* class Component::NoConnection : public std::exception{ */ /* private: */ /* std::string errormsg; */ /* public: */ /* NoConnection(std::string errorMsg); */ /* virtual ~NoConnection() throw(); */ /* virtual const char* what() const throw(); */ /* }; */ #endif
bfbe66884c88a07783d2838b402e7787bbb7e5e1
3f6f72804e5b7c6b7ddc9a07b294478e8c4eb877
/osg_hello/LODNode/LODNode.cpp
2d3e7b8382cdb344d9618daa3d1d5089ffcf7169
[]
no_license
love3forever/osg_learning
e76bc54e7fb6206e95b34341b330ccd7fd479bad
8e887f050a29564019b733abbd482953edf4fb79
refs/heads/master
2021-01-25T04:48:24.529317
2017-06-09T07:02:28
2017-06-09T07:02:28
93,479,875
0
0
null
null
null
null
GB18030
C++
false
false
599
cpp
LODNode.cpp
// LODNode.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<osg/LOD> #include<osgDB/ReadFile> #include<osgViewer/Viewer> int main(int argc,char** argv) { osg::Node* model = osgDB::readNodeFile("bunny-high.ive"); float r = model->getBound().radius(); osg::ref_ptr<osg::LOD> root = new osg::LOD; root->addChild(osgDB::readNodeFile("bunny-low.ive"), r * 7, FLT_MAX); root->addChild(osgDB::readNodeFile("bunny-mid.ive"), r * 3, r * 7); root->addChild(model, 0.0, r * 3); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); return viewer.run(); }
7fab69a63f95a4a41d58d8461771be7045c5cca9
3f21c24ff10cba14ca4ab16ee62e8c1213b60bd0
/src/classifiers/ClassifierManager.h
11ddba0caf33729e56b07daeb733e2ea46bea6dc
[]
no_license
watson-intu/self
273833269f5bf1027d823896e085ac675d1eb733
150dc55e193a1df01e7acfbc47610c29b279c2e7
refs/heads/develop
2021-01-20T03:15:02.118963
2018-04-16T08:19:31
2018-04-16T08:19:31
89,515,657
34
31
null
2018-04-16T08:15:51
2017-04-26T18:50:00
C++
UTF-8
C++
false
false
2,912
h
ClassifierManager.h
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef CLASSIFIER_MANAGER_H #define CLASSIFIER_MANAGER_H #include <list> #include "utils/Factory.h" #include "IClassifier.h" #include "topics/TopicManager.h" #include "SelfLib.h" // include last //! This class manages all active classifier instances. This classifiers subscribe to sensors //! and add concepts to the BlackBoard object contained by the SelfInstance. class SELF_API ClassifierManager { public: //! Types typedef std::list< IClassifier::SP > ClassifierList; //! Construction ClassifierManager(); ~ClassifierManager(); //! Accessors const ClassifierList & GetClassifierList() const; //! Start this manager, initializes all available Classifier objects. bool Start(); //! Stop this manager. bool Stop(); //! Add the classifier to this manager, it takes ownership of the object if accepted. bool AddClassifier(const IClassifier::SP & a_spClassifier, bool a_bOverride = false); //! Remove a classifier from this manager. bool RemoveClassifier(const IClassifier::SP & a_spClassifier); //! Find all classifiers with the gifen name bool FindClassifiers(const std::string & a_Type, std::vector<IClassifier::SP> & a_Overrides); void OnClassifierOverride(IClassifier * a_pClassifier); void OnClassifierOverrideEnd(IClassifier * a_pClassifer); template<typename T> T * FindClassifier() const { for (ClassifierList::const_iterator iClass = m_Classifiers.begin(); iClass != m_Classifiers.end(); ++iClass) { T * pClassifier = DynamicCast<T>((*iClass).get()); if (pClassifier != NULL) return pClassifier; } return NULL; } template<typename T> T * GetClassifier() { T * pClassifier = FindClassifier<T>(); if (pClassifier == NULL) { pClassifier = new T(); if (pClassifier->OnStart()) { m_Classifiers.push_back(IClassifier::SP(pClassifier)); return pClassifier; } delete pClassifier; pClassifier = NULL; } return pClassifier; } private: //! Data bool m_bActive; ClassifierList m_Classifiers; TopicManager * m_pTopicManager; //! Callbacks void OnSubscriber(const ITopics::SubInfo & a_Info); void OnClassifierEvent(const ITopics::Payload & a_Payload); }; inline const ClassifierManager::ClassifierList & ClassifierManager::GetClassifierList() const { return m_Classifiers; } #endif
57fa375e7cf0eeb8495def8c947ca4cc19c84cc5
642ce02205385799aec1521ea53dd59beff87c32
/TORTUGA/main.cpp
30fdbaf4fb7225358be01b51349207d5eed2cb08
[]
no_license
RubenJTL/Computacion-Grafica
6e270208aae7fa859f7f519580c3c80e4ef85576
8da579930e01dce8b2675b9eaf1ba6a97c7ca142
refs/heads/master
2020-03-28T02:27:00.462237
2018-11-28T16:11:21
2018-11-28T16:11:21
147,571,318
0
0
null
null
null
null
UTF-8
C++
false
false
2,898
cpp
main.cpp
#include <iostream> #include "primitivas.h" using namespace std; #define PI 3.14159265 GLsizei winWidth = 600, winHeight = 500; Window window; int xr=0,yr=0; void init(void){ glClearColor(1.0, 1.0, 1.0, 1.0); glMatrixMode(GL_PROJECTION); gluOrtho2D(-winWidth, winWidth, -winHeight, winHeight); } void drawSphereTurtle(Point centro,GLint radio_cuerpo){ GLint radiocuerpo=radio_cuerpo; GLint radiocabeza=radiocuerpo/2; GLint radiopatas=radiocuerpo/3; Point centro_patas_up_d=centro; Point centro_patas_up_i=centro; Point centro_patas_down_d=centro; Point centro_patas_down_i=centro; centro_patas_up_d.x+=radiocuerpo-radiopatas/2; centro_patas_up_d.y+=radiocuerpo-radiopatas/2; centro_patas_up_i.x-=radiocuerpo-radiopatas/2; centro_patas_up_i.y+=radiocuerpo-radiopatas/2; centro_patas_down_d.x+=radiocuerpo-radiopatas/2; centro_patas_down_d.y-=radiocuerpo-radiopatas/2; centro_patas_down_i.x-=radiocuerpo-radiopatas/2; centro_patas_down_i.y-=radiocuerpo-radiopatas/2; Point centro_cabeza=centro; centro_cabeza.y+=radiocuerpo+radiocabeza/2; circleMidPoint(centro,radiocuerpo,window); circleMidPoint(centro_cabeza,radiocabeza,window); circleMidPoint(centro_patas_up_d,radiopatas,window); circleMidPoint(centro_patas_up_i,radiopatas,window); circleMidPoint(centro_patas_down_d,radiopatas,window); circleMidPoint(centro_patas_down_i,radiopatas,window); } void keyboard(unsigned char key, int x, int y){ switch (key) { case 'w': yr=yr+1; cout<<y<<endl; glutPostRedisplay(); break; case 's': yr--; cout<<y<<endl; glutPostRedisplay(); break; case 'a': xr--; cout<<x<<endl; glutPostRedisplay(); break; case 'd': xr++; //glTranslatef(dest.getOrigin().x, dest.getOrigin().y, 0); cout<<x<<endl; glutPostRedisplay(); break; case 'e': //xr++; cout<<x<<endl; glRotatef(-1.0,0.,0.,0.1); glutPostRedisplay(); break; case 'q': //xr++; glRotatef(1,0.,0.,0.1); cout<<x<<endl; glutPostRedisplay(); break; } } void display(){ Point centro; centro.x = winWidth/2+xr; centro.y = winHeight/2+yr; GLint radio = 200; GLint radioy=100; glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0, 0.0, 0.0); //estrella(centro, radio); //circleMidPoint(centro, radio, window); //elipceMidPoint(centro, radio, radioy, window); drawSphereTurtle(centro,100); glFlush(); glutPostRedisplay(); glutSwapBuffers(); } int main(int argc, char **argv){ window.width = winWidth; window.height = winHeight; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(0,0); glutInitWindowSize(winWidth, winHeight); glutCreateWindow("Dibujo"); glTranslatef(-300, -250, 0.0); glutDisplayFunc(display); init(); glutKeyboardFunc(keyboard); glutMainLoop(); }
3ef44ed59856beddbd4d9d3529aec26b244bb9fc
f1a5508d96984ce0b45c02e1ba509393d7b6bf88
/Es_lezione_09/Exercise09_1.cxx
1720fd4e7f3b71131a07f39f0db4b51a5c0700e3
[]
no_license
AlessandroProserpio/LabSimNumerica
e3eab0eff21498d8f9dd74a7b49f20ae8157a015
7f0128891e4e859261bbf7786bb04b3d93f66945
refs/heads/master
2022-11-23T07:39:19.336286
2020-07-17T09:33:49
2020-07-17T09:33:49
278,032,292
0
0
null
null
null
null
UTF-8
C++
false
false
1,711
cxx
Exercise09_1.cxx
#include "cities.h" #include "population.h" #include <string> int main(){ const int ncities=32; const int npop=300; const int ngen=2000; //const int iprint=ngen; Cities c; // Cities in circle c.Cities_in_circle(ncities, 1.); Population pop1(npop, c); pop1.SortL1(); //pop1.sortL2(); ofstream Pop; cout << endl << "---------------- Cities in a circle -----------------"; for(int j=0; j<ngen; j++){ pop1.New_generation(); pop1.SortL1(); //pop1.SortL2(); if((j+1)%100==0) cout << endl << "Generation #" << j+1; //Pop.open("pop_circle_L2.dat", ios::app); Pop.open("pop_circle_L1.dat", ios::app); pop1.PrintL1(Pop, npop/2); Pop << endl; Pop.close(); } cout << endl; // Print ofstream Circle; Circle.open("cities_in_circle.dat"); c.Print(Circle); Circle.close(); Pop.open("pop_circle_best_path.dat"); pop1.PrintPath(Pop, 1); Pop << endl; pop1.PrintL1(Pop, 1); Pop.close(); // Cities in square c.Cities_in_square(ncities, 1.); Population pop2(npop, c); pop2.SortL1(); //pop2.SortL2(); cout << endl << "---------------- Cities in a square ------------------"; for(int j=0; j<ngen; j++){ pop2.New_generation(); pop2.SortL1(); //pop2.SortL2(); if((j+1)%100==0) cout << endl << "Generation #" << j+1; //if((j+1)%iprint==0){ //Pop.open("pop_circle_L2.dat", ios::app); Pop.open("pop_square_L1.dat", ios::app); pop2.PrintL1(Pop, npop/2); Pop << endl; Pop.close(); //} } cout << endl; // print ofstream Square; Square.open("cities_in_square.dat"); c.Print(Square); Square.close(); Pop.open("pop_square_best_path.dat"); pop2.PrintPath(Pop, 1); Pop << endl; pop2.PrintL1(Pop, 1); Pop.close(); return 0; }
4ef8e7028136cf518c83e1199388d276b8201caa
9526b3ee25e9252623d9ea41ba8b9658a541fa63
/sstmac/software/launch/launcher.cc
4db61f7a7e86e43e4ad23e6883db9b6077fa40bf
[ "BSD-3-Clause" ]
permissive
summonersRift/sst-macro
e6f3e80cdf70aa1e26e6ecf17e44960b522c4ae9
1307bb4f31e033dbbd2d9b82c54d3753446d31a4
refs/heads/master
2021-01-21T10:59:20.172254
2017-02-24T15:01:07
2017-02-24T15:01:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
cc
launcher.cc
/* * This file is part of SST/macroscale: * The macroscale architecture simulator from the SST suite. * Copyright (c) 2009 Sandia Corporation. * This software is distributed under the BSD License. * Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, * the U.S. Government retains certain rights in this software. * For more information, see the LICENSE file in the top * SST/macroscale directory. */ #include <sstmac/software/launch/launcher.h> #include <sstmac/software/launch/launch_event.h> #include <sstmac/software/launch/job_launcher.h> #include <sstmac/software/launch/app_launch.h> #include <sstmac/software/process/operating_system.h> #include <sstmac/software/process/app.h> #include <sprockit/sim_parameters.h> #include <sprockit/util.h> #include <unistd.h> #include <getopt.h> namespace sstmac { namespace sw { app_launcher::app_launcher(operating_system* os) : is_completed_(false), service(std::string("launcher"), software_id(0,0), os) { } app_launcher::~app_launcher() throw() { } void app_launcher::incoming_event(event* ev) { launch_event* lev = safe_cast(launch_event, ev); app_launch* launch = job_launcher::app_launcher(lev->aid()); if (lev->type() == launch_event::Start){ software_id sid(lev->aid(), lev->tid()); app* theapp = app_factory::get_param("name", launch->app_params(), sid, os_); int intranode_rank = num_apps_launched_[lev->aid()]++; int core_affinity = lev->core_affinity(intranode_rank); theapp->set_affinity(core_affinity); os_->increment_app_refcount(); os_->start_app(theapp); } else { bool app_done = launch->proc_done(); if (app_done){ bool sim_done = job_launcher::static_app_done(lev->aid()); if (sim_done){ os_->decrement_app_refcount(); } } } delete lev; } void app_launcher::start() { service::start(); if (!os_) { spkt_throw_printf(sprockit::value_error, "instantlaunch::start: OS hasn't been registered yet"); } } int launch_event::core_affinity(int intranode_rank) const { return thread::no_core_affinity; } } }
cf21528e40f29d972c2025b316766d4916e7b458
8f2dbf18b73e3cd5282edd3ec605e580a5a894fe
/Classes/HelloWorldScene.cpp
6402195737027772015a4b7f04fde505ed6bd07a
[]
no_license
Mizutome/projectTetris
7ecb67a2d8bc6c1f96210b9ab39c2b4b9a7c4cc8
c0a3d8e1e21a856f7ffeda7a6df4df8d8f094a84
refs/heads/master
2021-01-14T11:26:18.605007
2014-08-28T13:18:09
2014-08-28T13:18:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,792
cpp
HelloWorldScene.cpp
#include "HelloWorldScene.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } void HelloWorld::drawWorld() { static bool ifinit=false; static map<int,Sprite*> SpriteMap; static map<int,Sprite*> SpriteMap1; static map<int,Sprite*> SpriteMap2; Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); float StartPointx,StartPointy,interval; StartPointx=visibleSize.width*0.14; StartPointy=visibleSize.height-70; float ratio=2.5; float ratio2=1.3; interval=(visibleSize.width/80)*ratio; if(!ifinit) { LabelTTF* labelS=LabelTTF::create("SCORE: ", "Chalkduster", 28); labelS->setPosition(Vec2(visibleSize.width*0.42,visibleSize.height*((float)1/2-0.04))); this->addChild(labelS); label = LabelTTF::create("0", "Arial", 28); // position the label on the center of the screen label->setPosition(Vec2(visibleSize.width*0.42,visibleSize.height*((float)2/5-0.04))); // add the label as a child to this layer this->addChild(label); LabelTTF* labelN=LabelTTF::create("NEXT: ", "Chalkduster", 28); labelN->setPosition(Vec2(visibleSize.width*0.42,visibleSize.height*((float)3/4))); this->addChild(labelN); LabelTTF* labelL=LabelTTF::create("LEVEL: ", "Chalkduster", 28); labelL->setPosition(Vec2(visibleSize.width*0.42,visibleSize.height*((float)1/5+0.03))); this->addChild(labelL); labelLL=LabelTTF::create("5", "Arial", 28); labelLL->setPosition(Vec2(visibleSize.width*0.42,visibleSize.height*(0.12+0.03))); this->addChild(labelLL); ifinit=true; } char s[50]; sprintf(s,"%06d",score); string ss(s); label->setString(ss); sprintf(s,"%d",difficult+1); string sss(s); labelLL->setString(sss); int idx=0; for(vector<unsigned short>::iterator i=TheWorldToPrint.begin();i!=TheWorldToPrint.end();i++) { for(int j=0;j<16;j++) { unsigned short K=1; K=K<<j; if((*i&K)!=0) { if(SpriteMap.find(idx*16+j)!=SpriteMap.end()) continue; else { float x,y; x=StartPointx+j*interval; y=StartPointy; Sprite* sprite; if(j<2||j>13||idx>29) { sprite = Sprite::create("Ice_Block_NSMBDIY.png"); sprite->setScale(0.023f*ratio2); } else { sprite = Sprite::create("block.png"); sprite->setColor(Color3B(200, 100, 200)); sprite->setScale(0.045f*ratio2); } // position the sprite on the center of the screen sprite->setPosition(Vec2(x , y )); sprite->setOpacity(230); sprite->getTexture()->setAntiAliasTexParameters(); // add the sprite as a child to this layer this->addChild(sprite, 0); SpriteMap[idx*16+j]=sprite; } } else { if(SpriteMap.find(idx*16+j)!=SpriteMap.end()) { SpriteMap[idx*16+j]->removeFromParentAndCleanup(true); SpriteMap.erase(idx*16+j); } } } StartPointy-=interval; idx++; } StartPointx=visibleSize.width*0.14; StartPointy=visibleSize.height-70; interval=(visibleSize.width/80)*ratio; idx=0; for(vector<unsigned short>::iterator i=dynamicTetrisToPrint.begin();i!=dynamicTetrisToPrint.end();i++) { for(int j=0;j<16;j++) { unsigned short K=1; K=K<<j; if((*i&K)!=0) { if(SpriteMap1.find(idx*16+j)!=SpriteMap1.end()) continue; else { float x,y; x=StartPointx+j*interval; y=StartPointy; Sprite* sprite = Sprite::create("block.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(x , y )); sprite->setScale(0.045f*ratio2); sprite->setColor(Color3B(0, 100, 255)); sprite->setOpacity(230); sprite->getTexture()->setAntiAliasTexParameters(); // add the sprite as a child to this layer this->addChild(sprite, 0); SpriteMap1[idx*16+j]=sprite; } } else { if(SpriteMap1.find(idx*16+j)!=SpriteMap1.end()) { SpriteMap1[idx*16+j]->removeFromParentAndCleanup(true); SpriteMap1.erase(idx*16+j); } } } StartPointy-=interval; idx++; } StartPointx=visibleSize.width*0.57; StartPointy=visibleSize.height-200; interval=(visibleSize.width/80)*ratio; idx=0; for(vector<unsigned short>::iterator i=NextStructure.begin();i!=NextStructure.end();i++) { for(int j=0;j<16;j++) { unsigned short K=1; K=K<<j; if((*i&K)!=0) { if(SpriteMap2.find(idx*16+j)!=SpriteMap2.end()) continue; else { float x,y; x=StartPointx+j*interval; y=StartPointy; Sprite* sprite = Sprite::create("block.png"); // position the sprite on the center of the screen sprite->setPosition(Vec2(x , y )); sprite->setScale(0.045f*ratio2); sprite->setColor(Color3B(0, 255, 255)); sprite->setOpacity(230); sprite->getTexture()->setAntiAliasTexParameters(); // add the sprite as a child to this layer this->addChild(sprite, 0); SpriteMap2[idx*16+j]=sprite; } } else { if(SpriteMap2.find(idx*16+j)!=SpriteMap2.end()) { SpriteMap2[idx*16+j]->removeFromParentAndCleanup(true); SpriteMap2.erase(idx*16+j); } } } StartPointy-=interval; idx++; } } void HelloWorld::keyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event) { switch (keyCode) { case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW: action=3; break; case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW: action=0; break; case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW: startClick=true; action=1; break; case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW: startClick=true; action=2; break; default: break; } } void HelloWorld::keyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event) { startClick=false; longClick=false; action=10; } // on "init" you need to initialize your instance bool HelloWorld::init() { difficult=4; drawWorld(); noGameOVer=true; longClick=false; startClick=false; ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } if (!LayerGradient::initWithColor(ccc4(200, 200, 200, 255),ccc4(100, 100, 185, 255),ccp(0.0f, 2.0f))) //RGBA { return false; } // Director::getInstance()->getOpenGLView()->setDesignResolutionSize(500,600,ResolutionPolicy::EXACT_FIT); // // Director::getInstance()->getOpenGLView()->setFrameSize(500,600); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); Director::sharedDirector()->setDisplayStats(false); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object cocos2d::Vector<cocos2d::MenuItem*> pMenuItems; auto closeItem = MenuItemImage::create( "arrow_circle_left_32.png", "arrow_circle_left_32_touch.png", this, menu_selector(HelloWorld::menuCloseCallback)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y +visibleSize.height- closeItem->getContentSize().height/2)); closeItem->setOpacity(125); pMenuItems.pushBack(closeItem); auto closeItemUp = MenuItemImage::create( "arrow_up_32.png", "arrow_up_32_touch.png", this, menu_selector(HelloWorld::menuCloseCallbackUp)); closeItemUp->setPosition(Vec2(origin.x + visibleSize.width - (5*(closeItemUp->getContentSize().width/2)) , origin.y +visibleSize.height- closeItemUp->getContentSize().height/2)); closeItemUp->setOpacity(125); pMenuItems.pushBack(closeItemUp); auto closeItemDown = MenuItemImage::create( "arrow_down_32.png", "arrow_down_32_touch.png", this, menu_selector(HelloWorld::menuCloseCallbackDown)); closeItemDown->setPosition(Vec2(origin.x + visibleSize.width - (9*(closeItemUp->getContentSize().width/2)) , origin.y +visibleSize.height- closeItemUp->getContentSize().height/2)); closeItemDown->setOpacity(125); pMenuItems.pushBack(closeItemDown); // create menu, it's an autorelease object cocos2d::Menu* pMenu = cocos2d::Menu::createWithArray(pMenuItems); pMenu->setPosition(Vec2::ZERO); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label m_tetris= new Tetris(); labelGO = LabelTTF::create("Game Over!!", "Arial", 50); // position the label on the center of the screen labelGO->setPosition(Vec2(visibleSize.width*0.375,visibleSize.height/2)); // add the label as a child to this layer this->addChild(labelGO,99); labelGO->setVisible(false); action=10; m_tetris->update(TheWorldToPrint, dynamicTetrisToPrint,action,score,NextStructure,difficult); drawWorld(); this->schedule(schedule_selector(HelloWorld::testTimer), 0.015); this->schedule(schedule_selector(HelloWorld::testTimerb), 0.1); this->schedule(schedule_selector(HelloWorld::testTimerx), 0.01); auto keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyPressed = CC_CALLBACK_2(HelloWorld::keyPressed, this); keyboardListener->onKeyReleased = CC_CALLBACK_2(HelloWorld::keyReleased, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener, this); return true; } void HelloWorld::testTimer(float time) { static int previous_action=10; Size visibleSize = Director::getInstance()->getVisibleSize(); if(previous_action==1&&longClick) { action=1; } else if(previous_action==2&&longClick) action=2; if(noGameOVer) { updating=true; noGameOVer=m_tetris->update(TheWorldToPrint, dynamicTetrisToPrint,action,score,NextStructure,difficult); if(action==3) action=10; else if(action==1||action==2) { previous_action=action; action=10; } updating=false; } if(!noGameOVer) { labelGO->setVisible(true); } } void HelloWorld::testTimerx(float time) { if(!updating) drawWorld(); } void HelloWorld::testTimerb(float time) { static int count=0; if(startClick) { if(count++>=2) { longClick=true; } } else { count=0; longClick=false; } } void HelloWorld::menuCloseCallback(Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif labelGO->setVisible(false); noGameOVer=true; m_tetris->init(); score=0; //#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) // exit(0); //#endif } void HelloWorld::menuCloseCallbackUp(Ref* pSender) { if(difficult<9) difficult++; } void HelloWorld::menuCloseCallbackDown(Ref* pSender) { if(difficult>0) difficult--; }
35fd8177e151d5001ff6329b46f41ef5cedc3d5a
61f81f1d0c79a06ea7acfbfabd8c76bd4a5355e0
/OpenWAM/Source/ObjectTester.cpp
d53b689e475d5ed84b1b81bcd33a81983df992a1
[]
no_license
Greeeder/Program
8e46d46fea6afd61633215f4e8f6fd327cc0731f
b983df23d18a7d05a7fab693e7a9a3af067d48a5
refs/heads/master
2020-05-21T22:15:32.244096
2016-12-02T08:38:05
2016-12-02T08:38:08
63,854,561
3
0
null
null
null
null
UTF-8
C++
false
false
6,819
cpp
ObjectTester.cpp
#include "Globales.h" #include "TPipeHeatT.h" #include "TPipeIntHeatIntake.h" #include "TPipeIntHeatExhaust.h" #include "TPortIntHeatIntake.h" #include "TPortIntHeatExhaust.h" #include "TPipeExtHeatA.h" #include "TFluidAir.h" #include "TSldAl.h" #include "TMultiWiebe.h" #include "THRL.h" #include <chrono> #include <fstream> namespace __Ambient { double p_Pa = 100000; //!< The ambient pressure [Pa] double p_bar = 1; //!< The ambient pressure [bar] double T_K = 300; //!< The ambient temperature [K] double T_degC = 27; //!< The ambient temperature [degC] double HR = 50; //!< The humidity [%] } ; void TestHeatTransferInPipes(xml_node node_openwam); void BuildMaterialsDB(xml_node node_mat, std::map<string, TSolid*> &MaterialsDB); void TestCombustion(xml_node node_openwam); int main(){ xml_document File; if (!File.load_file("D:/OpenWAM/TCMVSProj/bin/debug/Input.xml")) cout << "The input file does not exist" << endl; xml_node node_openwam = File.child("OpenWAM"); //TestHeatTransferInPipes(node_openwam); TestCombustion(node_openwam); return EXIT_SUCCESS; } void TestCombustion(xml_node node_openwam){ TCombustion* Comb; TCombustion* Comb2; xml_node node_eng = GetNodeChild(node_openwam, "EngineBlock"); xml_node node_cmb = GetNodeChild(node_eng, "Combustion"); //xml_node node_wb = GetNodeChild(node_cmb, "Wiebe"); xml_node node_mwb = GetNodeChild(node_cmb, "MultiWiebe"); xml_node node_hrl = GetNodeChild(node_cmb, "HRL"); //Comb = new TMultiWiebe(); Comb = new THRL(); Comb->ReadCombustionData(node_hrl); Comb2 = new THRL(dynamic_cast<THRL*>(Comb)); for (int i = -10; i < 10; i++){ cout << (double)i << " " << Comb->getHRL((double)i) << endl; } double hrl = Comb->getHRL(5); //double hrl2 = Comb2->getHRL(5); } void TestHeatTransferInPipes(xml_node node_openwam){ int ncells = 5; double cellsize = 0.02; fstream fout; std::map<string, TSolid*> MaterialsDB; xml_node node_GD = GetNodeChild(node_openwam, "GeneralData"); xml_node node_mat = GetNodeChild(node_GD, "Materials"); BuildMaterialsDB(node_mat, MaterialsDB); xml_node node_pipeblock = GetNodeChild(node_openwam, "BlockOfPipes"); xml_node np = GetNodeChild(node_pipeblock, "Bop_Pipe"); VectorXd D = VectorXd::Ones(5) * 0.05; VectorXd Tgas = VectorXd::Constant(5, 530); VectorXd Re = VectorXd::Constant(5, 12000); std::vector<TFluid_ptr> Fluid; Fluid.resize(ncells); for (int i = 0; i < ncells; i++){ Fluid[i] = make_shared<TFluidAir>(); Fluid[i]->Funk(Tgas(i)); Fluid[i]->FunVisc(Tgas(i)); } xml_node node_ht = GetNodeChild(np, "Pip_HeatTransfer"); double IntHeatMult = GetAttributeAsDouble(node_ht, "IntMultiplier"); string Type = node_ht.attribute("HT_Type").as_string(); TPipeIntHeat *intheatobj; TPipeHeatT *htobj; TPipeExtHeat *extheatobj; if (Type == "IntakePipe"){ intheatobj = new TPipeIntHeatIntake(ncells, IntHeatMult, D, cellsize); } else if (Type == "ExhaustPipe"){ intheatobj = new TPipeIntHeatExhaust(ncells, IntHeatMult, D, cellsize); } else if (Type == "IntakePort"){ intheatobj = new TPortIntHeatIntake(ncells, IntHeatMult, D, cellsize); } else if (Type == "ExhaustPort"){ intheatobj = new TPortIntHeatExhaust(ncells, IntHeatMult, D, cellsize); } else{ cout << "Internal heat transfer in pipe not correctly defined" << endl; } string WallCalc = node_ht.attribute("WallCalculation").as_string(); if (WallCalc != "Constant"){ htobj = new TPipeHeatT(); htobj->ReadHeatTransferData(np, ncells, 0.02, MaterialsDB); htobj->BuildMatrix(D); xml_node node_eheat = GetNodeChild(node_ht, "Pht_External"); double velocity = GetAttributeAsDouble(node_eheat, "Velocity"); double extMult = GetAttributeAsDouble(node_eheat, "ExtMultiplier"); double emis = GetAttributeAsDouble(node_eheat, "Emissivity"); string Type2 = node_eheat.attribute("Type").as_string(); if (Type2 == "AirCooled"){ extheatobj = new TPipeExtHeatA(ncells, velocity, extMult, htobj->getExtDiameter().array(), cellsize, emis); } else if (Type2 == "WaterCooled"){ double Tw = GetAttributeAsDouble(node_eheat, "WaterTemp"); extheatobj = new TPipeExtHeatW(ncells, velocity, extMult, htobj->getExtDiameter().array(), cellsize, emis, Tw); } else if (Type2 == "Port"){ } htobj->AddExtHeatObject(extheatobj); } fout.open("Output.dat", fstream::out); VectorXd Qi; double dt = 0.1; auto start = chrono::steady_clock::now(); for (int i = 0; i < 3000; i++){ Qi = intheatobj->Heat(Tgas.array(), htobj->getTwallint().array(), Re, Fluid); Qi *= dt; htobj->AddInternalHeat(Qi); htobj->SolveExplicit(dt); fout << htobj->getTwallint()(0) << "\t"; fout << htobj->getTnodes()(0) << "\t"; fout << htobj->getTwallext()(0); fout << endl; } auto end = chrono::steady_clock::now(); auto diff = end - start; cout << chrono::duration <double, milli>(diff).count() << " ms" << endl; fout.close(); cout << endl << htobj->getTnodes() << endl; cout << htobj->getTwallint() << endl; cout << htobj->getTwallext(); } void BuildMaterialsDB(xml_node node_mat, std::map<string, TSolid*> &MaterialsDB){ for (xml_node node_m = GetNodeChild(node_mat, "Material"); node_m; node_m = node_m.next_sibling("Material")){ string matname = node_m.attribute("Name").as_string(); if (matname == "Aluminium"){ MaterialsDB[matname] = new TSldAl(); } else{ if (MaterialsDB.count(matname) == 0){ MaterialsDB[matname] = new TSolid(matname); xml_node node_prop; int ncoef; int i; ArrayXd Coefs; node_prop = GetNodeChild(node_m, "Conductivity"); ncoef = CountNodes(node_prop, "ConductivityCoef"); Coefs.setZero(ncoef); i = 0; for (xml_node node_c = GetNodeChild(node_prop, "ConductivityCoef"); node_c; node_c = node_c.next_sibling("ConductivityCoef")){ Coefs(i) = GetAttributeAsDouble(node_c, "Value"); i++; } MaterialsDB[matname]->setCoefCond(Coefs); node_prop = GetNodeChild(node_m, "Density"); ncoef = CountNodes(node_prop, "DensityCoef"); Coefs.setZero(ncoef); i = 0; for (xml_node node_c = GetNodeChild(node_prop, "DensityCoef"); node_c; node_c = node_c.next_sibling("DensityCoef")){ Coefs(i) = GetAttributeAsDouble(node_c, "Value"); i++; } MaterialsDB[matname]->setCoefDens(Coefs); node_prop = GetNodeChild(node_m, "HeatCapacity"); ncoef = CountNodes(node_prop, "HeatCapacityCoef"); Coefs.setZero(ncoef); i = 0; for (xml_node node_c = GetNodeChild(node_prop, "HeatCapacityCoef"); node_c; node_c = node_c.next_sibling("HeatCapacityCoef")){ Coefs(i) = GetAttributeAsDouble(node_c, "Value"); i++; } MaterialsDB[matname]->setCoefHeCap(Coefs); } else{ cout << "ERROR: Material " << matname << " is defined twice" << endl; } } } }
eabe8565364d24c309350290dc0bd07e278ced26
125ae0adb562478b184bbb35d40f2c43b335415c
/HAL/Common/tHALWatchdog.h
2465fc9041622bf7cff9468c0bbf0b64c265daad
[]
no_license
dulton/53_hero
ff49ce6096c379931d7649b654c5fa76de4630de
48057fe05e75f57b500a395e6ff8ff9c06da6895
refs/heads/master
2020-02-25T04:19:18.632727
2016-05-20T03:44:44
2016-05-20T03:44:44
62,197,327
3
2
null
2016-06-29T05:11:41
2016-06-29T05:11:38
null
WINDOWS-1252
C++
false
false
880
h
tHALWatchdog.h
/*****************************************************/ // Copyright © 2007-2012 Navico // Confidential and proprietary. All rights reserved. /*****************************************************/ #ifndef T_HAL_WATCHDOG_H #define T_HAL_WATCHDOG_H #pragma warning(push, 1) #include <QObject> #pragma warning(pop) #ifdef Q_OS_LINUX #include <sys/un.h> #endif #include "HAL/tHALIOInterface.h" class tHALWatchdog : public QObject { Q_OBJECT public: tHALWatchdog(bool enableCoprocessorWatchDog, tHALIOInterface* halIOInterface, QObject* parent = 0); ~tHALWatchdog(); void notifyShutdown(); public slots: void updateWatchdog(); private: void sendCommand(int command); #ifdef Q_OS_LINUX int m_ClientSocket; struct sockaddr_un m_SockAddr; #endif tHALIOInterface* m_HalIOInterface; bool m_CoprocessorWatchdogEnabled; }; #endif
e970100847098dc195c6ecd97639e7788a1fe369
4ad680a647ee4119cc141b290b8c345a79898737
/EScript/Compiler/Tokenizer.h
1cd284cfaee7df70c329549168775bd760040e00
[ "MIT" ]
permissive
PADrend/EScript
16ddc39fde601f91a4467976632e55e7decc52e1
491df975a9c81d9e22bc0e2fecb04a184f4e77c3
refs/heads/0.7.2.Egon
2023-08-02T07:15:45.006282
2015-12-31T17:41:26
2015-12-31T17:41:26
301,776,245
0
0
MIT
2020-10-13T10:03:29
2020-10-06T15:42:45
null
UTF-8
C++
false
false
1,828
h
Tokenizer.h
// Tokenizer.h // This file is part of the EScript programming language (https://github.com/EScript) // // Copyright (C) 2011-2013 Claudius Jähn <ClaudiusJ@live.de> // Copyright (C) 2011-2012 Benjamin Eikel <benjamin@eikel.org> // // Licensed under the MIT License. See LICENSE file for details. // --------------------------------------------------------------------------------- #ifndef TOKENIZER_H #define TOKENIZER_H #include "Token.h" #include "../Objects/Exception.h" #include "../Utils/StringId.h" #include "../Utils/ObjRef.h" #include <cstddef> #include <string> #include <cstring> #include <unordered_map> #include <vector> namespace EScript { //! [Tokenizer] class Tokenizer { public: typedef std::unordered_map<StringId, _CountedRef<Token> > tokenMap_t; typedef std::vector<_CountedRef<Token> > tokenList_t; static Token * identifyStaticToken(StringId id); //! [Tokenizer::Error] ---|> [Exception] ---|> [Object] class Error : public Exception { public: explicit Error(const std::string & s,int _line=-1):Exception(std::string("Tokenizer: ")+s) { setLine(_line); } }; // --- void getTokens( const std::string & codeU8,tokenList_t & tokens); void defineToken(const std::string & name,Token * value); private: Token * readNextToken(const std::string & codeU8, std::size_t & cursor,int &line,size_t & startPos,tokenList_t & tokens); Token * identifyToken(StringId id)const; static bool isNumber(const char c) { return c>='0' && c<='9'; } static bool isChar(char c) { return (c>='a' && c<='z') || (c>='A' && c<='Z') || c=='_' || c<0; } static bool isWhitechar(char c) { return (c=='\n'||c==' '||c=='\t'||c==13||c==3); } static bool isOperator(char c) { return strchr("+-/*|%&!<>=^.?:~@",c)!=nullptr; } tokenMap_t customTokens; }; } #endif // TOKENIZER_H
20655f31e714f506c462dac8b803c2815e8782b8
6beecae61b6cf917ea4acd90f4064a13375d4457
/cob_camera_sensors_ipa/common/src/UnicapCamera.cpp
9aeb94837f4e8c99158507b40882aedcf2a9cf0f
[]
no_license
ipa-rmb-mo/cob_bringup_sandbox
f1d0fd1f4d5fa239be27380efdfd12566eb99ecc
da256f1ef78d0e3e985685dd17d7930c56360414
refs/heads/master
2020-05-29T11:57:54.578091
2016-11-07T01:51:38
2016-11-07T01:51:38
56,847,368
0
1
null
2016-04-22T10:24:06
2016-04-22T10:24:06
null
UTF-8
C++
false
false
11,883
cpp
UnicapCamera.cpp
#ifdef __LINUX__ #include <highgui.h> #include "UnicapCamera.h" #include <stdio.h> #include <string.h> #include <vector> #include <math.h> #include <assert.h> UnicapCamera::UnicapCamera( ) { m_Handle = NULL; m_Device = NULL; m_Format = NULL; m_CameraActive = false; m_Resolution = 0; } UnicapCamera::UnicapCamera(int res) { m_Handle = NULL; m_Device = NULL; m_Format = NULL; m_CameraActive = false; m_Resolution = res; } UnicapCamera::~UnicapCamera() { if (m_Handle) free(m_Handle); if (m_Device) free(m_Device); if (m_Format) free(m_Format); } int UnicapCamera::Open() { unicap_device_t device; unicap_handle_t handle; unicap_format_t format; //Initialisation if (m_Device == NULL) { m_Device = (unicap_device_t *)malloc(sizeof(unicap_device_t)); if (m_Device == NULL) { printf("UnicapCamera::Open: Error, no memory!\n"); return ERROR_NO_MEMORY; } } if (m_Handle == NULL) { m_Handle = (unicap_handle_t *)malloc(sizeof(unicap_handle_t)); if (m_Handle == NULL) { printf("UnicapCamera::Open: Error, no memory!\n"); return ERROR_NO_MEMORY; } } if (m_Format == NULL) { m_Format = (unicap_format_t *)malloc(sizeof(unicap_format_t)); if (m_Format == NULL) { printf("UnicapCamera::Open: Error, no memory!\n"); return ERROR_NO_MEMORY; } } // Search camera devices if( !SUCCESS( unicap_enumerate_devices( NULL, &device, 0 ) ) ) { printf("UnicapCamera::Open: No device found!\n"); return ERROR_NO_CAMERAS_FOUND; } else { *m_Device = device; printf("UnicapCamera::Open: Device %s found, vendor: %s, controlled by %s, %s\n", m_Device->identifier, m_Device->vendor_name, m_Device->device, m_Device->cpi_layer); } /* Acquire a handle to this device */ if( !SUCCESS( unicap_open( &handle, m_Device ) ) ) { printf("UnicapCamera::Open: Failed to open device %s: %s\n", m_Device->identifier, strerror(errno)); return ERROR_CAMERA_COULD_NOT_BE_OPENED; } else { *m_Handle = handle; m_CameraActive = true; printf("DUnicapCamera::Open:evice %s successfully opened!\n", m_Device->identifier); } //Set format according to specified resolution if( !SUCCESS( unicap_enumerate_formats( *m_Handle, NULL, &format, m_Resolution ) ) ) { printf("UnicapCamera::Open: Failed to get video format, setting to default\n" ); //return UNSPECIFIED_ERROR;; } else { *m_Format = format; printf("UnicapCamera::Open: Format %s chosen\n", format.identifier ); printf("UnicapCamera::Open: Setting video format: \nwidth: %d\nheight: %d\nbpp: %d\nFOURCC: %c%c%c%c\n\n", \ m_Format->size.width,\ m_Format->size.height,\ m_Format->bpp, \ m_Format->fourcc & 0xff, \ ( m_Format->fourcc >> 8 ) & 0xff, \ ( m_Format->fourcc >> 16 ) & 0xff, \ ( m_Format->fourcc >> 24 ) & 0xff \ ); /* Set this video format */ if( !SUCCESS( unicap_set_format( *m_Handle, m_Format ) ) ) { printf("UnicapCamera::Open: Failed to set video format\n" ); return UNSPECIFIED_ERROR; } } unicap_property_t property; // Set white balance mode to auto strcpy( property.identifier, "white_balance_mode" ); if( !SUCCESS( unicap_get_property( *m_Handle, &property ) ) ) { fprintf( stderr, "UnicapCamera::Open: Failed to get WB mode property\n" ); exit( 1 ); } // Set auto on this property property.flags = UNICAP_FLAGS_AUTO;//UNICAP_FLAGS_MANUAL; unicap_set_property( handle, &property ); if( !SUCCESS( unicap_set_property( *m_Handle, &property ) ) ) { printf( "UnicapCamera::Open: Failed to set property!\n" ); return UNSPECIFIED_ERROR; } if( !SUCCESS( unicap_get_property( *m_Handle, &property ) ) ) { fprintf( stderr, "UnicapCamera::Open: Failed to get WB mode property\n" ); exit( 1 ); } printf( "UnicapCamera::Open: Current white balance mode: %s\n", property.flags & UNICAP_FLAGS_AUTO ? "AUTO" : "MANUAL" ); if( !SUCCESS( unicap_start_capture( *m_Handle ) ) ) { printf( "UnicapCamera::Open: Failed to start capture on device %s\n", m_Device->identifier ); return UNSPECIFIED_ERROR; } return OK; } int UnicapCamera::Close(void) { if( !SUCCESS( unicap_stop_capture( *m_Handle ) ) ) { printf( "Failed to stop capture on device: %s\n", m_Device->identifier ); } if( !SUCCESS( unicap_close( *m_Handle ) ) ) { printf("Failed to close the device: %s\n", m_Device->identifier ); return UNSPECIFIED_ERROR; } else { printf("UnicapCamera: %s closed\n",m_Device->identifier); return 0; } } int UnicapCamera::SetColorMode(int colorMode) { m_ColorMode = colorMode; return 0; } int UnicapCamera::ShowAvailableVideoFormats() { unicap_format_t format; for (int n=0;n < 10;n++) { if( !SUCCESS( unicap_enumerate_formats( *m_Handle, NULL, &format, n ) ) ) { printf("Failed to get video format\n" ); return UNSPECIFIED_ERROR;; } else { printf("Format %i: fcc: %i bpp:%i \n",n,format.fourcc,format.bpp); printf(" h_stepping: %i v_stepping %i \n",format.h_stepping,format.v_stepping); printf("size_count %i \n",format.size_count); } } return 1; } int UnicapCamera::ConvertImage(cv::Mat* inputImg, unicap_data_buffer_t * inputRawBufferData) { if (m_ColorMode == 0) { //printf("Kamera im RGB-Modus, keine Konvertierung notwendig; Puffer-Daten werden kopiert"); ConvRGBIplImage(inputImg, inputRawBufferData); } if (m_ColorMode == 1) { //printf("Kamera im Ymono-Modus, eine Konvertierung wird vorgenommen"); } if (m_ColorMode == 2) { //printf("Kamera im YVV411-Modus, eine Konvertierung wird vorgenommen"); } if (m_ColorMode == 3) { //printf("Kamera im YVV422-Modus, eine Konvertierung wird vorgenommen"); ConvUYVY2IplImage(inputImg, inputRawBufferData); } return m_ColorMode; } int UnicapCamera::ConvRGBIplImage(cv::Mat* Img, unicap_data_buffer_t * rawBufferData) { if (!m_Format) { printf("UnicapCamera::ConvUYVY2IplImage: Error, no format set\n"); return ERROR_NO_FORMAT_SET; } float r=0, g=0, b=0; unsigned int bufIndex = 0; unsigned char * pBuff=(unsigned char*)img->data; long Pos=0; while ( bufIndex < rawBufferData->buffer_size) { r = (float)(rawBufferData->data[bufIndex++]); g = (float)(rawBufferData->data[bufIndex++]); b = (float)(rawBufferData->data[bufIndex++]); pBuff[Pos++]=(unsigned char)b; pBuff[Pos++]=(unsigned char)g; pBuff[Pos++]=(unsigned char)r; } return bufIndex; // return the bufferindex; this value isn't used, it is only for the return statement } int UnicapCamera::ConvUYVY2IplImage(cv::Mat* Img, unicap_data_buffer_t * rawBufferData) { if (!m_Format) { printf("UnicapCamera::ConvUYVY2IplImage: Error, no format set\n"); return ERROR_NO_FORMAT_SET; } float u,y,v; float r,g,b; unsigned int bufIndex = 0; unsigned char * pBuff=(unsigned char*)img->data; long Pos=0; while ( bufIndex < rawBufferData->buffer_size) { u = (float)(rawBufferData->data[bufIndex++]); y = (float)(rawBufferData->data[bufIndex++]); v = (float)(rawBufferData->data[bufIndex++]); //Convert uyv to rgb y-=16; v-=128;u-=128; r = 1.164*y + 1.596*v; g = 1.164*y - 0.813*v - 0.391*u; b = 1.164*y + 2.018*u ; if (r > 255) r=255;if (r < 0) r=0; if (g > 255) g = 255;if (g < 0)g=0; if (b > 255) b=255;if (b <0)b=0; pBuff[Pos++]=(unsigned char)b; pBuff[Pos++]=(unsigned char)g; pBuff[Pos++]=(unsigned char)r; // UYVY Format y = (float)(rawBufferData->data[bufIndex++] & 0x00FF); y-=16; r = 1.164*y + 1.596*v ; g = 1.164*y - 0.813*v - 0.391*u; b = 1.164*y + 2.018*u ; if (r > 255) r=255;if (r < 0) r=0; if (g > 255) g = 255;if (g < 0) g=0; if (b > 255) b=255;if (b < 0) b=0; pBuff[Pos++]=(unsigned char)b; pBuff[Pos++]=(unsigned char)g; pBuff[Pos++]=(unsigned char)r; } return bufIndex; // return the bufferindex; this value isn't used, it is only for the return statement } int UnicapCamera::SetProperty(int propertyNo, int value ) { unicap_property_t property; unicap_property_t property_spec; unicap_void_property( &property_spec ); if (!IsCameraActive()) { printf("UnicapCamera::SetProperties: Please call open first! \n"); return ERROR_NOT_OPENED; } if( !SUCCESS( unicap_enumerate_properties( *m_Handle, &property_spec, &property, propertyNo ) ) ) { printf( "UnicapCamera::SetProperties: Failed to enumerate property\n" ); return UNSPECIFIED_ERROR; } property.value = value; printf("UnicapCamera::SetProperties: Setting property %d: %s to %f ... \n",propertyNo, property.identifier,property.value); if( !SUCCESS( unicap_set_property( *m_Handle, &property ) ) ) { printf( "UnicapCamera::SetProperties: Failed to set property!\n" ); return UNSPECIFIED_ERROR; } return OK; } int UnicapCamera::PrintCameraInformation() { unicap_format_t format; unicap_property_t property; int property_count; int format_count; if (!IsCameraActive()) { printf("UnicapCamera::SetProperties: Please call open first! \n"); return ERROR_NOT_OPENED; } unicap_reenumerate_properties( *m_Handle, &property_count ); unicap_reenumerate_formats( *m_Handle, &format_count ); printf( "Device: %s\n", m_Device->identifier ); printf( "\tProperties[%d]:\n", property_count ); for(int j = 0; SUCCESS( unicap_enumerate_properties( *m_Handle, NULL, &property, j ) ); j++ ) { printf( "\t\t%s\n", property.identifier ); } printf( "\tFormats[%d]:\n", format_count ); for(int j = 0; SUCCESS( unicap_enumerate_formats( *m_Handle, NULL, &format, j ) ); j++ ) { printf( "\t\t%s\n", format.identifier ); } return OK; } int UnicapCamera::GetColorImage(cv::Mat* img, char* FileName ) { unsigned char *image_buffer = NULL; unicap_data_buffer_t buffer; unicap_data_buffer_t *returned_buffer; int error = 0; // Initialize IPL image CV_Assert(img != 0); img->create(m_Format->size.height, m_Format->size.width, CV_8UC3); // Initialize the image buffer memset( &buffer, 0x0, sizeof( unicap_data_buffer_t ) ); if (!m_Format) { printf("UnicapCamera::Acquire: No format set!\n"); error = ERROR_NO_FORMAT_SET; } if ((error == 0) && (!m_Handle)) { printf("UnicapCamera::Acquire: No Camera handle available.\n"); error = ERROR_NOT_OPENED; } // Allocate memory for the image buffer if (error == 0) { if( !( image_buffer = (unsigned char *)malloc( m_Format->buffer_size ) ) ) { printf("UnicapCamera::Acquire: Failed to allocate %d bytes\n" ); error = ERROR_NO_MEMORY; } buffer.data = image_buffer; buffer.buffer_size = m_Format->buffer_size; } // Start the capture process on the device // Queue the buffer // The buffer now gets filled with image data by the capture device if (error == 0) { if( !SUCCESS( unicap_queue_buffer( *m_Handle, &buffer ) ) ) { printf("UnicapCamera::Acquire: Failed to queue a buffer on device: %s\n", m_Device->identifier ); error = UNSPECIFIED_ERROR; } } // Wait until the image buffer is ready if (error == 0) { if( !SUCCESS( unicap_wait_buffer( *m_Handle, &returned_buffer ) ) ) { printf("UnicapCamera::Acquire: Failed to wait for buffer on device: %s\n", m_Device->identifier ); error = UNSPECIFIED_ERROR; } } // Stop the device if (error == 0) { if( !returned_buffer->buffer_size ) { printf("UnicapCamera::Acquire: Returned a buffer size of 0!\n" ); error = UNSPECIFIED_ERROR; } } if (error == 0) { ConvertImage(img, returned_buffer); } if ((error==0) && (FileName)) cvSaveImage(FileName, Img); if (image_buffer) { free( image_buffer ); } return error; } #endif // __LINUX__
69c622719918501e970d9729ab20bfd776795953
354d662439d13cf8f89afeae89d9e5b68c2321c6
/src/real_dlib.cpp
500f22e70fa87ad591451ce5c76c7761d2d80d59
[]
no_license
bobbieVan/Facial-Landmark
b15d539cfd937c5d2cdb500e95260e48ecb74f92
d78014fcb2ed0104fc85691450427f4cdd07d933
refs/heads/master
2020-05-16T16:53:57.335876
2018-05-04T10:54:42
2018-05-04T10:54:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
cpp
real_dlib.cpp
#include <dlib/opencv.h> #include <opencv2/core/version.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv/cv.h> #include <opencv/highgui.h> #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing/render_face_detections.h> #include <dlib/image_processing.h> #include <dlib/gui_widgets.h> using namespace dlib; using namespace std; int main() { try { cv::VideoCapture cap(0); if (!cap.isOpened()) { cerr << "Unable to connect to camera" << endl; return 1; } image_window win; //摄像头分别率设置,若要提升分辨率,建议不要采用resize函数,这样会增加耗时。 //可增加两路视频信号输入,低分辨率计算关键点,将坐标进行相应变换,在高分辨率视频中呈现 cap.set(CV_CAP_PROP_FRAME_WIDTH, 160); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 120); // Load face detection and pose estimation models. frontal_face_detector detector = get_frontal_face_detector(); shape_predictor pose_model; deserialize("../model/dlib_point.dat") >> pose_model; // Grab and process frames until the main window is closed by the user. while(!win.is_closed()) { // Grab a frame long t0 = cv::getTickCount(); cv::Mat temp; if (!cap.read(temp)) { break; } cv_image<bgr_pixel> cimg(temp); // 人脸检测 std::vector<rectangle> faces = detector(cimg); // 绘制每个脸部矩形框 std::vector<full_object_detection> shapes; for (unsigned long i = 0; i < faces.size(); ++i){ cout<<(long)(faces[i].left())<<endl; shapes.push_back(pose_model(cimg, faces[i])); cv::rectangle(temp, cvPoint(faces[i].left(), faces[i].top()),cvPoint(faces[i].right(),faces[i].bottom()), CV_RGB(255, 255, 255), 1, 8, 0); } // 绘制每个脸部关键点 if (!shapes.empty()) { int faceNumber = shapes.size(); for (int j = 0; j < faceNumber; j++) { for (int i = 0; i < 68; i++) { cv::circle(temp, cvPoint(shapes[j].part(i).x(), shapes[j].part(i).y()), 3, cv::Scalar(0, 0, 255), -1); } } } // 播放及耗时计算 win.clear_overlay(); win.set_image(cimg); long t1 = cv::getTickCount(); double secss = (t1 - t0)/cv::getTickFrequency(); cout<<"dlib检测耗时:"<<" "<<secss<<endl; } } catch(serialization_error& e) { cout << "You need dlib's default face landmarking model file to run this example." << endl; cout << "You can get it from the following URL: " << endl; cout << " http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" << endl; cout << endl << e.what() << endl; } catch(exception& e) { cout << e.what() << endl; } }
a6d1f2c156b49f4ef9752c0c1d41f0d5587a1c88
032fe3c72c6bcc20c7d3e5b60c153ec10d7c82a4
/leetcode/src/clonegraph.cpp
2fcebbe2c8f79607ef0c06b2f849f70c7117b140
[]
no_license
waitin2010/Algorithm
9a8b500a0adbfa30c3e102a8c9a184b99a629abd
f387558624c4f829f6497a90c8a9abeb4e210118
refs/heads/master
2020-05-30T04:43:52.349423
2015-10-12T09:40:13
2015-10-12T09:40:13
19,803,292
0
0
null
null
null
null
UTF-8
C++
false
false
2,073
cpp
clonegraph.cpp
#include <iostream> #include <vector> #include <map> #include <queue> using namespace std; struct UndirectedGraphNode { int label; vector<UndirectedGraphNode *> neighbors; UndirectedGraphNode(int x) : label(x) {}; }; UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(node==NULL) return NULL; map<int,UndirectedGraphNode *> clonegraph; queue<UndirectedGraphNode*> queuegraph; // bfs, and construct all graph node queuegraph.push(node); while(!queuegraph.empty()){ UndirectedGraphNode *top = queuegraph.front(); queuegraph.pop(); if(clonegraph.find(top->label)==clonegraph.end()){//no found UndirectedGraphNode *newnode = new UndirectedGraphNode(top->label); clonegraph.insert(make_pair(newnode->label,newnode)); // push all the neighbor node into queue if(!top->neighbors.empty()){ for(int i=0;i<top->neighbors.size();i++) queuegraph.push(top->neighbors[i]); } } } //bfs, and construct the neighbor relationship for all node in clonegraph queuegraph.push(node); while(!queuegraph.empty()){ UndirectedGraphNode *top = queuegraph.front(); queuegraph.pop(); UndirectedGraphNode *newnode = clonegraph[top->label]; if(newnode->neighbors.empty()&&!top->neighbors.empty()){// newnode has not processed for(int i=0;i<top->neighbors.size();i++){ newnode->neighbors.push_back(clonegraph[top->neighbors[i]->label]); queuegraph.push(top->neighbors[i]); } } } return clonegraph[node->label]; } int main(){ cout<<"hello, my friend"<< endl; UndirectedGraphNode *node = new UndirectedGraphNode(0); node->neighbors.push_back(new UndirectedGraphNode(1)); node->neighbors.push_back(new UndirectedGraphNode(2)); cloneGraph(node); return 0; }
38290d503cee4ff92ac30c94ce7dcc6538304c79
0bf1f7b901118b5cbe3d51bbc5885fcb634419c5
/Cpp/SDK/UMG_TextButton_Popup_parameters.h
a28a6f999e34b07de8b61824436adc51e337810f
[]
no_license
zH4x-SDK/zMCDungeons-SDK
3a90a959e4a72f4007fc749c53b8775b7155f3da
ab9d8f0ab04b215577dd2eb067e65015b5a70521
refs/heads/main
2023-07-15T15:43:17.217894
2021-08-27T13:49:22
2021-08-27T13:49:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,866
h
UMG_TextButton_Popup_parameters.h
#pragma once // Name: DBZKakarot, Version: 1.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.ControllerTypeChanged struct UUMG_TextButton_Popup_C_ControllerTypeChanged_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.SetWarning struct UUMG_TextButton_Popup_C_SetWarning_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.Setup struct UUMG_TextButton_Popup_C_Setup_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.GetButtonReference struct UUMG_TextButton_Popup_C_GetButtonReference_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.Construct struct UUMG_TextButton_Popup_C_Construct_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.OnClicked struct UUMG_TextButton_Popup_C_OnClicked_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.BndEvt__UMG_Button_K2Node_ComponentBoundEvent_2_OnHovered__DelegateSignature struct UUMG_TextButton_Popup_C_BndEvt__UMG_Button_K2Node_ComponentBoundEvent_2_OnHovered__DelegateSignature_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.PreConstruct struct UUMG_TextButton_Popup_C_PreConstruct_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.ExecuteUbergraph_UMG_TextButton_Popup struct UUMG_TextButton_Popup_C_ExecuteUbergraph_UMG_TextButton_Popup_Params { }; // Function UMG_TextButton_Popup.UMG_TextButton_Popup_C.ButtonClick__DelegateSignature struct UUMG_TextButton_Popup_C_ButtonClick__DelegateSignature_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
32bde46dc25d81b330c33610f71d64f7705b74eb
56317b548ed1b04981f3553e915ddf28c334bc26
/DeviceDrivers/FlexCan/FlexCan.h
2946f78100539e2fdf7a1354b6dfcfca6622c948
[ "MIT" ]
permissive
MountainFu/KeCommon
8d1f9c14bd88229a6cf97301f8509777b6a280ff
94edff47ff9fd58aed3fd4a168261fcfc75f99fd
refs/heads/master
2023-09-03T07:29:31.264898
2021-11-15T04:00:58
2021-11-15T04:00:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
611
h
FlexCan.h
/* * can_il.h * * Created on: 14 gru 2020 * Author: Mati */ #ifndef CDD_CAN_IL_H_ #define CDD_CAN_IL_H_ #include "ICan.h" #include "fsl_flexcan.h" class FlexCan : public ICan { private: int mailboxCount; CAN_Type *can_base; static void WritePayloadRegisters(flexcan_frame_t *frame, const uint8_t *data, uint8_t dlc); public: explicit FlexCan(int mailboxCount); void ConfigRxMailbox(uint32_t id, uint8_t mb_id); bool Send(uint32_t id, Payload &data, uint8_t dlc) override; bool Receive(uint32_t *id, Payload *data, uint8_t dlc) override; }; #endif /* CDD_CAN_IL_H_ */
d1b33a62093bc3b58c2deaf3d5c60334b98c5f07
7f811dc30afd118f9060ef1bd0ac9e2ebb72ddc9
/src/BrainGraph.Compute/Group/TStatCalc.hpp
4a3f61c30dbad38427d7e501ffcfb65bfeda4ec9
[]
no_license
digitalnelson/BrainGraph
3f8f79850103095cc24ea90225104c4230b83407
b70fabed7f4db184bc2f3e5b63c827af7cacf8b0
refs/heads/master
2021-01-16T18:45:49.120297
2014-12-06T13:18:57
2014-12-06T13:18:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
hpp
TStatCalc.hpp
#pragma once #include <math.h> #include "TStat.hpp" namespace BrainGraph { namespace Compute { namespace Group { class TStatCalc { public: TStatCalc() { n1 = 0, n2 = 0; m1 = 0, m2 = 0; dv1 = 0, dv2 = 0; } void IncludeValue(int groupId, double value) { if (groupId == 0) { n1++; double delta = value - m1; m1 += delta / n1; if (n1 > 1) dv1 = dv1 + delta * (value - m1); } else { n2++; double delta = value - m2; m2 += delta / n2; if (n2 > 1) dv2 = dv2 + delta * (value - m2); } } TStat Calculate() { double v1 = abs(dv1) / (n1 - 1); double v2 = abs(dv2) / (n2 - 1); double tstat = 0; if (v1 < 0.00000001f && v2 < 0.00000001f) tstat = 0; else tstat = (m1 - m2) / sqrt((v1 / (double)n1) + (v2 / (double)n2)); TStat stat; stat.V1 = v1; stat.V2 = v2; stat.M1 = m1; stat.M2 = m2; stat.Value = tstat; return stat; } private: int n1, n2; double m1, m2; double dv1, dv2; }; } } }
f1a1985903988bedadcfb179f44518360e595def
c47b80e996fa5469fae837bdba6f213f2460e95c
/serialportsettingmodel.h
58701f04b296e3cb56d64f04fec8f611d3813297
[]
no_license
Felipeasg/LFTracking
c8e2670194205636fee18d1f355992728a51ead0
d1de1b26a11303923b170b65e3af0584ef869bb7
refs/heads/master
2021-01-10T17:19:37.678323
2020-07-12T01:02:19
2020-07-12T01:02:19
36,243,414
5
1
null
null
null
null
UTF-8
C++
false
false
1,052
h
serialportsettingmodel.h
#ifndef SERIALPORTSETTINGMODEL_H #define SERIALPORTSETTINGMODEL_H #include <QObject> #include "serialportsettingsconfigset.h" class SerialPortSettingModel : public QObject { Q_OBJECT public: explicit SerialPortSettingModel(QObject *parent = 0); ~SerialPortSettingModel(); static SerialPortSettingModel* getInstance(); int getBaudRate() const; void setBaudRate(int value); int getDataBits() const; void setDataBits(int value); int getParity() const; void setParity(int value); int getStopBits() const; void setStopBits(int value); int getFlowControl() const; void setFlowControl(int value); SerialPortSettingsConfigset getSerialPortConfigSet() const; void setSerialPortConfigSet(const SerialPortSettingsConfigset &value); QString getPortName() const; void setPortName(const QString &value); signals: public slots: private: static SerialPortSettingModel* uniqueInstance; SerialPortSettingsConfigset serialPortConfigSet; }; #endif // SERIALPORTSETTINGMODEL_H
c5ce64667dbff5899097d27f720cfe6ad57a09d9
2ed4bd0fd576db54ba4b8dc1e8096fda3b01d8c6
/server/XmlParser.cpp
5ea1739497089d55bb9c75297e3d96c463c4723f
[]
no_license
sergey-helloworld/client-server
cba255a66a4c53a548eec62a0e74f8fd47ac6494
aa50d593554c2aa83cfdcba9c437eacc889505ec
refs/heads/master
2020-04-11T23:58:45.280596
2018-12-17T20:30:29
2018-12-17T20:30:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,425
cpp
XmlParser.cpp
#include "stdafx.h" #include "XmlParser.h" #include <iostream> XmlParser::XmlParser(const std::string& buf) : buf_(buf) { pos.push_back(Position{0,buf_.size()}); } XmlParser& XmlParser::parse(const std::string& nodeName) { std::vector<Position> p; for(unsigned i = 0; i < pos.size(); ++i) { std::size_t pos1 = pos[i].start; int count = 0; while(true) { pos1 = buf_.find("<"+nodeName+">", pos1); if(pos1 == std::string::npos || pos1 > pos[i].end) break; p.push_back(Position{pos1+nodeName.size()+2, 0}); ++pos1; ++count; } if (!count) throw std::runtime_error("XmlParser::parse error: node name not found"); pos1 = pos[i].start; int count2 = 0; for(unsigned i2 = p.size()-count; i2 < p.size(); ++i2) { pos1 = buf_.find("</"+nodeName+">", pos1); if(pos1 > pos[i].end) break; p[i2].end = pos1; ++pos1; ++count2; } if (count != count2) throw std::runtime_error("XmlParser::parse error: xml element is missing"); } pos = p; return *this; } std::vector<std::string> XmlParser::getValues() { std::vector<std::string> v; for(auto& a: pos) { v.push_back(buf_.substr(a.start, a.end-a.start)); } resetPosition(); return v; } XmlParser& XmlParser::insertNode(const std::string& nodeName) { std::string strToInsert = "\n<"+nodeName+"></"+nodeName+">"; std::size_t newSize = strToInsert.size(); for(unsigned i = 0; i < pos.size(); ++i) { for(unsigned i2 = i; i2 < pos.size(); ++i2) { pos[i2].start += newSize; pos[i2].end += newSize; } buf_.insert(pos[i].start-newSize, strToInsert); pos[i].start-=nodeName.size()+3; } return *this; } void XmlParser::setValues(const std::vector<std::string>& values) { if (values.size() != pos.size()) throw std::runtime_error("XmlParser::setValues error: vector size != node count"); for(unsigned i = 0; i < pos.size(); ++i) { std::string strToInsert = values[i]; std::size_t newSize = strToInsert.size(); for(unsigned i2 = i; i2 < pos.size(); ++i2) { pos[i2].start += newSize; pos[i2].end += newSize; } buf_.insert(pos[i].start-newSize, strToInsert); } resetPosition(); } void XmlParser::resetPosition() { pos.erase(pos.begin()+1, pos.end()); pos[0].start = 0; pos[0].end = buf_.size(); } const std::string& XmlParser::getBuf() const { return buf_; }
06237e32cdcd439edeb560f59791f196043dc755
e1ce90c7469c8cc0e04c142db2aa1b046ac6d758
/project/regression.h
3666be4796a88449ac06d89c674d801ab4267f0b
[]
no_license
Daehyun-Bae/fin_term-project
3eff1ccaaf506c0fe5e47e333a4971d887f05a6e
322723165f3d1bd0db2e61cfc283d3b44e5e1b45
refs/heads/master
2021-01-20T06:46:14.408971
2017-07-17T01:57:00
2017-07-17T01:57:00
89,926,147
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
h
regression.h
#include <vector> #define EPOCH 200 #define ALPHA 0.01 #define BETA 0.015 using namespace std; void regression(vector<vector<double>> source, vector<double> *result) { int num_data = source[0].size(); double w0, w1, err, p, err_acc; for (int k = 0; k < num_data; k++) { // k = [0,11] Month // Initialize w0, w1, err_acc w0 = w1 = err_acc = 0; //printf("\nProccessing %d-Month Regression...\n", k+1); for (int i = 1; i <= EPOCH; i++) { for (int j = 0; j < source.size(); j++) { // j = [0,] Year p = w0 + w1*(j + 1)*BETA; // year 1 ~ err = p - source[j][k]; // get err (j-th year k-th month value) w0 = w0 - ALPHA*err; w1 = w1 - ALPHA*err*(j + 1)*BETA; // update parameter err_acc += err*err; /*if ((k == 0) && ((i % 20) == 0)) { printf("MONTH - %d [%d] err - %.5f\n", k + 1, i, err); // show error rate printf("Root Mean Square Error : %.5f\n", sqrt(err_acc / (i*(j+1)))); }*/ } //if(i%200==0) printf("EPOCH[%d] Root Mean Square Error : %.5f\n", i, sqrt(err_acc / (i*source.size()))); } // Push predicted value //printf("w0: %.5f\tw1:%.5f\n", w0, w1); result->push_back(w0 + w1*(k + 1)*BETA); } }
676ae575d0c99c62b6d943372c3beddabcdae2b9
4700fe6890025691c2429df598ec25914ec4c7da
/code/tools/gtkradiant/radiant/plugintoolbar.cpp
da3afd5cc4af860821ad76ac35811c1234accbb6
[]
no_license
QuakeEngines/xreal
1e7820f8b29de6fb22aa3e058a3c4ef528c1bb55
2fcbf9179fa22dc6e808bb65b879ac2ee7616ebd
refs/heads/master
2020-07-10T04:18:26.146005
2016-10-14T23:06:22
2016-10-14T23:06:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,186
cpp
plugintoolbar.cpp
/* Copyright (C) 2001-2006, William Joseph. All Rights Reserved. This file is part of GtkRadiant. GtkRadiant is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GtkRadiant is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plugintoolbar.h" #include "itoolbar.h" #include "modulesystem.h" #include <gtk/gtktoolbar.h> #include "stream/stringstream.h" #include "gtkutil/image.h" #include "gtkutil/container.h" #include "mainframe.h" #include "plugin.h" GtkImage* new_plugin_image( const char* filename ){ { StringOutputStream fullpath( 256 ); fullpath << GameToolsPath_get() << g_pluginsDir << "bitmaps/" << filename; GtkImage* image = image_new_from_file_with_mask( fullpath.c_str() ); if ( image != 0 ) { return image; } } { StringOutputStream fullpath( 256 ); fullpath << AppPath_get() << g_pluginsDir << "bitmaps/" << filename; GtkImage* image = image_new_from_file_with_mask( fullpath.c_str() ); if ( image != 0 ) { return image; } } { StringOutputStream fullpath( 256 ); fullpath << AppPath_get() << g_modulesDir << "bitmaps/" << filename; GtkImage* image = image_new_from_file_with_mask( fullpath.c_str() ); if ( image != 0 ) { return image; } } return image_new_missing(); } inline GtkToolbarChildType gtktoolbarchildtype_for_toolbarbuttontype( IToolbarButton::EType type ){ switch ( type ) { case IToolbarButton::eSpace: return GTK_TOOLBAR_CHILD_SPACE; case IToolbarButton::eButton: return GTK_TOOLBAR_CHILD_BUTTON; case IToolbarButton::eToggleButton: return GTK_TOOLBAR_CHILD_TOGGLEBUTTON; case IToolbarButton::eRadioButton: return GTK_TOOLBAR_CHILD_RADIOBUTTON; } ERROR_MESSAGE( "invalid toolbar button type" ); return (GtkToolbarChildType)0; } void toolbar_insert( GtkToolbar *toolbar, const char* icon, const char* text, const char* tooltip, IToolbarButton::EType type, GtkSignalFunc handler, gpointer data ){ gtk_toolbar_append_element( toolbar, gtktoolbarchildtype_for_toolbarbuttontype( type ), 0, text, tooltip, "", GTK_WIDGET( new_plugin_image( icon ) ), handler, data ); } void ActivateToolbarButton( GtkWidget *widget, gpointer data ){ const_cast<const IToolbarButton*>( reinterpret_cast<IToolbarButton*>( data ) )->activate(); } void PlugInToolbar_AddButton( GtkToolbar* toolbar, const IToolbarButton* button ){ toolbar_insert( toolbar, button->getImage(), button->getText(), button->getTooltip(), button->getType(), GTK_SIGNAL_FUNC( ActivateToolbarButton ), reinterpret_cast<gpointer>( const_cast<IToolbarButton*>( button ) ) ); } GtkToolbar* g_plugin_toolbar = 0; void PluginToolbar_populate(){ class AddToolbarItemVisitor : public ToolbarModules::Visitor { GtkToolbar* m_toolbar; public: AddToolbarItemVisitor( GtkToolbar * toolbar ) : m_toolbar( toolbar ) { } void visit( const char* name, const _QERPlugToolbarTable& table ) const { const std::size_t count = table.m_pfnToolbarButtonCount(); for ( std::size_t i = 0; i < count; ++i ) { PlugInToolbar_AddButton( m_toolbar, table.m_pfnGetToolbarButton( i ) ); } } } visitor( g_plugin_toolbar ); Radiant_getToolbarModules().foreachModule( visitor ); } void PluginToolbar_clear(){ container_remove_all( GTK_CONTAINER( g_plugin_toolbar ) ); } GtkToolbar* create_plugin_toolbar(){ GtkToolbar *toolbar; toolbar = GTK_TOOLBAR( gtk_toolbar_new() ); gtk_toolbar_set_orientation( toolbar, GTK_ORIENTATION_HORIZONTAL ); gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS ); gtk_widget_show( GTK_WIDGET( toolbar ) ); g_plugin_toolbar = toolbar; PluginToolbar_populate(); return toolbar; }
7a8dfd354857d8f73a10618519a3fbc97cefe4db
4bedfa9c7b231f7edc3b46e473de1eebbec324ef
/src/main.cpp
8b5772518e4710f6d3db356e942ddb1a1883c24a
[]
no_license
jp7hong/Tricycle
0d537afc8ae5dc31c24efe94755274548919bb0f
6574d57d0fad281e7800c9dd31a206b1520fc9fd
refs/heads/master
2021-07-03T18:39:02.557748
2017-09-26T12:42:19
2017-09-26T12:42:19
104,882,742
3
0
null
null
null
null
UTF-8
C++
false
false
1,214
cpp
main.cpp
/// /// @file main.cpp /// @author Junpyo Hong (jp7.hong@gmail.com) /// @date Aug 29, 2016 /// @version 1.0 /// /// @brief Calculates odometry for the tricycle drive /// #include <iostream> // std::cout #include <cstdlib> // atoi #include "TestTricycle.h" // CTestTricycle #define TEST_CASE_NUM (4) /// /// @brief show usage of this program /// @param exeFilename [in] executed filename /// @return void /// void ShowUsage(char* exeFilename) { std::cout << "Usage: " << exeFilename << " <test_case_num>" << std::endl; std::cout << "Range of <test_case_num>: 1.." << TEST_CASE_NUM << std::endl; } /// /// @brief entry point of this program /// @param argc [in] the number of arguments /// @param argv [in] string point array of arguments /// @return 0 on success /// int main(int argc, char* argv[]) { /// test case number int test_case = -1; /// check arguments if (argc != 2) { ShowUsage(argv[0]); return 0; } /// convert to integer test_case = atoi(argv[1]); /// if the argument is not within the range if (test_case <= 0 || test_case > TEST_CASE_NUM) { ShowUsage(argv[0]); return 0; } /// run test code CTestTricycle::GetInstance()->Run(test_case); return 0; }
feecb183a11e75b134f8a60d2b371349cafd7da8
8e803f907f122f30995360907cb0e52e91c4892e
/addon/lib/algorithm/saferplus.h
f527d5b88afa1abdc288e14fce2d170e278f76d8
[ "MIT" ]
permissive
tugrul/cryptian
a6a5e2d6c87822eb9964a77538b412b43fa862ad
1393bc54915dc8ecf6cc71128df4674923f61161
refs/heads/master
2023-08-11T03:28:25.005742
2023-03-12T15:18:41
2023-03-12T15:18:41
139,491,147
13
3
MIT
2023-07-20T07:48:20
2018-07-02T20:29:23
TypeScript
UTF-8
C++
false
false
855
h
saferplus.h
#include <algorithm-block.h> namespace cryptian { namespace algorithm { class Saferplus : public AlgorithmBlock { private: union block { unsigned int ui[4]; unsigned char uc[16]; char c[16]; }; union key_block { unsigned int ui[9]; unsigned char uc[36]; char c[36]; }; unsigned char key[33 * 16]; static const unsigned char safer_expf[256]; static const unsigned char safer_logf[512]; void do_fr(unsigned char[16], unsigned short); void do_ir(unsigned char[16], unsigned short); public: std::string getName(); std::size_t getVersion(); std::size_t getBlockSize(); std::vector<std::size_t> getKeySizes(); std::vector<char> encrypt(const std::vector<char>); std::vector<char> decrypt(const std::vector<char>); void reset(); }; }; };
7e7823075a2c6d072b8887cfbdef1e060753c722
f0bdee437c3016c22954c8225de7a44990e66fb0
/11066_Knuth Optimization_O(n^2).cpp
d214c9c0d5579a1a127ff8783f936efd14a88372
[]
no_license
sujangJin/Baekjoon-judge
214065b41b45e4f3c38383a319408d42b012227d
599450f9a3e22e6647ae050de120b0e9ba8e9fc9
refs/heads/master
2021-01-13T09:47:41.168041
2017-06-21T14:58:51
2017-06-21T14:58:51
69,648,512
2
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
11066_Knuth Optimization_O(n^2).cpp
#include<cstdio> #include<cstring> int a[501], s[501], d[501][501]; int go(int i, int j) { if (i == j) return 0; if (d[i][j] != -1) return d[i][j]; int &ans = d[i][j]; for (int k = i; k <= j - 1; k++) { int temp = go(i, k) + go(k + 1, j) + s[j] - s[i - 1]; if (ans == -1 || ans > temp) ans = temp; } return ans; } int main() { int t; scanf("%d", &t); while (t--) { memset(d, -1, sizeof(d)); memset(s, 0, sizeof(s)); int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", a + i); s[i] = s[i - 1] + a[i]; } printf("%d\n", go(1, n)); } return 0; }
e8b00fc120e1324fc38d2a07e45e6e8cc0effcbf
c618bbf2719431999b1007461df0865bab60c883
/dali/util/numpy.h
63487af097973cd93c26866a8a7d68ac40153ee6
[ "Apache-2.0" ]
permissive
NVIDIA/DALI
3d0d061135d19e092647e6522046b2ff23d4ef03
92ebbe5c20e460050abd985acb590e6c27199517
refs/heads/main
2023-09-04T01:53:59.033608
2023-09-01T13:45:03
2023-09-01T13:45:03
135,768,037
4,851
648
Apache-2.0
2023-09-12T18:00:22
2018-06-01T22:18:01
C++
UTF-8
C++
false
false
2,015
h
numpy.h
// Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef DALI_UTIL_NUMPY_H_ #define DALI_UTIL_NUMPY_H_ #include <string> #include "dali/core/common.h" #include "dali/core/tensor_shape.h" #include "dali/core/stream.h" #include "dali/pipeline/data/sample_view.h" #include "dali/pipeline/data/backend.h" #include "dali/pipeline/data/tensor.h" #include "dali/core/static_switch.h" #include "dali/kernels/transpose/transpose.h" #define NUMPY_ALLOWED_TYPES \ (bool, uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t, float, float16, \ double) namespace dali { namespace numpy { class DLL_PUBLIC HeaderData { public: TensorShape<> shape; const TypeInfo *type_info = nullptr; bool fortran_order = false; int64_t data_offset = 0; DALIDataType type() const; size_t size() const; size_t nbytes() const; }; DLL_PUBLIC void ParseHeader(HeaderData &parsed_header, InputStream *src); DLL_PUBLIC void ParseODirectHeader(HeaderData &parsed_header, InputStream *src, size_t o_direct_alignm, size_t o_direct_read_len_alignm); DLL_PUBLIC void FromFortranOrder(SampleView<CPUBackend> output, ConstSampleView<CPUBackend> input); DLL_PUBLIC void ParseHeaderContents(HeaderData& target, const std::string &header); DLL_PUBLIC Tensor<CPUBackend> ReadTensor(InputStream *src); } // namespace numpy } // namespace dali #endif // DALI_UTIL_NUMPY_H_
986439e2de2fb704e2277a026274358b47bb10da
cd6b98467b00f2e192af3c395e7a6f73651f14d1
/vai/3rd semester/imp/BINARY.cpp
4b79f5e905cf9049ec935a45d2728c3a92519ed6
[]
no_license
Anik-Roy/data-structure
de05840df5703e6871fc9402f3d2eeaf603f4d77
50b19812e11cfe7a88ce1d984ea20a227e66d4b7
refs/heads/master
2021-01-11T16:17:51.421268
2017-01-25T21:29:00
2017-01-25T21:29:00
80,059,744
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
BINARY.cpp
#include<iostream> using namespace std; int main() { int x,n,a; cin>> x,n,a; int st = 0; int en = n-1; int found = 0; while (en >= st) { int mid = (st+en)/2; if (mid==x) { found =1; break; } if(mid<x){ st=mid+1; } else { en=mid+1; } if (found ==1){ cout<< "yes"<<endl; } else { cout<<"no"<<endl; } } }
c41a5ab0d26a9adc626e6e4eee91550fd946390f
bb8bf7ad66476a11f405bae97f31ed617d83a3c8
/stackL/stackL.cpp
f9163cd803fa4ce36d7e7023803c4372e1bf3f15
[]
no_license
ShilinaAle/shilina_a_m
d1207922d828859af094cef1c02af408728e02e4
ed3710b590e8ca9b131cb667877470bfd2c72ea6
refs/heads/master
2021-09-10T07:39:23.581459
2018-03-22T08:05:23
2018-03-22T08:05:23
104,553,920
0
0
null
null
null
null
UTF-8
C++
false
false
1,575
cpp
stackL.cpp
#include"stackL.h" #include <iostream> #include <stdexcept> StackL::StackL(const StackL& rhs) { Node* pCopyFrom(rhs.pHead_->pNext_); Node* pCopyTo = new Node(nullptr, rhs.pHead_->data_); pHead_ = pCopyTo; while (pCopyFrom != nullptr) { pCopyTo -> pNext_= new Node(nullptr, pCopyFrom->data_); pCopyTo = pCopyTo->pNext_; pCopyFrom = pCopyFrom->pNext_; } } StackL::~StackL() { while (!isEmpty()) { pop(); } } void StackL::push(const int& a) { pHead_ = new Node(pHead_, a); } void StackL::pop() { if (!isEmpty()) { Node* pdeleted(pHead_); pHead_ = pdeleted->pNext_; delete pdeleted; } } int& StackL::top() { if (isEmpty()) { throw invalid_argument("You can not take an object from the empty stack"); } return pHead_->data_; } const int& StackL::top() const { if (isEmpty()) { throw invalid_argument("You can not take an object from the empty stack"); } return pHead_->data_; } bool StackL::isEmpty() const { return (!pHead_); } ostream& StackL::writeTo(ostream& ostrm) const { StackL a(*this); if (a.isEmpty()) { ostrm << "stack is empty"; } while (!a.isEmpty()) { ostrm << a.top() << ' '; a.pop(); } return ostrm; } StackL& StackL::operator = (const StackL& rhs) { StackL rhs_; Node* a; a = rhs.pHead_; while (a != nullptr) { rhs_.push(a->data_); a = a->pNext_; } while (!rhs_.isEmpty()) { push(rhs_.top()); rhs_.pop(); } return *this; } StackL::Node::Node(Node* pNext, const int& a) :pNext_(pNext), data_(a) {} ostream& operator << (ostream& ostrm, StackL& rhs) { return rhs.writeTo(ostrm); }
903abb6c5006a84008f7077a6e2a2623f1185e8a
0e7908cb1bead2fbf3d68c094d6417e47241d5c8
/MyPacMan/ghost.cpp
6a03e9b70a2a492ed99abf5cec3e5123d997837c
[]
no_license
egichcool/MyPacMan
c2eae417fb63555e90cf8e81b9b50afa36828194
d6f3293bbda5e570af1c5633099346302f9e6eb3
refs/heads/master
2020-11-26T19:47:46.369779
2020-01-09T23:36:02
2020-01-09T23:36:02
229,191,026
1
0
null
null
null
null
UTF-8
C++
false
false
3,977
cpp
ghost.cpp
#include "ghost.h" Ghost::Ghost() { animestate = 0; animation_modify_factor = 6; ghostdirection=left; is_scared=false; scared_white=false; } QRectF Ghost::boundingRect() const { return QRect(ghost_x-15,ghost_y-15,20,20); } void Ghost::setskin(int skin) { this->skin=skin; } void Ghost::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if(!is_scared) { switch(ghostdirection) { case left: if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,left1); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,left2); } break; case right: if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,right1); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,right2); } break; case down: if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,down1); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,down2); } break; case up: if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,up1); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,up2); } break; } } else { if(scared_white) { if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,scaredwhite); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,scaredwhite1); } } else { if(animestate==0) { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,scaredblue); } else { painter->drawPixmap(ghost_x-15,ghost_y-15,30,30,scaredblue1); } } } } void Ghost::advance() { if(animestate>2) { animestate=0; } else { animestate++; } } void Ghost::setGhost_X(int x) { ghost_x=x; } void Ghost::setGhost_Y(int y) { ghost_y=y; } void Ghost::setGhostColor(QString col) { scaredblue.load(image[skin][8]); scaredblue1.load(image[skin][9]); scaredwhite.load(image[skin][10]); scaredwhite1.load(image[skin][11]); if(col=="pink") { right1.load(image[skin][0]); right2.load(image[skin][1]); up1.load(image[skin][2]); up2.load(image[skin][3]); down1.load(image[skin][4]); down2.load(image[skin][5]); left1.load(image[skin][6]); left2.load(image[skin][7]); } if(col=="blue") { right1.load(image[skin][12]); right2.load(image[skin][13]); up1.load(image[skin][14]); up2.load(image[skin][15]); down1.load(image[skin][16]); down2.load(image[skin][17]); left1.load(image[skin][18]); left2.load(image[skin][19]); } else if(col=="orange") { right1.load(image[skin][20]); right2.load(image[skin][21]); up1.load(image[skin][22]); up2.load(image[skin][23]); down1.load(image[skin][24]); down2.load(image[skin][25]); left1.load(image[skin][26]); left2.load(image[skin][27]); } else if(col=="red") { right1.load(image[skin][28]); right2.load(image[skin][29]); up1.load(image[skin][30]); up2.load(image[skin][31]); down1.load(image[skin][32]); down2.load(image[skin][33]); left1.load(image[skin][34]); left2.load(image[skin][35]); } }
3ce8c99f452355fdd8d230149b1e4f0d705d016a
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/Learning Boost C++ Libraries/ch11/asyncsvr.hpp
28e4f4463c1e86828f9bff320a413254a8acedaa
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
1,231
hpp
asyncsvr.hpp
#ifndef ASYNCSVR_HPP #define ASYNCSVR_HPP #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <iostream> #include "asynconn.hpp" namespace asio = boost::asio; namespace sys = boost::system; typedef boost::shared_ptr<TCPAsyncConnection> TCPAsyncConnectionPtr; class TCPAsyncServer { public: TCPAsyncServer(asio::io_service& service, unsigned short p) : acceptor(service, asio::ip::tcp::endpoint( asio::ip::tcp::v4(), p)) { waitForConnection(); } void waitForConnection() { TCPAsyncConnectionPtr connectionPtr = boost::make_shared <TCPAsyncConnection>(acceptor.get_io_service()); acceptor.async_accept(connectionPtr->getSocket(), [this, connectionPtr](const sys::error_code & ec) { if (ec) { std::cerr << "Failed to accept connection: " << ec.message() << "\n"; } else { connectionPtr->waitForReceive(); waitForConnection(); } }); } private: asio::ip::tcp::acceptor acceptor; }; #endif /* ASYNCSVR_HPP */
686bbf8e110f691c904d6febf479ea038233f926
afe36e7d9c100847d42f2ccb10ea5f261ee141a1
/Project/persoana.cpp
a95bc11884c1d11ed800f7d29e6347e0bc17ade3
[]
no_license
laur0700/Tema1_POO
3147fbce76a322e03257b14d7e4de0613966b145
f9ddb0e20fd8094337beb2b237ca83745ebd66be
refs/heads/master
2021-04-24T04:43:52.186036
2020-03-25T20:08:01
2020-03-25T20:08:01
250,079,048
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
persoana.cpp
// // Created by Laurentiu-Andrei Postole on 25/03/2020. // #include "persoana.h" #include <string> void persoana::set_nume(string n) { nume = n; } void persoana::set_anul_nasterii(int an) { anul_nasterii = an; } void persoana::set_sex(char s) { sex = s; } string persoana::get_nume() { return nume; } int persoana::get_anul_nasterii() { return anul_nasterii; } char persoana::get_sex() { return sex; }
247e0dabcd85fabe50658559888660874f828426
668a892c1adc17a638592038cc64f9faa99f7cba
/exercises/c++/02_arrays/sieve.cc
e3b04d6f6e91242f9615e835b39ee2606a3f5702
[]
no_license
pindri/advanced_programming-2018-19
55b873281167c2510e80855314470700bf862f59
7e2167167f17b99a64c7cfc7b2d25ed84cde78d8
refs/heads/master
2020-03-31T22:01:01.098424
2019-02-11T17:27:41
2019-02-11T17:27:41
152,602,181
0
0
null
2018-10-11T14:09:01
2018-10-11T14:09:01
null
UTF-8
C++
false
false
1,135
cc
sieve.cc
/** * @file sieve.cc * @brief Implements the Sieve of Eratosthenes to compute prime numbers. * * Computes and prints the prime numbers less or equal than * a given integer n though an implementation of the Sieve of Eratosthenes. * The algorithm is optimized by enumerating the multiples * of each prime i starting from i*i. * * @author Patrick Indri * @date 13/01/19 */ #include <iostream> #include <cmath> int main() { int n; std::cout << "insert an integer: n = "; std::cin >> n; // an array of dimension n is allocated and initialized to TRUE int* ar{new int[n]}; for (int i = 0; i <= n; i++) { ar[i] = 1; } // the sieve of Eratosthenes is implemented in the following loop int j = 0; for (int i = 2; i<std::sqrt(n); i++){ if (ar[i] == 1) { j = i*i; while (j<=n){ ar[j] = 0; // all multiples of i are set to FALSE j = j + i; } } } // all the index of all the TRUE elements are printed int count = 1; for (int i = 2; i <= n; i++){ if (ar[i] == 1){ std::cout << count << ": "<< i << std::endl; count += 1; } } }
7ffabec4cc3c72f138b639749daa22b5963065dd
e63239e73b8ef114374842f4c433fbaa2bd29cf1
/cses-problemset/dynammic_Programming/Money_Sums.cpp
5a215e60f3e3cf05260287d35abf7df1fc4f8bae
[]
no_license
prakhar-ux1/ProblemSolving
2314edec64d3d2806aab06fc6ecabc87068c6eb6
5f745d5d61df314ec8a616a822bb4546bde269c4
refs/heads/main
2023-04-17T03:48:11.466671
2021-04-20T16:08:07
2021-04-20T16:08:07
359,712,023
0
0
null
null
null
null
UTF-8
C++
false
false
948
cpp
Money_Sums.cpp
// It does not matter how slowly you go as long as you do not stop #include<bits/stdc++.h> using namespace std; #define fio ios_base::sync_with_stdio(false);cin.tie(NULL); signed main() { int n; cin>>n; int ar[n],sum=0,k=0; for(int i=0;i<n;i++) {cin>>ar[i]; sum+=ar[i]; } bool dp[n+1][sum+1]; for(int i=0;i<=sum;i++) dp[0][i]=false; for(int i=0;i<=n;i++) dp[i][0]=true; for(int i=1;i<=n;i++) { for(int j=1;j<=sum;j++) { if(j>=ar[i-1]) dp[i][j]=dp[i-1][j-ar[i-1]]||dp[i-1][j]; else dp[i][j]=dp[i-1][j]; if(i==n&&dp[i][j]) k++; } } /* for(int j=0;j<=sum;j++) cout<<j<<" "; for(int i=0;i<=n;i++) {for(int j=0;j<=sum;j++) { cout<<dp[i][j]<<" "; } cout<<"\n";} */ cout<<k<<"\n"; for(int i=1;i<=sum;i++) if(dp[n][i]) cout<<i<<" "; }
f1e90623a52eed5ac0545c09a0e4e5111f0f7368
8442f074cfeecb4ca552ff0d6e752f939d6326f0
/1291A Even But Not Even.cpp
699a6def247108cab2f71c30adbed0b75f144834
[]
no_license
abufarhad/Codeforces-Problems-Solution
197d3f351fc01231bfefd1c4057be80643472502
b980371e887f62040bee340a8cf4af61a29eac26
refs/heads/master
2021-06-15T16:35:07.327687
2021-03-23T17:29:49
2021-03-23T17:29:49
170,741,904
43
32
null
null
null
null
UTF-8
C++
false
false
962
cpp
1291A Even But Not Even.cpp
#include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) cin>>n; #define scc(c) cin>>c; #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define l(s) s.size() #define asort(a) sort(a,a+n) int main() { ll t, i; cin>>t; while(t--) { ll n,j, cnt=0, cn=0; string s,s1; cin>>n>>s; fr(i, l(s)) { if( (s[i]-'0')%2 )cnt++; if(cnt==2)break; cn++; } if(cnt<2)cout<<-1<<endl; else { //cout<<cn<<endl; for(j=0;j<=cn; j++)cout<<s[j]; cout<<endl; } } return 0; } ///Before submit=> /// *check for integer overflow,array bounds /// *check for n=1
c0961a57640c133e26f79d941ed55f6993bc410d
df76858a526887db43d58bf7b0fe84c687f1be54
/kernel/KBASE/Logger.cpp
9cd7cf4d289d75048de7e6375341936e18cfb13a
[]
no_license
raine0524/base_utility
827a425018363c39702811c0874f02bf29c95697
d30efcb9bd67101a7e86aebcd3040a5670cd0d2e
refs/heads/master
2020-05-27T14:32:06.529608
2015-02-11T10:00:13
2015-02-11T10:00:13
30,641,579
0
0
null
null
null
null
GB18030
C++
false
false
9,574
cpp
Logger.cpp
/* KLog.cpp 日志类 */ #include "stdafx.h" #include "KBASE/Logger.h" #include "KBASE/AutoLock.h" #include "KBASE/Utils.h" #include "KBASE/DateTime.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifndef MAX_PATH #define MAX_PATH 256 #endif #define MAX_LOG_SIZE 200*1024*1024 KLogger* g_pLogger = NULL; int g_ModuleId = 0; FILE* g_LogFile = NULL; #ifndef WIN32 int getProcessName(char* processName, int len) { int count = 0; int nIndex = 0; char chPath[256] = {0}; char cParam[100] = {0}; char *cTem = chPath; int tmp_len; pid_t pId = getpid(); sprintf(cParam, "/proc/%d/exe", pId); count = readlink(cParam, chPath, 256); if (count < 0 || count >= 256) { return -1; } else { nIndex = count - 1; for( ; nIndex >= 0; nIndex--) { if( chPath[nIndex] == '/') { nIndex++; cTem += nIndex; break; } } } tmp_len = strlen(cTem); if (0 == tmp_len) { return -1; } if (len <= tmp_len + 1) { return -1; } strcpy(processName, cTem); return 0; } #endif bool IsExist(std::string path) { #ifdef WIN32 WIN32_FIND_DATAA wfd; bool rValue = 0 , res = false; HANDLE nFind = FindFirstFileA(path.c_str(),&wfd); if((nFind == INVALID_HANDLE_VALUE && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) || (path.substr(1.1).compare(":")==0)) { res = true; } else { res = false; } FindClose(nFind); return res; #else if (access(path.c_str(),0) == 0) { return true; } else { return false; } #endif } void CreateDirectoryR(std::string path) { #ifdef WIN32 char *key = "\\"; #else char *key = "/"; #endif { std::string parentPath = path.substr(0,path.find_last_of(key)); if(!IsExist(parentPath)){ CreateDirectoryR(parentPath); } #ifdef WIN32 CreateDirectoryA(path.c_str(),NULL); #else mkdir(path.c_str(),0755); #endif } } unsigned long get_file_size(const char *filename) { #ifdef WIN32 return 0; #else struct stat f_stat; if (stat(filename, &f_stat) == -1) { printf("get_file_size failed\r\n"); return -1; } return (long)f_stat.st_size; #endif } // void InitFd() // { // char filePath[MAX_PATH]={0}; // // KFormatDateTime dtNow; // GetNow(dtNow); // char pDayInfo[50]; // sprintf(pDayInfo , "%d-%d-%d",dtNow.GetYear(),dtNow.GetMonth(),dtNow.GetMDay()); // // { // #ifdef WIN32 // GetModuleFileNameA(NULL, filePath, MAX_PATH); // std::string LogDir("\\log\\avcond\\"); // std::string LogName("\\avconlog-"); // char *key = "\\"; // #else // strcpy(filePath,"/opt/avcon/avcond"); // std::string LogDir("/log/avcond/"); // std::string LogName("/avconlog-"); // char *key = "/"; // #endif // std::string p(filePath); // #ifdef WIN32 // std::string processName = p.substr(p.find_last_of(key)+1,p.length()); // processName=processName.substr(0,processName.find_last_of(".")==-1?processName.length():processName.find_last_of(".")); // p = p.substr(0 , p.find_last_of(key)==0?p.length():p.find_last_of(key)); // #else // char pProcessName[20]; // getProcessName(pProcessName,sizeof(pProcessName)); // std::string processName(pProcessName); // #endif // p += LogDir; // p += processName; // CreateDirectoryR(p); // p += LogName; // p += pDayInfo; // p += ".txt"; // g_LogFile = fopen(p.c_str() , "w"); // } // } //--------------------------------------------------------------------------------------- KLogger::KLogger() :m_nLevel(LL_ERROR) { } //--------------------------------------------------------------------------------------- KLogger::~KLogger() { } void KLogger::InitFd() { #ifndef WIN32 m_strFileDir = "/opt/avcon/avcond/log/avcond/"; char pProcessName[20]; getProcessName(pProcessName,sizeof(pProcessName)); std::string processName(pProcessName); m_strFileDir += processName + "/"; CreateDirectoryR(m_strFileDir); if(m_strFilePath.empty()) { CreateNewFile(); } #endif } void KLogger::CreateNewFile() { KFormatDateTime dtNow; GetNow(dtNow); char pLogFile[50]; sprintf(pLogFile , "%04d%02d%02d-%02d%02d%02d.log",dtNow.GetYear(),dtNow.GetMonth(),dtNow.GetMDay(),dtNow.GetHour(),dtNow.GetMinute(),dtNow.GetSecond()); m_strFilePath = m_strFileDir + pLogFile; } //--------------------------------------------------------------------------------------- // 初始化日志文件 bool KLogger::Open(LOG_LEVEL nLevel) { //日志级别 if(nLevel!=LL_NONE && nLevel!=LL_ERROR && nLevel!=LL_INFO && nLevel!=LL_DEBUG && nLevel!=LL_FILE) { return false; } m_nLevel = nLevel; InitFd(); return true; } //--------------------------------------------------------------------------------------- // 关闭日志文件 void KLogger::Close() { /*fclose(g_LogFile);*/ } //--------------------------------------------------------------------------------------- void KLogger::SetLevel(LOG_LEVEL nLevel) { if(nLevel!=LL_NONE && nLevel!=LL_ERROR && nLevel!=LL_INFO && nLevel!=LL_DEBUG && nLevel!=LL_FILE) { return; } m_nLevel = nLevel; } //--------------------------------------------------------------------------------------- LOG_LEVEL KLogger::GetLevel(void) { return m_nLevel; } //--------------------------------------------------------------------------------------- // 写日志 void KLogger::Write(const char* fmt,va_list args) { if(m_nLevel==LL_NONE) { return; } //合成日志信息 KFormatDateTime dtNow; GetNow(dtNow); std::string strNow = ""; dtNow.GetDateTime(strNow); char buffer1[2048]={0}; #ifdef WIN32 _vsnprintf(buffer1,sizeof(buffer1),fmt,args); #else vsnprintf(buffer1,sizeof(buffer1),fmt,args); #endif char buffer2[4096]={0}; snprintf(buffer2, sizeof(buffer2), "[%s] %s",strNow.c_str(),buffer1); #ifdef _WINDOWS TRACE(buffer2); #endif //日志输出到控制台 printf(buffer2); fflush(stdout); } //--------------------------------------------------------------------------------------- //写日志到文件 void KLogger::WriteFile(const char* fmt,va_list args) { if(m_nLevel==LL_NONE) { return; } KFormatDateTime dtNow; GetNow(dtNow); std::string strNow = ""; dtNow.GetDateTime(strNow); char buffer1[2048]={0}; char ServId[10]; #ifdef WIN32 _vsnprintf(buffer1,sizeof(buffer1),fmt,args); #else vsnprintf(buffer1,sizeof(buffer1),fmt,args); #endif char buffer2[4096]={0}; snprintf(buffer2, sizeof(buffer2), "[%s] %s",strNow.c_str(),buffer1); printf(buffer2); fflush(stdout); #ifndef WIN32 unsigned ulFileSize = get_file_size(m_strFilePath.c_str()); if(ulFileSize > MAX_LOG_SIZE || ulFileSize < 0) { printf("file size is %d\r\n",ulFileSize); CreateNewFile(); } FILE* pFile = fopen(m_strFilePath.c_str(),"a+"); if(NULL == pFile) { printf("[KBASE] Open log file failed\r\n"); return; } fprintf(pFile , "%s" , buffer2); fflush(pFile); fclose(pFile); #endif } //--------------------------------------------------------------------------------------- bool LOG::START(LOG_LEVEL nLevel) { if(g_pLogger==NULL) { g_pLogger = new KLogger(); return g_pLogger->Open(nLevel); } return true; } //--------------------------------------------------------------------------------------- void LOG::STOP() { if(g_pLogger) { g_pLogger->Close(); delete g_pLogger; g_pLogger=NULL; } } //--------------------------------------------------------------------------------------- void LOG::SETLEVEL(LOG_LEVEL nLevel) { if(g_pLogger) { g_pLogger->SetLevel(nLevel); } } //--------------------------------------------------------------------------------------- // DEBUG void LOG::DBG(const char* fmt,...) { if(g_pLogger) { LOG_LEVEL nLevel = g_pLogger->GetLevel(); if(nLevel >= LL_DEBUG) { va_list args; va_start(args, fmt); if (nLevel == LL_FILE) { g_pLogger->WriteFile(fmt,args); }else{ g_pLogger->Write(fmt,args); } va_end(args); } } } //--------------------------------------------------------------------------------------- // INFO void LOG::INF( const char* fmt,...) { if(g_pLogger) { LOG_LEVEL nLevel = g_pLogger->GetLevel(); if(nLevel >= LL_INFO) { va_list args; va_start(args, fmt); if (nLevel == LL_FILE) { g_pLogger->WriteFile(fmt,args); }else{ g_pLogger->Write(fmt,args); } va_end(args); } } } //--------------------------------------------------------------------------------------- // ERROR void LOG::ERR(const char* fmt,...) { if(g_pLogger) { LOG_LEVEL nLevel = g_pLogger->GetLevel(); if(nLevel >= LL_ERROR) { va_list args; va_start(args, fmt); if (nLevel == LL_FILE) { g_pLogger->WriteFile(fmt,args); }else{ g_pLogger->Write(fmt,args); } va_end(args); } } }
da6f5577160a2f3b4334f20afbc732454239532b
955129b4b7bcb4264be57cedc0c8898aeccae1ca
/python/mof/cpp/req_modify_guild_notice.h
8e146b80f925d784d868c11a8ce80f78ba907e09
[]
no_license
PenpenLi/Demos
cf270b92c7cbd1e5db204f5915a4365a08d65c44
ec90ebea62861850c087f32944786657bd4bf3c2
refs/heads/master
2022-03-27T07:33:10.945741
2019-12-12T08:19:15
2019-12-12T08:19:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
299
h
req_modify_guild_notice.h
#ifndef MOF_REQ_MODIFY_GUILD_NOTICE_H #define MOF_REQ_MODIFY_GUILD_NOTICE_H class req_modify_guild_notice{ public: void req_modify_guild_notice(void); void decode(ByteArray &); void PacketName(void); void ~req_modify_guild_notice(); void build(ByteArray &); void encode(ByteArray &); } #endif
be826dd32caa37a589a038a3efefa9c9cc92435f
54c67306d63bb69a5cf381d12108d3dc98ae0f5d
/common/goos/Interpreter.cpp
446704be11ce4ab752c6d2f958d5d296091d29bd
[ "ISC" ]
permissive
open-goal/jak-project
adf30a3459c24afda5b180e3abe1583c93458a37
d96dce27149fbf58586160cfecb634614f055943
refs/heads/master
2023-09-01T21:51:16.736237
2023-09-01T16:10:59
2023-09-01T16:10:59
289,585,720
1,826
131
ISC
2023-09-14T13:27:47
2020-08-22T23:55:21
Common Lisp
UTF-8
C++
false
false
63,363
cpp
Interpreter.cpp
/*! * @file Interpreter.cpp * The GOOS Interpreter and implementation of special and "built-in forms" */ #include "Interpreter.h" #include <utility> #include "ParseHelpers.h" #include "common/goos/Printer.h" #include "common/log/log.h" #include "common/util/FileUtil.h" #include "common/util/string_util.h" #include "common/util/unicode_util.h" #include "third-party/fmt/core.h" namespace goos { Interpreter::Interpreter(const std::string& username) { // Interpreter startup: // create the GOOS global environment global_environment = EnvironmentObject::make_new("global"); // create the environment which is be visible from GOAL goal_env = EnvironmentObject::make_new("goal"); // make both environments available in both. define_var_in_env(global_environment, global_environment, "*global-env*"); define_var_in_env(global_environment, goal_env, "*goal-env*"); define_var_in_env(goal_env, goal_env, "*goal-env*"); define_var_in_env(goal_env, global_environment, "*global-env*"); // set user profile name auto user = SymbolObject::make_new(reader.symbolTable, username); define_var_in_env(global_environment, user, "*user*"); define_var_in_env(goal_env, user, "*user*"); // setup maps special_forms = { {"define", &Interpreter::eval_define}, {"quote", &Interpreter::eval_quote}, {"set!", &Interpreter::eval_set}, {"lambda", &Interpreter::eval_lambda}, {"cond", &Interpreter::eval_cond}, {"or", &Interpreter::eval_or}, {"and", &Interpreter::eval_and}, {"macro", &Interpreter::eval_macro}, {"quasiquote", &Interpreter::eval_quasiquote}, {"while", &Interpreter::eval_while}, }; builtin_forms = {{"top-level", &Interpreter::eval_begin}, {"begin", &Interpreter::eval_begin}, {"exit", &Interpreter::eval_exit}, {"read", &Interpreter::eval_read}, {"read-data-file", &Interpreter::eval_read_data_file}, {"read-file", &Interpreter::eval_read_file}, {"print", &Interpreter::eval_print}, {"inspect", &Interpreter::eval_inspect}, {"load-file", &Interpreter::eval_load_file}, {"try-load-file", &Interpreter::eval_try_load_file}, {"eq?", &Interpreter::eval_equals}, {"gensym", &Interpreter::eval_gensym}, {"eval", &Interpreter::eval_eval}, {"cons", &Interpreter::eval_cons}, {"car", &Interpreter::eval_car}, {"cdr", &Interpreter::eval_cdr}, {"set-car!", &Interpreter::eval_set_car}, {"set-cdr!", &Interpreter::eval_set_cdr}, {"+", &Interpreter::eval_plus}, {"-", &Interpreter::eval_minus}, {"*", &Interpreter::eval_times}, {"/", &Interpreter::eval_divide}, {"=", &Interpreter::eval_numequals}, {"<", &Interpreter::eval_lt}, {">", &Interpreter::eval_gt}, {"<=", &Interpreter::eval_leq}, {">=", &Interpreter::eval_geq}, {"null?", &Interpreter::eval_null}, {"type?", &Interpreter::eval_type}, {"fmt", &Interpreter::eval_format}, {"error", &Interpreter::eval_error}, {"string-ref", &Interpreter::eval_string_ref}, {"string-length", &Interpreter::eval_string_length}, {"string-append", &Interpreter::eval_string_append}, {"string-starts-with?", &Interpreter::eval_string_starts_with}, {"string-ends-with?", &Interpreter::eval_string_ends_with}, {"string-split", &Interpreter::eval_string_split}, {"string-substr", &Interpreter::eval_string_substr}, {"ash", &Interpreter::eval_ash}, {"symbol->string", &Interpreter::eval_symbol_to_string}, {"string->symbol", &Interpreter::eval_string_to_symbol}, {"get-environment-variable", &Interpreter::eval_get_env}, {"make-string-hash-table", &Interpreter::eval_make_string_hash_table}, {"hash-table-set!", &Interpreter::eval_hash_table_set}, {"hash-table-try-ref", &Interpreter::eval_hash_table_try_ref}}; string_to_type = {{"empty-list", ObjectType::EMPTY_LIST}, {"integer", ObjectType::INTEGER}, {"float", ObjectType::FLOAT}, {"char", ObjectType::CHAR}, {"symbol", ObjectType::SYMBOL}, {"string", ObjectType::STRING}, {"pair", ObjectType::PAIR}, {"array", ObjectType::ARRAY}, {"lambda", ObjectType::LAMBDA}, {"macro", ObjectType::MACRO}, {"environment", ObjectType::ENVIRONMENT}}; // load the standard library load_goos_library(); } /*! * Add a user defined special form. The given function will be called with unevaluated arguments. * Lookup from these forms occurs after special/builtin, but before any env lookups. */ void Interpreter::register_form( const std::string& name, const std::function< Object(const Object&, Arguments&, const std::shared_ptr<EnvironmentObject>&)>& form) { m_custom_forms[name] = form; } Interpreter::~Interpreter() { // There are some circular references that prevent shared_ptrs from cleaning up if we // don't do this. global_environment.as_env()->vars.clear(); goal_env.as_env()->vars.clear(); } /*! * Disable printfs on errors, to make test output look less messy. */ void Interpreter::disable_printfs() { disable_printing = true; } /*! * Load the goos library, by interpreting (load-file "goal_src/goos-lib.gs") in the global env. */ void Interpreter::load_goos_library() { auto cmd = "(load-file \"goal_src/goos-lib.gs\")"; eval_with_rewind(reader.read_from_string(cmd), global_environment.as_env_ptr()); } /*! * In env, set the variable named "name" to the value var. */ void Interpreter::define_var_in_env(Object& env, Object& var, const std::string& name) { env.as_env()->vars[intern_ptr(name)] = var; } /*! * Get a symbol with the given name, creating one if none exist. */ Object Interpreter::intern(const std::string& name) { return SymbolObject::make_new(reader.symbolTable, name); } HeapObject* Interpreter::intern_ptr(const std::string& name) { return reader.symbolTable.intern_ptr(name); } /*! * Display the REPL, which will run until the user executes exit. */ void Interpreter::execute_repl(REPL::Wrapper& repl) { want_exit = false; while (!want_exit) { try { // read something from the user auto obj = reader.read_from_stdin("goos> ", repl); if (!obj) { continue; } // evaluate Object evald = eval_with_rewind(*obj, global_environment.as_env_ptr()); // print printf("%s\n", evald.print().c_str()); } catch (std::exception& e) { printf("REPL Error: %s\n", e.what()); } } } /*! * Signal an evaluation error. This throws an exception which will unwind the evaluation stack * for debugging. */ void Interpreter::throw_eval_error(const Object& o, const std::string& err) { throw std::runtime_error("[GOOS] Evaluation error on " + o.print() + ": " + err + "\n" + reader.db.get_info_for(o)); } /*! * Evaluate the given expression, with a "checkpoint" in the evaluation stack here. If there is an * evaluation error, there will be a print indicating there was an error in the evaluation of "obj", * and if possible what file/line "obj" comes from. */ Object Interpreter::eval_with_rewind(const Object& obj, const std::shared_ptr<EnvironmentObject>& env) { try { return eval(obj, env); } catch (std::runtime_error& e) { if (!disable_printing) { printf("-----------------------------------------\n"); printf("From object %s\nat %s\n", obj.inspect().c_str(), reader.db.get_info_for(obj).c_str()); } throw e; } } /*! * Sets dest to the global variable with the given name, if the variable exists. * Returns if the variable was found. */ bool Interpreter::get_global_variable_by_name(const std::string& name, Object* dest) { auto kv = global_environment.as_env()->vars.find( SymbolObject::make_new(reader.symbolTable, name).as_symbol()); if (kv != global_environment.as_env()->vars.end()) { *dest = kv->second; return true; } return false; } /*! * Sets the variable to the value. Overwrites an existing value, or creates a new global. */ void Interpreter::set_global_variable_by_name(const std::string& name, const Object& value) { auto sym = SymbolObject::make_new(reader.symbolTable, name).as_symbol(); global_environment.as_env()->vars[sym] = value; } void Interpreter::set_global_variable_to_symbol(const std::string& name, const std::string& value) { auto sym = SymbolObject::make_new(reader.symbolTable, value); set_global_variable_by_name(name, sym); } void Interpreter::set_global_variable_to_int(const std::string& name, int value) { set_global_variable_by_name(name, Object::make_integer(value)); } /*! * Get arguments being passed to a form. Don't evaluate them. There are two modes, "varargs" and * "not varargs". With varargs enabled, any number of unnamed and named arguments can be given. * Without varags, the unnamed/named arguments must match the spec. By default specs are "not * vararg" - use make_varags() to get a varargs spec. In general, macros/lambdas use specs, but * built-in forms use varargs. * * If form is "varargs", all arguments go to unnamed or named. * Ex: (.... a b :key-1 c d) will put a, b, d in unnamed and d in key-1 * * If form isn't "varargs", the expected number of unnamed arguments must match, unless "rest" * is specified, in which case the additional arguments are stored in rest. * * Also, if "varargs" isn't set, all keyword arguments must be defined. If the use doesn't provide * a value, the default value will be used instead. */ Arguments Interpreter::get_args(const Object& form, const Object& rest, const ArgumentSpec& spec) { Arguments args; // loop over forms in list const Object* current = &rest; while (!current->is_empty_list()) { const auto& arg = current->as_pair()->car; // did we get a ":keyword" if (arg.is_symbol() && arg.as_symbol()->name.at(0) == ':') { auto key_name = arg.as_symbol()->name.substr(1); const auto& kv = spec.named.find(key_name); // check for unknown key name if (!spec.varargs && kv == spec.named.end()) { throw_eval_error(form, "Key argument " + key_name + " wasn't expected"); } // check for multiple definition of key if (args.named.find(key_name) != args.named.end()) { throw_eval_error(form, "Key argument " + key_name + " multiply defined"); } // check for well-formed :key value expression current = &current->as_pair()->cdr; if (current->is_empty_list()) { throw_eval_error(form, "Key argument didn't have a value"); } args.named[key_name] = current->as_pair()->car; } else { // not a keyword. Add to unnamed or rest, depending on what we expect if (spec.varargs || args.unnamed.size() < spec.unnamed.size()) { args.unnamed.push_back(arg); } else { args.rest.push_back(arg); } } current = &current->as_pair()->cdr; } // Check expected key args and set default values on unset ones if possible for (auto& kv : spec.named) { const auto& defined_kv = args.named.find(kv.first); if (defined_kv == args.named.end()) { // key arg not given by user, try to use a default value. if (kv.second.has_default) { args.named[kv.first] = kv.second.default_value; } else { throw_eval_error(form, "key argument \"" + kv.first + "\" wasn't given and has no default value"); } } } // Check argument size, if spec defines it if (!spec.varargs) { if (args.unnamed.size() < spec.unnamed.size()) { throw_eval_error(form, "didn't get enough arguments"); } ASSERT(args.unnamed.size() == spec.unnamed.size()); if (!args.rest.empty() && spec.rest.empty()) { throw_eval_error(form, "got too many arguments"); } } return args; } /*! * Same as get_args, but named :key arguments are not parsed. */ Arguments Interpreter::get_args_no_named(const Object& form, const Object& rest, const ArgumentSpec& spec) { Arguments args; // Check expected key args, which should be none if (!spec.named.empty()) { throw_eval_error(form, "key arguments were expected in get_args_no_named"); } // loop over forms in list Object current = rest; while (!current.is_empty_list()) { auto arg = current.as_pair()->car; // not a keyword. Add to unnamed or rest, depending on what we expect if (spec.varargs || args.unnamed.size() < spec.unnamed.size()) { args.unnamed.push_back(arg); } else { args.rest.push_back(arg); } current = current.as_pair()->cdr; } // Check argument size, if spec defines it if (!spec.varargs) { if (args.unnamed.size() < spec.unnamed.size()) { throw_eval_error(form, "didn't get enough arguments"); } ASSERT(args.unnamed.size() == spec.unnamed.size()); if (!args.rest.empty() && spec.rest.empty()) { throw_eval_error(form, "got too many arguments"); } } return args; } /*! * Evaluate arguments in-place in the given environment. * Evaluation order is: * - unnamed, in order of appearance * - keyword, in alphabetical order * - rest, in order of appearance * * Note that in varargs mode, all unnamed arguments are put in unnamed, not rest. */ void Interpreter::eval_args(Arguments* args, const std::shared_ptr<EnvironmentObject>& env) { for (auto& arg : args->unnamed) { arg = eval_with_rewind(arg, env); } for (auto& kv : args->named) { kv.second = eval_with_rewind(kv.second, env); } for (auto& arg : args->rest) { arg = eval_with_rewind(arg, env); } } /*! * Parse argument spec found in lambda/macro definition. * Like (x y &key z &key (w my-default-value) &rest body) */ ArgumentSpec Interpreter::parse_arg_spec(const Object& form, Object& rest) { ArgumentSpec spec; Object current = rest; while (!current.is_empty_list()) { auto arg = current.as_pair()->car; if (!arg.is_symbol()) { throw_eval_error(form, "args must be symbols"); } if (arg.as_symbol()->name == "&rest") { // special case for &rest current = current.as_pair()->cdr; if (!current.is_pair()) { throw_eval_error(form, "rest arg must have a name"); } auto rest_name = current.as_pair()->car; if (!rest_name.is_symbol()) { throw_eval_error(form, "rest name must be a symbol"); } spec.rest = rest_name.as_symbol()->name; if (!current.as_pair()->cdr.is_empty_list()) { throw_eval_error(form, "rest must be the last argument"); } } else if (arg.as_symbol()->name == "&key") { // special case for &key current = current.as_pair()->cdr; auto key_arg = current.as_pair()->car; if (key_arg.is_symbol()) { // form is &key name auto key_arg_name = key_arg.as_symbol()->name; if (spec.named.find(key_arg_name) != spec.named.end()) { throw_eval_error(form, "key argument " + key_arg_name + " multiply defined"); } spec.named[key_arg_name] = NamedArg(); } else if (key_arg.is_pair()) { // form is &key (name default-value) auto key_iter = key_arg; auto kn = key_iter.as_pair()->car; key_iter = key_iter.as_pair()->cdr; if (!kn.is_symbol()) { throw_eval_error(form, "key argument must have a symbol as a name"); } auto key_arg_name = kn.as_symbol()->name; if (spec.named.find(key_arg_name) != spec.named.end()) { throw_eval_error(form, "key argument " + key_arg_name + " multiply defined"); } NamedArg na; if (!key_iter.is_pair()) { throw_eval_error(form, "invalid keyword argument definition"); } na.has_default = true; na.default_value = key_iter.as_pair()->car; if (!key_iter.as_pair()->cdr.is_empty_list()) { throw_eval_error(form, "invalid keyword argument definition"); } spec.named[key_arg_name] = na; } else { throw_eval_error(form, "invalid key argument"); } } else { spec.unnamed.push_back(arg.as_symbol()->name); } current = current.as_pair()->cdr; } return spec; } /*! * Argument check. * Must have the right number of unnamed arguments, with the right type. * Keyword arguments have a bool for "required" or not. * Extra keyword arguments are an error. */ void Interpreter::vararg_check( const Object& form, const Arguments& args, const std::vector<std::optional<ObjectType>>& unnamed, const std::unordered_map<std::string, std::pair<bool, std::optional<ObjectType>>>& named) { std::string err; if (!va_check(args, unnamed, named, &err)) { throw_eval_error(form, err); } } /*! * Evaluate a list and return the result of the last evaluation. */ Object Interpreter::eval_list_return_last(const Object& form, Object rest, const std::shared_ptr<EnvironmentObject>& env) { Object o = std::move(rest); Object rv = Object::make_empty_list(); for (;;) { if (o.is_pair()) { auto op = o.as_pair(); rv = eval_with_rewind(op->car, env); o = op->cdr; } else if (o.is_empty_list()) { return rv; } else { throw_eval_error(form, "malformed body to evaluate"); } } } /*! * If o isn't an environment object, throws an evaluation error on form. */ void Interpreter::expect_env(const Object& form, const Object& o) { if (!o.is_env()) { throw_eval_error(form, "Object " + o.print() + " is a " + object_type_to_string(o.type) + " but was expected to be an environment"); } } /*! * Highest-level evaluation dispatch. */ Object Interpreter::eval(Object obj, const std::shared_ptr<EnvironmentObject>& env) { switch (obj.type) { case ObjectType::SYMBOL: return eval_symbol(obj, env); case ObjectType::PAIR: return eval_pair(obj, env); case ObjectType::INTEGER: case ObjectType::FLOAT: case ObjectType::STRING: case ObjectType::CHAR: return obj; default: throw_eval_error(obj, "cannot evaluate this object"); return Object(); } } namespace { /*! * Try to find a symbol in an env or parent env. If successful, set dest and return true. Otherwise * return false. */ bool try_symbol_lookup(const Object& sym, const std::shared_ptr<EnvironmentObject>& env, Object* dest) { // booleans are hard-coded here if (sym.as_symbol()->name == "#t" || sym.as_symbol()->name == "#f") { *dest = sym; return true; } // loop up envs until we find it. EnvironmentObject* search_env = env.get(); for (;;) { const auto& kv = search_env->vars.find(sym.as_symbol()); if (kv != search_env->vars.end()) { *dest = kv->second; return true; } auto pe = search_env->parent_env.get(); if (pe) { search_env = pe; } else { return false; } } } } // namespace /*! * Evaluate a symbol by finding the closest scoped variable with matching name. */ Object Interpreter::eval_symbol(const Object& sym, const std::shared_ptr<EnvironmentObject>& env) { Object result; if (!try_symbol_lookup(sym, env, &result)) { throw_eval_error(sym, "symbol is not defined"); } return result; } bool Interpreter::eval_symbol(const Object& sym, const std::shared_ptr<EnvironmentObject>& env, Object* result) { return try_symbol_lookup(sym, env, result); } /*! * Evaluate a pair, either as special form, builtin form, macro application, or lambda application. */ Object Interpreter::eval_pair(const Object& obj, const std::shared_ptr<EnvironmentObject>& env) { const auto& pair = obj.as_pair(); const Object& head = pair->car; const Object& rest = pair->cdr; // first see if we got a symbol: if (head.type == ObjectType::SYMBOL) { const auto& head_sym = head.as_symbol(); // try a special form first const auto& kv_sf = special_forms.find(head_sym->name); if (kv_sf != special_forms.end()) { return ((*this).*(kv_sf->second))(obj, rest, env); } // try builtins next const auto& kv_b = builtin_forms.find(head_sym->name); if (kv_b != builtin_forms.end()) { Arguments args = get_args(obj, rest, make_varargs()); // all "built-in" forms expect arguments to be evaluated (that's why they aren't special) eval_args(&args, env); return ((*this).*(kv_b->second))(obj, args, env); } // try custom forms next const auto& kv_u = m_custom_forms.find(head_sym->name); if (kv_u != m_custom_forms.end()) { Arguments args = get_args(obj, rest, make_varargs()); return (kv_u->second)(obj, args, env); } // try macros next Object macro_obj; if (try_symbol_lookup(head, env, &macro_obj) && macro_obj.is_macro()) { const auto& macro = macro_obj.as_macro(); Arguments args = get_args(obj, rest, macro->args); auto mac_env_obj = EnvironmentObject::make_new(); auto mac_env = mac_env_obj.as_env_ptr(); mac_env->parent_env = env; // not 100% clear that this is right set_args_in_env(obj, args, macro->args, mac_env); // expand the macro! return eval_with_rewind(eval_list_return_last(macro->body, macro->body, mac_env), env); } } // eval the head and try it as a lambda Object eval_head = eval_with_rewind(head, env); if (eval_head.type != ObjectType::LAMBDA) { throw_eval_error(obj, "head of form didn't evaluate to lambda"); } const auto& lam = eval_head.as_lambda(); Arguments args = get_args(obj, rest, lam->args); eval_args(&args, env); auto lam_env_obj = EnvironmentObject::make_new(); auto lam_env = lam_env_obj.as_env_ptr(); lam_env->parent_env = lam->parent_env; set_args_in_env(obj, args, lam->args, lam_env); return eval_list_return_last(lam->body, lam->body, lam_env); } /*! * Given some arguments, an argument spec, and and environment, define the arguments are variables * in the environment. */ void Interpreter::set_args_in_env(const Object& form, const Arguments& args, const ArgumentSpec& arg_spec, const std::shared_ptr<EnvironmentObject>& env) { if (arg_spec.rest.empty() && args.unnamed.size() != arg_spec.unnamed.size()) { throw_eval_error(form, "did not get the expected number of unnamed arguments (got " + std::to_string(args.unnamed.size()) + ", expected " + std::to_string(arg_spec.unnamed.size()) + ")"); } else if (!arg_spec.rest.empty() && args.unnamed.size() < arg_spec.unnamed.size()) { throw_eval_error(form, "args with rest didn't get enough arguments (got " + std::to_string(args.unnamed.size()) + " but need at least " + std::to_string(arg_spec.unnamed.size()) + ")"); } // unnamed args for (size_t i = 0; i < arg_spec.unnamed.size(); i++) { env->vars[intern(arg_spec.unnamed.at(i)).as_symbol()] = args.unnamed.at(i); } // named args for (const auto& kv : arg_spec.named) { env->vars[intern(kv.first).as_symbol()] = args.named.at(kv.first); } // rest args if (!arg_spec.rest.empty()) { // will correctly handle the '() case env->vars[intern(arg_spec.rest).as_symbol()] = build_list(args.rest); } else { if (!args.rest.empty()) { throw_eval_error(form, "got too many arguments"); } } } /*! * Define a variable in the current environment. The env can be overwritten with :env keyword arg */ Object Interpreter::eval_define(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { auto args = get_args(form, rest, make_varargs()); vararg_check(form, args, {ObjectType::SYMBOL, {}}, {{"env", {false, {}}}}); auto define_env = env; if (args.has_named("env")) { auto result = eval_with_rewind(args.get_named("env"), env); expect_env(form, result); define_env = result.as_env_ptr(); } Object value = eval_with_rewind(args.unnamed[1], env); define_env->vars[args.unnamed[0].as_symbol()] = value; return value; } /*! * Set an existing variable. If there is no existing variable in the current environment, will * look at the parent environment. */ Object Interpreter::eval_set(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { auto args = get_args(form, rest, make_varargs()); vararg_check(form, args, {ObjectType::SYMBOL, {}}, {}); auto to_define = args.unnamed.at(0); Object to_set = eval_with_rewind(args.unnamed.at(1), env); std::shared_ptr<EnvironmentObject> search_env = env; for (;;) { auto kv = search_env->vars.find(to_define.as_symbol()); if (kv != search_env->vars.end()) { kv->second = to_set; return kv->second; } auto pe = search_env->parent_env; if (pe) { search_env = pe; } else { throw_eval_error(to_define, "symbol is not defined"); } } } /*! * Lambda definition special form. */ Object Interpreter::eval_lambda(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (!rest.is_pair()) { throw_eval_error(form, "lambda must receive two arguments"); } Object arg_list = rest.as_pair()->car; if (!arg_list.is_pair() && !arg_list.is_empty_list()) { throw_eval_error(form, "lambda argument list must be a list"); } Object new_lambda = LambdaObject::make_new(); auto l = new_lambda.as_lambda(); l->args = parse_arg_spec(form, arg_list); Object rrest = rest.as_pair()->cdr; if (!rrest.is_pair()) { throw_eval_error(form, "lambda body must be a list"); } l->body = rrest; l->parent_env = env; return new_lambda; } /*! * Macro definition special form. */ Object Interpreter::eval_macro(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (!rest.is_pair()) { throw_eval_error(form, "macro must receive two arguments"); } Object arg_list = rest.as_pair()->car; if (!arg_list.is_pair() && !arg_list.is_empty_list()) { throw_eval_error(form, "macro argument list must be a list"); } Object new_macro = MacroObject::make_new(); auto m = new_macro.as_macro(); m->args = parse_arg_spec(form, arg_list); Object rrest = rest.as_pair()->cdr; if (!rrest.is_pair()) { throw_eval_error(form, "macro body must be a list"); } m->body = rrest; m->parent_env = env; return new_macro; } /*! * Quote special form: (quote x) -> x */ Object Interpreter::eval_quote(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { (void)env; auto args = get_args_no_named(form, rest, make_varargs()); if (args.unnamed.size() != 1) { throw_eval_error(form, "invalid number of arguments to quote"); } return args.unnamed.front(); } /*! * Recursive quasi-quote evaluation */ Object Interpreter::quasiquote_helper(const Object& form, const std::shared_ptr<EnvironmentObject>& env) { const Object* lst_iter = &form; std::vector<Object> result; for (;;) { if (lst_iter->type == ObjectType::PAIR) { const Object& item = lst_iter->as_pair()->car; if (item.type == ObjectType::PAIR) { if (item.as_pair()->car.type == ObjectType::SYMBOL && item.as_pair()->car.as_symbol()->name == "unquote") { const Object& unquote_arg = item.as_pair()->cdr; if (unquote_arg.type != ObjectType::PAIR || unquote_arg.as_pair()->cdr.type != ObjectType::EMPTY_LIST) { throw_eval_error(form, "unquote must have exactly 1 arg"); } result.push_back(eval_with_rewind(unquote_arg.as_pair()->car, env)); lst_iter = &lst_iter->as_pair()->cdr; continue; } else if (item.as_pair()->car.type == ObjectType::SYMBOL && item.as_pair()->car.as_symbol()->name == "unquote-splicing") { const Object& unquote_arg = item.as_pair()->cdr; if (unquote_arg.type != ObjectType::PAIR || unquote_arg.as_pair()->cdr.type != ObjectType::EMPTY_LIST) { throw_eval_error(form, "unquote must have exactly 1 arg"); } // bypass normal addition: lst_iter = &lst_iter->as_pair()->cdr; Object splice_result = eval_with_rewind(unquote_arg.as_pair()->car, env); const Object* to_add = &splice_result; for (;;) { if (to_add->type == ObjectType::PAIR) { result.push_back(to_add->as_pair()->car); to_add = &to_add->as_pair()->cdr; } else if (to_add->type == ObjectType::EMPTY_LIST) { break; } else { throw_eval_error(form, "malformed unquote-splicing result"); } } continue; } else { result.push_back(quasiquote_helper(item, env)); lst_iter = &lst_iter->as_pair()->cdr; continue; } } result.push_back(item); lst_iter = &lst_iter->as_pair()->cdr; } else if (lst_iter->type == ObjectType::EMPTY_LIST) { return build_list(std::move(result)); } else { throw_eval_error(form, "malformed quasiquote"); } } } /*! * Quasiquote (backtick) evaluation */ Object Interpreter::eval_quasiquote(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (rest.type != ObjectType::PAIR || rest.as_pair()->cdr.type != ObjectType::EMPTY_LIST) throw_eval_error(form, "quasiquote must have one argument!"); return quasiquote_helper(rest.as_pair()->car, env); } bool Interpreter::truthy(const Object& o) { return !(o.is_symbol() && o.as_symbol()->name == "#f"); } /*! * Scheme "cond" statement - tested by integrated tests only. */ Object Interpreter::eval_cond(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (rest.type != ObjectType::PAIR) throw_eval_error(form, "cond must have at least one clause, which must be a form"); Object result; Object lst = rest; for (;;) { if (lst.type == ObjectType::PAIR) { Object current_case = lst.as_pair()->car; if (current_case.type != ObjectType::PAIR) throw_eval_error(lst, "bogus cond case"); // check condition: Object condition_result = eval_with_rewind(current_case.as_pair()->car, env); if (truthy(condition_result)) { if (current_case.as_pair()->cdr.type == ObjectType::EMPTY_LIST) { return condition_result; } // got a match! return eval_list_return_last(current_case, current_case.as_pair()->cdr, env); } else { // no match, continue. lst = lst.as_pair()->cdr; } } else if (lst.type == ObjectType::EMPTY_LIST) { return SymbolObject::make_new(reader.symbolTable, "#f"); } else { throw_eval_error(form, "malformed cond"); } } } /*! * Short circuiting "or" statement */ Object Interpreter::eval_or(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (rest.type != ObjectType::PAIR) { throw_eval_error(form, "or must have at least one argument!"); } Object lst = rest; for (;;) { if (lst.type == ObjectType::PAIR) { Object current = eval_with_rewind(lst.as_pair()->car, env); if (truthy(current)) { return current; } lst = lst.as_pair()->cdr; } else if (lst.type == ObjectType::EMPTY_LIST) { return SymbolObject::make_new(reader.symbolTable, "#f"); } else { throw_eval_error(form, "invalid or form"); } } } /*! * Short circuiting "and" statement */ Object Interpreter::eval_and(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (rest.type != ObjectType::PAIR) { throw_eval_error(form, "and must have at least one argument!"); } Object lst = rest; Object current; for (;;) { if (lst.type == ObjectType::PAIR) { current = eval_with_rewind(lst.as_pair()->car, env); if (!truthy(current)) { return SymbolObject::make_new(reader.symbolTable, "#f"); } lst = lst.as_pair()->cdr; } else if (lst.type == ObjectType::EMPTY_LIST) { return current; } else { throw_eval_error(form, "invalid and form"); } } } /*! * Cheating "while loop" because we do not have tail recursion optimization yet. */ Object Interpreter::eval_while(const Object& form, const Object& rest, const std::shared_ptr<EnvironmentObject>& env) { if (rest.type != ObjectType::PAIR) { throw_eval_error(form, "while must have condition and body"); } Object condition = rest.as_pair()->car; Object body = rest.as_pair()->cdr; if (body.type != ObjectType::PAIR) { throw_eval_error(form, "while must have condition and body"); } Object rv = SymbolObject::make_new(reader.symbolTable, "#f"); while (truthy(eval_with_rewind(condition, env))) { rv = eval_list_return_last(form, body, env); } return rv; } /*! * Exit GOOS. Accepts and ignores all arguments; */ Object Interpreter::eval_exit(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)form; (void)args; (void)env; want_exit = true; return Object::make_empty_list(); } /*! * Begin form */ Object Interpreter::eval_begin(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; if (!args.named.empty()) { throw_eval_error(form, "begin form cannot have keyword arguments"); } if (args.unnamed.empty()) { return Object::make_empty_list(); } else { return args.unnamed.back(); } } /*! * Read form, which runs the Reader on a string. */ Object Interpreter::eval_read(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); try { return reader.read_from_string(args.unnamed.at(0).as_string()->data); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("reader error inside of read:\n") + e.what()); } return Object::make_empty_list(); } /*! * Reads list data from a file, returns the pair. Not a lot of safety here! */ Object Interpreter::eval_read_data_file(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); try { return reader.read_from_file({args.unnamed.at(0).as_string()->data}).as_pair()->cdr; } catch (std::runtime_error& e) { throw_eval_error(form, std::string("reader error inside of read-file:\n") + e.what()); } return Object::make_empty_list(); } /*! * Open and run the Reader on a text file. */ Object Interpreter::eval_read_file(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); try { return reader.read_from_file({args.unnamed.at(0).as_string()->data}); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("reader error inside of read-file:\n") + e.what()); } return Object::make_empty_list(); } /*! * Combines read-file and eval to load in a file. */ Object Interpreter::eval_load_file(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); Object o; try { o = reader.read_from_file({args.unnamed.at(0).as_string()->data}); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("reader error inside of load-file:\n") + e.what()); } try { return eval_with_rewind(o, global_environment.as_env_ptr()); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("eval error inside of load-file:\n") + e.what()); } return Object::make_empty_list(); } /*! * Combines read-file and eval to load in a file. Return #f if it doesn't exist. */ Object Interpreter::eval_try_load_file(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); auto path = {args.unnamed.at(0).as_string()->data}; if (!fs::exists(file_util::get_file_path(path))) { return SymbolObject::make_new(reader.symbolTable, "#f"); } Object o; try { o = reader.read_from_file(path); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("reader error inside of try-load-file:\n") + e.what()); } try { return eval_with_rewind(o, global_environment.as_env_ptr()); } catch (std::runtime_error& e) { throw_eval_error(form, std::string("eval error inside of try-load-file:\n") + e.what()); } return SymbolObject::make_new(reader.symbolTable, "#t"); } /*! * Print the form to stdout, including a newline. * Returns () */ Object Interpreter::eval_print(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}}, {}); if (!disable_printing) { printf("%s\n", args.unnamed.at(0).print().c_str()); } return Object::make_empty_list(); } /*! * Print the inspection of a form to stdout, including a newline. * Returns () */ Object Interpreter::eval_inspect(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}}, {}); if (!disable_printing) { printf("%s\n", args.unnamed.at(0).inspect().c_str()); } return Object::make_empty_list(); } /*! * Fancy equality check (using Object::operator==) */ Object Interpreter::eval_equals(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}, {}}, {}); return SymbolObject::make_new(reader.symbolTable, args.unnamed[0] == args.unnamed[1] ? "#t" : "#f"); } /*! * Convert a number to an integer */ IntType Interpreter::number_to_integer(const Object& obj) { switch (obj.type) { case ObjectType::INTEGER: return obj.integer_obj.value; case ObjectType::FLOAT: return (int64_t)obj.float_obj.value; case ObjectType::CHAR: return (int8_t)obj.char_obj.value; default: throw_eval_error(obj, "object cannot be interpreted as a number!"); } return 0; } /*! * Convert a number to floating point */ FloatType Interpreter::number_to_float(const Object& obj) { switch (obj.type) { case ObjectType::INTEGER: return obj.integer_obj.value; case ObjectType::FLOAT: return obj.float_obj.value; default: throw_eval_error(obj, "object cannot be interpreted as a number!"); } return 0; } /*! * Convert number to template type. */ template <> FloatType Interpreter::number(const Object& obj) { return number_to_float(obj); } /*! * Convert number to template type. */ template <> IntType Interpreter::number(const Object& obj) { return number_to_integer(obj); } /*! * Template implementation of addition. */ template <typename T> Object Interpreter::num_plus(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; (void)form; T result = 0; for (const auto& arg : args.unnamed) { result += number<T>(arg); } return Object::make_number<T>(result); } /*! * Addition */ Object Interpreter::eval_plus(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { if (!args.named.empty() || args.unnamed.empty()) { throw_eval_error(form, "+ must receive at least one unnamed argument!"); } switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_plus<int64_t>(form, args, env); case ObjectType::FLOAT: return num_plus<double>(form, args, env); default: throw_eval_error(form, "+ must have a numeric argument"); return Object::make_empty_list(); } } /*! * Template implementation of multiplication. */ template <typename T> Object Interpreter::num_times(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; (void)form; T result = 1; for (const auto& arg : args.unnamed) { result *= number<T>(arg); } return Object::make_number<T>(result); } /*! * Multiplication */ Object Interpreter::eval_times(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { if (!args.named.empty() || args.unnamed.empty()) { throw_eval_error(form, "* must receive at least one unnamed argument!"); } switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_times<int64_t>(form, args, env); case ObjectType::FLOAT: return num_times<double>(form, args, env); default: throw_eval_error(form, "* must have a numeric argument"); return Object::make_empty_list(); } } /*! * Template implementation of subtraction. */ template <typename T> Object Interpreter::num_minus(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; (void)form; T result; if (args.unnamed.size() > 1) { result = number<T>(args.unnamed[0]); for (uint32_t i = 1; i < args.unnamed.size(); i++) { result -= number<T>(args.unnamed[i]); } } else { result = -number<T>(args.unnamed[0]); } return Object::make_number<T>(result); } /*! * Subtraction */ Object Interpreter::eval_minus(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { if (!args.named.empty() || args.unnamed.empty()) { throw_eval_error(form, "- must receive at least one unnamed argument!"); } switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_minus<int64_t>(form, args, env); case ObjectType::FLOAT: return num_minus<double>(form, args, env); default: throw_eval_error(form, "- must have a numeric argument"); return Object::make_empty_list(); } } /*! * Template implementation of division. */ template <typename T> Object Interpreter::num_divide(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; (void)form; T result = number<T>(args.unnamed[0]) / number<T>(args.unnamed[1]); return Object::make_number<T>(result); } /*! * Division */ Object Interpreter::eval_divide(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}, {}}, {}); switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_divide<int64_t>(form, args, env); case ObjectType::FLOAT: return num_divide<double>(form, args, env); default: throw_eval_error(form, "/ must have a numeric argument"); return Object::make_empty_list(); } } /*! * Compare numbers for equality */ Object Interpreter::eval_numequals(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; if (!args.named.empty() || args.unnamed.size() < 2) { throw_eval_error(form, "= must receive at least two unnamed arguments!"); } bool result = true; switch (args.unnamed.front().type) { case ObjectType::INTEGER: { int64_t ref = number_to_integer(args.unnamed.front()); for (uint32_t i = 1; i < args.unnamed.size(); i++) { if (ref != number_to_integer(args.unnamed[i])) { result = false; break; } } } break; case ObjectType::FLOAT: { double ref = number_to_float(args.unnamed.front()); for (uint32_t i = 1; i < args.unnamed.size(); i++) { if (ref != number_to_float(args.unnamed[i])) { result = false; break; } } } break; default: throw_eval_error(form, "= must have a numeric argument"); return Object::make_empty_list(); } return SymbolObject::make_new(reader.symbolTable, result ? "#t" : "#f"); } template <typename T> Object Interpreter::num_lt(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)form; (void)env; T a = number<T>(args.unnamed[0]); T b = number<T>(args.unnamed[1]); return SymbolObject::make_new(reader.symbolTable, (a < b) ? "#t" : "#f"); } Object Interpreter::eval_lt(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}, {}}, {}); switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_lt<int64_t>(form, args, env); case ObjectType::FLOAT: return num_lt<double>(form, args, env); default: throw_eval_error(form, "< must have a numeric argument"); return Object::make_empty_list(); } } template <typename T> Object Interpreter::num_gt(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)form; (void)env; T a = number<T>(args.unnamed[0]); T b = number<T>(args.unnamed[1]); return SymbolObject::make_new(reader.symbolTable, (a > b) ? "#t" : "#f"); } Object Interpreter::eval_gt(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}, {}}, {}); switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_gt<int64_t>(form, args, env); case ObjectType::FLOAT: return num_gt<double>(form, args, env); default: throw_eval_error(form, "> must have a numeric argument"); return Object::make_empty_list(); } } template <typename T> Object Interpreter::num_leq(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)form; (void)env; T a = number<T>(args.unnamed[0]); T b = number<T>(args.unnamed[1]); return SymbolObject::make_new(reader.symbolTable, (a <= b) ? "#t" : "#f"); } Object Interpreter::eval_leq(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}, {}}, {}); switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_leq<int64_t>(form, args, env); case ObjectType::FLOAT: return num_leq<double>(form, args, env); default: throw_eval_error(form, "<= must have a numeric argument"); return Object::make_empty_list(); } } template <typename T> Object Interpreter::num_geq(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)form; (void)env; T a = number<T>(args.unnamed[0]); T b = number<T>(args.unnamed[1]); return SymbolObject::make_new(reader.symbolTable, (a >= b) ? "#t" : "#f"); } Object Interpreter::eval_geq(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}, {}}, {}); switch (args.unnamed.front().type) { case ObjectType::INTEGER: return num_geq<int64_t>(form, args, env); case ObjectType::FLOAT: return num_geq<double>(form, args, env); default: throw_eval_error(form, ">= must have a numeric argument"); return Object::make_empty_list(); } } Object Interpreter::eval_eval(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { vararg_check(form, args, {{}}, {}); return eval(args.unnamed[0], env); } Object Interpreter::eval_car(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::PAIR}, {}); return args.unnamed[0].as_pair()->car; } Object Interpreter::eval_set_car(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::PAIR, {}}, {}); args.unnamed[0].as_pair()->car = args.unnamed[1]; return args.unnamed[0]; } Object Interpreter::eval_set_cdr(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::PAIR, {}}, {}); args.unnamed[0].as_pair()->cdr = args.unnamed[1]; return args.unnamed[0]; } Object Interpreter::eval_cdr(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::PAIR}, {}); return args.unnamed[0].as_pair()->cdr; } Object Interpreter::eval_gensym(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {}, {}); return SymbolObject::make_new(reader.symbolTable, "gensym" + std::to_string(gensym_id++)); } Object Interpreter::eval_cons(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}, {}}, {}); return PairObject::make_new(args.unnamed[0], args.unnamed[1]); } Object Interpreter::eval_null(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}}, {}); return SymbolObject::make_new(reader.symbolTable, args.unnamed[0].is_empty_list() ? "#t" : "#f"); } Object Interpreter::eval_type(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{ObjectType::SYMBOL}, {}}, {}); auto kv = string_to_type.find(args.unnamed[0].as_symbol()->name); if (kv == string_to_type.end()) { throw_eval_error(form, "invalid type given to type?"); } if (args.unnamed[1].type == kv->second) { return SymbolObject::make_new(reader.symbolTable, "#t"); } else { return SymbolObject::make_new(reader.symbolTable, "#f"); } } Object Interpreter::eval_format(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; if (args.unnamed.size() < 2) { throw_eval_error(form, "format must get at least two arguments"); } auto dest = args.unnamed.at(0); auto format_str = args.unnamed.at(1); if (!format_str.is_string()) { throw_eval_error(form, "format string must be a string"); } // Note: this might be relying on internal implementation details of libfmt to work properly // and isn't a great solution. std::vector<fmt::basic_format_arg<fmt::format_context>> args2; std::vector<std::string> strings; for (size_t i = 2; i < args.unnamed.size(); i++) { if (args.unnamed.at(i).is_string()) { strings.push_back(args.unnamed.at(i).as_string()->data); } else { strings.push_back(args.unnamed.at(i).print()); } } for (auto& x : strings) { args2.push_back(fmt::detail::make_arg<fmt::format_context>(x)); } auto formatted = fmt::vformat(format_str.as_string()->data, fmt::format_args(args2.data(), static_cast<unsigned>(args2.size()))); if (truthy(dest)) { lg::print(formatted.c_str()); } return StringObject::make_new(formatted); } Object Interpreter::eval_error(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); throw_eval_error(form, "Error: " + args.unnamed.at(0).as_string()->data); return Object::make_empty_list(); } Object Interpreter::eval_string_ref(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING, ObjectType::INTEGER}, {}); auto str = args.unnamed.at(0).as_string(); auto idx = args.unnamed.at(1).as_int(); if ((size_t)idx >= str->data.size()) { throw_eval_error(form, fmt::format("String index {} out of range for string of size {}", idx, str->data.size())); } return Object::make_char(str->data.at(idx)); } Object Interpreter::eval_string_length(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING}, {}); auto str = args.unnamed.at(0).as_string(); return Object::make_integer(str->data.length()); } Object Interpreter::eval_string_append(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; if (!args.named.empty()) { throw_eval_error(form, "string-append does not accept named arguments"); } std::string result; for (auto& arg : args.unnamed) { if (!arg.is_string()) { throw_eval_error(form, "string-append can only operate on strings"); } result += arg.as_string()->data; } return StringObject::make_new(result); } Object Interpreter::eval_string_starts_with(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING, ObjectType::STRING}, {}); auto& str = args.unnamed.at(0).as_string()->data; auto& suffix = args.unnamed.at(1).as_string()->data; if (str_util::starts_with(str, suffix)) { return SymbolObject::make_new(reader.symbolTable, "#t"); } return SymbolObject::make_new(reader.symbolTable, "#f"); } Object Interpreter::eval_string_ends_with(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING, ObjectType::STRING}, {}); auto& str = args.unnamed.at(0).as_string()->data; auto& suffix = args.unnamed.at(1).as_string()->data; if (str_util::ends_with(str, suffix)) { return SymbolObject::make_new(reader.symbolTable, "#t"); } return SymbolObject::make_new(reader.symbolTable, "#f"); } Object Interpreter::eval_string_split(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING, ObjectType::STRING}, {}); auto& str = args.unnamed.at(0).as_string()->data; auto& delim = args.unnamed.at(1).as_string()->data; return pretty_print::build_list(str_util::split(str, delim.at(0))); } Object Interpreter::eval_string_substr(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {ObjectType::STRING, ObjectType::INTEGER, ObjectType::INTEGER}, {}); auto& str = args.unnamed.at(0).as_string()->data; auto off = args.unnamed.at(1).as_int(); auto len = args.unnamed.at(2).as_int(); return StringObject::make_new(len != 0 ? str.substr(off, len) : str.substr(off)); } Object Interpreter::eval_ash(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& env) { (void)env; vararg_check(form, args, {{}, {}}, {}); auto val = number_to_integer(args.unnamed.at(0)); auto sa = number_to_integer(args.unnamed.at(1)); if (sa >= 0 && sa < 64) { return Object::make_integer(val << sa); } else if (sa > -64) { return Object::make_integer(val >> -sa); } else { throw_eval_error(form, fmt::format("Shift amount {} is out of range", sa)); return Object::make_empty_list(); } } Object Interpreter::eval_symbol_to_string(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>&) { vararg_check(form, args, {ObjectType::SYMBOL}, {}); return StringObject::make_new(args.unnamed.at(0).as_symbol()->name); } Object Interpreter::eval_string_to_symbol(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>&) { vararg_check(form, args, {ObjectType::STRING}, {}); return SymbolObject::make_new(reader.symbolTable, args.unnamed.at(0).as_string()->data); } Object Interpreter::eval_get_env(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>&) { vararg_check(form, args, {ObjectType::STRING}, {{"default", {false, ObjectType::STRING}}}); const std::string var_name = args.unnamed.at(0).as_string()->data; auto env_p = get_env(var_name); if (env_p.empty()) { if (args.has_named("default")) { return args.get_named("default"); } else { throw_eval_error(form, fmt::format("env-var {} not found and no default provided", var_name)); return Object::make_empty_list(); } } return StringObject::make_new(env_p); } /*! * Create a new empty hash table object. */ Object Interpreter::eval_make_string_hash_table(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& /*env*/) { vararg_check(form, args, {}, {}); return StringHashTableObject::make_new(); } /*! * Set a value in a hash table. Overwrites a previous value or inserts a new one. * Returns empty list always. */ Object Interpreter::eval_hash_table_set(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& /*env*/) { vararg_check(form, args, {ObjectType::STRING_HASH_TABLE, {}, {}}, {}); const char* str = nullptr; if (args.unnamed.at(1).is_symbol()) { str = args.unnamed.at(1).as_symbol()->name.c_str(); } else if (args.unnamed.at(1).is_string()) { str = args.unnamed.at(1).as_string()->data.c_str(); } else { throw_eval_error(form, "Hash table must use symbol or string as the key."); } args.unnamed.at(0).as_string_hash_table()->data[str] = args.unnamed.at(2); return Object::make_empty_list(); } /*! * Try to look up a value by key in a hash table. The result is a pair of (success . value). */ Object Interpreter::eval_hash_table_try_ref(const Object& form, Arguments& args, const std::shared_ptr<EnvironmentObject>& /*env*/) { vararg_check(form, args, {ObjectType::STRING_HASH_TABLE, {}}, {}); const auto* table = args.unnamed.at(0).as_string_hash_table(); const char* str = nullptr; if (args.unnamed.at(1).is_symbol()) { str = args.unnamed.at(1).as_symbol()->name.c_str(); } else if (args.unnamed.at(1).is_string()) { str = args.unnamed.at(1).as_string()->data.c_str(); } else { throw_eval_error(form, "Hash table must use symbol or string as the key."); } const auto& it = table->data.find(str); if (it == table->data.end()) { // not in table return PairObject::make_new(SymbolObject::make_new(reader.symbolTable, "#f"), Object::make_empty_list()); } else { return PairObject::make_new(SymbolObject::make_new(reader.symbolTable, "#t"), it->second); } } } // namespace goos
c3552ee36b7bd5e202e7eef23859aaff305824f7
09ff5ea9a484f5af1ceec74b65108a2aab25942d
/putoff.h
974ba7dece5859128402d8a884182ce852789980
[]
no_license
InaNon/Rogue-like
aa9a6c23233da9c8331ee10223a7ee3097d45435
174a9711ada841e88456a260ceee19d4c3067b04
refs/heads/master
2021-05-09T04:18:12.893935
2018-02-08T04:29:00
2018-02-08T04:29:00
119,261,507
0
0
null
null
null
null
UTF-8
C++
false
false
196
h
putoff.h
#ifndef DEF_PutOff #define DEF_PutOff #include "define.h" #include "selectbox.h" class PutOff : public SelectBox { private: public: BOXNUM NextBox(); PutOff(char*); ~PutOff(); }; #endif
449a254df0f23c5e81902f013bf4c4f9bb376c16
39bd02bc9d5bdc3fe00433b9080c5466451f792e
/engine/runtime/libs/base/private/GxBase/Storage/Impl.Windows/Windows.AsyncFileStream.hxx
7a360375575a8fcb81336473e23b55eb191a411c
[]
no_license
selmentdev/graphyte-engine
7db986ec0b24b458348d4d632c661ce9f81ad671
ed7bcda3d077d2eaa47c2d738b9d03c57adf60f2
refs/heads/master
2022-03-05T11:09:07.598388
2021-01-10T00:42:54
2021-01-10T00:42:54
219,206,110
4
0
null
null
null
null
UTF-8
C++
false
false
9,937
hxx
Windows.AsyncFileStream.hxx
#pragma once #include <GxBase/Storage/IStream.hxx> #include <GxBase/System/Impl.Windows/Windows.Helpers.hxx> #include <GxBase/System/Impl.Windows/Windows.Types.hxx> namespace Graphyte::Storage { class WindowsAsyncFileStream final : public IStream { private: static constexpr const DWORD DefaultBufferSize = 64 * 1024; private: HANDLE m_Handle; OVERLAPPED m_Async; int64_t m_Size; int64_t m_Position; uint64_t m_AsyncPosition; std::unique_ptr<std::byte[]> m_Buffers[2]; size_t m_SerializePosition; int32_t m_SerializeBuffer; int32_t m_StreamBuffer; int32_t m_CurrentAsyncReadBuffer; bool m_IsEOF; bool m_IsReading; private: bool Close() noexcept { if (this->IsValidHandle()) { CloseHandle(this->m_Handle); this->m_Handle = nullptr; } return true; } __forceinline void SwapBuffers() noexcept { this->m_StreamBuffer ^= 0b1; this->m_SerializeBuffer ^= 0b1; this->m_SerializePosition = 0; } __forceinline void UpdateAsync() noexcept { ULARGE_INTEGER li{}; li.QuadPart = this->m_AsyncPosition; this->m_Async.Offset = li.LowPart; this->m_Async.OffsetHigh = li.HighPart; } void UpdateFileOffsetAfterRead(DWORD processed) noexcept { this->m_IsReading = false; this->m_AsyncPosition += processed; this->UpdateAsync(); if (this->m_AsyncPosition >= static_cast<uint64_t>(this->m_Size)) { this->m_IsEOF = true; } } bool WaitForAsyncRead() noexcept { if (this->m_IsEOF || !this->m_IsReading) { return true; } DWORD dwProcessed{}; if (GetOverlappedResult(this->m_Handle, &this->m_Async, &dwProcessed, TRUE) != FALSE) { this->UpdateFileOffsetAfterRead(dwProcessed); return true; } else if (GetLastError() == ERROR_HANDLE_EOF) { this->m_IsEOF = true; return true; } return false; } void StartAsyncRead( int32_t buffer) noexcept { if (!this->m_IsEOF) { this->m_IsReading = true; this->m_CurrentAsyncReadBuffer = buffer; DWORD dwProcessed{}; if (ReadFile(this->m_Handle, this->m_Buffers[buffer].get(), DefaultBufferSize, &dwProcessed, &this->m_Async) != FALSE) { this->UpdateFileOffsetAfterRead(dwProcessed); } else { DWORD dwError = GetLastError(); if (dwError != ERROR_IO_PENDING) { this->m_IsEOF = true; this->m_IsReading = false; } } } } __forceinline void StartStreamBufferRead() noexcept { this->StartAsyncRead(m_StreamBuffer); } __forceinline void StartSerializeBufferRead() noexcept { this->StartAsyncRead(m_SerializeBuffer); } __forceinline bool IsValidHandle() const noexcept { return this->m_Handle != nullptr && this->m_Handle != INVALID_HANDLE_VALUE; } public: WindowsAsyncFileStream( HANDLE handle) noexcept : m_Handle{ handle } , m_Async{} , m_Size{} , m_Position{} , m_AsyncPosition{} , m_Buffers{} , m_SerializePosition{} , m_SerializeBuffer{} , m_StreamBuffer{ 1 } , m_CurrentAsyncReadBuffer{} , m_IsEOF{ false } , m_IsReading{ false } { GX_ASSERT(this->IsValidHandle()); LARGE_INTEGER li{}; GetFileSizeEx(this->m_Handle, &li); this->m_Size = li.QuadPart; this->m_Buffers[0] = std::make_unique<std::byte[]>(DefaultBufferSize); this->m_Buffers[1] = std::make_unique<std::byte[]>(DefaultBufferSize); this->StartSerializeBufferRead(); } virtual ~WindowsAsyncFileStream() noexcept { this->WaitForAsyncRead(); this->Close(); } public: virtual Status Flush() noexcept final override { return Status::Success; } virtual Status Read( std::span<std::byte> buffer, size_t& processed) noexcept final override { GX_ASSERT(this->IsValidHandle()); processed = 0; if (buffer.empty()) { return Status::Success; } if (this->m_Position >= this->m_Size) { // // Already saw EOF. // return Status::EndOfStream; } if (this->m_CurrentAsyncReadBuffer == this->m_SerializeBuffer) { if (!this->WaitForAsyncRead()) { return Status::ReadFault; } this->StartStreamBufferRead(); } while (!buffer.empty()) { int64_t requested = std::min<int64_t>({ static_cast<int64_t>(buffer.size()), static_cast<int64_t>(DefaultBufferSize - m_SerializePosition), static_cast<int64_t>(m_Size - m_Position) }); GX_ASSERT(requested <= DefaultBufferSize); if (requested > 0) { size_t to_copy = static_cast<size_t>(requested); std::memcpy( buffer.data(), &m_Buffers[m_SerializeBuffer][m_SerializePosition], to_copy); m_SerializePosition += to_copy; GX_ASSERT(m_SerializePosition <= DefaultBufferSize); m_Position += to_copy; GX_ASSERT(m_Position <= m_Size); processed += to_copy; buffer = buffer.subspan(to_copy); GX_ASSERT(m_Position <= m_Size); if (m_Position >= m_Size) { break; } } else { if (!this->WaitForAsyncRead()) { return Status::ReadFault; } this->SwapBuffers(); this->StartStreamBufferRead(); } } if (!buffer.empty()) { return Status::EndOfStream; } return Status::Success; } virtual Status Write( [[maybe_unused]] std::span<const std::byte> buffer, [[maybe_unused]] size_t& processed) noexcept final override { GX_ASSERT(this->IsValidHandle()); processed = 0; GX_ASSERT_NOT_IMPLEMENTED(); return Status::NotImplemented; } virtual int64_t GetSize() noexcept final override { GX_ASSERT(this->IsValidHandle()); return this->m_Size; } virtual int64_t GetPosition() noexcept final override { GX_ASSERT(this->IsValidHandle()); return this->m_Position; } virtual Status SetPosition( int64_t value, SeekOrigin origin) noexcept final override { GX_ASSERT(this->IsValidHandle()); switch (origin) { case SeekOrigin::Begin: { return this->SetPosition(value); } case SeekOrigin::Current: { return this->SetPosition(this->m_Position + value); } case SeekOrigin::End: { return this->SetPosition(m_Size - value); } } GX_ASSERT(false); return Status::InvalidArgument; } virtual Status SetPosition( int64_t value) noexcept final override { GX_ASSERT(this->IsValidHandle()); GX_ASSERT(value >= 0); GX_ASSERT(value <= m_Size); int64_t delta = value - m_Position; if (delta == 0) { return Status::Success; } if (!this->WaitForAsyncRead()) { return Status::Failure; } m_Position = value; bool in_range = ((delta < 0) && ((static_cast<int64_t>(m_SerializePosition) - std::abs(delta)) >= 0)) || ((delta > 0) && ((delta + m_SerializePosition) < DefaultBufferSize)); if (in_range) { m_SerializePosition += static_cast<size_t>(delta); } else { GX_ASSERT(value >= 0); m_IsEOF = true; m_AsyncPosition = static_cast<uint64_t>(value); UpdateAsync(); m_CurrentAsyncReadBuffer = m_SerializeBuffer; m_SerializePosition = 0; StartSerializeBufferRead(); } return Status::Success; } }; }
c451800738e184a1763aa1608d22107830841c89
f3e813535f75fb461e2306f1ad18596ac233e758
/odb_api_bundle-0.17.6-Source/odb_api/src/odb_api/odb2netcdf/odb2netcdf_main.cc
f7d7c33b1f26a2deff50afc8ab7b65353f2308b2
[ "Apache-2.0" ]
permissive
vyesubabu/metview
47f9de3eb5f1bf418e513ed306aa2279635b79c7
74c2b9bc28673001fd02e00194e92c53a897fb62
refs/heads/master
2021-05-17T16:42:41.697859
2018-04-09T15:08:19
2018-04-09T15:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
cc
odb2netcdf_main.cc
#include <unistd.h> #include <iostream> #include <string> #include <netcdfcpp.h> #include "odb_api/odbcapi.h" #include "odb_api/CommandLineParser.h" #include "odb_api/ODBModule.h" #include "ecml/core/ExecutionContext.h" #include "Odb2NetCDF.h" #include "Odb2NetcdfModule.h" /// @author Anne Fouilloux using namespace std; using namespace eckit; using namespace odb; using namespace odb::tool; static const string usage = "Usage: odb2netcdf -i [odb_filename|odb_filename_prefix] [-2d] -o netcdf_filename"; int runScripts(const vector<string>& params) { ecml::ExecutionContext context; ODBModule odbModule; Odb2NetcdfModule odb2NetcdfModule; context.import(odbModule); context.import(odb2NetcdfModule); for (size_t i(0); i < params.size(); ++i) { context.executeScriptFile(params[i]); } return 0; } int main(int argc, char *argv[]) { odb_start_with_args(argc, argv); CommandLineParser args(argc, argv); args.registerOptionWithArgument("-i"); args.registerOptionWithArgument("-o"); bool twoD (args.optionIsSet("-2d")); bool ecml (args.optionIsSet("-ecml")); string input (args.optionArgument<string>("-i", "")), output (args.optionArgument<string>("-o", "")); if (input.size() && output.size()) { if (twoD) { Odb2NetCDF_2D converter (input, output); converter.convert(); } else { Odb2NetCDF_1D converter (input, output); converter.convert(); } return 0; } if (ecml) { std::vector<std::string> params(args.parameters()); params.erase(params.begin()); return runScripts(params); } cerr << usage << endl; return 1; }
941f71e1292025fc7ecd62162d3cea8abbf72eae
948e99a7b8dd581dc3b024481063a21c0cd0a4a4
/PDxProjects/PTool/PCreatePlaneDlg.h
27f7d0b4ca571bc704d58c72538061af9ae63b33
[ "Apache-2.0" ]
permissive
bear1704/DX11_Portfolio
70be74f821f58d1c538fcb2d4b32b4d27cbf92d4
8ab70c793cf7f10eceaea34afb786264828c09a0
refs/heads/master
2021-02-16T22:56:19.258566
2020-03-05T02:28:02
2020-03-05T02:28:02
245,050,671
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
h
PCreatePlaneDlg.h
#pragma once #include "PTool.h" const int kLoopLifetime = 777; // PCreatePlaneDlg 대화 상자 class PCreatePlaneDlg : public CDialogEx { DECLARE_DYNAMIC(PCreatePlaneDlg) public: CPToolApp* app; public: PCreatePlaneDlg(CWnd* pParent = nullptr); // 표준 생성자입니다. virtual ~PCreatePlaneDlg(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_CreatePlane }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); afx_msg void OnBtnClickedSelectTexture(); afx_msg void OnBtnClickedSelectScript(); afx_msg void OnBnClickedCancel(); afx_msg void OnBnClickedBtnInitialize(); float m_PlaneHeight; float m_FrameInterval; float m_LifeTime; float m_SpriteXInit; float m_SpriteYInit; float m_XOffset; float m_YOffset; float m_PlaneWidth; CString m_PlaneName; BOOL m_CurrentPlaneIsLoop; std::vector<PTexture*> tex_list; int m_XCount; int m_YCount; float m_TextureWidth; float m_TextureHeight; //World Matrix float m_WorldTx; float m_WorldTy; float m_WorldTz; float m_WorldRx; float m_WorldRy; float m_WorldRz; float m_WorldSx; float m_WorldSy; float m_WorldSz; afx_msg void OnBnClickedCheckIsblended(); BOOL m_IsMultiTexture; };
d80bf5b8f2fd421e0b9055e933b4800bc00eaee7
35cbc0049d0c88cd9282a3c82980500bc2093cf2
/2018-9-8/P4525.cpp
d6124afd09df5ff44999395a172fbc27c8a26586
[]
no_license
ciwomuli/NOIP2017exercise
9f96026a7c88548a0d2783374b0a9582012acf33
e13a818f14da49b3ec94626e7f664301a9da985e
refs/heads/master
2023-01-22T14:02:02.850686
2020-12-04T14:21:08
2020-12-04T14:21:08
108,097,370
0
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
P4525.cpp
#include <cstdio> #include <cmath> #include <cstdlib> #include <algorithm> #include <iostream> using namespace std; const double eps = 1e-10; double a,b,c,d,L,R; inline double F(double x) { return (c * x + d) / (a * x + b); } inline double simpson(double a,double b) { double c=a+(b-a)/2; return (F(a)+4*F(c)+F(b))*(b-a)/6; } double asr(double a,double b,double eps,double S) { double c=a+(b-a)/2; double lS=simpson(a,c),rS=simpson(c,b); if(fabs(lS+rS-S)<=15*eps) return lS+rS+(lS+rS-S)/15.0; return asr(a,c,eps/2,lS)+asr(c,b,eps/2,rS); } int main(){ cin >> a >> b >> c >> d >> L >> R; printf("%.6lf", asr(L, R, eps, 0)); }
5d29f6f95d45a8c69fc42cf7d8be1c98de9c2133
e9d02b84373746a2d7e01a1b56e4c2d6e92cbe07
/Miquel/SDL6_Handout/ModuleIntroScene.cpp
141a33522f9a83db7f887c35e7aa723911463f40
[]
no_license
LordUnicorn31/Sub2pewdiepie-Studios
e8add292eb39e26add44aa82f97cb31447b51e03
82c0fdef03d0ec23066930683abfc9ee86da021a
refs/heads/master
2020-04-23T20:26:33.641427
2020-01-15T13:27:16
2020-01-15T13:27:16
171,440,458
0
0
null
null
null
null
UTF-8
C++
false
false
1,278
cpp
ModuleIntroScene.cpp
#include "Globals.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleRender.h" #include "ModulePlayer.h" #include "ModuleSceneSpace.h" #include "ModuleIntroScene.h" //#include "SDL_mixer/include/SDL_mixer.h" #include "SDL/include/SDL.h" // Reference at https://www.youtube.com/watch?v=OEhmUuehGOA ModuleIntroScene::ModuleIntroScene() {} ModuleIntroScene::~ModuleIntroScene() {} // Load assets bool ModuleIntroScene::Start() { LOG("Loading space scene"); /*Mix_Init(MIX_INIT_OGG); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024); intromusic = Mix_LoadMUS("rtype/intro.ogg"); Mix_PlayMusic(intromusic, -1);*/ background = App->textures->Load("rtype/intro.png"); App->player->Enable(); return true; } // UnLoad assets bool ModuleIntroScene::CleanUp() { LOG("Unloading space scene"); App->textures->Unload(background); App->player->Disable(); /*Mix_CloseAudio(); Mix_Quit();*/ return true; } // Update: draw background update_status ModuleIntroScene::Update() { // Move camera forward ----------------------------- /*int scroll_speed = 1; App->player->position.x += 1; App->render->camera.x -= 3;*/ // Draw everything -------------------------------------- App->render->Blit(background, 0, 0, NULL); return UPDATE_CONTINUE; }
5575658c4398468fff97209516d79bf962621790
7ee32ddb0cdfdf1993aa4967e1045790690d7089
/Codeforces/Yandex13Circles.cpp
f692a077f872f5e198fa56b4c171ef0b42aebb4d
[]
no_license
ajimenezh/Programing-Contests
b9b91c31814875fd5544d63d7365b3fc20abd354
ad47d1f38b780de46997f16fbaa3338c9aca0e1a
refs/heads/master
2020-12-24T14:56:14.154367
2017-10-16T21:05:01
2017-10-16T21:05:01
11,746,917
1
2
null
null
null
null
UTF-8
C++
false
false
1,668
cpp
Yandex13Circles.cpp
#include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <utility> #include <set> #include <map> #include <deque> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <stdio.h> using namespace std; #define fo(i,n) for(int i=0; i<(int)n; i++) #define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++) #define mp(a,b) make_pair(a,b) #define pb(x) push_back(x) #define pii pair<int,int> long long gcd(long long a, long long b) { if (b>a) return gcd(b,a); if (b==0) return a; return gcd(b,a%b); } long long sqr(long long a) {return a*a;} pair<long long, long long> f(long long x1, long long y1, long long x2, long long y2, long long x3, long long y3) { long long num = (sqr(x2-x1)+sqr(y2-y1)); long long den = 2LL*abs(x1*y2 + x2*y3 + x3*y1 - x1*y3 - x2*y1 - x3*y2); den = sqr(den); long long g = gcd(num,den); num /= g; den /= g; num *= (sqr(x2-x3)+sqr(y2-y3)); g = gcd(num,den); num /= g; den /= g; num *= (sqr(x3-x1)+sqr(y3-y1)); g = gcd(num,den); num /= g; den /= g; return make_pair(num,den); } map<pair<long,long>,int> tot; int main() { freopen("circles.in","r",stdin); freopen("circles.out","w",stdout); int n; cin>>n; for (int i=0; i<n; i++) { int x1,x2,x3,y1,y2,y3; scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2,&x3,&y3); tot[f(x1,y1,x2,y2,x3,y3)]++; } int res = 0; for (map<pair<long,long>,int>::iterator it = tot.begin(); it!=tot.end(); it++) { res = max(res,(*it).second); } cout<<res; return 0; }
b4375d4d0e47963e5e63abed090805f30689f314
85a4b5e0b5eab4e1ceee1d25da94439a9f2390ac
/example/src/main.cpp
8d20e9b848e3cbc56ab0c9125a4aa2894bedded8
[ "MIT" ]
permissive
m1keall1son/ofxRemoteProjectionMapper
2deff22b08904c3fb1ba0f90494732e3a0053f33
1b54ca4a5d9ccc03002e8d5ada86785d5bd979b2
refs/heads/master
2020-03-15T06:29:03.244724
2018-05-11T16:58:51
2018-05-11T16:58:51
132,008,685
3
1
null
null
null
null
UTF-8
C++
false
false
542
cpp
main.cpp
#include "ofMain.h" #include "ofApp.h" //======================================================================== int main( ){ ofGLFWWindowSettings winSettings; winSettings.numSamples = 8; winSettings.width = 1280; winSettings.height = 800; winSettings.windowMode = OF_WINDOW; //winSettings.multiMonitorFullScreen = true; winSettings.setGLVersion(3, 2); auto win = ofCreateWindow(winSettings); auto app = std::make_shared<ofApp>(); ofRunApp(win, std::move(app)); ofRunMainLoop(); }
f3a76404cc03413db9f9933f0542ce64222d1d0e
25bf268b8171fcb4a7d3b59088a36ae31fc29fe5
/openuasl-server/src/skeleton/SessionManager.cpp
0be668ee1f5c200caaad4eda22023e958c610d31
[]
no_license
openuasl/openuasl-server
55749f050c3f6a901ac87083a4c5e70b8be64adc
68956fb9994026295f9aef6236fedf896239d0a7
refs/heads/master
2020-12-24T15:14:44.178963
2014-08-29T04:55:35
2014-08-29T04:55:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,784
cpp
SessionManager.cpp
#ifdef _WIN32 #define _WIN32_WINNT 0x0501 #endif // _WIN32 #include <openuasl/skeleton/SessionManager.h> #include <string> #include <boost/foreach.hpp> typedef boost::unique_lock<boost::shared_mutex> \ UniqueLock; typedef boost::shared_lock<boost::shared_mutex> \ SharedLock; namespace openuasl{ namespace server{ namespace skeleton{ bool SessionManager::InsertSession(BaseSession* session) { UniqueLock lock(this->_SharedMutex); this->_ConnectedSessions.erase(session->_SessionId); this->_ConnectedSessions.insert(SessionList::value_type(session->_SessionId, session)); lock.unlock(); return true; } void SessionManager::EreaseSession(BaseSession* session) { UniqueLock lock(this->_SharedMutex); this->_ConnectedSessions.erase(session->_SessionId); lock.unlock(); } void SessionManager::EreaseSession(std::string& id) { UniqueLock lock(this->_SharedMutex); this->_ConnectedSessions.erase(id); lock.unlock(); } BaseSession* SessionManager::GetSession(std::string& id) { SharedLock lock(this->_SharedMutex); return this->_ConnectedSessions[id]; } bool SessionManager::IsExistSession(std::string& id) { SharedLock lock(this->_SharedMutex); return (this->_ConnectedSessions.find(id) != this->_ConnectedSessions.end())? true : false; } StringVector* SessionManager::GetConnectedSessionIdList() { SharedLock lock(this->_SharedMutex); boost::numeric::ublas::vector<std::string>* result = new boost::numeric::ublas::vector<std::string>(_ConnectedSessions.size()); int i = 0; for(SessionList::iterator it = _ConnectedSessions.begin(); it != _ConnectedSessions.end(); ++it, ++i) { result->insert_element(i, it->first); } return result; } }}} // openuasl.server.skeleton
df68e1e1307578a42d550e201c5d9b7738df89d5
7c1a85221375ca94b429f3765bc0bd6238d4476c
/src/displayHandler/main.cpp
7ee8e8cd16a79cf0c94d8467fdedaa3f16cfb5a4
[]
no_license
anormen/courseCPP_TeamE
6fef3622d875bb84fdd2f95c32c53ebc108caa98
1ae95bc97082e801a0a8b2e5850de2c8cd83cabf
refs/heads/main
2023-01-21T09:50:33.112271
2020-11-27T12:53:51
2020-11-27T12:53:51
308,600,164
1
1
null
null
null
null
UTF-8
C++
false
false
246
cpp
main.cpp
#include <thread> #include "display_handler.hpp" #include "display_class.hpp" #include "data_class.hpp" #include "frames.hpp" int main() { displayHandler disp; while(disp.run()){ //do someting if needed }; return 0; }
3d590947a584ecc97ca661a23566bd4709b12877
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/1320.cpp
8e9433bff50c0cbe2fd1123f8388a0ba19eb9f97
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
705
cpp
1320.cpp
#include <iostream> #include <unordered_set> using namespace std; int main() { ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; int pb = 0, eb = 0, co = 0; unordered_set<string> seen; string word; for (int i = 0; i < n; ++i) { cin >> word; seen.insert(word); ++pb; } for (int i = 0; i < m; ++i) { cin >> word; if (seen.find(word) != seen.end()) { ++co; --pb; } else { ++eb; } } if (pb < eb) { cout << "NO"; } else if (pb > eb) { cout << "YES"; } else { cout << (co % 2 == 1 ? "YES" : "NO"); } cout << endl; return 0; }
0f04d30dec776b5ef7f4cd6809e9a91842f34421
03b830414faedabf35eac66e0d7baf477133300b
/src/20200602/62paly.cpp
8846be5bfb068f977cc04f1372c28b8e3c63c9b2
[]
no_license
liupengzhouyi/nowCoder
12abb70c30b6872a73c993365575d4d888795c7e
14fa3aa5a54def9f34f4552f01088a6c4dd5f96d
refs/heads/master
2022-10-04T21:14:02.085585
2020-06-05T10:11:43
2020-06-05T10:11:43
267,886,016
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
62paly.cpp
// // Created by 刘鹏 on 2020/6/1. // #include<iostream> #include<string> using namespace std; int paly62() { string str1,str2; while(cin>>str1>>str2) { int i; for(i=0;i<str1.size();i++) { if(str2.find(str1[i])==-1) { cout<<"false"<<endl; break; } } if(i==str1.size()) //++i和i++在循环里没有区别,最后i都等于str1.size() cout<<"true"<<endl; } return 0; }
e15ae434db9d1b078eb58f02b6c8f3a5d10d7db8
66bbd0e00b507668de90fe652aa47d8e35a25de8
/test/iem/event_strategy_test.cpp
7b99021b633c1483b48f3b5a17734673f0a39035
[ "MIT" ]
permissive
rheineke/cpp-iem
0a83c8625af900f23df59503481aaf9a638a4a80
65e35751204efc194829c7da629fe25653581be0
refs/heads/master
2021-01-11T03:34:14.760743
2017-04-30T10:47:51
2017-04-30T10:47:51
71,016,303
6
0
null
null
null
null
UTF-8
C++
false
false
273
cpp
event_strategy_test.cpp
// Copyright 2016 Reece Heineke<reece.heineke@gmail.com> #include "iem/event_strategy.hpp" #include "gtest/gtest.h" namespace iem { TEST(EventStrategyTest, AssertNoThrow) { const auto os = event_orders(Event::SAME, 1); EXPECT_EQ(os.size(), 4); } } // namespace iem