blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f0216e89c610941eb73cd2ae3cb91680801d96ea
eb9c1dc78432e67d7fc89407652b605b177af97c
/stl/vector/vector_clear.cpp
21d89ac1109e2e817d79bddab5c674ba9d25e5be
[]
no_license
raghu-yemmanuru/code4fun
1a8e2550681abe60cf0b7077db11c2d453f3c0ba
19422b93848b8b2c26fa7978f876b2a264c56471
refs/heads/master
2020-04-04T21:48:54.262098
2015-02-24T22:19:28
2015-02-24T22:19:28
29,117,492
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include <iostream> #include <vector> using namespace std; class Widget { public: Widget() { cout << "Constructed " << this << endl; } ~Widget() { cout << "Destructed " << this << endl; } }; int main() { vector<Widget*> v; for (int i = 0; i < 5; i++) { v.push_back(new Widget()); } //v.clear(); vector<Widget*>::iterator itr; for (itr = v.begin(); itr != v.end();) { delete *itr; itr = v.erase(itr); } cout << v.size() << endl; }
[ "raghavendradatt@gmail.com" ]
raghavendradatt@gmail.com
1dfcd5cb921751cd24fda5a80a08cae82299202a
040078fa17e66a74b30efd635328dfd1c37c41e2
/1137.cc
936914dd0cc08ab0ad6bb4b069e1698cb74584f8
[]
no_license
mosthandsomeman/PAT_A
80d4ef654a796a5dc47db170529ff98d6b45b32a
e8fb5c3bc1df4013ba0e9bd70e01131794a339cd
refs/heads/master
2020-04-14T20:17:48.373130
2019-01-07T10:08:13
2019-01-07T10:08:13
164,088,515
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
cc
//#include<cstdio> //#include<cstdlib> //#include<vector> //#include<cstring> //#include<algorithm> //#include<map> //#include<iostream> //#include<string> //#include<cmath> //using namespace std; //int P, M, N, score; //struct Node //{ // char id[24]; // int P, Gm, Gf, G; //}; //vector<Node*> vec; //map<string, Node*> mmap; //string id; //bool cmp(Node *& a, Node *&b) { // return a->G != b->G ? a->G > b->G:strcmp(a->id, b->id) < 0; //} //int main() { // scanf("%d %d %d", &P, &M, &N); // for (int i = 0;i < P;++i) { // cin >> id >> score; // if (score >= 200) { // Node * node = new Node; // node->Gf = node->Gm = node->G = -1; // node->P = score; // strcpy(node->id, id.c_str()); // vec.push_back(node); // mmap[id] = node; // } // } // for (int i = 0;i < M;++i) { // cin >> id >> score; // if (mmap.find(id) != mmap.end()) { // mmap[id]->Gm = score; // } // } // for (int i = 0;i < N;++i) { // cin >> id >> score; // if (mmap.find(id) != mmap.end()) { // mmap[id]->Gf = score; // } // } // for (int i = 0;i < vec.size();++i) { // if (vec[i]->Gm > vec[i]->Gf) { // vec[i]->G = round(vec[i]->Gm * 0.4 + vec[i]->Gf * 0.6); // } // else { // vec[i]->G = vec[i]->Gf; // } // } // sort(vec.begin(), vec.end(), cmp); // for (int i = 0;i < vec.size();++i) { // if (vec[i]->G >= 60) { // printf("%s %d %d %d %d\n", vec[i]->id, vec[i]->P, vec[i]->Gm, vec[i]->Gf, vec[i]->G); // } // } // system("pause"); // return 0; //}
[ "fuzhichao@binghuoshan.com" ]
fuzhichao@binghuoshan.com
db07b2e16a991d650b3b85fe6734e94fa5d96ff7
90517ce1375e290f539748716fb8ef02aa60823b
/solved/c-e/document-analyzer/lightoj/analyzer.cpp
6f58b294ad249c4ce1c21bbb671355260ae947b0
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
Code4fun4ever/pc-code
23e4b677cffa57c758deeb655fd4f71b36807281
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
refs/heads/master
2021-01-15T08:15:00.681534
2014-09-08T05:28:39
2014-09-08T05:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,622
cpp
#include <cctype> #include <cstdio> #include <cstring> #include <set> #include <vector> using namespace std; #define MAXLINE 100 #define MAXWORD 10 #define MAXNWORDS 50000 #define Zero(v) memset((v), 0, sizeof(v)) typedef unsigned char uch; typedef unsigned int u32; typedef pair<int, int> II; struct Reader { int b; Reader() { read(); } void read() { b = getchar_unlocked(); } void skip() { while (b >= 0 && b <= 32) read(); } u32 next_u32() { u32 v = 0; for (skip(); b > 32; read()) v = 10*v+b-48; return v; } void skip_line() { for (; b != 10 && b != 13 && b >= 0; read()); char p = b; read(); if ((p == 10 && b == 13) || (p == 13 && b == 10)) read(); } void next_line(char *s, int &l) { for (l = 0; b != 10 && b != 13 && b >= 0; read()) { *s++ = b; ++l; } *s = 0; while (b == 10 || b == 13) read(); } }; // // Hash Map // #define HASHB 4096 struct HM { struct Key { char w[MAXWORD + 1]; Key(char *W) { strcpy(w, W); } bool operator==(const Key &x) const { return strcmp(w, x.w) == 0; } }; struct KV { Key k; int v; KV(const Key &K, int V) : k(K), v(V) {} }; typedef vector<KV> KVV; KVV b[HASHB]; u32 fnv_hash(const Key &k) const { uch *p = reinterpret_cast<uch*>(const_cast<char*>(k.w)); u32 h = 2166136261U; for (int i = 0; p[i] != 0; ++i) h = (h * 16777619U) ^ p[i]; return h; } int add(const Key &k, int v) { int i = fnv_hash(k) % HASHB; for (int j = 0, J = b[i].size(); j < J; ++j) if (b[i][j].k == k) return b[i][j].v; b[i].push_back(KV(k, v)); return v; } }; // // Simple list // struct Node { int d; // data int n; // next }; Node pool[MAXNWORDS]; int nnodes; struct List { int h, t; void append(int d) { int nd = ++nnodes; pool[nd].d = d, pool[nd].n = 0; if (h == 0) h = nd; else pool[t].n = nd; t = nd; } int get() { return pool[h].d; } void next() { h = pool[h].n; } bool empty() { return h == 0; } }; Reader rr; int p, q; char line[MAXLINE + 1]; int len; int nwords; // total number of words int uwords; // number of unique words List loc[MAXNWORDS]; // locations of every unique word in the text void read_text() { HM hm; Zero(loc); nnodes = 0; nwords = uwords = 0; while (true) { rr.next_line(line, len); if (strcmp("END", line) == 0) break; int i = 0; while (true) { while (i < len && ! islower(line[i])) ++i; if (i >= len) break; char *tok = &line[i]; while (islower(line[i])) ++i; line[i] = 0; int id = hm.add(HM::Key(tok), uwords); if (id == uwords) ++uwords; ++nwords; loc[id].append(nwords); } } } void solve() { multiset<II> s; p = 1; q = nwords; for (int i = 0; i < uwords; ++i) { s.insert(II(loc[i].get(), i)); loc[i].next(); } while (true) { II a = *(s.begin()); II b = *(s.rbegin()); if (b.first - a.first < q - p) p = a.first, q = b.first; if (loc[a.second].empty()) break; s.erase(s.begin()); s.insert(II(loc[a.second].get(), a.second)); loc[a.second].next(); } } int main() { int T = rr.next_u32(); rr.skip_line(); int ncase = 0; while (T--) { read_text(); solve(); printf("Case %d: %d %d\n", ++ncase, p, q); } return 0; }
[ "leonardo@diptongonante.com" ]
leonardo@diptongonante.com
920f86f1bbca2233e5ce76c772059234edf3b95d
e0cd22a3dbf1589cee37c33374607ed2ce66e95e
/cpp/opensourcesrcs/vcf/include/graphics/Polygon.h
ccb00389a289c6e6e6d0dccc3ec443476c45accd
[]
no_license
CodeOpsTech/DesignPatternsCpp
1335402e2c88a4b8715430210ec153af7bb733be
2c67495ffdc65443fae98b2879f7b608e3562876
refs/heads/master
2021-01-11T19:19:48.498940
2017-07-19T02:52:56
2017-07-19T02:52:56
79,355,314
1
0
null
null
null
null
UTF-8
C++
false
false
2,874
h
/** *Copyright (c) 2000-2001, Jim Crafton *All rights reserved. *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions *are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS *OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *NB: This software will not save the world. */ /* Generated by Together */ #ifndef POLYGON_H #define POLYGON_H namespace VCF{ class GRAPHICSKIT_API Polygon : public VCF::Object, public VCF::Path{ public: Polygon(); virtual ~Polygon(); virtual bool contains(Rect * rect); virtual bool contains(Point * pt); virtual bool intersects(Point* pt); virtual bool intersects(Rect* rect); virtual Rect* getBounds(); virtual PathEnumerator* getPathEnumerator( Matrix2D* transform ); void lineTo( const double& x, const double& y ); void moveTo( const double& x, const double& y ); void close(); void clear(); protected: class GRAPHICSKIT_API PolyPathEnumerator : public Object, public PathEnumerator { public: PolyPathEnumerator( Polygon* source, Matrix2D* matrix ); virtual ~PolyPathEnumerator(); virtual WindingType getWindingRule(); bool hasMoreSegments(); void next(); virtual ulong32 getPointCount(); virtual SegmentType getSegment( Point* points ); virtual Enumerator<Point*>* flattenPoints(); virtual Rect* getBounds(); private: Polygon* m_source; std::vector<PathPoint*> m_transformedPoints; std::vector<PathPoint*>::iterator m_pathIterator; Rect m_bounds; }; friend class GRAPHICSKIT_API PolyPathEnumerator; Rect m_bounds; ulong32 m_currentMoveToIndex; std::vector<PathPoint*> m_points; Polygon::PolyPathEnumerator* m_pathEnumerator; }; }; #endif //POLYGON_H
[ "ganesh@codeops.tech" ]
ganesh@codeops.tech
075a0df4fccb03abc7265209019fe6772d02401f
6adaa27bb61f5e580942998b871188054f5ce0fe
/HProf/profiler/profiler.h
b5ad5a8e03931c906dfaf12b30d6aa4db5f610b1
[ "MIT" ]
permissive
DeweyTaylor/Toolkit
9966534e8690d10c8ff40964af7e482ecf94d5a8
e9166b171956abf06bf963bc3b0399ce9a62317b
refs/heads/master
2021-01-20T06:03:42.741545
2017-05-02T00:25:22
2017-05-02T00:25:22
89,835,688
0
0
null
null
null
null
UTF-8
C++
false
false
2,163
h
// profiler.h // (c) 2010-2017 James Dewey Taylor // 20 June 2010 : profiler section started // 29 April 2017 : ported to Haiku and generalized // Note: This section is based on the concepts described in Game Developer // Magazine, December 2002: Inner Product, Interactive Profiling, Part 1 #ifndef __PROFILER_H__ #define __PROFILER_H__ #include <string> #include <stdint.h> #include <iostream> #include "ProfWindow.h" using namespace std; //static void ProfTrace(const char* str) { ProfTrace(BString(str)); } //static void ProfTrace(string str) { ProfTrace(BString(str.c_str())); } extern void ProfTrace(BString); #define PTRACE ProfTrace inline uint64_t os_fast_get_integer_timestamp() { static uint32_t lo, hi; asm volatile ("rdtsc":"=a"(lo),"=d"(hi)); return (((uint64_t)(hi)) << 32) | lo; } //#define QueryPerformaceCounter os_fast_get_integer_timestamp class Program_Zone { public: Program_Zone(const char*); // add item to __Profiler_Zone_List ~Program_Zone(); // remove item from __Profiler_Zone_List string Name; uint64_t StartTime; uint64_t TotalTime; uint64_t SubTime; int CallCount; //double LastHVal; //double LastSVal; }; struct Zone_List_Item // converts Program_Zones objects into a linked list { Program_Zone* Item; Zone_List_Item* Next; }; class Profile_Scope_Var // dummy object for handling entering and exiting Program_Zones { public: Profile_Scope_Var(Program_Zone*); // push onto the stack ~Profile_Scope_Var(); // pop off of the stack and do some preliminary calculations }; struct Profile_Stack_Item // the stack used by Profile_Scope_Var to manage self-times vs hierarchical times { Program_Zone* Item; Profile_Stack_Item* Next; }; void Profiler_Update(); // the update functions... crunches numbers in the __Profiler_Zone_List and the (bool) determines whether the output is drawn or not #define Profile_Scope(x) Profile_Scope_Var scope_##__LINE__(&__ ## x); #define Define_Zone(name) Program_Zone __##name(#name); /*class Profiler { public: private: Program_Zone[] Zones; };*/ #endif
[ "DeweyTaylor@users.noreply.github.com" ]
DeweyTaylor@users.noreply.github.com
c3ac9c94e9c327c6fcd754227b2382c73a359fa4
b9d25b94a6ed2e9021a4f8174614872b0bfb303c
/test/class_name_test.cpp
ed608c0825a9c84f8f97c6bea2843114ee1f50e4
[ "BSD-3-Clause" ]
permissive
PickNikRobotics/memory_leak
cc0fda29e05da2d83cd4d839219c571ecd0ab4fb
8757fbadbbaf5d892b9b19dfd587239c9d48487d
refs/heads/master
2020-07-27T14:17:27.284240
2019-09-17T19:00:03
2019-09-17T19:00:03
209,120,433
0
0
null
null
null
null
UTF-8
C++
false
false
3,087
cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, PickNik LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of PickNik LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Mike Lautman Desc: TODO(mlautman): */ /** EXAMPLES: EXPECT_FALSE(robot_state.hasFixedLinks()); EXPECT_EQ(robot_state.getFixedLinksCount(), 0); EXPECT_TRUE(robot_state.getPrimaryFixedLink() == NULL); EXPECT_GT(robot_state.getFixedLinksMode(), 0); EXPECT_LT( fabs(vars[0] - 0), EPSILON) << "Virtual joint in wrong position " << vars[0]; */ // C++ #include <string> // ROS #include <ros/ros.h> // Testing #include <gtest/gtest.h> // Main class #include <memory_leak/class_name.h> namespace memory_leak { class TestClassName : public ::testing::Test { public: void SetUp() override { nh_.reset(new ros::NodeHandle("~")) server_.reset(new ClassName()); } void TearDown() override { } protected: std::unique_ptr<ros::NodeHandle> nh_; ClassNamePtr server_; }; // class TestClassName TEST_F(TestClassName, TestNameOfClass) { std::string expected_class_name = "class_name"; ASSERT_STREQ(server_->name_.c_str(), expected_class_name.c_str()); } } // namespace memory_leak int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "class_name_test"); ros::AsyncSpinner spinner(1); spinner.start(); int result = RUN_ALL_TESTS(); spinner.stop(); ros::shutdown(); return result; }
[ "mikeblautman@github.com" ]
mikeblautman@github.com
8220e704a78cb09c0aede53cc1a712334d0a01d1
1fb827b1f8925ad3af50087db79921caa46f634e
/chrome/browser/vr/service/browser_xr_device.cc
a6e6ebaf2bc9a34dc52790218de714520ed35c14
[ "BSD-3-Clause" ]
permissive
zhanfang/chromium
3ec94d5b277cdfa07bba2f27a2ec68f96759c3aa
a1aca6ba1633043bac831c28cdd6c7da4bbeed21
refs/heads/master
2022-12-01T12:09:09.834764
2018-06-13T05:16:33
2018-06-13T05:16:33
137,167,141
2
0
null
2018-06-13T05:36:37
2018-06-13T05:36:37
null
UTF-8
C++
false
false
4,497
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/vr/service/browser_xr_device.h" #include "chrome/browser/vr/service/vr_display_host.h" #include "device/vr/vr_device.h" namespace vr { BrowserXrDevice::BrowserXrDevice(device::VRDevice* device, bool is_fallback) : device_(device), is_fallback_(is_fallback), weak_ptr_factory_(this) { device_->SetVRDeviceEventListener(this); display_info_ = device->GetVRDisplayInfo(); } BrowserXrDevice::~BrowserXrDevice() { device_->SetVRDeviceEventListener(nullptr); } void BrowserXrDevice::OnChanged( device::mojom::VRDisplayInfoPtr vr_device_info) { display_info_ = vr_device_info.Clone(); for (VRDisplayHost* display : displays_) { display->OnChanged(vr_device_info.Clone()); } } void BrowserXrDevice::StopExclusiveSession() { if (exclusive_session_controller_) { exclusive_session_controller_->StopSession(); exclusive_session_controller_ = nullptr; presenting_display_host_ = nullptr; } } void BrowserXrDevice::OnExitPresent() { if (presenting_display_host_) { presenting_display_host_->OnExitPresent(); presenting_display_host_ = nullptr; } } void BrowserXrDevice::OnActivate(device::mojom::VRDisplayEventReason reason, base::OnceCallback<void(bool)> on_handled) { if (listening_for_activation_display_host_) { listening_for_activation_display_host_->OnActivate(reason, std::move(on_handled)); } else { std::move(on_handled).Run(true /* will_not_present */); } } void BrowserXrDevice::OnDeactivate(device::mojom::VRDisplayEventReason reason) { for (VRDisplayHost* display : displays_) { display->OnDeactivate(reason); } } void BrowserXrDevice::OnDisplayHostAdded(VRDisplayHost* display) { displays_.insert(display); } void BrowserXrDevice::OnDisplayHostRemoved(VRDisplayHost* display) { DCHECK(display); displays_.erase(display); if (display == presenting_display_host_) { ExitPresent(display); DCHECK(presenting_display_host_ == nullptr); } if (display == listening_for_activation_display_host_) { // Not listening for activation. listening_for_activation_display_host_ = nullptr; GetDevice()->SetListeningForActivate(false); } } void BrowserXrDevice::ExitPresent(VRDisplayHost* display) { if (display == presenting_display_host_) { StopExclusiveSession(); } } void BrowserXrDevice::RequestPresent( VRDisplayHost* display, device::mojom::VRSubmitFrameClientPtr submit_client, device::mojom::VRPresentationProviderRequest request, device::mojom::VRRequestPresentOptionsPtr present_options, device::mojom::VRDisplayHost::RequestPresentCallback callback) { device_->RequestPresent( std::move(submit_client), std::move(request), std::move(present_options), base::BindOnce(&BrowserXrDevice::OnRequestPresentResult, weak_ptr_factory_.GetWeakPtr(), display, std::move(callback))); } void BrowserXrDevice::OnRequestPresentResult( VRDisplayHost* display, device::mojom::VRDisplayHost::RequestPresentCallback callback, bool result, device::mojom::VRDisplayFrameTransportOptionsPtr transport_options, device::XrSessionController* exclusive_session_controller) { if (result && (displays_.find(display) != displays_.end())) { presenting_display_host_ = display; exclusive_session_controller_ = exclusive_session_controller; std::move(callback).Run(result, std::move(transport_options)); } else { std::move(callback).Run(false, nullptr); if (result) { exclusive_session_controller_ = exclusive_session_controller; StopExclusiveSession(); } } } void BrowserXrDevice::UpdateListeningForActivate(VRDisplayHost* display) { if (display->ListeningForActivate() && display->InFocusedFrame()) { bool was_listening = !!listening_for_activation_display_host_; listening_for_activation_display_host_ = display; if (!was_listening) OnListeningForActivate(true); } else if (listening_for_activation_display_host_ == display) { listening_for_activation_display_host_ = nullptr; OnListeningForActivate(false); } } void BrowserXrDevice::OnListeningForActivate(bool is_listening) { device_->SetListeningForActivate(is_listening); } } // namespace vr
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1d2fe7a7ac60981cde6cfb15d2fe084fc72c8a01
e722790a5a3066b196e8b8b958f90870b58e0e81
/src/searchstack.hpp
a5434c64ede9ed938b96193c8953446c16852f5f
[ "MIT" ]
permissive
whackashoe/ataxx-engine
392a1f844ca24b0ef9930afadccf19cbc3d6714a
a6360549a69ca862be4058a5e21ecf2b872938d0
refs/heads/master
2021-01-25T14:57:12.560453
2018-02-10T17:33:44
2018-02-10T17:33:44
123,741,163
0
0
null
2018-03-03T23:47:34
2018-03-03T23:47:34
null
UTF-8
C++
false
false
227
hpp
#ifndef SEARCHSTACK_HPP_INCLUDED #define SEARCHSTACK_HPP_INCLUDED #include "move.hpp" typedef struct { int ply; #ifdef KILLER_MOVES Move killer; #endif #ifdef NULLMOVE bool nullmove; #endif } searchStack; #endif
[ "Twipply@gmail.com" ]
Twipply@gmail.com
a64d7ca8435815c57236237b45631c67e3cc07b5
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/components/webdata/common/web_data_service_base.cc
3418eb4dc8dbea5d8b9adffa14f608f661fd0e8a
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,871
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/webdata/common/web_data_service_base.h" #include "base/bind.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread.h" #include "components/webdata/common/web_database_service.h" //////////////////////////////////////////////////////////////////////////////// // // WebDataServiceBase implementation. // //////////////////////////////////////////////////////////////////////////////// using base::Bind; using base::Time; WebDataServiceBase::WebDataServiceBase( scoped_refptr<WebDatabaseService> wdbs, const ProfileErrorCallback& callback, const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread) : base::RefCountedDeleteOnMessageLoop<WebDataServiceBase>(ui_thread), wdbs_(wdbs), profile_error_callback_(callback) { } void WebDataServiceBase::ShutdownOnUIThread() { } void WebDataServiceBase::Init() { DCHECK(wdbs_.get()); wdbs_->RegisterDBErrorCallback(profile_error_callback_); wdbs_->LoadDatabase(); } void WebDataServiceBase::ShutdownDatabase() { if (!wdbs_.get()) return; wdbs_->ShutdownDatabase(); } void WebDataServiceBase::CancelRequest(Handle h) { if (!wdbs_.get()) return; wdbs_->CancelRequest(h); } bool WebDataServiceBase::IsDatabaseLoaded() { if (!wdbs_.get()) return false; return wdbs_->db_loaded(); } void WebDataServiceBase::RegisterDBLoadedCallback( const DBLoadedCallback& callback) { if (!wdbs_.get()) return; wdbs_->RegisterDBLoadedCallback(callback); } WebDatabase* WebDataServiceBase::GetDatabase() { if (!wdbs_.get()) return NULL; return wdbs_->GetDatabaseOnDB(); } WebDataServiceBase::~WebDataServiceBase() { }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
6e3a6b16d25ad31f397eec2aa6a03c463174f14a
b89c1ee3232b7680f723e591166207930d7b3c29
/Exception/gamestartexception.hpp
c06b2011160daa06db38f0ab5c2a026b7488a6dd
[]
no_license
RaphaelWW/schafkopf-base-engine
efc6c81d214d4eb5b4d93d38ae55106cd96ecf13
c756d7604690f692ba65340de78c16eb2e1c67c5
refs/heads/master
2021-05-20T11:11:32.909741
2020-04-03T16:07:10
2020-04-03T16:07:10
252,268,418
0
0
null
null
null
null
UTF-8
C++
false
false
470
hpp
/* * nogamedecision.hpp * * Created on: Sep 30, 2019 * Author: raphael */ #ifndef EXCEPTION_GAMESTARTEXCEPTION_HPP_ #define EXCEPTION_GAMESTARTEXCEPTION_HPP_ #include <exception> #include <string.h> using namespace std; class GameStartException: public exception { public: GameStartException(string msg) : m_msg(msg) { } char * what() { return strdup(m_msg.c_str()); } private: string m_msg; }; #endif /* EXCEPTION_GAMESTARTEXCEPTION_HPP_ */
[ "raphael.wild@tum.de" ]
raphael.wild@tum.de
f65d6e6ee149c08702e27a90e8300c08309786d7
578ddde49416381e23a5a464187352d914f26bfb
/Uno1.0.ino
45325ed2abee02f3ffb3f258fc3b6e52aae9bce1
[]
no_license
Martin837/AIS
2360a65bd0aefd6bdc09eebb93e319e964553334
6eef3e2ad4691fe4ed2224bf625fd1b69cd66ecf
refs/heads/main
2023-07-21T08:08:32.095582
2021-08-08T02:36:53
2021-08-08T02:36:53
393,815,556
0
0
null
null
null
null
UTF-8
C++
false
false
15,948
ino
#include <SoftwareSerial.h> #include <Adafruit_Sensor.h> #include <ArduinoJson.h> #include <DHT.h> //?sensores #define Sensor1 A0 #define Sensor2 A1 #define Sensor3 A2 #define Sensor4 A3 #define Sensor5 A4 int Dht11 = 8; int Ws = 3; //?variables float h1 = 0; float h2 = 0; float h3 = 0; float h4 = 0; float h5 = 0; float threshold1l = 100; float threshold2l = 110; float threshold3l = 130; float threshold4l = 160; float threshold5l = 150; float threshold1h = 180; float threshold2h = 150; float threshold3h = 180; float threshold4h = 200; float threshold5h = 190; float temp = 0; int fan = 7; int manual = 6; int mn = 0; int ecode = 0; int s1 = 9; int s2 = 10; int s3 = 11; int s4 = 12; int s5 = 13; bool s1s = 0; bool s2s = 0; bool s3s = 0; bool s4s = 0; bool s5s = 0; bool agua = 0; int l_error = 5; int btn1 = 2; int btn1s = 0; int buzzer = 4; //?RX pin, TX pin SoftwareSerial s(0,1); //?dht #define DHTPIN 8 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); void setup(){ s.begin(115200); dht.begin(); pinMode(btn1, INPUT); pinMode(manual, INPUT); pinMode(Ws, INPUT); pinMode(fan, OUTPUT); pinMode(l_error, OUTPUT); pinMode(s1, OUTPUT); pinMode(s2, OUTPUT); pinMode(s3, OUTPUT); pinMode(s4, OUTPUT); pinMode(s5, OUTPUT); pinMode(buzzer, OUTPUT); digitalWrite(l_error, LOW); } void humedad(){ / ?Valores humedad for(int i = 0; i <= 100; i++){ h1 = h1 + analogRead(Sensor1); delay(1); h1 = h1 / 100.00; h2 = h2 + analogRead(Sensor2); delay(1); h2 = h2 / 100.00; h3 = h3 + analogRead(Sensor3); delay(1); h3 = h3 / 100.00; h4 = h4 + analogRead(Sensor4); delay(1); h4 = h4 / 100.00; h5 = h5 + analogRead(Sensor5); delay(1); h5 = h5 / 100.00; } } void s1error(){ while(true){ humedad(); digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 1; Serial.println(h1); if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 1 digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); Serial.println(ecode); } if(h1 < 1000){ return; } } } void s2error(){ while(true){ humedad(); digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 2; if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 2 digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); } if(h2 < 1000){ return; } } } void s3error(){ while(true){ humedad(); digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 3; if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 3 digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); } if(h3 < 1000){ return; } } } void s4error(){ while(true){ humedad(); digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 4; if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 4 digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); } if(h4 < 1000){ return; } } } void s5error(){ while(true){ humedad(); digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 5; if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 5 digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); } if(h5 < 1000){ return; } } } void dhterror(){ while(true){ digitalWrite(l_error, HIGH); btn1s = digitalRead(btn1); ecode = 6; if(btn1s == 1){ //? 0 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(1500); //? 6 digitalWrite(buzzer, HIGH); delay(1000); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); delay(300); digitalWrite(buzzer, HIGH); delay(500); digitalWrite(buzzer, LOW); } if(temp < 40){ return; } } } void RA(){ for(int i = 0; i <= 100; i++){ h1 = h1 + analogRead(Sensor1); delay(1); h1 = h1 / 100.00; h2 = h2 + analogRead(Sensor2); delay(1); h2 = h2 / 100.00; h3 = h3 + analogRead(Sensor3); delay(1); h3 = h3 / 100.00; h4 = h4 + analogRead(Sensor4); delay(1); h4 = h4 / 100.00; h5 = h5 + analogRead(Sensor5); delay(1); h5 = h5 / 100.00; } //?riego if(h1 < threshold1l){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, HIGH); while(true){ agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); return; } humedad(); if(h1 > threshold1h){ digitalWrite(s1, LOW); s1s = 0; return; } } } if(h1 > 1000){ s1error(); } if(h1 >= threshold1h){ digitalWrite(s1, LOW); s1s = 0; } Serial.println(h1); if(h2 < threshold2l && s1s == 0){ digitalWrite(s1, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s2, HIGH); while(true){ agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); return; } humedad(); if(h2 > threshold2h){ digitalWrite(s2, LOW); s2s = 0; return; } } } if(h2 > 1000){ s2error(); } if(h2 >= threshold2h){ digitalWrite(s2, LOW); s2s = 0; } if(h3 < threshold3l && s2s == 0){ digitalWrite(s2, LOW); digitalWrite(s1, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s3, HIGH); while(true){ agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); return; } humedad(); if(h3 > threshold3h){ digitalWrite(s3, LOW); s3s = 0; return; } } } if(h3 > 1000){ s3error(); } if(h3 >= threshold3h){ digitalWrite(s3, LOW); s3s = 0; } if(h4 < threshold4l && s3s == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s1, LOW); digitalWrite(s5, LOW); digitalWrite(s4, HIGH); while(true){ agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); } humedad(); if(h1 > threshold1h){ digitalWrite(s4, LOW); s4s = 0; return; } } } if(h4 > 1000){ s4error(); } if(h4 >= threshold4h){ digitalWrite(s4, LOW); s4s = 0; } if(h5 < threshold5l && s4s == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s1, LOW); digitalWrite(s5, HIGH); while(true){ agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); return; } humedad(); if(h5 > threshold5h){ digitalWrite(s5, LOW); s5s = 0; return; } } } if(h5 > 1000){ s5error(); } if(h5 >= threshold5h){ digitalWrite(s5, LOW); s5s = 0; } } void loop(){ //?modo manual o automático mn = digitalRead(manual); //?Temperatura y ventilador digitalWrite(l_error, LOW); temp = dht.readTemperature(); if(temp >= 30){ digitalWrite(fan, HIGH); } else if(temp > 40){ dhterror(); } else{ digitalWrite(fan, LOW); } //? Sensor de agua agua = digitalRead(Ws); delay(10); if(agua == 0){ digitalWrite(s2, LOW); digitalWrite(s3, LOW); digitalWrite(s4, LOW); digitalWrite(s5, LOW); digitalWrite(s1, LOW); } //?Comunicación con esp8266 // StaticJsonDocument<1000> doc; // DeserializationError error = deserializeJson(doc, json); // doc["agua"] = agua; // doc["error"] = ecode; //doc["humedad1"] = h1; // doc["humedad2"] = h2; // doc["humedad3"] = h3; // doc["humedad4"] = h4; // doc["humedad5"] = h5; // doc["manual"] = mn; // doc["sector1"] = s1s; // doc["sector2"] = s2s; // doc["sector3"] = s3s; // doc["sector4"] = s4s; // doc["sector5"] = s5s; // if(s.available()>0){ // doc.printTo(s); // } if(mn == 1){ humedad(); } else if (mn == 0 && agua == 1){ RA(); } Serial.println(ecode); }
[ "noreply@github.com" ]
Martin837.noreply@github.com
e81b892b9ce92bc11ffff2212ddc253a0bc74fc6
0827ed8fce48247b81af7f0332f9a4d96f5fab42
/csis252/examples/inheritance/squareType.cpp
c7296804fadcfc8e79cfaff1e2c79bc55c8f6ff6
[]
no_license
rosskyl/MSUM-C-C-Classes
7b5ffa1c2789603a045665f76af3f8ef86d36b44
f28462cbf20ef55579cbc6b1b4fc799250dd60f2
refs/heads/master
2021-01-21T14:56:49.851471
2017-05-19T16:36:56
2017-05-19T16:36:56
91,825,664
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#include "squareType.h" void squareType::setDimension(double side) { rectangleType::setDimension(side,side); }
[ "rosskyl@mnstate.edu" ]
rosskyl@mnstate.edu
0c823b6a9015c09f920ba607e27d4ab1efbf9f9b
b415e8d193c8a6a4fa74488a360fb1e94edef343
/sharpIR/sharpIR.ino
2c5a2bba80ef4cdc920deaad8b2a2e2b759bdd30
[]
no_license
nitinvinayak/arduino-basic-codes
9ae1a184a4dc910e49e599d051b9a6c1a5b4d997
702e69c18f63f9fc01406ca6f43cd4fc1bca230e
refs/heads/master
2020-03-18T15:10:25.159133
2018-12-01T09:52:35
2018-12-01T09:52:35
134,891,055
0
1
null
null
null
null
UTF-8
C++
false
false
474
ino
#define sensor A0 // Sharp IR GP2Y0A41SK0F (4-30cm, analog) void setup() { Serial.begin(9600); // start the serial port pinMode(2,OUTPUT); } void loop() { digitalWrite(2,HIGH); // 5v float volts = analogRead(sensor)*0.0048828125; // value from sensor * (5/1024) int distance = 13*pow(volts, -1); // worked out from datasheet graph delay(1000); // slow down serial port if (distance <= 30){ Serial.println(distance); // print the distance } }
[ "noreply@github.com" ]
nitinvinayak.noreply@github.com
d1977af1d5018517e305464d44eae85c4939b962
cbe1d6e16e9798129f1dc1867a90d55ab8c923c8
/src/Timer.h
d5a893dbba6fbd6c7f61b4c4c330121540e6f904
[]
no_license
COM8/proto-assignments
d330823f4566f878f3ec7c4aad3a5c6595d352e7
ffbfc02529db087238f4b47014aace89166a26cd
refs/heads/master
2021-06-16T17:37:04.873868
2019-10-02T07:53:44
2019-10-02T07:53:44
129,932,857
0
5
null
2019-10-02T07:53:46
2018-04-17T16:18:39
C++
UTF-8
C++
false
false
740
h
#pragma once #include <mutex> #include <thread> #include <chrono> #include <atomic> #include "TimerTickable.h" #include "Logger.h" #include "Consts.h" enum TimerState { t_stop, t_run, t_reset, }; class Timer { public: Timer(bool tick, unsigned int intervallMS, TimerTickable *tT, int identifier); ~Timer(); void start(); void stop(); void reset(); private: bool tick; unsigned int intervallMS; TimerState state; std::thread* timerThread; TimerTickable *tT; int identifier; std::mutex *stateMutex; std::timed_mutex mut; std::atomic_bool locked; void timerTask(); void lock(); void unlock(); void sleepFor(const unsigned int ms); void wakeup(); };
[ "sauter.fabian@mailbox.org" ]
sauter.fabian@mailbox.org
8a1b48ed219dc636ec7c134fbca6b68e1c8794d6
b07a8d45a10b8c99a355803e3e4228e34bcb0d02
/src/ofApp.cpp
bace0a126ff650a97849a2168ef5344dfaacf8bd
[]
no_license
yutatoga/lovePulse
f48ee0fbba8611ee1ca48f17beb32cd332ac1954
0a02976294ca660ce777149191e2621e3666822d
refs/heads/master
2021-01-02T09:13:39.391114
2014-10-25T13:13:14
2014-10-25T13:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,350
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0,0,0); ofEnableSmoothing(); ofSetVerticalSync(true); fbo.allocate( ofGetWidth(), ofGetHeight(), GL_RGBA32F_ARB, 8); image.loadImage("c_background_black_300.jpg"); rectangleImage.set(0, 0, image.getWidth(), ofGetHeight()); ofEnableAlphaBlending(); ofSetLineWidth(1); firstBackground = true; fbo.begin(); ofClear(255,255,255, 0); fbo.end(); ofSetBackgroundAuto(false); //gui hideGui = true; gui.setup(); gui.setPosition(10, 20); gui.add(toggleFill.setup("fill", false)); gui.add(toggleFullScreen.setup("fullscreen", false)); gui.add(toggleWireColorFromPhoto.setup("wire color from photo", true)); gui.add(toggleDrawImage.setup("draw image", false)); gui.add(sliderWireColor.setup("wire color", ofColor::white, ofColor(0, 0), ofColor(255, 255))); gui.add(sliderWireLineWidth.setup("wire line width", 1., 0., 10.)); gui.add(sliderPalseLineWidth.setup("palse line width", 2., 0., 10.)); gui.add(buttonReset.setup("triangulation reset")); gui.add(sliderFrameRate.setup("framerate", 60, 1, 60)); gui.add(toggleSimpleColorPulse.setup("simple color", true)); gui.add(toggleLive.setup("live", true)); // listener for gui buttonReset.addListener(this, &ofApp::resetTriangulation); toggleFullScreen.addListener(this, &ofApp::fullScreen); sliderFrameRate.addListener(this, &ofApp::setFrameRate); //sound soundPlayer.loadSound("kin_6k.wav"); soundPlayer.setMultiPlay(true); //for live doAdd = false; doErase = false; doFill = false; } void ofApp::setFrameRate(int & sliderFrameRate){ ofSetFrameRate(sliderFrameRate); } void ofApp::resetTriangulation(){ triangulation.reset(); } void ofApp::fullScreen(){ ofToggleFullscreen(); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ // reset screen ofSetColor(0, 0, 0, 7); ofRect(0, 0, ofGetWidth(), ofGetHeight()); ofSetColor(255, 255, 255, 255); if (toggleDrawImage) { image.draw(0, 0, image.width, image.height); } // palse layer fbo.begin(); // screen update ofEnableBlendMode(OF_BLENDMODE_ALPHA); ofSetColor(0, 0, 0, 2); ofRect(0, 0, ofGetWidth(), ofGetHeight()); ofSetColor(255, 255, 255, 255); //mesh if (toggleLive) { //live(manually add or erase) addMeshAction(doAdd); eraseMeshAction(doErase); } else { // auto addMeshAction(ofGetFrameNum()%60 == 1 && ofRandom(2)>1); eraseMeshAction(ofGetFrameNum()%60 == 2 && ofRandom(2)>1.8); } fbo.end(); ofEnableBlendMode(OF_BLENDMODE_ALPHA); // draw mesh ofPushStyle(); toggleFill ? ofFill() : ofNoFill(); if (doFill) { doFill = false; ofFill(); }else{ ofNoFill(); } ofSetLineWidth(sliderWireLineWidth); ofEnableBlendMode(OF_BLENDMODE_ALPHA); triangulation.draw(); ofPopStyle(); //draw fbo(pulse layer) fbo.draw(0, 0); // hide below for live if (!hideGui) { // gui gui.draw(); // debug stringstream ss; ss << "framerate: " << ofToString(ofGetFrameRate(), 0); ofDrawBitmapString(ss.str(), 10, 15); // guide line ofPushStyle(); ofSetColor(255, 255, 0); ofLine(0, ofGetHeight()/2., ofGetWidth(), ofGetHeight()/2.); ofLine(ofGetWidth()/2., 0, ofGetWidth()/2., ofGetHeight()); ofSetColor(255, 0, 255); ofLine(image.getWidth(), 0, image.getWidth(), ofGetHeight()); ofLine(0, image.getHeight(), ofGetWidth(), image.getHeight()); ofPopStyle(); } } void ofApp::addMeshAction(bool boolAddMesh){ if (boolAddMesh) { doAdd = false; //mesh setup ofEnableBlendMode(OF_BLENDMODE_ADD); ofMesh mesh; mesh.setMode(OF_PRIMITIVE_LINES); mesh.enableColors(); mesh.enableIndices(); //pulse position ofVec2f start(ofRandom(0, image.width-1), ofRandom(0, image.height-1)); ofVec2f end(start.x+ofRandom(-1000, 1000), start.y+ofRandom(-1000, 1000)); //add mesh point for (int i = 0; i<ofRandom(10, 100); i++) { float theta = ofRandom(0, 2*PI); float amplitude = 300*pow(ofRandom(0,1), 2); ofPoint meshPoint(sin(theta)*amplitude+start.x, cos(theta)*amplitude+start.y, 0); triangulation.addPoint(meshPoint); } //update mesh triangulation.triangulate(image); // palse if (toggleSimpleColorPulse) { mesh.addVertex(start); mesh.addColor(ofColor(255, 255, 255, 255)); mesh.addVertex(end); mesh.addColor(ofColor(255, 255, 255, 0)); int indexNum = mesh.getIndices().size(); mesh.addIndex(indexNum); mesh.addIndex(indexNum+1); }else{ // set color from photo if (rectangleImage.inside(end)){ // end.x>=0 && end.y>=0 && end.x<image.width && end.y<image.height) mesh.addVertex(start); mesh.addColor(image.getColor(start.x, start.y)); mesh.addVertex(end); ofColor endColor = image.getColor(end.x, end.y); mesh.addColor(ofColor(endColor.r, endColor.g, endColor.b, 0)); int indexNum = mesh.getIndices().size(); mesh.addIndex(indexNum); mesh.addIndex(indexNum+1); }else{ mesh.addVertex(start); ofColor color = image.getColor(start.x, start.y); mesh.addColor(color); mesh.addVertex(end); mesh.addColor(ofColor(color.r, color.g, color.b, 0)); int indexNum = mesh.getIndices().size(); mesh.addIndex(indexNum); mesh.addIndex(indexNum+1); } } ofSetLineWidth(sliderPalseLineWidth); ofEnableBlendMode(OF_BLENDMODE_ADD); soundPlayer.play(); // pulse draw on fbo mesh.draw(); } } void ofApp::eraseMeshAction(bool boolEraseMesh){ if (boolEraseMesh) { doErase = false; //erase points triangulation.erase(); //update mesh triangulation.triangulate(image); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch (key) { case 'h': hideGui = !hideGui; ofShowCursor(); break; case 'a': doAdd = true; break; case 'f': ofToggleFullscreen(); case ' ': doFill = true; doAdd = true; break; case 'e': doErase = true; break; default: break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ // destroy triangulation.erase(); } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "yuta.toga@gmail.com" ]
yuta.toga@gmail.com
488668a5f02255889ce93b41c63ab47be4515a72
ff7ae135bd7ca88a43589b57bb80bedc72b77fc7
/spdlog/details/os.h
dddc5ad6acb3a71e1ce1e9ce5b97eefd41769bdf
[ "MIT" ]
permissive
parvmor/da
4341ddaf5b99c5216a17799c18a08ad842d0189c
4bd2f0a7ac63b2022513ddeb5487983a4e3fa7bd
refs/heads/master
2020-08-22T15:03:30.901634
2019-12-13T16:19:40
2019-12-13T16:19:40
216,422,071
1
0
null
null
null
null
UTF-8
C++
false
false
3,139
h
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include <ctime> // std::time_t #include "spdlog/common.h" namespace spdlog { namespace details { namespace os { spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT; std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT; std::tm localtime() SPDLOG_NOEXCEPT; std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT; std::tm gmtime() SPDLOG_NOEXCEPT; // eol definition #if !defined(SPDLOG_EOL) #ifdef _WIN32 #define SPDLOG_EOL "\r\n" #else #define SPDLOG_EOL "\n" #endif #endif SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL; // folder separator #ifdef _WIN32 static const char folder_sep = '\\'; #else SPDLOG_CONSTEXPR static const char folder_sep = '/'; #endif void prevent_child_fd(FILE *f); // fopen_s on non windows for writing bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode); // Remove filename. return 0 on success int remove(const filename_t &filename) SPDLOG_NOEXCEPT; // Remove file if exists. return 0 on success // Note: Non atomic (might return failure to delete if concurrently deleted by // other process/thread) int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT; int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT; // Return if file exists. bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT; // Return file size according to open FILE* object size_t filesize(FILE *f); // Return utc offset in minutes or throw spdlog_ex on failure int utc_minutes_offset(const std::tm &tm = details::os::localtime()); // Return current thread id as size_t // It exists because the std::this_thread::get_id() is much slower(especially // under VS 2013) size_t _thread_id() SPDLOG_NOEXCEPT; // Return current thread id as size_t (from thread local storage) size_t thread_id() SPDLOG_NOEXCEPT; // This is avoid msvc issue in sleep_for that happens if the clock changes. // See https://github.com/gabime/spdlog/issues/609 void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT; std::string filename_to_str(const filename_t &filename); int pid() SPDLOG_NOEXCEPT; // Determine if the terminal supports colors // Source: https://github.com/agauniyal/rang/ bool is_color_terminal() SPDLOG_NOEXCEPT; // Determine if the terminal attached // Source: https://github.com/agauniyal/rang/ bool in_terminal(FILE *file) SPDLOG_NOEXCEPT; #if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || \ defined(SPDLOG_WCHAR_FILENAMES)) && \ defined(_WIN32) void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target); #endif // Return directory name from given path or empty string // "abc/file" => "abc" // "abc/" => "abc" // "abc" => "" // "abc///" => "abc//" filename_t dir_name(filename_t path); // Create a dir from the given path. // Return true if succeeded or if this dir already exists. bool create_dir(filename_t path); } // namespace os } // namespace details } // namespace spdlog #ifdef SPDLOG_HEADER_ONLY #include "os-inl.h" #endif
[ "wiedeflo@gmail.com" ]
wiedeflo@gmail.com
7ed17013197cfcc23e5d19d1b5e8b9523402b970
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Filtering/QuadEdgeMeshFiltering/test/itkLaplacianDeformationQuadEdgeMeshFilterWithSoftConstraintsTest.cxx
a0155ac1b3311b47231001482a53acf07af33b36
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "...
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
4,369
cxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkQuadEdgeMesh.h" #include "itkMeshFileReader.h" #include "itkMeshFileWriter.h" #include "itkQuadEdgeMeshParamMatrixCoefficients.h" #include "itkLaplacianDeformationQuadEdgeMeshFilterWithSoftConstraints.h" #include "VNLSparseLUSolverTraits.h" int itkLaplacianDeformationQuadEdgeMeshFilterWithSoftConstraintsTest( int argc, char* argv[] ) { // ** ERROR MESSAGE AND HELP ** // if( argc != 4 ) { std::cout <<"Requires 3 argument: " <<std::endl; std::cout <<"1-Input file name " <<std::endl; std::cout <<"2-Output file name " <<std::endl; std::cout <<"3-Use Mixed Area" <<std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef double CoordType; typedef itk::QuadEdgeMesh< CoordType, Dimension > MeshType; typedef itk::MeshFileReader< MeshType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->Update(); typedef VNLSparseLUSolverTraits< CoordType > SolverType; typedef itk::LaplacianDeformationQuadEdgeMeshFilterWithSoftConstraints< MeshType, MeshType, SolverType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( reader->GetOutput() ); filter->SetOrder( 1 ); filter->SetLambda( 1. ); if( atoi( argv[3] ) == 1 ) { filter->SetAreaComputationType( FilterType::MIXEDAREA ); } else { filter->SetAreaComputationType( FilterType::NONE ); } typedef itk::ConformalMatrixCoefficients< MeshType > CoefficientType; CoefficientType coeff; filter->SetCoefficientsMethod( &coeff ); MeshType::VectorType nullVector( 0. ); std::map< MeshType::PointIdentifier, MeshType::VectorType > constraints; constraints[ 150 ] = nullVector; constraints[ 292 ] = nullVector; constraints[ 185 ] = nullVector; constraints[ 180 ] = nullVector; constraints[ 153 ] = nullVector; constraints[ 183 ] = nullVector; constraints[ 226 ] = nullVector; MeshType::VectorType d( 0. ); d[2] = -0.1; constraints[ 729 ] = d; constraints[ 938 ] = d; MeshType::VectorType e( 0. ); e[1] = 0.1; e[2] = -0.1; constraints[ 40 ] = e; constraints[ 371 ] = e; std::map< MeshType::PointIdentifier, MeshType::VectorType >::const_iterator it = constraints.begin(); while( it != constraints.end() ) { filter->SetDisplacement( it->first, it->second ); ++it; } filter->SetLocalLambda( 371, 0.1 ); try { filter->Update(); } catch( itk::ExceptionObject& except ) { std::cerr << "Failure: " << except.what(); return EXIT_FAILURE; } typedef itk::MeshFileWriter< MeshType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[2] ); writer->Update(); MeshType::Pointer inputMesh = reader->GetOutput(); MeshType::Pointer outputMesh = filter->GetOutput(); it = constraints.begin(); MeshType::PointType iPt, oPt; MeshType::VectorType displacement; while( it != constraints.end() ) { iPt = inputMesh->GetPoint( it->first ); oPt = outputMesh->GetPoint( it->first ); displacement = oPt - iPt; if( it->second.GetNorm() > 1e-6 ) { if( displacement.GetNorm() < 1e-6 ) { std::cerr << "Id: " << it->first << " * no displacement" << std::endl; return EXIT_FAILURE; } } ++it; } return EXIT_SUCCESS; }
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
f23a65eee3c23715d2a8bc31b17900227a9ebdee
173152aebdc0ffde5bbb7cfb9745762f3e14e3bc
/src/camera.cpp
3e4fe03693444ecb049083d78eee0053f23fcc32
[ "MIT" ]
permissive
TimQuelch/renderer
c50ed34da06a95c626cad8df333876f9058054a6
4e542e737071b2d165b9a5ab444939243719ca67
refs/heads/master
2020-08-17T13:39:23.956004
2019-12-19T08:12:12
2019-12-19T08:12:12
215,674,134
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
cpp
#include "camera.h" #include <random> #include <stdexcept> #include <fmt/format.h> namespace renderer { Camera::Camera(Vec const& eye, Vec const& lookAt, Vec const& up, double fov) : eye_{eye} , axis_{Axis::fromZY(lookAt - eye, up)} , planeDist_{0.5 / tan(degToRad(fov) / 2)} {} auto Camera::rayThroughPixel(int x, int y, int width, int height, Rng& rng) const -> Ray { if (x >= width || y >= height || x < 0 || y < 0) { throw std::invalid_argument{fmt::format( "Requested ray ({}, {}) is out of camera bounds ({}, {})", x, y, width, height)}; } auto unit = std::uniform_real_distribution<double>{0, 1}; auto const aspectRatio = static_cast<double>(width) / height; // y component is negative so down-right is positive in pixel coords, but up-right is // positive in space coords auto const xComp = axis_.x * aspectRatio * ((x + unit(rng)) / width - 0.5); auto const yComp = -axis_.y * ((y + unit(rng)) / height - 0.5); auto const zComp = axis_.z * planeDist_; auto const direction = xComp + yComp + zComp; return {eye_, direction.normalized()}; } // namespace renderer } // namespace renderer
[ "tim@quelch.name" ]
tim@quelch.name
9b983381222bb13ab4ee87ab6b3bc323e3413661
215111e92a3dfc535ce1c1ce25a35fb6003ab575
/cf/neps/e.cpp
b855c3ee71c1a42841b7310c4d672fd833bab6af
[]
no_license
emanueljuliano/Competitive_Programming
6e65aa696fb2bb0e2251e5a68657f4c79cd8f803
86fefe4d0e3ee09b5766acddc8c78ed8b60402d6
refs/heads/master
2023-06-23T04:52:43.910062
2021-06-26T11:34:42
2021-06-26T11:34:42
299,115,304
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(0);cin.tie(0); #define endl '\n' #define f first #define s second #define pb push_back typedef long long ll; typedef pair<int, int> ii; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3fll; int main(){ _ int n; cin >> n; cout << (n-9+24)%24 << endl; exit(0); }
[ "emanueljulianoms@gmail.com" ]
emanueljulianoms@gmail.com
28181c4cf0debf56a69f996ae660b0d65d2cc7c8
e5c6bbe97f6ef41271e7f9006adf24284dccff0d
/Ships Class/Ships Class/Ship.hpp
42bfff45715770b366d797329b441200a4698bab
[]
no_license
anazeneli/fordham-cs2
941a9c5c06cb13643edfaeff79c824825c96cf82
4e5ef20fde251a6d19d6ba7f818f28baf70ca4bc
refs/heads/master
2021-01-12T01:21:11.238268
2017-01-20T00:11:03
2017-01-20T00:11:03
78,373,534
0
0
null
null
null
null
UTF-8
C++
false
false
3,153
hpp
// // Ship.hpp // Ships Class // // Created by Ana Zeneli on 12/2/16. // Copyright © 2016 Ana Zeneli. All rights reserved. // #ifndef Ship_hpp #define Ship_hpp #include <stdio.h> #include <iostream> #include <string> using namespace std; /* Design a Ship class that has the following members: • A member variable for the name of the ship (a string) • A member variable for the year that the ship was built (a string) • A constructor and appropriate accessors and mutators • A virtual print function that displays the ship’s name and the year it was built. */ class Ship { private: string shipName; string yearBuilt; public: Ship() { shipName = " "; yearBuilt = " " ; } ~Ship(); Ship( string theName, string theYear ) { shipName = theName; yearBuilt = theYear; } string getName() const { return shipName; } string getYear() const { return yearBuilt; } virtual void printInfo() const { cout << "Ship Name: " << shipName << endl; cout << "Year Built: " << yearBuilt << endl; } }; /* Design a CruiseShip class that is derived from the Ship class. The CruiseShip class should have the following members: • A member variable for the maximum number of passengers (an int) • A constructor and appropriate accessors and mutators • A print function that overrides the print function in the base class. The CruiseShip class’s print function should display only the ship’s name and the maximum number of passengers. */ class CruiseShip : public Ship { private: int maxPassengers; public: CruiseShip() : Ship() { maxPassengers = 0; } ~CruiseShip(); CruiseShip(string theName, string theYear, int passengers) : Ship(theName, theYear) { maxPassengers = passengers; } void printInfo() const { cout << "Ship Name: " << getName() << endl; cout << "Year Built: " << getYear() << endl; cout << "Maximum passengers: " << maxPassengers << endl; } }; /* Design a CargoShip class that is derived from the Ship class. The CargoShip class should have the following members: • A member variable for the cargo capacity in tonnage (an int). • A constructor and appropriate accessors and mutators. • A print function that overrides the print function in the base class. The CargoShip class’s print function should display only the ship’s name and the ship’s cargo capacity. */ class CargoShip : public Ship { private: int cargoCapacity; // in tonnage public: CargoShip() : Ship() { cargoCapacity = 0; } ~CargoShip(); CargoShip(string theName, string theYear, int tonnage) : Ship(theName, theYear) { cargoCapacity = tonnage; } void printInfo() const { cout << "Ship Name: " << getName() << endl; cout << "Year Built: " << getYear() << endl; cout << "Cargo capacity: " << cargoCapacity << endl; } }; #endif /* Ship_hpp */
[ "anazeneli1@Anas-Air.home" ]
anazeneli1@Anas-Air.home
90345e96f2a165826c03ab92479c534fffe7778e
822927ee8b2cb458d161f99eaa2cefce6234924e
/SoundFX.h
f2863b1fd2701768bbcfc48c92eb83ec914da162
[]
no_license
polus314/mister-roboto
8ed1ca966639b2f3a0eca1446dccb459323727be
86c41b289b6ea89b28f5c98386b4c640835543af
refs/heads/master
2020-04-07T04:40:24.548378
2017-03-11T00:26:18
2017-03-11T00:26:18
51,494,297
0
0
null
2016-04-29T03:00:00
2016-02-11T04:37:56
C++
UTF-8
C++
false
false
2,187
h
//----------------------------------------------------------------------------- // Project: Mister Roboto // // Purpose: This class provides a convenient interface for playing the sounds // music I have for the game. //----------------------------------------------------------------------------- #ifndef SOUNDFX_H #define SOUNDFX_H #include <SFML\Audio.hpp> enum class MusicType { MAIN_MENU, ROAMING, FIGHTING }; class SoundFX { public: //-------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------- SoundFX(); //-------------------------------------------------------------------------- // Plays the sound for changing which option is highlighted in a menu //-------------------------------------------------------------------------- void playSelectionChange(); //-------------------------------------------------------------------------- // Plays the sound for leaving one menu or entering a new one //-------------------------------------------------------------------------- void playMenuEnterExit(); //-------------------------------------------------------------------------- // Starts playing the music specified by m. Stops any music that was // previously playing //-------------------------------------------------------------------------- void playMusic(MusicType m); //-------------------------------------------------------------------------- // Sets the volume of all music and sounds played. Value passed is // interpreted as a percentage, from 0 to 100. //-------------------------------------------------------------------------- void setVolume(int vol); //-------------------------------------------------------------------------- // Returns the volume of all music and sounds played. Value returned // represents the volume as a percentage, from 0 to 100. //-------------------------------------------------------------------------- int getVolume() const; private: Music music; SoundBuffer buf[5]; Sound sounds[5]; float currentVolume; }; #endif
[ "jppolecat@gmail.com" ]
jppolecat@gmail.com
7f5cf38e18646f6c948e0f9526881cf8304cf52e
028d5493934abc77587914009c03d21b9db9bbfd
/基于QT的企业合同管理系统的设计与实现/code/ContractManagement/welcome.h
3a7d062284ffe67325c9450d0e6059cb38cb30ce
[]
no_license
18847138124/20151104780_kongdejing
bd103ae252cab656cc60bb1bddd1222f901eb603
7e8cd148ec702861758eb1a918682c529b2af549
refs/heads/master
2020-04-01T08:39:23.688304
2019-03-20T09:06:14
2019-03-20T09:06:14
153,040,950
0
0
null
null
null
null
UTF-8
C++
false
false
843
h
#ifndef WELCOME_H #define WELCOME_H //防止声明冲突 #include <QDialog> //对话框 //命名空间 namespace Ui { class Welcome; } //欢迎页面 class Welcome : public QDialog { Q_OBJECT public: //客户端类型 //枚举两种 enum ClientType { Apply, //申请端 Check //审核端 }; //QWidge *parent表示父类窗口 =0表示它的标志位 // explicit主要用于 "修饰 "构造函数. 指明构造函数只能显示使用,目的是为了防止不必要的隐式转化. //类的构造函数声明 explicit Welcome(QWidget *parent = 0); ~Welcome(); ClientType type(); //当前选择的类型 //槽函数 private slots: void on_enterBtn_clicked();//屏幕按钮会对enterBtn响应 private: Ui::Welcome *ui;//图形化界面设置 }; #endif // WELCOME_H
[ "18847138124@163.com" ]
18847138124@163.com
bd4e55151ef25b574f14bd2c746a4109e4092aaf
82a3c45e7a5d27812e9226af0feccdd50bf11dfb
/NewTrainingFramework/Texture (2019_10_09 07_33_18 UTC).cpp
6893ed3fcb71cfc6543ad9f9c9fe29eeb48b6d49
[ "MIT" ]
permissive
Stefania12/GameloftGameEngine
abea777a9ea46c660a0f0c9c2648805f67339d53
00555504d48e905fc3e7593cdf4806992f58fcd0
refs/heads/master
2020-09-05T10:11:34.428471
2019-11-06T19:44:15
2019-11-06T19:44:15
220,068,377
0
0
null
null
null
null
UTF-8
C++
false
false
3,597
cpp
#include "stdafx.h" #include "Texture.h" #include "TextureResource.h" void getFacePixelArray(char* source, char* destination, int height, int width, int offset, int startx, int nr_bytes) { for (int i = startx; i < startx + height / 3; i++) memcpy(destination + (i - startx) * nr_bytes * width / 4, source + i * width * nr_bytes + offset * nr_bytes, width * nr_bytes / 4); } Texture::Texture(TextureResource* t) { tr = t; Load(); } void Texture::Bind(int slot) { glActiveTexture(GL_TEXTURE0 + slot); if (tr->type == "2d") glBindTexture(GL_TEXTURE_2D, texture_id); } void Texture::Load() { glGenTextures(1, &texture_id); GLuint textureType; if (tr->type == "2d") textureType = GL_TEXTURE_2D; else textureType = GL_TEXTURE_CUBE_MAP; glBindTexture(textureType, texture_id); if (tr->min_filter == "LINEAR") glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if (tr->mag_filter == "LINEAR") glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (tr->wrap_s == "CLAMP_TO_EDGE") { glTexParameteri(textureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); } else { if (tr->wrap_s == "GL_REPEAT") glTexParameteri(textureType, GL_TEXTURE_WRAP_S, GL_REPEAT); } if (tr->wrap_t == "CLAMP_TO_EDGE") { glTexParameteri(textureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { if (tr->wrap_t == "GL_REPEAT") glTexParameteri(textureType, GL_TEXTURE_WRAP_T, GL_REPEAT); } int width, height, bpp; char* pixels_array = LoadTGA(tr->path.c_str(), &width, &height, &bpp); if (tr->type == "2d") { switch (bpp) { case 32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels_array); break; case 24: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels_array); break; default: std::cout << "Unknown texture... too bad:(" << std::endl; assert(false); } glBindTexture(GL_TEXTURE_2D, 0); } else { GLuint rgb, nr_bytes; if (bpp == 32) { nr_bytes = 4; rgb = GL_RGBA; } else if (bpp == 24) { nr_bytes = 3; rgb = GL_RGB; } else { std::cout << "Unknown texture... too bad:(" << std::endl; assert(false); } char* subbuffer = new char[width / 4 * height / 3 * nr_bytes]; getFacePixelArray(pixels_array, subbuffer, height, width, width / 2, height / 3, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); getFacePixelArray(pixels_array, subbuffer, height, width, 0, height / 3, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); getFacePixelArray(pixels_array, subbuffer, height, width, width / 4, 0, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); getFacePixelArray(pixels_array, subbuffer, height, width, width / 4, 2 * height / 3, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); getFacePixelArray(pixels_array, subbuffer, height, width, width / 4, height / 3, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); getFacePixelArray(pixels_array, subbuffer, height, width, 3 * width / 4, height / 3, nr_bytes); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, rgb, width / 4, height / 3, 0, rgb, GL_UNSIGNED_BYTE, subbuffer); delete[] subbuffer; } delete[] pixels_array; } Texture::~Texture() { }
[ "stefania.damian1207@gmail.com" ]
stefania.damian1207@gmail.com
fa7280271e00bc62be735432ec9e178e229809d5
b3c94e765603de4df6b1dbdb6849fdc164b8294a
/Qt5-C-PlusPlus-Programming-Cookbook/Chapter 2/ButtonAnimationGroup/mainwindow.cpp
54739a7d779e6680872053b6a6c86fb21d46797b
[]
no_license
Abd-Elrazek/Books-Cpp
9e056cc34c81d77f7c0d639ec677750deed22f6b
a7300a9ec3e0e2cbf973bc52defc92d823aa9246
refs/heads/master
2020-04-18T10:33:16.158063
2018-09-27T07:38:55
2018-09-27T07:38:55
167,470,897
1
0
null
2019-05-25T17:16:00
2019-01-25T02:22:00
C++
UTF-8
C++
false
false
1,579
cpp
#include <QPropertyAnimation> #include <QParallelAnimationGroup> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QPropertyAnimation *FirstAnimation = new QPropertyAnimation(ui->FirstButton, "geometry"); FirstAnimation->setDuration(5000); FirstAnimation->setStartValue(ui->FirstButton->geometry()); FirstAnimation->setEndValue(QRect(400, 50, 60, 20)); QPropertyAnimation *SecondAnimation = new QPropertyAnimation(ui->SecondButton, "geometry"); SecondAnimation->setDuration(4000); SecondAnimation->setStartValue(ui->SecondButton->geometry()); SecondAnimation->setEndValue(QRect(400, 100, 60, 20)); QPropertyAnimation *ThirdAnimation = new QPropertyAnimation(ui->ThirdButton, "geometry"); ThirdAnimation->setDuration(3000); ThirdAnimation->setStartValue(ui->ThirdButton->geometry()); ThirdAnimation->setEndValue(QRect(400, 150, 60, 20)); QEasingCurve MyCurve; MyCurve.setType(QEasingCurve::OutBounce); MyCurve.setAmplitude(0.5); MyCurve.setOvershoot(1.2); MyCurve.setPeriod(0.7); FirstAnimation->setEasingCurve(MyCurve); SecondAnimation->setEasingCurve(MyCurve); ThirdAnimation->setEasingCurve(MyCurve); QParallelAnimationGroup *MyGroup = new QParallelAnimationGroup; MyGroup->addAnimation(FirstAnimation); MyGroup->addAnimation(SecondAnimation); MyGroup->addAnimation(ThirdAnimation); MyGroup->start(); } MainWindow::~MainWindow() { delete ui; }
[ "noreply@github.com" ]
Abd-Elrazek.noreply@github.com
cb8e05522ffdb88b4210e71f895a46b1b37412b4
8ae7a23f05805fd71d4be13686cf35d8994762ed
/mame150/src/emu/machine/6821pia.h
bc6cbecd78589c9cd29f4b1b5b1a60643cf49396
[]
no_license
cyberkni/276in1JAMMA
fb06ccc6656fb4346808a24beed8977996da91b2
d1a68172d4f3490cf7f6e7db25d5dfd4cde3bb22
refs/heads/master
2021-01-18T09:38:36.974037
2013-10-07T18:30:02
2013-10-07T18:30:02
13,152,960
1
0
null
null
null
null
UTF-8
C++
false
false
6,664
h
/********************************************************************** Motorola 6821 PIA interface and emulation Notes: * get_port_b_z_mask() gives the caller the bitmask that shows which bits are high-impendance when reading port B, and thus neither 0 or 1. get_output_cb2_z() returns the same info for the CB2 pin. * set_port_a_z_mask allows the input callback to indicate which port A bits are disconnected. For these bits, the read operation will return the output buffer's contents. * The 'alt' interface functions are used when the A0 and A1 address bits are swapped. * All 'int' data or return values are bool, and should be converted to bool at some point. **********************************************************************/ #pragma once #ifndef __6821PIA_H__ #define __6821PIA_H__ #include "emu.h" /*************************************************************************** DEVICE CONFIGURATION MACROS ***************************************************************************/ #define MCFG_PIA6821_ADD(_tag, _intrf) \ MCFG_DEVICE_ADD(_tag, PIA6821, 0) \ pia6821_device::static_set_interface(*device, _intrf); #define MCFG_PIA6821_MODIFY(_tag, _intrf) \ MCFG_DEVICE_MODIFY(_tag) \ pia6821_device::static_set_interface(*device, _intrf); #define MCFG_PIA6822_ADD(_tag, _intrf) \ MCFG_DEVICE_ADD(_tag, PIA6822, 0) \ pia6821_device::static_set_interface(*device, _intrf); #define MCFG_PIA6822_MODIFY(_tag, _intrf) \ MCFG_DEVICE_MODIFY(_tag) \ pia6821_device::static_set_interface(*device, _intrf); /*************************************************************************** TYPE DEFINITIONS ***************************************************************************/ // ======================> pia6821_interface struct pia6821_interface { devcb_read8 m_in_a_cb; devcb_read8 m_in_b_cb; devcb_read_line m_in_ca1_cb; devcb_read_line m_in_cb1_cb; devcb_read_line m_in_ca2_cb; devcb_read_line m_in_cb2_cb; devcb_write8 m_out_a_cb; devcb_write8 m_out_b_cb; devcb_write_line m_out_ca2_cb; devcb_write_line m_out_cb2_cb; devcb_write_line m_irq_a_cb; devcb_write_line m_irq_b_cb; }; // ======================> pia6821_device class pia6821_device : public device_t, public pia6821_interface { public: // construction/destruction pia6821_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); // static configuration helpers static void static_set_interface(device_t &device, const pia6821_interface &interface); DECLARE_READ8_MEMBER( read ) { return reg_r(offset); } DECLARE_WRITE8_MEMBER( write ) { reg_w(offset, data); } DECLARE_READ8_MEMBER( read_alt ) { return reg_r(((offset << 1) & 0x02) | ((offset >> 1) & 0x01)); } DECLARE_WRITE8_MEMBER( write_alt ) { reg_w(((offset << 1) & 0x02) | ((offset >> 1) & 0x01), data); } UINT8 port_b_z_mask() const { return ~m_ddr_b; } // see first note in .c void set_port_a_z_mask(UINT8 data) { m_port_a_z_mask = data; }// see second note in .c DECLARE_READ8_MEMBER( porta_r ); UINT8 porta_r() { return porta_r(machine().driver_data()->generic_space(), 0); } DECLARE_WRITE8_MEMBER( porta_w ); void porta_w(UINT8 data) { porta_w(machine().driver_data()->generic_space(), 0, data); } void set_a_input(UINT8 data, UINT8 z_mask); UINT8 a_output(); DECLARE_READ_LINE_MEMBER( ca1_r ); DECLARE_WRITE_LINE_MEMBER( ca1_w ); DECLARE_READ_LINE_MEMBER( ca2_r ); DECLARE_WRITE_LINE_MEMBER( ca2_w ); int ca2_output(); int ca2_output_z(); DECLARE_READ8_MEMBER( portb_r ); UINT8 portb_r() { return portb_r(machine().driver_data()->generic_space(), 0); } DECLARE_WRITE8_MEMBER( portb_w ); void portb_w(UINT8 data) { portb_w(machine().driver_data()->generic_space(), 0, data); } UINT8 b_output(); DECLARE_READ_LINE_MEMBER( cb1_r ); DECLARE_WRITE_LINE_MEMBER( cb1_w ); DECLARE_READ_LINE_MEMBER( cb2_r ); DECLARE_WRITE_LINE_MEMBER( cb2_w ); int cb2_output(); int cb2_output_z(); int irq_a_state() const { return m_irq_a_state; } int irq_b_state() const { return m_irq_b_state; } protected: // device-level overrides virtual void device_start(); virtual void device_reset(); private: UINT8 reg_r(UINT8 offset); void reg_w(UINT8 offset, UINT8 data); void update_interrupts(); UINT8 get_in_a_value(); UINT8 get_in_b_value(); UINT8 get_out_a_value(); UINT8 get_out_b_value(); void set_out_ca2(int data); void set_out_cb2(int data); UINT8 port_a_r(); UINT8 ddr_a_r(); UINT8 control_a_r(); UINT8 port_b_r(); UINT8 ddr_b_r(); UINT8 control_b_r(); void send_to_out_a_func(const char* message); void send_to_out_b_func(const char* message); void port_a_w(UINT8 data); void ddr_a_w(UINT8 data); void port_b_w(UINT8 data); void ddr_b_w(UINT8 data); void control_a_w(UINT8 data); void control_b_w(UINT8 data); devcb_resolved_read8 m_in_a_func; devcb_resolved_read8 m_in_b_func; devcb_resolved_read_line m_in_ca1_func; devcb_resolved_read_line m_in_cb1_func; devcb_resolved_read_line m_in_ca2_func; devcb_resolved_read_line m_in_cb2_func; devcb_resolved_write8 m_out_a_func; devcb_resolved_write8 m_out_b_func; devcb_resolved_write_line m_out_ca2_func; devcb_resolved_write_line m_out_cb2_func; devcb_resolved_write_line m_irq_a_func; devcb_resolved_write_line m_irq_b_func; UINT8 m_in_a; UINT8 m_in_ca1; UINT8 m_in_ca2; UINT8 m_out_a; UINT8 m_out_ca2; UINT8 m_port_a_z_mask; UINT8 m_ddr_a; UINT8 m_ctl_a; UINT8 m_irq_a1; UINT8 m_irq_a2; UINT8 m_irq_a_state; UINT8 m_in_b; UINT8 m_in_cb1; UINT8 m_in_cb2; UINT8 m_out_b; UINT8 m_out_cb2; UINT8 m_last_out_cb2_z; UINT8 m_ddr_b; UINT8 m_ctl_b; UINT8 m_irq_b1; UINT8 m_irq_b2; UINT8 m_irq_b_state; // variables that indicate if access a line externally - // used to for logging purposes ONLY bool m_in_a_pushed; bool m_out_a_needs_pulled; bool m_in_ca1_pushed; bool m_in_ca2_pushed; bool m_out_ca2_needs_pulled; bool m_in_b_pushed; bool m_out_b_needs_pulled; bool m_in_cb1_pushed; bool m_in_cb2_pushed; bool m_out_cb2_needs_pulled; bool m_logged_port_a_not_connected; bool m_logged_port_b_not_connected; bool m_logged_ca1_not_connected; bool m_logged_ca2_not_connected; bool m_logged_cb1_not_connected; bool m_logged_cb2_not_connected; }; // device type definition extern const device_type PIA6821; #endif /* __6821PIA_H__ */
[ "dan@van.derveer.com" ]
dan@van.derveer.com
1c658756ba674ba6476c6276a562669a08cf085f
e42a3102609ca259626a71d1be6fa5adfcf78979
/GINnJUCE/src/Toggle.cpp
a3e85b126acd414c8c798358f5d6bcf52decd676
[]
no_license
adamszaruga/GINnJUCE-Example
bde878151234f4ccef5fde979ce8cec692cf34ab
0c2ecdd2259c7fdd4bec27f8b684c095a6c5dfc1
refs/heads/master
2021-06-27T14:58:12.172258
2017-09-12T21:33:34
2017-09-12T21:33:34
103,317,955
6
2
null
null
null
null
UTF-8
C++
false
false
2,584
cpp
/* ============================================================================== This file was auto-generated by the GINnJUCE Transpiler. You're welcome! ============================================================================== */ #include "Toggle.h" Toggle::Toggle() { initializeText(); initializePaths(); addAndMakeVisible(background); addAndMakeVisible(label); } Toggle::~Toggle() { } void Toggle::paint(Graphics& g) { } void Toggle::resized() { background.setBounds(0, 0, 64, 30); label.setBounds(16, 6, 39, 18); } void Toggle::initializeText() { // Text initialization for label Font labelFont(String("Myriad"), String("Myriad-Roman"), 14.0f); labelFont.setHorizontalScale(1.0f); label.setFont(labelFont); label.setColour(TextEditor::ColourIds::backgroundColourId, Colour(0x00000000)); label.setColour(TextEditor::ColourIds::textColourId, Colour(0xff000000)); label.setColour(TextEditor::ColourIds::outlineColourId , Colour(0x00000000)); label.setColour(TextEditor::ColourIds::focusedOutlineColourId , Colour(0x00000000)); label.setColour(TextEditor::ColourIds::shadowColourId , Colour(0x00000000)); label.setText( "FUZZ\n" ); label.moveCaretToTop(false); label.setCaretVisible(false); label.setReadOnly(true); label.setScrollbarsShown(false); label.setIndents(0, 0); label.setLineSpacing(1.20000008174351f); label.setMultiLine(true, false); } void Toggle::initializePaths() { // Path initialization for background Path backgroundPath; backgroundPath.startNewSubPath(Point<float>(64.0f, 30.0f)); backgroundPath.cubicTo( Point<float>(64.0f, 30.0f), Point<float>(0.0f, 30.0f), Point<float>(0.0f, 30.0f) ); backgroundPath.cubicTo( Point<float>(0.0f, 30.0f), Point<float>(0.0f, 0.0f), Point<float>(0.0f, 0.0f) ); backgroundPath.cubicTo( Point<float>(0.0f, 0.0f), Point<float>(64.0f, 0.0f), Point<float>(64.0f, 0.0f) ); backgroundPath.cubicTo( Point<float>(64.0f, 0.0f), Point<float>(64.0f, 30.0f), Point<float>(64.0f, 30.0f) ); backgroundPath.closeSubPath(); const PathStrokeType backgroundStroke (1.0f, PathStrokeType::JointStyle::mitered, PathStrokeType::EndCapStyle::butt); const FillType backgroundFill (Colour(0xff424242)); const FillType backgroundStrokeFill (Colour(0x00000000)); background.setPath(backgroundPath); background.setStrokeType(backgroundStroke); background.setFill(backgroundFill); background.setStrokeFill(backgroundStrokeFill); }
[ "adam@users-MacBook-Air.local" ]
adam@users-MacBook-Air.local
41952bc519219a15ce173687e66b60f974bba275
67f631e4215a3a91cdec95ad22714af769d01d64
/assn1.cpp
180230b53f5db99519ef2974cae2849e7ad3135a
[]
no_license
abiramrnair/Simple-Assignments
6e60e1e1c4a29781fb8ccb50455e539033dc70d1
646f109140088b71f1129c00cae451603ffafb2b
refs/heads/master
2021-10-28T15:24:52.970443
2018-11-20T00:26:31
2018-11-20T00:26:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,404
cpp
#include <iostream> using namespace std; // Define some functions double calcAverage(char*values[], int sz) { // Function 'A' cout << "Average" << endl; // Prints out the name for (int i = 0; i < sz; i++) { // Prints out each term of the input cout << atof(values[i]) << " "; } cout << endl; double sum = 0; int *count, *arrayPtr; count = &sz; arrayPtr = new int[*count]; for (int i = 0; i < *count; i++) { // Put in values into this dynamic array arrayPtr[i] = atof(values[i]); } for (int i = 0; i < sz; i++) { // Store the sum of the values in the dynamic array sum += arrayPtr[i]; } sum = sum / sz; return sum; delete count; // Deletion of the dynamic variables delete[]arrayPtr; } double calcMedian(char*values[], double sz) { // Function 'M' cout << "Median" << endl; double median; for (int i = 0; i < sz; i++) { // Prints out each term of the input cout << atof(values[i]) << " "; } double *count, double *arrayPtr; count = &sz; double *arrayPtr = new double[sz]; for (int i = 0; i < *count; i++) { // Put in values into this dynamic array arrayPtr[i] = atof(values[i]); } cout << endl; if (*count % 2 != 0) { // In case array spaces are odd numbered *count = (*count / 2) + 0.5; median = arrayPtr[*count]; } else { // In case array spaces are even numbered median = (arrayPtr[*count / 2] + arrayPtr[(*count / 2) + 1])/2; } return median; delete count; delete[]arrayPtr; } double calcSum(char*values[]) { // Function 'F' double sum = 0; cout << "Sum" << endl; // Prints out the name of the function for (int i = 0; i < 3; i++) { // Prints out each term of the input array cout << atof(values[i]) << " "; } cout << endl; const int size = 3; double miniArray[size]; for (int i = 0; i < 3; i++) { miniArray[i] = atof(values[i]); } for (int i = 0; i < 3; i++) { sum += miniArray[i]; } return sum; } int main(int argc, char *argv[]) { char c; switch (*argv[1]) { // Use a switch statement that analyzes the first array space in argv case 'A': cout << "The average is " << calcAverage(&argv[2], argc - 2) << endl; break; case 'M': cout << "The median is " << calcMedian(&argv[2], argc - 2) << endl; break; case 'F': cout << "The sum is " << calcSum(&argv[2]) << endl; break; } cin >> c; }
[ "noreply@github.com" ]
abiramrnair.noreply@github.com
d04458d3199da849ae84a0c4b9cb7504464eac77
0dae7744c9461082a402ad413b112bc734d3fee9
/src/scenes/angleLineScene/angleLineScene.h
956a921652c52381c560e5d6ad70f2944bacc59a
[]
no_license
ma286/sketches
7df1226fb5abed06610f29255166bd847c6a4f03
37c2dc6163d0454eeb56127f86705c3e22add05a
refs/heads/master
2021-04-18T22:19:08.372157
2013-06-23T11:40:34
2013-06-23T11:40:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
766
h
#pragma once #include "ofMain.h" #include "angleLengthLine.h" #include "baseScene.h" class angleLineScene : public baseScene { public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofPolyline line; angleLengthLine angleLine; vector < angleLengthLine > alines; void clear(){ line.clear(); //angleLine.clear(); alines.clear(); } };
[ "zach@openframeworks.cc" ]
zach@openframeworks.cc
c677508dc156f759918a71fe030fa8dda9b08662
a5a1213414c839c8807ae9326fcfb3d94a93557c
/projects/Final/src/main.cpp
a82391feab999549e67c009864338242af9ea8ef
[]
no_license
DashingCats/Final_CG
83d6b4cb3e3fe001dada4101764a09554bd08ccc
8059d8b07898551dd180db9db8555e3872a4a14a
refs/heads/main
2023-04-10T14:20:32.848788
2021-04-25T20:51:02
2021-04-25T20:51:02
359,630,878
0
0
null
null
null
null
UTF-8
C++
false
false
21,725
cpp
//Just a simple handler for simple initialization stuffs #include "Utilities/BackendHandler.h" #include <filesystem> #include <json.hpp> #include <fstream> #include <Texture2D.h> #include <Texture2DData.h> #include <MeshBuilder.h> #include <MeshFactory.h> #include <NotObjLoader.h> #include <ObjLoader.h> #include <VertexTypes.h> #include <ShaderMaterial.h> #include <RendererComponent.h> #include <TextureCubeMap.h> #include <TextureCubeMapData.h> #include <Timing.h> #include <GameObjectTag.h> #include <InputHelpers.h> #include <IBehaviour.h> #include <CameraControlBehaviour.h> #include <FollowPathBehaviour.h> #include <SimpleMoveBehaviour.h> int main() { int frameIx = 0; float fpsBuffer[128]; float minFps, maxFps, avgFps; int selectedVao = 0; // select cube by default std::vector<GameObject> controllables; BackendHandler::InitAll(); // Let OpenGL know that we want debug output, and route it to our handler function glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback(BackendHandler::GlDebugMessage, nullptr); // Enable texturing glEnable(GL_TEXTURE_2D); // Push another scope so most memory should be freed *before* we exit the app { #pragma region Shader and ImGui Shader::sptr passthroughShader = Shader::Create(); passthroughShader->LoadShaderPartFromFile("shaders/passthrough_vert.glsl", GL_VERTEX_SHADER); passthroughShader->LoadShaderPartFromFile("shaders/passthrough_frag.glsl", GL_FRAGMENT_SHADER); passthroughShader->Link(); // Load our shaders Shader::sptr shader = Shader::Create(); shader->LoadShaderPartFromFile("shaders/vertex_shader.glsl", GL_VERTEX_SHADER); shader->LoadShaderPartFromFile("shaders/frag_blinn_phong_textured.glsl", GL_FRAGMENT_SHADER); shader->Link(); glm::vec3 lightPos = glm::vec3(0.0f, 0.0f, 5.0f); glm::vec3 lightCol = glm::vec3(0.9f, 0.85f, 0.5f); float lightAmbientPow = 0.05f; float lightSpecularPow = 1.0f; glm::vec3 ambientCol = glm::vec3(1.0f); float ambientPow = 0.1f; float lightLinearFalloff = 0.09f; float lightQuadraticFalloff = 0.032f; bool mode_1 = true; bool mode_2 = false; bool mode_3 = false; bool mode_4 = false; bool mode_5 = false; // These are our application / scene level uniforms that don't necessarily update // every frame shader->SetUniform("u_LightPos", lightPos); shader->SetUniform("u_LightCol", lightCol); shader->SetUniform("u_AmbientLightStrength", lightAmbientPow); shader->SetUniform("u_SpecularLightStrength", lightSpecularPow); shader->SetUniform("u_AmbientCol", ambientCol); shader->SetUniform("u_AmbientStrength", ambientPow); shader->SetUniform("u_LightAttenuationConstant", 1.0f); shader->SetUniform("u_LightAttenuationLinear", lightLinearFalloff); shader->SetUniform("u_LightAttenuationQuadratic", lightQuadraticFalloff); PostEffect* basicEffect; int activeEffect = 0; std::vector<PostEffect*> effects; NoEffect* noEffect; Final* finalEffect; // We'll add some ImGui controls to control our shader BackendHandler::imGuiCallbacks.push_back([&]() { if (ImGui::CollapsingHeader("Assignment 1 Toggles")) { if (ImGui::Checkbox("No Lighting", &mode_1)) { mode_2 = false; mode_3 = false; mode_4 = false; } if (ImGui::Checkbox("Ambient Only", &mode_2)) { mode_1 = false; mode_3 = false; mode_4 = false; } if (ImGui::Checkbox("Specular Only", &mode_3)) { mode_1 = false; mode_2 = false; mode_4 = false; } if (ImGui::Checkbox("Specular + Ambient", &mode_4)) { mode_1 = false; mode_2 = false; mode_3 = false; } if (ImGui::Checkbox("No Texture", &mode_5)) { glBindTexture(GL_TEXTURE_2D, 0); } } int camerapos = 3; shader->SetUniform("u_mode1", (int)mode_1); shader->SetUniform("u_mode2", (int)mode_2); shader->SetUniform("u_mode3", (int)mode_3); shader->SetUniform("u_mode4", (int)mode_4); shader->SetUniform("u_mode5", (int)mode_5); shader->SetUniform("viewpos", camerapos); if (ImGui::CollapsingHeader("Effect controls")) { ImGui::SliderInt("Chosen Effect", &activeEffect, 0, effects.size() - 1); if (activeEffect == 0) { ImGui::Text("Active Effect: No Effect"); } if (activeEffect == 1) { ImGui::Text("Active Effect: Depth Of Field Effect"); Final* temp = (Final*)effects[activeEffect]; //float focalLength = temp->GetFocalLength(); //float aparture = temp->GetAparture(); //float planeInFocus = temp->GetPlaneInFocus(); /*ImGui::SliderFloat("Focal Length", &focalLength, 0, 100); { temp->SetFocalLength(focalLength); } ImGui::SliderFloat("Aparture", &aparture, 0, 100); { temp->SetAparture(aparture); } ImGui::SliderFloat("Plane In Focus", &planeInFocus, 0, 100); { temp->SetPlaneInFocus(planeInFocus); }*/ } } if (ImGui::CollapsingHeader("Environment generation")) { if (ImGui::Button("Regenerate Environment", ImVec2(200.0f, 40.0f))) { EnvironmentGenerator::RegenerateEnvironment(); } } if (ImGui::CollapsingHeader("Scene Level Lighting Settings")) { if (ImGui::ColorPicker3("Ambient Color", glm::value_ptr(ambientCol))) { shader->SetUniform("u_AmbientCol", ambientCol); } if (ImGui::SliderFloat("Fixed Ambient Power", &ambientPow, 0.01f, 1.0f)) { shader->SetUniform("u_AmbientStrength", ambientPow); } } if (ImGui::CollapsingHeader("Light Level Lighting Settings")) { if (ImGui::DragFloat3("Light Pos", glm::value_ptr(lightPos), 0.01f, -10.0f, 10.0f)) { shader->SetUniform("u_LightPos", lightPos); } if (ImGui::ColorPicker3("Light Col", glm::value_ptr(lightCol))) { shader->SetUniform("u_LightCol", lightCol); } if (ImGui::SliderFloat("Light Ambient Power", &lightAmbientPow, 0.0f, 1.0f)) { shader->SetUniform("u_AmbientLightStrength", lightAmbientPow); } if (ImGui::SliderFloat("Light Specular Power", &lightSpecularPow, 0.0f, 1.0f)) { shader->SetUniform("u_SpecularLightStrength", lightSpecularPow); } if (ImGui::DragFloat("Light Linear Falloff", &lightLinearFalloff, 0.01f, 0.0f, 1.0f)) { shader->SetUniform("u_LightAttenuationLinear", lightLinearFalloff); } if (ImGui::DragFloat("Light Quadratic Falloff", &lightQuadraticFalloff, 0.01f, 0.0f, 1.0f)) { shader->SetUniform("u_LightAttenuationQuadratic", lightQuadraticFalloff); } } auto name = controllables[selectedVao].get<GameObjectTag>().Name; ImGui::Text(name.c_str()); auto behaviour = BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao]); ImGui::Checkbox("Relative Rotation", &behaviour->Relative); ImGui::Text("Q/E -> Yaw\nLeft/Right -> Roll\nUp/Down -> Pitch\nY -> Toggle Mode"); minFps = FLT_MAX; maxFps = 0; avgFps = 0; for (int ix = 0; ix < 128; ix++) { if (fpsBuffer[ix] < minFps) { minFps = fpsBuffer[ix]; } if (fpsBuffer[ix] > maxFps) { maxFps = fpsBuffer[ix]; } avgFps += fpsBuffer[ix]; } ImGui::PlotLines("FPS", fpsBuffer, 128); ImGui::Text("MIN: %f MAX: %f AVG: %f", minFps, maxFps, avgFps / 128.0f); }); #pragma endregion // GL states glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glDepthFunc(GL_LEQUAL); // New #pragma region TEXTURE LOADING // Load some textures from files Texture2D::sptr stone = Texture2D::LoadFromFile("images/Stone_001_Diffuse.png"); Texture2D::sptr stoneSpec = Texture2D::LoadFromFile("images/Stone_001_Specular.png"); Texture2D::sptr grass = Texture2D::LoadFromFile("images/grass.jpg"); Texture2D::sptr noSpec = Texture2D::LoadFromFile("images/grassSpec.png"); Texture2D::sptr box = Texture2D::LoadFromFile("images/box.bmp"); Texture2D::sptr boxSpec = Texture2D::LoadFromFile("images/box-reflections.bmp"); Texture2D::sptr simpleFlora = Texture2D::LoadFromFile("images/SimpleFlora.png"); Texture2D::sptr book = Texture2D::LoadFromFile("images/Book of Sun_Book_color.png"); //LUT3D testCube("cubes/BrightenedCorrection.cube"); // Load the cube map //TextureCubeMap::sptr environmentMap = TextureCubeMap::LoadFromImages("images/cubemaps/skybox/sample.jpg"); TextureCubeMap::sptr environmentMap = TextureCubeMap::LoadFromImages("images/cubemaps/skybox/ToonSky.jpg"); // Creating an empty texture Texture2DDescription desc = Texture2DDescription(); desc.Width = 1; desc.Height = 1; desc.Format = InternalFormat::RGB8; Texture2D::sptr texture2 = Texture2D::Create(desc); // Clear it with a white colour texture2->Clear(); #pragma endregion ///////////////////////////////////// Scene Generation ////////////////////////////////////////////////// #pragma region Scene Generation // We need to tell our scene system what extra component types we want to support GameScene::RegisterComponentType<RendererComponent>(); GameScene::RegisterComponentType<BehaviourBinding>(); GameScene::RegisterComponentType<Camera>(); // Create a scene, and set it to be the active scene in the application GameScene::sptr scene = GameScene::Create("test"); Application::Instance().ActiveScene = scene; // We can create a group ahead of time to make iterating on the group faster entt::basic_group<entt::entity, entt::exclude_t<>, entt::get_t<Transform>, RendererComponent> renderGroup = scene->Registry().group<RendererComponent>(entt::get_t<Transform>()); // Create a material and set some properties for it ShaderMaterial::sptr stoneMat = ShaderMaterial::Create(); stoneMat->Shader = shader; stoneMat->Set("s_Diffuse", stone); stoneMat->Set("s_Specular", stoneSpec); stoneMat->Set("u_Shininess", 2.0f); stoneMat->Set("u_TextureMix", 0.0f); ShaderMaterial::sptr grassMat = ShaderMaterial::Create(); grassMat->Shader = shader; grassMat->Set("s_Diffuse", grass); grassMat->Set("s_Specular", noSpec); grassMat->Set("u_Shininess", 2.0f); grassMat->Set("u_TextureMix", 0.0f); ShaderMaterial::sptr boxMat = ShaderMaterial::Create(); boxMat->Shader = shader; boxMat->Set("s_Diffuse", box); boxMat->Set("s_Specular", boxSpec); boxMat->Set("u_Shininess", 8.0f); boxMat->Set("u_TextureMix", 0.0f); ShaderMaterial::sptr simpleFloraMat = ShaderMaterial::Create(); simpleFloraMat->Shader = shader; simpleFloraMat->Set("s_Diffuse", simpleFlora); simpleFloraMat->Set("s_Specular", noSpec); simpleFloraMat->Set("u_Shininess", 8.0f); simpleFloraMat->Set("u_TextureMix", 0.0f); ShaderMaterial::sptr bookmat = ShaderMaterial::Create(); bookmat->Shader = shader; bookmat->Set("s_Diffuse", book); bookmat->Set("s_Specular", noSpec); bookmat->Set("u_Shininess", 8.0f); bookmat->Set("u_TextureMix", 0.0f); GameObject obj1 = scene->CreateEntity("Ground"); { VertexArrayObject::sptr vao = ObjLoader::LoadFromFile("models/plane.obj"); obj1.emplace<RendererComponent>().SetMesh(vao).SetMaterial(grassMat); } GameObject obj2 = scene->CreateEntity("monkey_quads"); { VertexArrayObject::sptr vao = ObjLoader::LoadFromFile("models/monkey_quads.obj"); obj2.emplace<RendererComponent>().SetMesh(vao).SetMaterial(stoneMat); obj2.get<Transform>().SetLocalPosition(0.0f, 0.0f, 2.0f); obj2.get<Transform>().SetLocalRotation(0.0f, 0.0f, -90.0f); BehaviourBinding::BindDisabled<SimpleMoveBehaviour>(obj2); } GameObject obj3 = scene->CreateEntity("Book"); { VertexArrayObject::sptr vao = ObjLoader::LoadFromFile("models/Book of Sun.obj"); obj3.get<Transform>().SetLocalPosition(0.0f, 0.0f, 5.0f); obj3.emplace<RendererComponent>().SetMesh(vao).SetMaterial(bookmat); } std::vector<glm::vec2> allAvoidAreasFrom = { glm::vec2(-4.0f, -4.0f) }; std::vector<glm::vec2> allAvoidAreasTo = { glm::vec2(4.0f, 4.0f) }; std::vector<glm::vec2> rockAvoidAreasFrom = { glm::vec2(-3.0f, -3.0f), glm::vec2(-19.0f, -19.0f), glm::vec2(5.0f, -19.0f), glm::vec2(-19.0f, 5.0f), glm::vec2(-19.0f, -19.0f) }; std::vector<glm::vec2> rockAvoidAreasTo = { glm::vec2(3.0f, 3.0f), glm::vec2(19.0f, -5.0f), glm::vec2(19.0f, 19.0f), glm::vec2(19.0f, 19.0f), glm::vec2(-5.0f, 19.0f) }; glm::vec2 spawnFromHere = glm::vec2(-19.0f, -19.0f); glm::vec2 spawnToHere = glm::vec2(19.0f, 19.0f); EnvironmentGenerator::AddObjectToGeneration("models/simplePine.obj", simpleFloraMat, 150, spawnFromHere, spawnToHere, allAvoidAreasFrom, allAvoidAreasTo); EnvironmentGenerator::AddObjectToGeneration("models/simpleTree.obj", simpleFloraMat, 150, spawnFromHere, spawnToHere, allAvoidAreasFrom, allAvoidAreasTo); EnvironmentGenerator::AddObjectToGeneration("models/simpleRock.obj", simpleFloraMat, 40, spawnFromHere, spawnToHere, rockAvoidAreasFrom, rockAvoidAreasTo); EnvironmentGenerator::GenerateEnvironment(); // Create an object to be our camera GameObject cameraObject = scene->CreateEntity("Camera"); { cameraObject.get<Transform>().SetLocalPosition(0, 3, 3).LookAt(glm::vec3(0, 0, 0)); // We'll make our camera a component of the camera object Camera& camera = cameraObject.emplace<Camera>();// Camera::Create(); camera.SetPosition(glm::vec3(0, 3, 3)); camera.SetUp(glm::vec3(0, 0, 1)); camera.LookAt(glm::vec3(0)); camera.SetFovDegrees(90.0f); // Set an initial FOV camera.SetOrthoHeight(3.0f); BehaviourBinding::Bind<CameraControlBehaviour>(cameraObject); } int width, height; glfwGetWindowSize(BackendHandler::window, &width, &height); GameObject framebufferObject = scene->CreateEntity("Basic Effect"); { basicEffect = &framebufferObject.emplace<PostEffect>(); basicEffect->Init(width, height); } GameObject noEffectObject = scene->CreateEntity("No Effect"); { noEffect = &noEffectObject.emplace<NoEffect>(); noEffect->Init(width, height); } effects.push_back(noEffect); GameObject finalEffectObject = scene->CreateEntity("Depth Of Field Effect"); { finalEffect = &finalEffectObject.emplace<Final>(); finalEffect->Init(width, height); } effects.push_back(finalEffect); #pragma endregion ////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////// SKYBOX /////////////////////////////////////////////// { // Load our shaders Shader::sptr skybox = std::make_shared<Shader>(); skybox->LoadShaderPartFromFile("shaders/skybox-shader.vert.glsl", GL_VERTEX_SHADER); skybox->LoadShaderPartFromFile("shaders/skybox-shader.frag.glsl", GL_FRAGMENT_SHADER); skybox->Link(); ShaderMaterial::sptr skyboxMat = ShaderMaterial::Create(); skyboxMat->Shader = skybox; skyboxMat->Set("s_Environment", environmentMap); skyboxMat->Set("u_EnvironmentRotation", glm::mat3(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1, 0, 0)))); skyboxMat->RenderLayer = 100; MeshBuilder<VertexPosNormTexCol> mesh; MeshFactory::AddIcoSphere(mesh, glm::vec3(0.0f), 1.0f); MeshFactory::InvertFaces(mesh); VertexArrayObject::sptr meshVao = mesh.Bake(); GameObject skyboxObj = scene->CreateEntity("skybox"); skyboxObj.get<Transform>().SetLocalPosition(0.0f, 0.0f, 0.0f); skyboxObj.get_or_emplace<RendererComponent>().SetMesh(meshVao).SetMaterial(skyboxMat); } //////////////////////////////////////////////////////////////////////////////////////// // We'll use a vector to store all our key press events for now (this should probably be a behaviour eventually) std::vector<KeyPressWatcher> keyToggles; { // This is an example of a key press handling helper. Look at InputHelpers.h an .cpp to see // how this is implemented. Note that the ampersand here is capturing the variables within // the scope. If you wanted to do some method on the class, your best bet would be to give it a method and // use std::bind keyToggles.emplace_back(GLFW_KEY_T, [&]() { cameraObject.get<Camera>().ToggleOrtho(); }); controllables.push_back(obj2); keyToggles.emplace_back(GLFW_KEY_KP_ADD, [&]() { BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao])->Enabled = false; selectedVao++; if (selectedVao >= controllables.size()) selectedVao = 0; BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao])->Enabled = true; }); keyToggles.emplace_back(GLFW_KEY_KP_SUBTRACT, [&]() { BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao])->Enabled = false; selectedVao--; if (selectedVao < 0) selectedVao = controllables.size() - 1; BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao])->Enabled = true; }); keyToggles.emplace_back(GLFW_KEY_Y, [&]() { auto behaviour = BehaviourBinding::Get<SimpleMoveBehaviour>(controllables[selectedVao]); behaviour->Relative = !behaviour->Relative; }); } // Initialize our timing instance and grab a reference for our use Timing& time = Timing::Instance(); time.LastFrame = glfwGetTime(); ///// Game loop ///// while (!glfwWindowShouldClose(BackendHandler::window)) { glfwPollEvents(); // Update the timing time.CurrentFrame = glfwGetTime(); time.DeltaTime = static_cast<float>(time.CurrentFrame - time.LastFrame); time.DeltaTime = time.DeltaTime > 1.0f ? 1.0f : time.DeltaTime; // Update our FPS tracker data fpsBuffer[frameIx] = 1.0f / time.DeltaTime; frameIx++; if (frameIx >= 128) frameIx = 0; // We'll make sure our UI isn't focused before we start handling input for our game if (!ImGui::IsAnyWindowFocused()) { // We need to poll our key watchers so they can do their logic with the GLFW state // Note that since we want to make sure we don't copy our key handlers, we need a const // reference! for (const KeyPressWatcher& watcher : keyToggles) { watcher.Poll(BackendHandler::window); } } // Iterate over all the behaviour binding components scene->Registry().view<BehaviourBinding>().each([&](entt::entity entity, BehaviourBinding& binding) { // Iterate over all the behaviour scripts attached to the entity, and update them in sequence (if enabled) for (const auto& behaviour : binding.Behaviours) { if (behaviour->Enabled) { behaviour->Update(entt::handle(scene->Registry(), entity)); } } }); // Clear the screen basicEffect->Clear(); //greyscaleEffect->Clear(); //sepiaEffect->Clear(); for (int i = 0; i < effects.size(); i++) { effects[i]->Clear(); } glClearColor(0.08f, 0.17f, 0.31f, 1.0f); glEnable(GL_DEPTH_TEST); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update all world matrices for this frame scene->Registry().view<Transform>().each([](entt::entity entity, Transform& t) { t.UpdateWorldMatrix(); }); // Grab out camera info from the camera object Transform& camTransform = cameraObject.get<Transform>(); glm::mat4 view = glm::inverse(camTransform.LocalTransform()); glm::mat4 projection = cameraObject.get<Camera>().GetProjection(); glm::mat4 viewProjection = projection * view; float camerapos = cameraObject.get<Camera>().GetPosition().z; // Sort the renderers by shader and material, we will go for a minimizing context switches approach here, // but you could for instance sort front to back to optimize for fill rate if you have intensive fragment shaders renderGroup.sort<RendererComponent>([](const RendererComponent& l, const RendererComponent& r) { // Sort by render layer first, higher numbers get drawn last if (l.Material->RenderLayer < r.Material->RenderLayer) return true; if (l.Material->RenderLayer > r.Material->RenderLayer) return false; // Sort by shader pointer next (so materials using the same shader run sequentially where possible) if (l.Material->Shader < r.Material->Shader) return true; if (l.Material->Shader > r.Material->Shader) return false; // Sort by material pointer last (so we can minimize switching between materials) if (l.Material < r.Material) return true; if (l.Material > r.Material) return false; return false; }); // Start by assuming no shader or material is applied Shader::sptr current = nullptr; ShaderMaterial::sptr currentMat = nullptr; basicEffect->BindBuffer(0); // Iterate over the render group components and draw them renderGroup.each( [&](entt::entity e, RendererComponent& renderer, Transform& transform) { // If the shader has changed, set up it's uniforms if (current != renderer.Material->Shader) { current = renderer.Material->Shader; current->Bind(); BackendHandler::SetupShaderForFrame(current, view, projection); } //// If the material has changed, apply it if (currentMat != renderer.Material) { currentMat = renderer.Material; currentMat->Apply(); } // Render the mesh BackendHandler::RenderVAO(renderer.Material->Shader, renderer.Mesh, viewProjection, transform); }); basicEffect->UnbindBuffer(); effects[activeEffect]->ApplyEffect(basicEffect); effects[activeEffect]->DrawToScreen(); // Draw our ImGui content BackendHandler::RenderImGui(); scene->Poll(); glfwSwapBuffers(BackendHandler::window); time.LastFrame = time.CurrentFrame; } // Nullify scene so that we can release references Application::Instance().ActiveScene = nullptr; //Clean up the environment generator so we can release references EnvironmentGenerator::CleanUpPointers(); BackendHandler::ShutdownImGui(); } // Clean up the toolkit logger so we don't leak memory Logger::Uninitialize(); return 0; }
[ "taylor.horsman@ontariotechu.net" ]
taylor.horsman@ontariotechu.net
0c439216280d3038a41f0affb8e66dac68508cd4
39dd8539a44d9ae1b333697aa8cfd92db1387b8f
/jetpack/src/main.cpp
a478ec7fc4a0076738aa5384ec3b61339d316e11
[]
no_license
arnavkapoor/OpenGL_Jetpack
ae54acb650b24005a37f44dad74c7223d0313ace
922cfda944728b75f977935e4e7e6d4fb6c6541d
refs/heads/master
2020-04-16T23:53:34.084711
2019-01-26T12:26:03
2019-01-26T12:26:03
166,029,538
0
0
null
null
null
null
UTF-8
C++
false
false
20,159
cpp
#include "main.h" #include "timer.h" #include "player.h" #define debug(x) cerr << #x << " is " << x << endl; using namespace std; GLMatrices Matrices; GLuint programID; GLFWwindow *window; /************************** * Customizable functions * **************************/ Ball ball1; Floor base; Magnets magnet; vector<Coins> mycoins; vector<Beams> mybeams; vector<Balloons> myballoons; vector<Balloons> dragonball; vector<Boomerang> myboomerangs; vector<pair<Beams, Beams> > mypairbeams; vector<Score> mydigs; vector<Bonus> mybonus; vector<Semicircle> mysemi; Dragon smaug; float screen_zoom = 1, screen_center_x = 0, screen_center_y = 0; float camera_rotation_angle = 0; int f = 0; Timer t60(1.0 / 60); Timer t15(1.0 / 15); Timer t1(1.0 / 4); Timer tdragon(1.0 / 2); Timer magapp(30.0 / 1); Timer magdisapp(4.96 / 1); int score = 0; int lives = 10; bool magpres = 0; int inside = 0; int level = 1; /* Render the scene with openGL */ /* Edit this function according to your assignment */ void draw() { char buffer[50]; sprintf(buffer, "lives: %d", lives); if (smaug.lives < 0) sprintf(buffer, "YOU HAVE WON !!!!!!!!!!!"); glfwSetWindowTitle(window, buffer); if (lives == 0) quit(window); // clear the color and depth in the frame buffer reset_screen(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // use the loaded shader program // Don't change unless you know what you are doing glUseProgram(programID); // Eye - Location of camera. Don't change unless you are sure!! glm::vec3 eye(0, 1.5 * 150, 25); // Target - Where is the camera looking at. Don't change unless you are sure!! glm::vec3 target(0, 1.5 * 150, 0); // Up - Up vector defines tilt of camera. Don't change unless you are sure!! glm::vec3 up(0, 1, 0); // Compute Camera matrix (view) Matrices.view = glm::lookAt(eye, target, up); // Rotating Camera for 3D // Don't change unless you are sure!! // Matrices.view = glm::lookAt(glm::vec3(0, 0, 3), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); // Fixed camera for 2D (ortho) in XY plane // Compute ViewProject matrix as view/camera might not be changed for this frame (basic scenario) // Don't change unless you are sure!! glm::mat4 VP = Matrices.projection * Matrices.view; // Send our transformation to the currently bound shader, in the "MVP" uniform // For each model you render, since the MVP will be different (at least the M part) // Don't change unless you are sure!! glm::mat4 MVP; // MVP = Projection * View * Model for (int i = 0; i < mysemi.size(); i++) mysemi[i].draw(VP); if (level == 2 and smaug.lives >= 0) smaug.draw(VP); // Scene render ball1.draw(VP); base.draw(VP); magnet.draw(VP); for (int i = 0; i < mycoins.size(); i++) mycoins[i].draw(VP); for (int i = 0; i < mybeams.size(); i++) mybeams[i].draw(VP); for (int i = 0; i < myballoons.size(); i++) myballoons[i].draw(VP); for (int i = 0; i < dragonball.size(); i++) dragonball[i].draw(VP); for (int i = 0; i < myboomerangs.size(); i++) myboomerangs[i].draw(VP); for (int i = 0; i < mybonus.size(); i++) mybonus[i].draw(VP); for (int i = 0; i < myboomerangs.size(); i++) { mypairbeams[i].first.draw(VP); mypairbeams[i].second.draw(VP); } for (int i = 0; i < mydigs.size(); i++) mydigs[i].draw(VP); } void tick_input(GLFWwindow *window) { if (!inside) { int left = glfwGetKey(window, GLFW_KEY_LEFT); int right = glfwGetKey(window, GLFW_KEY_RIGHT); int up = glfwGetKey(window, GLFW_KEY_UP); int water = glfwGetKey(window, GLFW_KEY_SPACE); if (left) { ball1.tick(DIR_LEFT); } if (right) { ball1.tick(DIR_RIGHT); } if (up) { ball1.tick(DIR_UP); } if (!(up or left or right)) { ball1.tick(DIR_DOWN); } if (water and t1.processTick()) { Balloons balloons1 = Balloons(ball1.position.x + 50.0f, ball1.position.y + 50.0f, ball1.speedx, ball1.speedy, 20.0f, COLOR_BLUE); myballoons.push_back(balloons1); } } } void render_score(int hundreds, int tens, int ones) { mydigs.clear(); vector<int> vals; vals.push_back(hundreds); vals.push_back(tens); vals.push_back(ones); vector<int> valid[10]; int arr1[] = {0, 1, 2, 3, 4, 7, 8, 9}; int arr2[] = {0, 2, 3, 5, 6, 7, 8, 9}; int arr3[] = {0, 4, 5, 6, 8, 9}; int arr4[] = {0, 2, 6, 8}; int arr5[] = {0, 2, 3, 5, 6, 8, 9}; int arr6[] = {0, 1, 3, 4, 5, 6, 7, 8, 9}; int arr7[] = {2, 3, 4, 5, 6, 8, 9}; valid[1].insert(valid[1].end(), arr1, arr1 + (sizeof(arr1) / sizeof(arr1[0]))); valid[2].insert(valid[2].end(), arr2, arr2 + (sizeof(arr2) / sizeof(arr2[0]))); valid[3].insert(valid[3].end(), arr3, arr3 + (sizeof(arr3) / sizeof(arr3[0]))); valid[4].insert(valid[4].end(), arr4, arr4 + (sizeof(arr4) / sizeof(arr4[0]))); valid[5].insert(valid[5].end(), arr5, arr5 + (sizeof(arr5) / sizeof(arr5[0]))); valid[6].insert(valid[6].end(), arr6, arr6 + (sizeof(arr6) / sizeof(arr6[0]))); valid[7].insert(valid[7].end(), arr7, arr7 + (sizeof(arr7) / sizeof(arr7[0]))); for (int i = 0; i < vals.size(); i++) { int xoffset = 50 * i; int yoffset = -150; int myvalue = vals[i]; for (int j = 1; j <= 7; j++) { for (int k = 0; k < valid[j].size(); k++) { if (valid[j][k] == myvalue and j == 1) mydigs.push_back(Score(xoffset + 10, yoffset + 10, 90)); if (valid[j][k] == myvalue and j == 2) mydigs.push_back(Score(xoffset, yoffset + 20, 0)); if (valid[j][k] == myvalue and j == 3) mydigs.push_back(Score(xoffset - 10, yoffset + 10, 90)); if (valid[j][k] == myvalue and j == 4) mydigs.push_back(Score(xoffset - 10, yoffset - 10, 90)); if (valid[j][k] == myvalue and j == 5) mydigs.push_back(Score(xoffset, yoffset - 20, 0)); if (valid[j][k] == myvalue and j == 6) mydigs.push_back(Score(xoffset + 10, yoffset - 10, 90)); if (valid[j][k] == myvalue and j == 7) mydigs.push_back(Score(xoffset, yoffset, 0)); } } } } void tick_elements() { if (level == 2 and tdragon.processTick() and smaug.lives >= 0) { float srcx = smaug.position.x - 45; float srcy = smaug.position.y - 45; float tarx = ball1.position.x; float tary = ball1.position.y; Balloons enemy1 = Balloons(srcx, srcy, -12 + (tarx - srcx) * 0.05, -20 + (tary + 100 - srcy) * (0.05), 10, COLOR_BLOOD); dragonball.push_back(enemy1); } if (score < 0) score = 0; if (score > 20 and level == 1) { mybeams.clear(); myballoons.clear(); mybonus.clear(); myboomerangs.clear(); mypairbeams.clear(); mysemi.clear(); mycoins.clear(); level = 2; smaug.position.x = 500; smaug.position.y = 500; smaug.box.x = 500; smaug.box.y = 500; } int hundreds = (score / 100) % 10; int tens = (score / 10) % 10; int ones = (score / 1) % 10; render_score(hundreds, tens, ones); if (magapp.processTick() and level == 1) { magpres = 1; magnet.position.x = -350 + rand() % 700; magnet.position.y = 0 + rand() % 700; } if (magdisapp.processTick()) { magpres = 0; magnet.position.x = 900; magnet.position.y = 900; } if (magpres) { if (magnet.position.x - ball1.position.x > 0) ball1.position.x += 5; if (magnet.position.x - ball1.position.x < 0) ball1.position.x -= 5; if (magnet.position.y - ball1.position.y > 0) { ball1.speedy += 0.3; ball1.position.y += 5; } if (magnet.position.y - ball1.position.y < 0) { ball1.speedy -= 0.1; ball1.position.y -= 5; } } for (int i = 0; i < mycoins.size(); i++) mycoins[i].tick(); for (int i = 0; i < mybeams.size(); i++) mybeams[i].tick(SINGLE); for (int i = 0; i < myballoons.size(); i++) myballoons[i].tick(); for (int i = 0; i < dragonball.size(); i++) dragonball[i].tick(); for (int i = 0; i < myboomerangs.size(); i++) myboomerangs[i].tick(); for (int i = 0; i < mybonus.size(); i++) mybonus[i].tick(); for (int i = 0; i < mysemi.size(); i++) mysemi[i].tick(); for (int i = 0; i < mypairbeams.size(); i++) { mypairbeams[i].first.tick(DOUBLE_TOP); mypairbeams[i].second.tick(DOUBLE_BOTTOM); } bounding_box_t boxplayer = ball1.box; if (level == 2) { bounding_box_t boxdragon = smaug.box; for (int i = 0; i < myballoons.size(); i++) { bounding_box_t boxballoon = myballoons[i].box; if (detect_collision(boxdragon, boxballoon)) { smaug.lives--; myballoons.erase(myballoons.begin() + i); } } } inside = 0; for (int i = 0; i < mysemi.size(); i++) { bounding_box_t boxsemi = mysemi[i].box; if (detect_collision(boxplayer, boxsemi)) { ball1.speedy = 0; ball1.speedx = 0; float x = ball1.position.x; float h = boxsemi.x; float r = mysemi[i].radius; float k = boxsemi.y - (r / 2); float y = (pow(double(r * r - (x - h) * (x - h)), 0.500)) + k; if (isnan(y)) y = ball1.position.y; debug(y); ball1.position.y = y; inside = 1; } } for (int i = 0; i < mycoins.size(); i++) { bounding_box_t boxcoin = mycoins[i].box; if (detect_collision(boxplayer, boxcoin)) { score += mycoins[i].score; debug(score); mycoins.erase(mycoins.begin() + i); } } for (int i = 0; i < mybeams.size(); i++) { bounding_box_t boxbeam = mybeams[i].box; if (detect_collision(boxplayer, boxbeam)) { if (!inside) { score -= 1; lives -= 1; } mybeams.erase(mybeams.begin() + i); } } for (int i = 0; i < dragonball.size(); i++) { bounding_box_t boxbeam = dragonball[i].box; if (detect_collision(boxplayer, boxbeam)) { lives -= 1; dragonball.erase(dragonball.begin() + i); } } for (int i = 0; i < mypairbeams.size(); i++) { bounding_box_t boxbeam1 = mypairbeams[i].first.box; bounding_box_t boxbeam2 = mypairbeams[i].second.box; if (detect_collision(boxplayer, boxbeam1) or detect_collision(boxplayer, boxbeam2)) { if (!inside) { score -= 2; lives -= 1; } mypairbeams.erase(mypairbeams.begin() + i); } } for (int i = 0; i < myboomerangs.size(); i++) { bounding_box_t boxboomerang = myboomerangs[i].box; if (detect_collision(boxplayer, boxboomerang)) { if (!inside) { score -= 1; lives -= 1; } myboomerangs.erase(myboomerangs.begin() + i); } if (myboomerangs[i].position.y < 0) myboomerangs.erase(myboomerangs.begin() + i); } for (int i = 0; i < mybonus.size(); i++) { bounding_box_t boxboomerang = mybonus[i].box; if (detect_collision(boxplayer, boxboomerang)) { score += mybonus[i].score; lives += mybonus[i].score; mybonus.erase(mybonus.begin() + i); } if (mybonus[i].position.y < 0) mybonus.erase(mybonus.begin() + i); } for (int i = 0; i < mybeams.size(); i++) { for (int j = 0; j < myballoons.size(); j++) { bounding_box_t boxbeam = mybeams[i].box; bounding_box_t boxballoon = myballoons[j].box; if (detect_collision(boxballoon, boxbeam)) { score += 1; mybeams.erase(mybeams.begin() + i); myballoons.erase(myballoons.begin() + j); } if (myballoons[j].position.y <= -45.0f) myballoons.erase(myballoons.begin() + j); } } for (int i = 0; i < dragonball.size(); i++) { for (int j = 0; j < myballoons.size(); j++) { bounding_box_t boxdragon = dragonball[i].box; bounding_box_t boxballoon = myballoons[j].box; if (detect_collision(boxdragon, boxballoon)) { dragonball.erase(dragonball.begin() + i); myballoons.erase(myballoons.begin() + j); } if (myballoons[j].position.y <= -45.0f) myballoons.erase(myballoons.begin() + j); } if (dragonball[i].position.y <= -45.0f) dragonball.erase(dragonball.begin() + i); } } /* Initialize the OpenGL rendering properties */ /* Add all the models to be created here */ void initGL(GLFWwindow *window, int width, int height) { /* Objects should be created before any other gl function and shaders */ // Create the models smaug = Dragon(5700, 400, COLOR_GOLD); for (int i = 0; i < 1000; i += 2) { Coins coin1; if (rand() % 3 >= 1) coin1 = Coins(500 * i + rand() % 25, rand() % 600 + 100, 30, COLOR_NEONGREEN, 1); else coin1 = Coins(500 * i + rand() % 25, rand() % 600 + 100, 30, COLOR_SILVER, 2); mycoins.push_back(coin1); } for (int i = 0; i < 1000; i += 2) { Beams beam1; beam1 = Beams(500 * i + rand() % 25, rand() % 600 + 200, rand() % 180, COLOR_BEAM); mybeams.push_back(beam1); } for (int i = 2; i < 1000; i += 4) { Beams beam1; Beams beam2; beam1 = Beams(400 * i, 400, 90, COLOR_RED, 1); beam2 = Beams(400 * i, 200, 90, COLOR_RED, 1); mypairbeams.push_back(make_pair(beam1, beam2)); } for (int i = 2; i < 1000; i += 8) { Boomerang boom1; boom1 = Boomerang(500 * i + rand() % 25, 700, COLOR_BLACK); myboomerangs.push_back(boom1); } for (int i = 4; i <= 100; i += 15) { Semicircle semi1 = Semicircle(500 * i + rand() % 25, 300 + rand() % 200, 150, COLOR_BLACK); mysemi.push_back(semi1); } for (int i = 3; i < 1000; i += 4) { if (rand() % 2) { Bonus bonus1 = Bonus(500 * i + rand() % 25, 250, 20, 1, COLOR_BLACK); mybonus.push_back(bonus1); } else { Bonus bonus1 = Bonus(500 * i + rand() % 25, 200, 30, 2, COLOR_GOLD); mybonus.push_back(bonus1); } } magnet = Magnets(5000, 5000, 30, COLOR_DARKBLUE); ball1 = Ball(0, 0, COLOR_RED); base = Floor(COLOR_GREEN); // Create and compile our GLSL program from the shaders programID = LoadShaders("Sample_GL.vert", "Sample_GL.frag"); // Get a handle for our "MVP" uniform Matrices.MatrixID = glGetUniformLocation(programID, "MVP"); reshapeWindow(window, width, height); // Background color of the scene glClearColor(COLOR_BACKGROUND.r / 256.0, COLOR_BACKGROUND.g / 256.0, COLOR_BACKGROUND.b / 256.0, 0.0f); // R, G, B, A glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); cout << "VENDOR: " << glGetString(GL_VENDOR) << endl; cout << "RENDERER: " << glGetString(GL_RENDERER) << endl; cout << "VERSION: " << glGetString(GL_VERSION) << endl; cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl; } int main(int argc, char **argv) { srand(time(0)); int width = 600; int height = 600; window = initGLFW(width, height); initGL(window, width, height); /* Draw in loop */ while (!glfwWindowShouldClose(window)) { // Process timers if (t60.processTick()) { // 60 fps // OpenGL Draw commands draw(); // Swap Frame Buffer in double buffering glfwSwapBuffers(window); tick_elements(); tick_input(window); } // Poll for Keyboard and mouse events glfwPollEvents(); } quit(window); } pair<float, float> myrotate(float angle, float x, float y, float origx, float origy) { pair<float, float> rotated_point; rotated_point.first = (x - origx) * cos(angle) - (y - origy) * sin(angle) + origx; rotated_point.second = (x - origx) * sin(angle) + (y - origy) * cos(angle) + origy; return rotated_point; } bool line_eq(pair<float, float> line1, pair<float, float> line2, pair<float, float> pnt) { float y = pnt.second; float y1 = line1.second; float y2 = line2.second; float x = pnt.first; float x1 = line1.first; float x2 = line2.first; float myvar = ((y - y1) * (x2 - x1)) - ((y2 - y1) * (x - x1)); return (myvar >= 0) ? true : false; } bool lines_collision(pair<float, float> line1, pair<float, float> line2, pair<float, float> same1, pair<float, float> same2, pair<float, float> diff1, pair<float, float> diff2, pair<float, float> diff3, pair<float, float> diff4) { bool s1 = line_eq(line1, line2, same1); bool s2 = line_eq(line1, line2, same2); bool d1 = line_eq(line1, line2, diff1); bool d2 = line_eq(line1, line2, diff2); bool d3 = line_eq(line1, line2, diff3); bool d4 = line_eq(line1, line2, diff4); if (s1 == s2 and d1 == d2 and d2 == d3 and d3 == d4 and s1 != d1) return true; else return false; } bool detect_collision(bounding_box_t a, bounding_box_t b) { pair<float, float> ap1, ap2, ap3, ap4, bp1, bp2, bp3, bp4; ap1 = myrotate(a.angle, a.x + (a.width / 2), a.y + (a.height / 2), a.x, a.y); ap2 = myrotate(a.angle, a.x + (a.width / 2), a.y - (a.height / 2), a.x, a.y); ap3 = myrotate(a.angle, a.x - (a.width / 2), a.y - (a.height / 2), a.x, a.y); ap4 = myrotate(a.angle, a.x - (a.width / 2), a.y + (a.height / 2), a.x, a.y); bp1 = myrotate(b.angle, b.x + (b.width / 2), b.y + (b.height / 2), b.x, b.y); bp2 = myrotate(b.angle, b.x + (b.width / 2), b.y - (b.height / 2), b.x, b.y); bp3 = myrotate(b.angle, b.x - (b.width / 2), b.y - (b.height / 2), b.x, b.y); bp4 = myrotate(b.angle, b.x - (b.width / 2), b.y + (b.height / 2), b.x, b.y); if (lines_collision(ap1, ap2, ap3, ap4, bp1, bp2, bp3, bp4)) return false; if (lines_collision(ap2, ap3, ap4, ap1, bp1, bp2, bp3, bp4)) return false; if (lines_collision(ap3, ap4, ap1, ap2, bp1, bp2, bp3, bp4)) return false; if (lines_collision(ap4, ap1, ap2, ap3, bp1, bp2, bp3, bp4)) return false; if (lines_collision(bp1, bp2, bp3, bp4, ap1, ap2, ap3, ap4)) return false; if (lines_collision(bp2, bp3, bp4, bp1, ap1, ap2, ap3, ap4)) return false; if (lines_collision(bp3, bp4, bp1, bp2, ap1, ap2, ap3, ap4)) return false; if (lines_collision(bp4, bp1, bp2, bp3, ap1, ap2, ap3, ap4)) return false; return true; } void reset_screen() { float top = screen_center_y + 600 / screen_zoom; float bottom = screen_center_y - 600 / screen_zoom; float left = screen_center_x - 600 / screen_zoom; float right = screen_center_x + 600 / screen_zoom; Matrices.projection = glm::ortho(left, right, bottom, top, 0.1f, 500.0f); }
[ "arnavk805@gitlab.com" ]
arnavk805@gitlab.com
9e67ab671fa37a550ee240685d8039944fffae56
17e8b775ec28c774857919b8df957145adf2e606
/spoj/hotels.cpp
ecd9252774670c0509e17b491738fbb4f7399485
[]
no_license
chamow97/Competitive-Coding
30b5acc77d51207c55eca91b8da161d80a3fbfab
8f2d8a1ca6881dbde9c75735240d4e4f681e0138
refs/heads/master
2021-04-28T21:40:05.294842
2019-09-15T13:25:59
2019-09-15T13:25:59
77,766,905
5
0
null
null
null
null
UTF-8
C++
false
false
1,614
cpp
//template by chamow #include<bits/stdc++.h> /*-------------------------------------------------------- */ using namespace std; /*-------------------------------------------------------- */ #define rep(i,val,n) for(ll i=val;i<n;i++) #define per(j,val,n) for(ll j=val;j>=n;j--) #define pb push_back #define pi 3.14157 #define mp make_pair #define MODULO 1000000007 #define INF 1000000000000000 /*-------------------------------------------------------- */ typedef long long ll; typedef vector<bool> boolean; typedef vector<ll> vec; /*-------------------------------------------------------- */ ll gcd(ll a, ll b) { if(b == 0) { return a; } return gcd(b, a%b); } ll lcm(ll a, ll b) { return ((a*b)/gcd(a,b)); } long long int read_int(){ char r; bool start=false,neg=false; long long int ret=0; while(true){ r=getchar(); if((r-'0'<0 || r-'0'>9) && r!='-' && !start){ continue; } if((r-'0'<0 || r-'0'>9) && r!='-' && start){ break; } if(start)ret*=10; start=true; if(r=='-')neg=true; else ret+=r-'0'; } if(!neg) return ret; else return -ret; } /*-------------------------------------------------------- */ int main() { ll n, m; n = read_int(); m = read_int(); vec arr(n,0); rep(i,0,n) { arr[i] = read_int(); } vec prefix(n, 0); prefix[0] = arr[0]; rep(i,1,n) { prefix[i] = prefix[i-1] + arr[i]; } ll i = 0, j = 0; ll maximum = 0; while(i <= j && j <= n-1) { ll val = prefix[j] - prefix[i] + arr[i]; if(val <= m) { maximum = max(maximum, val); j++; } else { i++; } // cout<<"ads"; } printf("%lld", maximum); return 0; }
[ "chamowstudios@outlook.com" ]
chamowstudios@outlook.com
e0eab323b90828fc7984861bc05f5cc2c402fa86
5791b78c64fc4076330af128b950e5cc544e333b
/windows/pw6e.official/CPlusPlus/Chapter02/HelloVectorGraphicsPath/HelloVectorGraphicsPath/MainPage.xaml.cpp
36e7c850068f37e7393ba6119d69588e10304943
[ "MIT" ]
permissive
nnaabbcc/exercise
509e2c63389fec768ca07153844b71b864d63a20
b7ebb55adf9a75ed223555128d77e0f2548450b5
refs/heads/master
2023-02-26T07:52:40.093958
2023-02-22T01:12:56
2023-02-22T01:12:56
55,337,514
1
1
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" using namespace HelloVectorGraphicsPath; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 MainPage::MainPage() { InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void MainPage::OnNavigatedTo(NavigationEventArgs^ e) { (void) e; // Unused parameter }
[ "nnaabbcc.zhao@gmail.com" ]
nnaabbcc.zhao@gmail.com
37c1e572c9ad70869c1b1759da75dcfad92c32d9
87f3fe3687cd59328f45c6b9c25102a27cf64778
/Swapping_1.cpp
fc14390c31fae9ee920bb04ff3cf1e3d196cbdab
[]
no_license
HemantSrivastava01/Cpp-Programs
c36d5828c4d76889e18320079149f5ab1a11fd51
8d1c52a6665fb3bbe741a8d856d5e4cd84d30643
refs/heads/main
2023-03-05T22:22:07.587362
2021-02-24T14:30:00
2021-02-24T14:30:00
341,922,171
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
//program for swapping values between two variables without //using 3rd variable #include<iostream> using namespace std; main(){ int a,b; cout<<"enter value of a : "; cin>>a; cout<<"enter value of b : "; cin>>b; cout<<"values of a & b before swapping is : "<<a<<","<<b<<endl; a=a+b; b=a-b; a=a-b; cout<<"values of a & b after swapping is : "<<a<<","<<b<<endl; }
[ "noreply@github.com" ]
HemantSrivastava01.noreply@github.com
7671c56c31a70a5065562691623c63671c6ca860
04b1803adb6653ecb7cb827c4f4aa616afacf629
/media/audio/android/audio_track_output_stream.cc
1012622b8884b1e1f7252e3a18b8268131fb79e1
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
6,163
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/audio/android/audio_track_output_stream.h" #include <cmath> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/time/default_tick_clock.h" #include "jni/AudioTrackOutputStream_jni.h" #include "media/audio/audio_manager_base.h" #include "media/base/audio_sample_types.h" #include "media/base/audio_timestamp_helper.h" using base::android::AttachCurrentThread; using base::android::ScopedJavaLocalRef; namespace media { // Android audio format. For more information, please see: // https://developer.android.com/reference/android/media/AudioFormat.html enum { kEncodingPcm16bit = 2, // ENCODING_PCM_16BIT kEncodingAc3 = 5, // ENCODING_AC3 kEncodingEac3 = 6, // ENCODING_E_AC3 }; AudioTrackOutputStream::AudioTrackOutputStream(AudioManagerBase* manager, const AudioParameters& params) : params_(params), audio_manager_(manager), tick_clock_(base::DefaultTickClock::GetInstance()) { if (!params_.IsBitstreamFormat()) { audio_bus_ = AudioBus::Create(params_); } } AudioTrackOutputStream::~AudioTrackOutputStream() { DCHECK(!callback_); } bool AudioTrackOutputStream::Open() { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); JNIEnv* env = AttachCurrentThread(); j_audio_output_stream_.Reset(Java_AudioTrackOutputStream_create(env)); int format = kEncodingPcm16bit; if (params_.IsBitstreamFormat()) { if (params_.format() == AudioParameters::AUDIO_BITSTREAM_AC3) { format = kEncodingAc3; } else if (params_.format() == AudioParameters::AUDIO_BITSTREAM_EAC3) { format = kEncodingEac3; } else { NOTREACHED(); } } return Java_AudioTrackOutputStream_open(env, j_audio_output_stream_, params_.channels(), params_.sample_rate(), format); } void AudioTrackOutputStream::Start(AudioSourceCallback* callback) { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); callback_ = callback; Java_AudioTrackOutputStream_start(AttachCurrentThread(), j_audio_output_stream_, reinterpret_cast<intptr_t>(this)); } void AudioTrackOutputStream::Stop() { DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); Java_AudioTrackOutputStream_stop(AttachCurrentThread(), j_audio_output_stream_); callback_ = nullptr; } void AudioTrackOutputStream::Close() { DCHECK(!callback_); DCHECK(audio_manager_->GetTaskRunner()->BelongsToCurrentThread()); Java_AudioTrackOutputStream_close(AttachCurrentThread(), j_audio_output_stream_); audio_manager_->ReleaseOutputStream(this); } // This stream is always used with sub second buffer sizes, where it's // sufficient to simply always flush upon Start(). void AudioTrackOutputStream::Flush() {} void AudioTrackOutputStream::SetMute(bool muted) { if (params_.IsBitstreamFormat() && muted) { LOG(WARNING) << "Mute is not supported for compressed audio bitstream formats."; return; } if (muted_ == muted) return; muted_ = muted; Java_AudioTrackOutputStream_setVolume( AttachCurrentThread(), j_audio_output_stream_, muted_ ? 0.0 : volume_); } void AudioTrackOutputStream::SetVolume(double volume) { if (params_.IsBitstreamFormat()) { LOG(WARNING) << "Volume change is not supported for compressed audio " "bitstream formats."; return; } // Track |volume_| since AudioTrack uses a scaled value. volume_ = volume; if (muted_) return; Java_AudioTrackOutputStream_setVolume(AttachCurrentThread(), j_audio_output_stream_, volume); } void AudioTrackOutputStream::GetVolume(double* volume) { *volume = volume_; } // AudioOutputStream::SourceCallback implementation methods called from Java. ScopedJavaLocalRef<jobject> AudioTrackOutputStream::OnMoreData( JNIEnv* env, jobject obj, jobject audio_data, jlong delay_in_frame) { DCHECK(callback_); base::TimeDelta delay = AudioTimestampHelper::FramesToTime(delay_in_frame, params_.sample_rate()); void* native_buffer = env->GetDirectBufferAddress(audio_data); if (params_.IsBitstreamFormat()) { // For bitstream formats, use the direct buffer memory to avoid additional // memory copy. std::unique_ptr<AudioBus> audio_bus( AudioBus::WrapMemory(params_, native_buffer)); audio_bus->set_is_bitstream_format(true); callback_->OnMoreData(delay, tick_clock_->NowTicks(), 0, audio_bus.get()); if (audio_bus->GetBitstreamDataSize() <= 0) return nullptr; return Java_AudioTrackOutputStream_createAudioBufferInfo( env, j_audio_output_stream_, audio_bus->GetBitstreamFrames(), audio_bus->GetBitstreamDataSize()); } // For PCM format, we need extra memory to convert planar float32 into // interleaved int16. callback_->OnMoreData(delay, tick_clock_->NowTicks(), 0, audio_bus_.get()); int16_t* native_bus = reinterpret_cast<int16_t*>(native_buffer); audio_bus_->ToInterleaved<SignedInt16SampleTypeTraits>(audio_bus_->frames(), native_bus); return Java_AudioTrackOutputStream_createAudioBufferInfo( env, j_audio_output_stream_, audio_bus_->frames(), sizeof(*native_bus) * audio_bus_->channels() * audio_bus_->frames()); } void AudioTrackOutputStream::OnError(JNIEnv* env, jobject obj) { DCHECK(callback_); callback_->OnError(); } jlong AudioTrackOutputStream::GetAddress(JNIEnv* env, jobject obj, jobject byte_buffer) { return reinterpret_cast<jlong>(env->GetDirectBufferAddress(byte_buffer)); } } // namespace media
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
68b16f438f36229838b691b4d627fa221036267c
1dd9cd30ae46b0f4b5bf79770d72d6049adb3b56
/Hackerrank/number_of_subarrays_of_given_length_and_given_sum_subarray_division.cpp
fb69496d555b03aab81399babc30a0c0f5003b20
[]
no_license
yashsaxena972/Competitive-coding
1c553b32eb467c45dec5ed5341b6ab5d73bcac0b
688bd317ccbc061d18015779528d0683298aeeed
refs/heads/master
2023-02-01T21:00:45.493123
2020-12-20T16:26:39
2020-12-20T16:26:39
289,275,577
0
1
null
null
null
null
UTF-8
C++
false
false
2,600
cpp
// Sub-array Division or Count of subarrays having given length and given sum /* Given a chocolate bar, two children, Lily and Ron, are determining how to share it. Each of the squares has an integer on it. Lily decides to share a contiguous segment of the bar selected such that: The length of the segment matches Ron's birth month, and, The sum of the integers on the squares is equal to his birth day. You must determine how many ways she can divide the chocolate. Consider the chocolate bar as an array of squares, . She wants to find segments summing to Ron's birth day, with a length equalling his birth month, . In this case, there are two segments meeting her criteria: and . */ #include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); // Complete the birthday function below. int birthday(vector<int> s, int d, int m) { int currSum = 0; int ans = 0; int n = s.size(); for(int i=0;i<m;i++){ currSum += s[i]; } if(currSum == d){ ans++; } for(int j=m;j<n;j++){ currSum = currSum + s[j] - s[j-m]; if(currSum == d){ ans++; } } return ans; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string n_temp; getline(cin, n_temp); int n = stoi(ltrim(rtrim(n_temp))); string s_temp_temp; getline(cin, s_temp_temp); vector<string> s_temp = split(rtrim(s_temp_temp)); vector<int> s(n); for (int i = 0; i < n; i++) { int s_item = stoi(s_temp[i]); s[i] = s_item; } string dm_temp; getline(cin, dm_temp); vector<string> dm = split(rtrim(dm_temp)); int d = stoi(dm[0]); int m = stoi(dm[1]); int result = birthday(s, d, m); fout << result << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
[ "40518300+yashsaxena972@users.noreply.github.com" ]
40518300+yashsaxena972@users.noreply.github.com
1a53afc89fd4e33bd496a79ca386e7f04c9009fa
ef7157cf22f84b16e5b764890d59a5c4ef10c70e
/app.h
2f16bb5ef739c85d6c979b350ee2bbb8ec0d9611
[]
no_license
nathanczh/DRosc-root
bb77e75bf6b7c2174049f156a138066c74ffecf5
379c2cfa59f95d4dab7ea5edef96e8bfe2a224e1
refs/heads/master
2020-07-24T11:48:16.537940
2019-12-18T17:34:15
2019-12-18T17:34:15
207,914,502
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
h
#ifndef APP_H #define APP_H #include <utility> #include <iostream> #include <fstream> #include <cmath> #include <TH1D.h> #include <TGraph.h> #include <TTree.h> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <TTreeReaderArray.h> #include <TCanvas.h> #include <TString.h> #include <TObject.h> #include <TBranch.h> #define MAX_N_BOARDS 16 #define N_CHANNELS 4 #define MAX_CHANNELS MAX_N_BOARDS * N_CHANNELS #define N_BINS 1024 double PEAK_THRESHOLD = -1.0; class EventData{ public: double time[N_BINS]; double waveform[N_BINS]; }; // typedef struct { // double time[N_BINS]; // double waveform[N_BINS]; // } EventData; class EventStats{ public: double amplitude; double peak_time; double charge; double rise_time; double difference; }; class BoardId{ public: int channel; int board; BoardId(int board, int channel) { this->channel = channel; this->board = board; } virtual ULong_t Hash() const{ return channel + board * N_CHANNELS; } bool operator <(const BoardId& rhs) const { return Hash() < rhs.Hash(); } TString str(TString type){ TString s; s.Form("%lu" + type,this->Hash()); return s; } TString str(){ TString s; s.Form("%lu",this->Hash()); return s; } }; #endif
[ "nathan.chan.zh@gmail.com" ]
nathan.chan.zh@gmail.com
a99a0667f7858a0c3c58ac77f94f5ca0108b4e49
6141ca74d015eb03a39cdc73ed6844c4cbb9815e
/archive-patcher/src/main/java/com/google/archivepatcher/generator/bsdiff/wrapper/bsdiff_jni.cc
aa5a85b7cc7ccff1c377173da26cfa5f6a114b86
[]
no_license
EvilMouth/DiffPatchRecord
9dc50955fa1b41fef9fd50cd5cd18b30f1499387
d4423751ac9f20f351b8eeb697fc6a5c69134a63
refs/heads/master
2023-01-08T08:04:54.204546
2020-10-27T06:31:18
2020-10-27T06:31:18
279,252,866
11
2
null
null
null
null
UTF-8
C++
false
false
6,465
cc
// Copyright 2017 Google LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <err.h> #include <fcntl.h> #include <jni.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cstddef> #include <cstdio> #include <cstdlib> #include <limits> #include "bsdiff/bsdiff.h" #include "bsdiff/patch_writer_factory.h" #include "third_party/absl/memory/memory.h" #include "third_party/java/jdk/include/jni.h" #include "third_party/java_src/archive_patcher/com_google_archivepatcher_generator_bsdiff_wrapper_BsDiffNativePatchWriter.h" #include "third_party/java_src/archive_patcher/com_google_archivepatcher_generator_bsdiff_wrapper_BsDiffNativePatchWriter.h" #include "util/java/jni_helper.h" namespace { uint8_t* MapFile(JNIEnv* env, const char* filename, size_t* filesize) { int fd = open(filename, O_RDONLY); if (fd < 0) { env->ThrowNew( env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("Unable to open file for mapping: " + std::string(filename)).c_str()); return nullptr; } struct stat st; if (fstat(fd, &st) != 0) { env->ThrowNew( env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("Unable to perform fstat() on file: " + std::string(filename)) .c_str()); return nullptr; } // Should work as long as file size fits uint64_t. if (static_cast<uint64_t>(st.st_size) > std::numeric_limits<size_t>::max()) { env->ThrowNew(env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("File too large: " + std::string(filename)).c_str()); close(fd); return nullptr; } *filesize = st.st_size; void* ret = mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (ret == MAP_FAILED) { if (close(fd) != 0) { env->ThrowNew( env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("Unable to close file after map failed: " + std::string(filename)) .c_str()); } env->ThrowNew( env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("Mapping the file has failed: " + std::string(filename)).c_str()); return nullptr; } if (close(fd) != 0) { env->ThrowNew(env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), ("Unable to close file: " + std::string(filename)).c_str()); return nullptr; } return static_cast<uint8_t*>(ret); } jbyteArray GeneratePatch(JNIEnv* env, const uint8_t* old_buf, size_t old_size, const uint8_t* new_buf, size_t new_size) { std::vector<uint8_t> patch; std::unique_ptr<bsdiff::PatchWriterInterface> patch_writer = bsdiff::CreateEndsleyPatchWriter(&patch); int bsdiff_return_value = bsdiff::bsdiff(old_buf, old_size, new_buf, new_size, /* min_length= */ 16, patch_writer.get(), nullptr); if (bsdiff_return_value != 0) { env->ThrowNew(env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), "BsDiff has failed during generation."); return nullptr; } jbyteArray result = env->NewByteArray(patch.size()); env->SetByteArrayRegion(result, 0, patch.size(), (jbyte*)patch.data()); return result; } } // namespace // nativeGeneratePatchFile() - returns a byte array with the generated patch. // Performs a cleanup operation and releases all used resources from memory. jbyteArray Java_com_google_archivepatcher_generator_bsdiff_wrapper_BsDiffNativePatchWriter_nativeGeneratePatchFile( JNIEnv* env, jclass /*jcls*/, jstring old_filename, jstring new_filename) { const char* old_file = env->GetStringUTFChars(old_filename, nullptr); const char* new_file = env->GetStringUTFChars(new_filename, nullptr); if (old_file == nullptr || new_file == nullptr) { env->ThrowNew(env->FindClass("com/google/archivepatcher/generator/bsdiff/" "wrapper/NativeBsDiffException"), "Unable to retrieve one of the diff files."); return nullptr; } size_t old_size, new_size; uint8_t* old_buf = MapFile(env, old_file, &old_size); uint8_t* new_buf = MapFile(env, new_file, &new_size); env->ReleaseStringUTFChars(old_filename, old_file); env->ReleaseStringUTFChars(new_filename, new_file); if (!old_buf) { if (new_buf) { munmap(new_buf, new_size); // Ignore error on error. } return nullptr; } if (!new_buf) { if (old_buf) { munmap(old_buf, old_size); // ignore error on error. } return nullptr; } jbyteArray result = GeneratePatch(env, old_buf, old_size, new_buf, new_size); munmap(old_buf, old_size); munmap(new_buf, new_size); return result; } // nativeGeneratePatchData() - returns a byte array with the generated patch. jbyteArray Java_com_google_archivepatcher_generator_bsdiff_wrapper_BsDiffNativePatchWriter_nativeGeneratePatchData( JNIEnv* env, jclass /*jcls*/, jbyteArray old_data, jbyteArray new_data) { jsize old_size = env->GetArrayLength(old_data); jsize new_size = env->GetArrayLength(new_data); auto old_buf = absl::make_unique<uint8_t[]>(old_size); auto new_buf = absl::make_unique<uint8_t[]>(new_size); env->GetByteArrayRegion(old_data, 0, old_size, reinterpret_cast<jbyte*>(old_buf.get())); env->GetByteArrayRegion(new_data, 0, new_size, reinterpret_cast<jbyte*>(new_buf.get())); return GeneratePatch(env, old_buf.get(), old_size, new_buf.get(), new_size); }
[ "izyhang@gmail.com" ]
izyhang@gmail.com
6f20cfabf8b3b07760d71ee352eaf3d91e776bb6
01d767e6e0c237a2688aed222153ab80d2640b79
/668-kth-smallest-number-in-multiplication-table/668-kth-smallest-number-in-multiplication-table.cpp
0a1ee282ca117602af916470c70ab29b3bea37ea
[]
no_license
Samiatrix/Leetcode-Problems
75669ec7a11ccfaa61737c84acc7d704c6cd5767
529704d47206ccc574af7fa79df85edafcd768db
refs/heads/master
2022-06-29T05:34:08.326534
2022-06-24T10:58:00
2022-06-24T10:58:00
239,309,504
1
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
class Solution { public: int countLessThanOrEqualToMid(int n, int m, int mid){ int count = 0; for(int i=1;i<=n;i++){ count += min((mid/i), m); } return count; } int findKthNumber(int m, int n, int k) { int l = 1, r = m*n; int ans = -1; while(l<=r){ int mid = l+(r-l)/2; if(countLessThanOrEqualToMid(m, n, mid) >= k){ ans = mid; r = mid-1; } else l = mid+1; } return ans; } };
[ "37403386+Samiatrix@users.noreply.github.com" ]
37403386+Samiatrix@users.noreply.github.com
283a78d4ec133f91343a5d0afcd8de6063fbffa3
50e400043b373d3ccfe4140b13407b21cb38181b
/app_files/libraries/GFX_Library_for_Arduino/src/databus/Arduino_ESP32SPI.h
44a098336986e3586a36c2476697d997dce15104
[]
no_license
gizTM/my-arduino-source-files
4b60e9ecb895e722bb8f3996135877b80c11ee13
4f9d17a8e21a03042a8eec445d4bfacc3a08c126
refs/heads/master
2021-06-03T14:13:49.355317
2021-04-26T18:13:19
2021-04-26T18:13:19
136,066,369
2
0
null
null
null
null
UTF-8
C++
false
false
3,673
h
/* * start rewrite from: * https://github.com/espressif/arduino-esp32.git */ #ifdef ESP32 #ifndef _ARDUINO_ESP32SPI_H_ #define _ARDUINO_ESP32SPI_H_ #include "soc/spi_struct.h" #include "soc/dport_reg.h" typedef volatile uint32_t *PORTreg_t; ///< PORT register type #include "Arduino_DataBus.h" #define SPI_DEFAULT_FREQ 40000000 #define SPI_CLK_IDX(p) ((p == 0) ? SPICLK_OUT_IDX : ((p == 1) ? SPICLK_OUT_IDX : ((p == 2) ? HSPICLK_OUT_IDX : ((p == 3) ? VSPICLK_OUT_IDX : 0)))) #define SPI_MISO_IDX(p) ((p == 0) ? SPIQ_OUT_IDX : ((p == 1) ? SPIQ_OUT_IDX : ((p == 2) ? HSPIQ_OUT_IDX : ((p == 3) ? VSPIQ_OUT_IDX : 0)))) #define SPI_MOSI_IDX(p) ((p == 0) ? SPID_IN_IDX : ((p == 1) ? SPID_IN_IDX : ((p == 2) ? HSPID_IN_IDX : ((p == 3) ? VSPID_IN_IDX : 0)))) #define SPI_SPI_SS_IDX(n) ((n == 0) ? SPICS0_OUT_IDX : ((n == 1) ? SPICS1_OUT_IDX : ((n == 2) ? SPICS2_OUT_IDX : SPICS0_OUT_IDX))) #define SPI_HSPI_SS_IDX(n) ((n == 0) ? HSPICS0_OUT_IDX : ((n == 1) ? HSPICS1_OUT_IDX : ((n == 2) ? HSPICS2_OUT_IDX : HSPICS0_OUT_IDX))) #define SPI_VSPI_SS_IDX(n) ((n == 0) ? VSPICS0_OUT_IDX : ((n == 1) ? VSPICS1_OUT_IDX : ((n == 2) ? VSPICS2_OUT_IDX : VSPICS0_OUT_IDX))) #define SPI_SS_IDX(p, n) ((p == 0) ? SPI_SPI_SS_IDX(n) : ((p == 1) ? SPI_SPI_SS_IDX(n) : ((p == 2) ? SPI_HSPI_SS_IDX(n) : ((p == 3) ? SPI_VSPI_SS_IDX(n) : 0)))) #define SPI_INUM(u) (2) #define SPI_INTR_SOURCE(u) ((u == 0) ? ETS_SPI0_INTR_SOURCE : ((u == 1) ? ETS_SPI1_INTR_SOURCE : ((u == 2) ? ETS_SPI2_INTR_SOURCE : ((p == 3) ? ETS_SPI3_INTR_SOURCE : 0)))) class Arduino_ESP32SPI : public Arduino_DataBus { public: Arduino_ESP32SPI(int8_t dc = -1, int8_t cs = -1, int8_t sck = -1, int8_t mosi = -1, int8_t miso = -1, uint8_t spi_num = VSPI, bool is_shared_interface = true); // Constructor virtual void begin(int32_t speed = 0, int8_t dataMode = SPI_MODE0); virtual void beginWrite(); virtual void writeCommand(uint8_t); virtual void writeCommand16(uint16_t); virtual void writeCommand32(uint32_t); virtual void write(uint8_t); virtual void write16(uint16_t); virtual void write32(uint32_t); virtual void writeC8D8(uint8_t c, uint8_t d); virtual void writeC8D16(uint8_t c, uint16_t d); virtual void writeC8D16D16(uint8_t c, uint16_t d1, uint16_t d2); virtual void writeRepeat(uint16_t p, uint32_t len); virtual void writeBytes(uint8_t *data, uint32_t len); virtual void writePixels(uint16_t *data, uint32_t len); virtual void writePattern(uint8_t *data, uint8_t len, uint32_t repeat); virtual void endWrite(); virtual void sendCommand(uint8_t); virtual void sendCommand16(uint16_t); virtual void sendCommand32(uint32_t); virtual void sendData(uint8_t); virtual void sendData16(uint16_t); virtual void sendData32(uint32_t); protected: virtual void flush_data_buf(); private: INLINE void WRITE8BIT(uint8_t c); INLINE void WRITE9BIT(uint32_t c); INLINE void CS_HIGH(void); INLINE void CS_LOW(void); INLINE void DC_HIGH(void); INLINE void DC_LOW(void); int8_t _dc, _cs, _sck, _mosi, _miso; uint8_t _spi_num; bool _is_shared_interface; int32_t _speed; uint32_t _div = 0; PORTreg_t dcPortSet; ///< PORT register for data/command SET PORTreg_t dcPortClr; ///< PORT register for data/command CLEAR PORTreg_t csPortSet; ///< PORT register for chip select SET PORTreg_t csPortClr; ///< PORT register for chip select CLEAR uint32_t dcPinMask; ///< Bitmask for data/command uint32_t csPinMask; ///< Bitmask for chip select spi_t *_spi; uint8_t _bitOrder; uint8_t data_buf[64] = {0}; uint32_t *data_buf32 = (uint32_t *)&data_buf; uint16_t data_buf_bit_idx = 0; }; #endif // _ARDUINO_ESP32SPI_H_ #endif // #ifdef ESP32
[ "tharinee_fang@hotmail.com" ]
tharinee_fang@hotmail.com
b1ef34cce16e5721a7515effbaa77b1946979a8c
b3c2f39c37a466b349eda2a0f2cb296ae809d33e
/minisat/simp/SimpSolver.cc
9d62c54c098587b0116a76bcdbc9d38690002eb3
[ "MIT" ]
permissive
mvdwerve/minisat
0851f4040285530cd1f3a9e50f9fa56421b80b6d
1a584c5a2e2e3a60148b33768a5e6a691536a508
refs/heads/master
2021-07-09T21:07:32.560746
2017-10-03T16:53:32
2017-10-03T16:53:32
104,076,179
0
0
null
2017-09-19T13:07:57
2017-09-19T13:07:57
null
UTF-8
C++
false
false
23,002
cc
/***********************************************************************************[SimpSolver.cc] Copyright (c) 2006, Niklas Een, Niklas Sorensson Copyright (c) 2007-2010, Niklas Sorensson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ #include "minisat/mtl/Sort.h" #include "minisat/simp/SimpSolver.h" #include "minisat/utils/System.h" using namespace Minisat; //================================================================================================= // Options: static const char* _cat = "SIMP"; static BoolOption opt_use_asymm (_cat, "asymm", "Shrink clauses by asymmetric branching.", false); static BoolOption opt_use_rcheck (_cat, "rcheck", "Check if a clause is already implied. (costly)", false); static BoolOption opt_use_elim (_cat, "elim", "Perform variable elimination.", true); static IntOption opt_grow (_cat, "grow", "Allow a variable elimination step to grow by a number of clauses.", 0); static IntOption opt_clause_lim (_cat, "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX)); static IntOption opt_subsumption_lim (_cat, "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX)); static DoubleOption opt_simp_garbage_frac(_cat, "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false)); //================================================================================================= // Constructor/Destructor: SimpSolver::SimpSolver() : grow (opt_grow) , clause_lim (opt_clause_lim) , subsumption_lim (opt_subsumption_lim) , simp_garbage_frac (opt_simp_garbage_frac) , use_asymm (opt_use_asymm) , use_rcheck (opt_use_rcheck) , use_elim (opt_use_elim) , extend_model (true) , merges (0) , asymm_lits (0) , eliminated_vars (0) , elimorder (1) , use_simplification (true) , occurs (ClauseDeleted(ca)) , elim_heap (ElimLt(n_occ)) , bwdsub_assigns (0) , n_touched (0) { vec<Lit> dummy(1,lit_Undef); ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below. bwdsub_tmpunit = ca.alloc(dummy); remove_satisfied = false; } SimpSolver::~SimpSolver() { } Var SimpSolver::newVar(lbool upol, bool dvar) { Var v = Solver::newVar(upol, dvar); frozen .insert(v, (char)false); eliminated.insert(v, (char)false); if (use_simplification){ n_occ .insert( mkLit(v), 0); n_occ .insert(~mkLit(v), 0); occurs .init (v); touched .insert(v, 0); elim_heap .insert(v); } return v; } void SimpSolver::releaseVar(Lit l) { assert(!isEliminated(var(l))); if (!use_simplification && var(l) >= max_simp_var) // Note: Guarantees that no references to this variable is // left in model extension datastructure. Could be improved! Solver::releaseVar(l); else // Otherwise, don't allow variable to be reused. Solver::addClause(l); } lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp) { vec<Var> extra_frozen; lbool result = l_True; do_simp &= use_simplification; if (do_simp){ // Assumptions must be temporarily frozen to run variable elimination: for (int i = 0; i < assumptions.size(); i++){ Var v = var(assumptions[i]); // If an assumption has been eliminated, remember it. assert(!isEliminated(v)); if (!frozen[v]){ // Freeze and store. setFrozen(v, true); extra_frozen.push(v); } } result = lbool(eliminate(turn_off_simp)); } if (result == l_True) result = Solver::solve_(); else if (verbosity >= 1) printf("c ===============================================================================\n"); if (result == l_True && extend_model) extendModel(); if (do_simp) // Unfreeze the assumptions that were frozen: for (int i = 0; i < extra_frozen.size(); i++) setFrozen(extra_frozen[i], false); return result; } bool SimpSolver::addClause_(vec<Lit>& ps) { #ifndef NDEBUG for (int i = 0; i < ps.size(); i++) assert(!isEliminated(var(ps[i]))); #endif int nclauses = clauses.size(); if (use_rcheck && implied(ps)) return true; if (!Solver::addClause_(ps)) return false; if (use_simplification && clauses.size() == nclauses + 1){ CRef cr = clauses.last(); const Clause& c = ca[cr]; // NOTE: the clause is added to the queue immediately and then // again during 'gatherTouchedClauses()'. If nothing happens // in between, it will only be checked once. Otherwise, it may // be checked twice unnecessarily. This is an unfortunate // consequence of how backward subsumption is used to mimic // forward subsumption. subsumption_queue.insert(cr); for (int i = 0; i < c.size(); i++){ occurs[var(c[i])].push(cr); n_occ[c[i]]++; touched[var(c[i])] = 1; n_touched++; if (elim_heap.inHeap(var(c[i]))) elim_heap.increase(var(c[i])); } } return true; } void SimpSolver::removeClause(CRef cr) { const Clause& c = ca[cr]; if (use_simplification) for (int i = 0; i < c.size(); i++){ n_occ[c[i]]--; updateElimHeap(var(c[i])); occurs.smudge(var(c[i])); } Solver::removeClause(cr); } bool SimpSolver::strengthenClause(CRef cr, Lit l) { Clause& c = ca[cr]; assert(decisionLevel() == 0); assert(use_simplification); // FIX: this is too inefficient but would be nice to have (properly implemented) // if (!find(subsumption_queue, &c)) subsumption_queue.insert(cr); if (c.size() == 2){ removeClause(cr); c.strengthen(l); }else{ detachClause(cr, true); c.strengthen(l); attachClause(cr); remove(occurs[var(l)], cr); n_occ[l]--; updateElimHeap(var(l)); } return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true; } // Returns FALSE if clause is always satisfied ('out_clause' should not be used). bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause) { merges++; out_clause.clear(); bool ps_smallest = _ps.size() < _qs.size(); const Clause& ps = ps_smallest ? _qs : _ps; const Clause& qs = ps_smallest ? _ps : _qs; for (int i = 0; i < qs.size(); i++){ if (var(qs[i]) != v){ for (int j = 0; j < ps.size(); j++) if (var(ps[j]) == var(qs[i])){ if (ps[j] == ~qs[i]) return false; else goto next; } out_clause.push(qs[i]); } next:; } for (int i = 0; i < ps.size(); i++) if (var(ps[i]) != v) out_clause.push(ps[i]); return true; } // Returns FALSE if clause is always satisfied. bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size) { merges++; bool ps_smallest = _ps.size() < _qs.size(); const Clause& ps = ps_smallest ? _qs : _ps; const Clause& qs = ps_smallest ? _ps : _qs; const Lit* __ps = (const Lit*)ps; const Lit* __qs = (const Lit*)qs; size = ps.size()-1; for (int i = 0; i < qs.size(); i++){ if (var(__qs[i]) != v){ for (int j = 0; j < ps.size(); j++) if (var(__ps[j]) == var(__qs[i])){ if (__ps[j] == ~__qs[i]) return false; else goto next; } size++; } next:; } return true; } void SimpSolver::gatherTouchedClauses() { if (n_touched == 0) return; int i,j; for (i = j = 0; i < subsumption_queue.size(); i++) if (ca[subsumption_queue[i]].mark() == 0) ca[subsumption_queue[i]].mark(2); for (i = 0; i < nVars(); i++) if (touched[i]){ const vec<CRef>& cs = occurs.lookup(i); for (j = 0; j < cs.size(); j++) if (ca[cs[j]].mark() == 0){ subsumption_queue.insert(cs[j]); ca[cs[j]].mark(2); } touched[i] = 0; } for (i = 0; i < subsumption_queue.size(); i++) if (ca[subsumption_queue[i]].mark() == 2) ca[subsumption_queue[i]].mark(0); n_touched = 0; } bool SimpSolver::implied(const vec<Lit>& c) { assert(decisionLevel() == 0); trail_lim.push(trail.size()); for (int i = 0; i < c.size(); i++) if (value(c[i]) == l_True){ cancelUntil(0); return true; }else if (value(c[i]) != l_False){ assert(value(c[i]) == l_Undef); uncheckedEnqueue(~c[i]); } bool result = propagate() != CRef_Undef; cancelUntil(0); return result; } // Backward subsumption + backward subsumption resolution bool SimpSolver::backwardSubsumptionCheck(bool verbose) { int cnt = 0; int subsumed = 0; int deleted_literals = 0; assert(decisionLevel() == 0); while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){ // Empty subsumption queue and return immediately on user-interrupt: if (asynch_interrupt){ subsumption_queue.clear(); bwdsub_assigns = trail.size(); break; } // Check top-level assignments by creating a dummy clause and placing it in the queue: if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){ Lit l = trail[bwdsub_assigns++]; ca[bwdsub_tmpunit][0] = l; ca[bwdsub_tmpunit].calcAbstraction(); subsumption_queue.insert(bwdsub_tmpunit); } CRef cr = subsumption_queue.peek(); subsumption_queue.pop(); Clause& c = ca[cr]; if (c.mark()) continue; if (verbose && verbosity >= 2 && cnt++ % 1000 == 0) printf("c subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals); assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point. // Find best variable to scan: Var best = var(c[0]); for (int i = 1; i < c.size(); i++) if (occurs[var(c[i])].size() < occurs[best].size()) best = var(c[i]); // Search all candidates: vec<CRef>& _cs = occurs.lookup(best); CRef* cs = (CRef*)_cs; for (int j = 0; j < _cs.size(); j++) if (c.mark()) break; else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){ Lit l = c.subsumes(ca[cs[j]]); if (l == lit_Undef) subsumed++, removeClause(cs[j]); else if (l != lit_Error){ deleted_literals++; if (!strengthenClause(cs[j], ~l)) return false; // Did current candidate get deleted from cs? Then check candidate at index j again: if (var(l) == best) j--; } } } return true; } bool SimpSolver::asymm(Var v, CRef cr) { Clause& c = ca[cr]; assert(decisionLevel() == 0); if (c.mark() || satisfied(c)) return true; trail_lim.push(trail.size()); Lit l = lit_Undef; for (int i = 0; i < c.size(); i++) if (var(c[i]) != v && value(c[i]) != l_False) uncheckedEnqueue(~c[i]); else l = c[i]; if (propagate() != CRef_Undef){ cancelUntil(0); asymm_lits++; if (!strengthenClause(cr, l)) return false; }else cancelUntil(0); return true; } bool SimpSolver::asymmVar(Var v) { assert(use_simplification); const vec<CRef>& cls = occurs.lookup(v); if (value(v) != l_Undef || cls.size() == 0) return true; for (int i = 0; i < cls.size(); i++) if (!asymm(v, cls[i])) return false; return backwardSubsumptionCheck(); } static void mkElimClause(vec<uint32_t>& elimclauses, Lit x) { elimclauses.push(toInt(x)); elimclauses.push(1); } static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c) { int first = elimclauses.size(); int v_pos = -1; // Copy clause to elimclauses-vector. Remember position where the // variable 'v' occurs: for (int i = 0; i < c.size(); i++){ elimclauses.push(toInt(c[i])); if (var(c[i]) == v) v_pos = i + first; } assert(v_pos != -1); // Swap the first literal with the 'v' literal, so that the literal // containing 'v' will occur first in the clause: uint32_t tmp = elimclauses[v_pos]; elimclauses[v_pos] = elimclauses[first]; elimclauses[first] = tmp; // Store the length of the clause last: elimclauses.push(c.size()); } bool SimpSolver::eliminateVar(Var v) { assert(!frozen[v]); assert(!isEliminated(v)); assert(value(v) == l_Undef); // Split the occurrences into positive and negative: // const vec<CRef>& cls = occurs.lookup(v); vec<CRef> pos, neg; for (int i = 0; i < cls.size(); i++) (find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]); // Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no // clause must exceed the limit on the maximal clause size (if it is set): // int cnt = 0; int clause_size = 0; for (int i = 0; i < pos.size(); i++) for (int j = 0; j < neg.size(); j++) if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) && (++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim))) return true; // Delete and store old clauses: eliminated[v] = true; setDecisionVar(v, false); eliminated_vars++; if (pos.size() > neg.size()){ for (int i = 0; i < neg.size(); i++) mkElimClause(elimclauses, v, ca[neg[i]]); mkElimClause(elimclauses, mkLit(v)); }else{ for (int i = 0; i < pos.size(); i++) mkElimClause(elimclauses, v, ca[pos[i]]); mkElimClause(elimclauses, ~mkLit(v)); } for (int i = 0; i < cls.size(); i++) removeClause(cls[i]); // Produce clauses in cross product: vec<Lit>& resolvent = add_tmp; for (int i = 0; i < pos.size(); i++) for (int j = 0; j < neg.size(); j++) if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent)) return false; // Free occurs list for this variable: occurs[v].clear(true); // Free watchers lists for this variable, if possible: if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true); if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true); return backwardSubsumptionCheck(); } bool SimpSolver::substitute(Var v, Lit x) { assert(!frozen[v]); assert(!isEliminated(v)); assert(value(v) == l_Undef); if (!ok) return false; eliminated[v] = true; setDecisionVar(v, false); const vec<CRef>& cls = occurs.lookup(v); vec<Lit>& subst_clause = add_tmp; for (int i = 0; i < cls.size(); i++){ Clause& c = ca[cls[i]]; subst_clause.clear(); for (int j = 0; j < c.size(); j++){ Lit p = c[j]; subst_clause.push(var(p) == v ? x ^ sign(p) : p); } removeClause(cls[i]); if (!addClause_(subst_clause)) return ok = false; } return true; } void SimpSolver::extendModel() { int i, j; Lit x; for (i = elimclauses.size()-1; i > 0; i -= j){ for (j = elimclauses[i--]; j > 1; j--, i--) if (modelValue(toLit(elimclauses[i])) != l_False) goto next; x = toLit(elimclauses[i]); model[var(x)] = lbool(!sign(x)); next:; } } bool SimpSolver::eliminate(bool turn_off_elim) { if (!simplify()) return false; else if (!use_simplification) return true; // Main simplification loop: // while (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0){ gatherTouchedClauses(); // printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns); if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) && !backwardSubsumptionCheck(true)){ ok = false; goto cleanup; } // Empty elim_heap and return immediately on user-interrupt: if (asynch_interrupt){ assert(bwdsub_assigns == trail.size()); assert(subsumption_queue.size() == 0); assert(n_touched == 0); elim_heap.clear(); goto cleanup; } // printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size()); for (int cnt = 0; !elim_heap.empty(); cnt++){ Var elim = elim_heap.removeMin(); if (asynch_interrupt) break; if (isEliminated(elim) || value(elim) != l_Undef) continue; if (verbosity >= 2 && cnt % 100 == 0) printf("c elimination left: %10d\r", elim_heap.size()); if (use_asymm){ // Temporarily freeze variable. Otherwise, it would immediately end up on the queue again: bool was_frozen = frozen[elim]; frozen[elim] = true; if (!asymmVar(elim)){ ok = false; goto cleanup; } frozen[elim] = was_frozen; } // At this point, the variable may have been set by assymetric branching, so check it // again. Also, don't eliminate frozen variables: if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){ ok = false; goto cleanup; } checkGarbage(simp_garbage_frac); } assert(subsumption_queue.size() == 0); } cleanup: // If no more simplification is needed, free all simplification-related data structures: if (turn_off_elim){ touched .clear(true); occurs .clear(true); n_occ .clear(true); elim_heap.clear(true); subsumption_queue.clear(true); use_simplification = false; remove_satisfied = true; ca.extra_clause_field = false; max_simp_var = nVars(); // Force full cleanup (this is safe and desirable since it only happens once): rebuildOrderHeap(); garbageCollect(); }else{ // Cheaper cleanup: checkGarbage(); } if (verbosity >= 1 && elimclauses.size() > 0) printf("c | Eliminated clauses: %10.2f Mb |\n", double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024)); return ok; } //================================================================================================= // Garbage Collection methods: void SimpSolver::relocAll(ClauseAllocator& to) { if (!use_simplification) return; // All occurs lists: // for (int i = 0; i < nVars(); i++){ occurs.clean(i); vec<CRef>& cs = occurs[i]; for (int j = 0; j < cs.size(); j++) ca.reloc(cs[j], to); } // Subsumption queue: // for (int i = subsumption_queue.size(); i > 0; i--){ CRef cr = subsumption_queue.peek(); subsumption_queue.pop(); if (ca[cr].mark()) continue; ca.reloc(cr, to); subsumption_queue.insert(cr); } // Temporary clause: // ca.reloc(bwdsub_tmpunit, to); } void SimpSolver::garbageCollect() { // Initialize the next region to a size corresponding to the estimated utilization degree. This // is not precise but should avoid some unnecessary reallocations for the new region: ClauseAllocator to(ca.size() - ca.wasted()); to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields. relocAll(to); Solver::relocAll(to); if (verbosity >= 2) printf("c | Garbage collection: %12d bytes => %12d bytes |\n", ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size); to.moveTo(ca); }
[ "mvdwerve@outlook.com" ]
mvdwerve@outlook.com
55bf1b0b83d59137cdbe6e6e859d7eeafc9574a2
702e6bba478747234b34fad37b37c78f888b7818
/Paper4最新1128/server/source/event/Event list.cpp
58b77060ecfa30095f53f89c245110a30ce5bc67
[]
no_license
2015ECCSSPaperProject/MAIN
f18b3525f3fa6dda371302b50d72b5a08016baad
b106502de5f2e7977badc56e767268036282f221
refs/heads/master
2021-01-13T00:37:06.767556
2016-02-24T09:51:12
2016-02-24T09:51:12
43,874,999
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
#include "Event list.h" #include "Event.h" Event_list::Event_list() : root(nullptr) {} Event_list::~Event_list() { if (root) Deleat_all_node( root ); } void Event_list::push(Event *in) { root = new Node(in, nullptr, root); if (root->next) root->next->back = root; } void Event_list::Update() { Node *node_pointer = root; while (true) { if (node_pointer == nullptr) break; if (node_pointer->ev->Update()) { if (node_pointer == root) { node_pointer = root->next; delete root; root = node_pointer; } else { Node *next_pointer = node_pointer->next; node_pointer->back->next = node_pointer->next; delete node_pointer; node_pointer = next_pointer; } } else node_pointer = node_pointer->next; } } void Event_list::Deleat_all_node( Node *root ) { if (root->next) Deleat_all_node( root->next ); delete root; } Event_list::Node::Node(Event *ev, Node *back, Node *next) : ev(ev), back(back), next(next) {} Event_list::Node::~Node() { delete ev; } Event_list *event_list = nullptr;
[ "ridley.skirmisher@gmail.com" ]
ridley.skirmisher@gmail.com
9df203289729517bfe6cf6696ecc70122965a6ba
8567438779e6af0754620a25d379c348e4cd5a5d
/content/browser/frame_host/frame_tree_node_blame_context_unittest.cc
7f90717427493d54279ff6ba0d0572782ab1e849
[ "BSD-3-Clause" ]
permissive
thngkaiyuan/chromium
c389ac4b50ccba28ee077cbf6115c41b547955ae
dab56a4a71f87f64ecc0044e97b4a8f247787a68
refs/heads/master
2022-11-10T02:50:29.326119
2017-04-08T12:28:57
2017-04-08T12:28:57
84,073,924
0
1
BSD-3-Clause
2022-10-25T19:47:15
2017-03-06T13:04:15
null
UTF-8
C++
false
false
9,222
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/frame_host/frame_tree_node_blame_context.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/trace_event_analyzer.h" #include "base/trace_event/trace_buffer.h" #include "base/trace_event/trace_event_argument.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/common/frame_owner_properties.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/web/WebSandboxFlags.h" namespace content { namespace { bool EventPointerCompare(const trace_analyzer::TraceEvent* lhs, const trace_analyzer::TraceEvent* rhs) { CHECK(lhs); CHECK(rhs); return *lhs < *rhs; } void OnTraceDataCollected(base::Closure quit_closure, base::trace_event::TraceResultBuffer* buffer, const scoped_refptr<base::RefCountedString>& json, bool has_more_events) { buffer->AddFragment(json->data()); if (!has_more_events) quit_closure.Run(); } void ExpectFrameTreeNodeObject(const trace_analyzer::TraceEvent* event) { EXPECT_EQ("navigation", event->category); EXPECT_EQ("FrameTreeNode", event->name); } void ExpectFrameTreeNodeSnapshot(const trace_analyzer::TraceEvent* event) { ExpectFrameTreeNodeObject(event); EXPECT_TRUE(event->HasArg("snapshot")); EXPECT_TRUE(event->arg_values.at("snapshot") ->IsType(base::Value::Type::DICTIONARY)); } std::string GetParentNodeID(const trace_analyzer::TraceEvent* event) { const base::Value* arg_snapshot = event->arg_values.at("snapshot").get(); const base::DictionaryValue* snapshot; EXPECT_TRUE(arg_snapshot->GetAsDictionary(&snapshot)); if (!snapshot->HasKey("parent")) return std::string(); const base::DictionaryValue* parent; EXPECT_TRUE(snapshot->GetDictionary("parent", &parent)); std::string parent_id; EXPECT_TRUE(parent->GetString("id_ref", &parent_id)); return parent_id; } std::string GetSnapshotURL(const trace_analyzer::TraceEvent* event) { const base::Value* arg_snapshot = event->arg_values.at("snapshot").get(); const base::DictionaryValue* snapshot; EXPECT_TRUE(arg_snapshot->GetAsDictionary(&snapshot)); if (!snapshot->HasKey("url")) return std::string(); std::string url; EXPECT_TRUE(snapshot->GetString("url", &url)); return url; } } // namespace class FrameTreeNodeBlameContextTest : public RenderViewHostImplTestHarness { public: FrameTree* tree() { return contents()->GetFrameTree(); } FrameTreeNode* root() { return tree()->root(); } int process_id() { return root()->current_frame_host()->GetProcess()->GetID(); } // Creates a frame tree specified by |shape|, which is a string of paired // parentheses. Each pair of parentheses represents a FrameTreeNode, and the // nesting of parentheses represents the parent-child relation between nodes. // Nodes represented by outer-most parentheses are children of the root node. // NOTE: Each node can have at most 9 child nodes, and the tree height (i.e., // max # of edges in any root-to-leaf path) must be at most 9. // See the test cases for sample usage. void CreateFrameTree(const char* shape) { main_test_rfh()->InitializeRenderFrameIfNeeded(); CreateSubframes(root(), 1, shape); } void RemoveAllNonRootFrames() { while (root()->child_count()) tree()->RemoveFrame(root()->child_at(0)); } void StartTracing() { base::trace_event::TraceLog::GetInstance()->SetEnabled( base::trace_event::TraceConfig("*"), base::trace_event::TraceLog::RECORDING_MODE); } void StopTracing() { base::trace_event::TraceLog::GetInstance()->SetDisabled(); } std::unique_ptr<trace_analyzer::TraceAnalyzer> CreateTraceAnalyzer() { base::trace_event::TraceResultBuffer buffer; base::trace_event::TraceResultBuffer::SimpleOutput trace_output; buffer.SetOutputCallback(trace_output.GetCallback()); base::RunLoop run_loop; buffer.Start(); base::trace_event::TraceLog::GetInstance()->Flush( base::Bind(&OnTraceDataCollected, run_loop.QuitClosure(), base::Unretained(&buffer))); run_loop.Run(); buffer.Finish(); return base::WrapUnique( trace_analyzer::TraceAnalyzer::Create(trace_output.json_output)); } private: int CreateSubframes(FrameTreeNode* node, int self_id, const char* shape) { int consumption = 0; for (int child_num = 1; shape[consumption++] == '('; ++child_num) { int child_id = self_id * 10 + child_num; tree()->AddFrame(node, process_id(), child_id, blink::WebTreeScopeType::Document, std::string(), base::StringPrintf("uniqueName%d", child_id), blink::WebSandboxFlags::None, FrameOwnerProperties()); FrameTreeNode* child = node->child_at(child_num - 1); consumption += CreateSubframes(child, child_id, shape + consumption); } return consumption; } }; // Creates a frame tree, tests if (i) the creation of each new frame is // correctly traced, and (ii) the topology given by the snapshots is correct. TEST_F(FrameTreeNodeBlameContextTest, FrameCreation) { /* Shape of the frame tree to be created: * () * / \ * () () * / \ | * () () () * | * () */ const char* tree_shape = "(()())((()))"; StartTracing(); CreateFrameTree(tree_shape); StopTracing(); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer = CreateTraceAnalyzer(); trace_analyzer::TraceEventVector events; trace_analyzer::Query q = trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_CREATE_OBJECT) || trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_SNAPSHOT_OBJECT); analyzer->FindEvents(q, &events); // Two events for each new node: creation and snapshot. EXPECT_EQ(12u, events.size()); std::set<FrameTreeNode*> creation_traced; std::set<FrameTreeNode*> snapshot_traced; for (auto* event : events) { ExpectFrameTreeNodeObject(event); FrameTreeNode* node = tree()->FindByID(strtol(event->id.c_str(), nullptr, 16)); EXPECT_NE(nullptr, node); if (event->HasArg("snapshot")) { ExpectFrameTreeNodeSnapshot(event); EXPECT_FALSE(base::ContainsValue(snapshot_traced, node)); snapshot_traced.insert(node); std::string parent_id = GetParentNodeID(event); EXPECT_FALSE(parent_id.empty()); EXPECT_EQ(node->parent(), tree()->FindByID(strtol(parent_id.c_str(), nullptr, 16))); } else { EXPECT_EQ(TRACE_EVENT_PHASE_CREATE_OBJECT, event->phase); EXPECT_FALSE(base::ContainsValue(creation_traced, node)); creation_traced.insert(node); } } } // Deletes frames from a frame tree, tests if the destruction of each frame is // correctly traced. TEST_F(FrameTreeNodeBlameContextTest, FrameDeletion) { /* Shape of the frame tree to be created: * () * / \ * () () * / \ | * () () () * | * () */ const char* tree_shape = "(()())((()))"; CreateFrameTree(tree_shape); std::set<int> node_ids; for (FrameTreeNode* node : tree()->Nodes()) node_ids.insert(node->frame_tree_node_id()); StartTracing(); RemoveAllNonRootFrames(); StopTracing(); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer = CreateTraceAnalyzer(); trace_analyzer::TraceEventVector events; trace_analyzer::Query q = trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_DELETE_OBJECT); analyzer->FindEvents(q, &events); // The removal of all non-root nodes should be traced. EXPECT_EQ(6u, events.size()); for (auto* event : events) { ExpectFrameTreeNodeObject(event); int id = strtol(event->id.c_str(), nullptr, 16); EXPECT_TRUE(base::ContainsValue(node_ids, id)); node_ids.erase(id); } } // Changes URL of the root node. Tests if URL change is correctly traced. TEST_F(FrameTreeNodeBlameContextTest, URLChange) { main_test_rfh()->InitializeRenderFrameIfNeeded(); GURL url1("http://a.com/"); GURL url2("https://b.net/"); StartTracing(); root()->SetCurrentURL(url1); root()->SetCurrentURL(url2); root()->ResetForNewProcess(); StopTracing(); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer = CreateTraceAnalyzer(); trace_analyzer::TraceEventVector events; trace_analyzer::Query q = trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_SNAPSHOT_OBJECT); analyzer->FindEvents(q, &events); std::sort(events.begin(), events.end(), EventPointerCompare); // Three snapshots are traced, one for each URL change. EXPECT_EQ(3u, events.size()); EXPECT_EQ(url1.spec(), GetSnapshotURL(events[0])); EXPECT_EQ(url2.spec(), GetSnapshotURL(events[1])); EXPECT_EQ("", GetSnapshotURL(events[2])); } } // namespace content
[ "hedonist.ky@gmail.com" ]
hedonist.ky@gmail.com
91ca9875328533b9e827ba7457b60e94d5df0e1b
c3106e8b2d46dc5c23dd1797b00462f2873dd321
/Codeforces/Contest954/A.Diagonal_Walking.cpp
efd38e030971b180c102ead7815f57ae0f086eb0
[]
no_license
cppaymurat/Codeforces_contests
00dfa66b6b3ce60566c044633ba3a4bd731356fb
2e900f372af6c67b07f8700a60baa0bdb24d9b2e
refs/heads/main
2023-05-25T07:41:23.063186
2021-06-06T14:26:06
2021-06-06T14:26:06
374,211,344
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; string str; cin>>n; cin>>str; string save = str; int k = str.find("UR"); int c = 0; int ans1 = n; int ans2 = n; for(int i = 0; i < str.length(); i++) { if (str[i] == 'U' && str[i + 1] == 'R' && i + 1 < str.length()) { ans1--; i++; } else if (str[i] == 'R' && str[i + 1] == 'U' && i + 1 < str.length()) { ans1--; i++; } } cout<<ans1; return 0; }
[ "cppaymurat@gmail.com" ]
cppaymurat@gmail.com
b272922eb039f3cf9e7b2a39591d862cf571c7e2
19999e0f98e2077e8207e54350fb701a5a04c22e
/Placement/subPlacement.cxx
4355cecd944809548836a613d820be9ec2a54962
[ "MIT" ]
permissive
wangjiaqingll/UMICH-Physical-Design-Tools
e9e26977554e585e181be6394f6b2428ac9105d1
fa0d990fc9def762e3a2843707a7d8a4784d2f8b
refs/heads/master
2022-11-13T11:05:36.106620
2020-07-13T06:35:26
2020-07-13T06:35:26
277,409,848
1
1
null
null
null
null
UTF-8
C++
false
false
4,193
cxx
/************************************************************************** *** *** Copyright (c) 1995-2000 Regents of the University of California, *** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov *** Copyright (c) 2000-2002 Regents of the University of Michigan, *** Saurabh N. Adya and Igor L. Markov *** *** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu *** Original Affiliation: UCLA, Computer Science Department, *** Los Angeles, CA 90095-1596 USA *** *** 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. *** *** ***************************************************************************/ // Created: Igor Markov, VLSI CAD ABKGROUP UCLA, June 15, 1997. #ifdef _MSC_VER #pragma warning (disable:4786) #endif #include <iostream> #include <string.h> #include "ABKCommon/abkcommon.h" #include "Geoms/plGeom.h" #include "subPlacement.h" Point SubPlacement::getCenterOfGravity() const { Point cog(0,0); for (unsigned i=0; i<getSize(); i++) { cog.x+=points(i).x; cog.y+=points(i).y; } cog.x/=getSize(); cog.y/=getSize(); return cog; } Point SubPlacement::getCenterOfGravity(double * weights) const { Point cog(0,0); for (unsigned i=0; i<getSize(); i++) { cog.x+=weights[i]*points(i).x; cog.y+=weights[i]*points(i).y; } cog.x/=getSize(); cog.y/=getSize(); return cog; } double SubPlacement::getPolygonArea() const { double area=0.0; for (unsigned i=0; i<getSize()-1; i++) area+=points(i).x * points(i+1).y - points(i+1).x * points(i).y; area+=points(getSize()-1).x * points(0).y - points(0).x*points(getSize()-1).y; return 0.5*area; } bool SubPlacement::isInsidePolygon(const Point& p) const { unsigned counter = 0; unsigned i; double xinters; Point p1,p2; p1 = points(0); for (i=0;i<getSize();i++) { p2 = points(i % getSize()); if (p.y > min(p1.y,p2.y)) { if (p.y <= max(p1.y,p2.y)) { if (p.x <= max(p1.x,p2.x)) { if (p1.y != p2.y) { xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x; if (p1.x == p2.x || p.x <= xinters) counter++; } } } } p1 = p2; } if (counter % 2 == 0) return(false); // outisde else return(true); // inside } ostream& operator<<(ostream& out, const SubPlacement& arg) { TimeStamp tm; out << tm; out << " Total points in sub placement : " << arg.getSize() << endl; for (unsigned i=0; i<arg.getSize(); i++) out << arg.points(i) << endl ; return out; } #ifndef AUTHMAR #define AUTHMAR static const char AuthorMarkov[50]="062897, Igor Markov, VLSI CAD ABKGROUP UCLA"; #endif double operator- (const SubPlacement& arg1, const SubPlacement& arg2) /* returns the Linf distance between placements which you can compare then to epsilon */ { abkfatal(arg1.getSize()==arg2.getSize()," Comparing placements of different size"); double dst,max=0; for (unsigned i=0; i < arg1.getSize(); i++) { dst=mDist(arg1[i],arg2[i]); if (max < dst) max=dst; } return max; }
[ "wangjiaqing.ll@qq.com" ]
wangjiaqing.ll@qq.com
670ab8519fdce99ba6c442f032af7b45d05fd1b6
b53795b88ab0201e48c5dc5737e97dfd27e07b22
/source/client/source/eterLib/GrpScreen.cpp
24bd73e07033d3abab3b59bb576a6c24279a13d3
[]
no_license
davidkm2/globalmetin
9cc63395974eb74b5784a1bf5e733622c7303aa4
d1a21b549c68e311416544e03ca6218351e12d2f
refs/heads/main
2023-05-27T08:10:08.506239
2021-05-24T01:57:37
2021-05-24T01:57:37
370,181,109
2
1
null
null
null
null
UTF-8
C++
false
false
25,262
cpp
#include "StdAfx.h" #include "GrpScreen.h" #include "Camera.h" #include "StateManager.h" DWORD CScreen::ms_diffuseColor = 0xffffffff; DWORD CScreen::ms_clearColor = 0L; DWORD CScreen::ms_clearStencil = 0L; float CScreen::ms_clearDepth = 1.0f; Frustum CScreen::ms_frustum; void CScreen::RenderLine3d(float sx, float sy, float sz, float ex, float ey, float ez) { assert(ms_lpd3dDevice != NULL); SPDTVertexRaw vertices[2] = { { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, ez, ms_diffuseColor, 0.0f, 0.0f } }; if (SetPDTStream(vertices, 2)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1); STATEMANAGER.DrawPrimitive(D3DPT_LINELIST, 0, 1); } } void CScreen::RenderBox3d(float sx, float sy, float sz, float ex, float ey, float ez) { assert(ms_lpd3dDevice != NULL); SPDTVertexRaw vertices[8] = { { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex+1.0f, ey, ez, ms_diffuseColor, 0.0f, 0.0f } }; if (SetPDTStream(vertices, 8)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.DrawPrimitive(D3DPT_LINELIST, 0, 4); } } void CScreen::RenderBar3d(float sx, float sy, float sz, float ex, float ey, float ez) { assert(ms_lpd3dDevice != NULL); SPDTVertexRaw vertices[4] = { { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, }; if (SetPDTStream(vertices, 4)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } } void CScreen::RenderBar3d(const D3DXVECTOR3 * c_pv3Positions) { assert(ms_lpd3dDevice != NULL); SPDTVertexRaw vertices[4] = { { c_pv3Positions[0].x, c_pv3Positions[0].y, c_pv3Positions[0].z, ms_diffuseColor, 0.0f, 0.0f }, { c_pv3Positions[2].x, c_pv3Positions[2].y, c_pv3Positions[2].z, ms_diffuseColor, 0.0f, 0.0f }, { c_pv3Positions[1].x, c_pv3Positions[1].y, c_pv3Positions[1].z, ms_diffuseColor, 0.0f, 0.0f }, { c_pv3Positions[3].x, c_pv3Positions[3].y, c_pv3Positions[3].z, ms_diffuseColor, 0.0f, 0.0f }, }; if (SetPDTStream(vertices, 4)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } } void CScreen::RenderGradationBar3d(float sx, float sy, float sz, float ex, float ey, float ez, DWORD dwStartColor, DWORD dwEndColor) { assert(ms_lpd3dDevice != NULL); if (sx==ex) return; if (sy==ey) return; SPDTVertexRaw vertices[4] = { { sx, sy, sz, dwStartColor, 0.0f, 0.0f }, { sx, ey, ez, dwEndColor, 0.0f, 0.0f }, { ex, sy, sz, dwStartColor, 0.0f, 0.0f }, { ex, ey, ez, dwEndColor, 0.0f, 0.0f }, }; if (SetPDTStream(vertices, 4)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } } void CScreen::RenderLineCube(float sx, float sy, float sz, float ex, float ey, float ez) { SPDTVertexRaw vertices[8] = { { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, sy, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, ez, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, }; if (SetPDTStream(vertices, 8)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.SetTransform(D3DTS_WORLD, ms_lpd3dMatStack->GetTop()); SetDefaultIndexBuffer(DEFAULT_IB_LINE_CUBE); STATEMANAGER.DrawIndexedPrimitive(D3DPT_LINELIST, 0, 8, 0, 4*3); } } void CScreen::RenderCube(float sx, float sy, float sz, float ex, float ey, float ez) { SPDTVertexRaw vertices[8] = { { sx, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, sz, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, sz, ms_diffuseColor, 0.0f, 0.0f }, { sx, sy, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, sy, ez, ms_diffuseColor, 0.0f, 0.0f }, { sx, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, { ex, ey, ez, ms_diffuseColor, 0.0f, 0.0f }, }; if (SetPDTStream(vertices, 8)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.SetTransform(D3DTS_WORLD, ms_lpd3dMatStack->GetTop()); SetDefaultIndexBuffer(DEFAULT_IB_FILL_CUBE); STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 8, 0, 4*3); } } void CScreen::RenderCube(float sx, float sy, float sz, float ex, float ey, float ez, D3DXMATRIX matRotation) { D3DXVECTOR3 v3Center = D3DXVECTOR3((sx + ex) * 0.5f, (sy + ey) * 0.5f, (sz + ez) * 0.5f); D3DXVECTOR3 v3Vertex[8] = { D3DXVECTOR3(sx, sy, sz), D3DXVECTOR3(ex, sy, sz), D3DXVECTOR3(sx, ey, sz), D3DXVECTOR3(ex, ey, sz), D3DXVECTOR3(sx, sy, ez), D3DXVECTOR3(ex, sy, ez), D3DXVECTOR3(sx, ey, ez), D3DXVECTOR3(ex, ey, ez), }; SPDTVertexRaw vertices[8]; for(int i = 0; i < 8; i++) { v3Vertex[i] = v3Vertex[i] - v3Center; D3DXVec3TransformCoord(&v3Vertex[i], &v3Vertex[i], &matRotation); v3Vertex[i] = v3Vertex[i] + v3Center; vertices[i].px = v3Vertex[i].x; vertices[i].py = v3Vertex[i].y; vertices[i].pz = v3Vertex[i].z; vertices[i].diffuse = ms_diffuseColor; vertices[i].u = 0.0f; vertices[i].v = 0.0f; } if (SetPDTStream(vertices, 8)) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); STATEMANAGER.SetTransform(D3DTS_WORLD, ms_lpd3dMatStack->GetTop()); SetDefaultIndexBuffer(DEFAULT_IB_FILL_CUBE); STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 8, 0, 4*3); } } void CScreen::RenderLine2d(float sx, float sy, float ex, float ey, float z) { RenderLine3d(sx, sy, z, ex, ey, z); } void CScreen::RenderBox2d(float sx, float sy, float ex, float ey, float z) { RenderBox3d(sx, sy, z, ex, ey, z); } void CScreen::RenderBar2d(float sx, float sy, float ex, float ey, float z) { RenderBar3d(sx, sy, z, ex, ey, z); } void CScreen::RenderGradationBar2d(float sx, float sy, float ex, float ey, DWORD dwStartColor, DWORD dwEndColor, float ez) { RenderGradationBar3d(sx, sy, ez, ex, ey, ez, dwStartColor, dwEndColor); } void CScreen::RenderCircle2d(float fx, float fy, float fz, float fRadius, int iStep) { int count; float theta, delta; float x, y, z; std::vector<D3DXVECTOR3> pts; pts.clear(); pts.resize(iStep); theta = 0.0; delta = 2 * D3DX_PI / float(iStep); for (count=0; count<iStep; count++) { x = fx + fRadius * cosf(theta); y = fy + fRadius * sinf(theta); z = fz; pts[count] = D3DXVECTOR3(x, y, z); theta += delta; } for (count=0; count<iStep - 1; count++) { RenderLine3d(pts[count].x, pts[count].y, pts[count].z, pts[count + 1].x, pts[count + 1].y, pts[count + 1].z); } RenderLine3d(pts[iStep - 1].x, pts[iStep - 1].y, pts[iStep - 1].z, pts[0].x, pts[0].y, pts[0].z); } void CScreen::RenderCircle3d(float fx, float fy, float fz, float fRadius, int iStep) { int count; float theta, delta; std::vector<D3DXVECTOR3> pts; pts.clear(); pts.resize(iStep); theta = 0.0; delta = 2 * D3DX_PI / float(iStep); const D3DXMATRIX & c_rmatInvView = CCameraManager::Instance().GetCurrentCamera()->GetBillboardMatrix(); for (count=0; count<iStep; count++) { pts[count] = D3DXVECTOR3(fRadius * cosf(theta), fRadius * sinf(theta), 0.0f); D3DXVec3TransformCoord(&pts[count], &pts[count], &c_rmatInvView); theta += delta; } for (count=0; count<iStep - 1; count++) { RenderLine3d(fx+pts[count].x, fy+pts[count].y, fz+pts[count].z, fx+pts[count + 1].x, fy+pts[count + 1].y, fz+pts[count + 1].z); } RenderLine3d(fx+pts[iStep - 1].x, fy+pts[iStep - 1].y, fz+pts[iStep - 1].z, fx+pts[0].x, fy+pts[0].y, fz+pts[0].z); } class CD3DXMeshRenderingOption : public CScreen { public: DWORD m_dwVS; CD3DXMeshRenderingOption(D3DFILLMODE d3dFillMode, const D3DXMATRIX & c_rmatWorld) { ms_lpd3dDevice->GetFVF(&m_dwVS); STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR); STATEMANAGER.SaveTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); STATEMANAGER.SaveTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE); STATEMANAGER.SetRenderState(D3DRS_FILLMODE, d3dFillMode); STATEMANAGER.SaveTransform(D3DTS_WORLD, &c_rmatWorld); STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); } virtual ~CD3DXMeshRenderingOption() { ms_lpd3dDevice->SetFVF(m_dwVS); STATEMANAGER.RestoreTransform(D3DTS_WORLD); STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLORARG1); STATEMANAGER.RestoreTextureStageState(0, D3DTSS_COLOROP); STATEMANAGER.RestoreTextureStageState(0, D3DTSS_ALPHAOP); STATEMANAGER.SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); } }; void CScreen::RenderD3DXMesh(LPD3DXMESH lpMesh, const D3DXMATRIX * c_pmatWorld, float fx, float fy, float fz, float fRadius, D3DFILLMODE d3dFillMode) { D3DXMATRIX matTranslation; D3DXMATRIX matScaling; D3DXMatrixTranslation(&matTranslation, fx, fy, fz); D3DXMatrixScaling(&matScaling, fRadius, fRadius, fRadius); D3DXMATRIX matWorld; matWorld = matScaling * matTranslation; if (c_pmatWorld) { matWorld *= *c_pmatWorld; } CD3DXMeshRenderingOption SetRenderingOption(d3dFillMode, matWorld); LPDIRECT3DINDEXBUFFER9 lpIndexBuffer; LPDIRECT3DVERTEXBUFFER9 lpVertexBuffer; lpMesh->GetIndexBuffer(&lpIndexBuffer); lpMesh->GetVertexBuffer(&lpVertexBuffer); STATEMANAGER.SetFVF(lpMesh->GetFVF()); STATEMANAGER.SetIndices(lpIndexBuffer, 0); STATEMANAGER.SetStreamSource(0, lpVertexBuffer, 24); STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, lpMesh->GetNumVertices(), 0, lpMesh->GetNumFaces()); } void CScreen::RenderSphere(const D3DXMATRIX * c_pmatWorld, float fx, float fy, float fz, float fRadius, D3DFILLMODE d3dFillMode) { RenderD3DXMesh(ms_lpSphereMesh, c_pmatWorld, fx, fy, fz, fRadius, d3dFillMode); } void CScreen::RenderCylinder(const D3DXMATRIX * c_pmatWorld, float fx, float fy, float fz, float fRadius, float /*fLength*/, D3DFILLMODE d3dFillMode) { RenderD3DXMesh(ms_lpCylinderMesh, c_pmatWorld, fx, fy, fz, fRadius, d3dFillMode); } void CScreen::RenderTextureBox(float sx, float sy, float ex, float ey, float z, float su, float sv, float eu, float ev) { assert(ms_lpd3dDevice != NULL); TPDTVertex vertices[4]; vertices[0].position = TPosition(sx, sy, z); vertices[0].diffuse = ms_diffuseColor; vertices[0].texCoord = TTextureCoordinate(su, sv); vertices[1].position = TPosition(ex, sy, z); vertices[1].diffuse = ms_diffuseColor; vertices[1].texCoord = TTextureCoordinate(eu, sv); vertices[2].position = TPosition(sx, ey, z); vertices[2].diffuse = ms_diffuseColor; vertices[2].texCoord = TTextureCoordinate(su, ev); vertices[3].position = TPosition(ex, ey, z); vertices[3].diffuse = ms_diffuseColor; vertices[3].texCoord = TTextureCoordinate(eu, ev); #ifdef WORLD_EDITOR STATEMANAGER.SetTransform(D3DTS_WORLD, ms_lpd3dMatStack->GetTop()); #endif STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); SetDefaultIndexBuffer(DEFAULT_IB_FILL_RECT); if (SetPDTStream(vertices, 4)) STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 4, 0, 2); } void CScreen::RenderBillboard(D3DXVECTOR3 * Position, D3DXCOLOR & Color) { assert(ms_lpd3dDevice != NULL); TPDTVertex vertices[4]; vertices[0].position = TPosition(Position[0].x, Position[0].y, Position[0].z); vertices[0].diffuse = Color; vertices[0].texCoord = TTextureCoordinate(0, 0); vertices[1].position = TPosition(Position[1].x, Position[1].y, Position[1].z); vertices[1].diffuse = Color; vertices[1].texCoord = TTextureCoordinate(1, 0); vertices[2].position = TPosition(Position[2].x, Position[2].y, Position[2].z); vertices[2].diffuse = Color; vertices[2].texCoord = TTextureCoordinate(0, 1); vertices[3].position = TPosition(Position[3].x, Position[3].y, Position[3].z); vertices[3].diffuse = Color; vertices[3].texCoord = TTextureCoordinate(1, 1); STATEMANAGER.SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); SetDefaultIndexBuffer(DEFAULT_IB_FILL_RECT); if (SetPDTStream(vertices, 4)) STATEMANAGER.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 4, 0, 2); } void CScreen::DrawMinorGrid(float xMin, float yMin, float xMax, float yMax, float xminorStep, float yminorStep, float zPos) { float x, y; for (y = yMin; y <= yMax; y += yminorStep) RenderLine2d(xMin, y, xMax, y, zPos); for (x = xMin; x <= xMax; x += xminorStep) RenderLine2d(x, yMin, x, yMax, zPos); } void CScreen::DrawGrid(float xMin, float yMin, float xMax, float yMax, float xmajorStep, float ymajorStep, float xminorStep, float yminorStep, float zPos) { xMin*=xminorStep; xMax*=xminorStep; yMin*=yminorStep; yMax*=yminorStep; xmajorStep*=xminorStep; ymajorStep*=yminorStep; float x, y; SetDiffuseColor(0.5f, 0.5f, 0.5f); DrawMinorGrid(xMin, yMin, xMax, yMax, xminorStep, yminorStep, zPos); SetDiffuseColor(0.7f, 0.7f, 0.7f); for (y = 0.0f; y >= yMin; y -= ymajorStep) RenderLine2d(xMin, y, xMax, y, zPos); for (y = 0.0f; y <= yMax; y += ymajorStep) RenderLine2d(xMin, y, xMax, y, zPos); for (x = 0.0f; x >= xMin; x -= xmajorStep) RenderLine2d(x, yMin, x, yMax, zPos); for (x = 0.0f; x <= yMax; x += xmajorStep) RenderLine2d(x, yMin, x, yMax, zPos); SetDiffuseColor(1.0f, 1.0f, 1.0f); RenderLine2d(xMin, 0.0f, xMax, 0.0f, zPos); RenderLine2d(0.0f, yMin, 0.0f, yMax, zPos); } void CScreen::SetCursorPosition(int x, int y, int hres, int vres) { D3DXVECTOR3 v; v.x = -(((2.0f * x) / hres) - 1) / ms_matProj._11; v.y = (((2.0f * y) / vres) - 1) / ms_matProj._22; v.z = 1.0f; D3DXMATRIX matViewInverse=ms_matInverseView; ms_vtPickRayDir.x = v.x * matViewInverse._11 + v.y * matViewInverse._21 + v.z * matViewInverse._31; ms_vtPickRayDir.y = v.x * matViewInverse._12 + v.y * matViewInverse._22 + v.z * matViewInverse._32; ms_vtPickRayDir.z = v.x * matViewInverse._13 + v.y * matViewInverse._23 + v.z * matViewInverse._33; ms_vtPickRayOrig.x = matViewInverse._41; ms_vtPickRayOrig.y = matViewInverse._42; ms_vtPickRayOrig.z = matViewInverse._43; ms_Ray.SetStartPoint(ms_vtPickRayOrig); ms_Ray.SetDirection(-ms_vtPickRayDir, 51200.0f); } bool CScreen::GetCursorPosition(float* px, float* py, float* pz) { if (!GetCursorXYPosition(px, py)) return false; if (!GetCursorZPosition(pz)) return false; return true; } bool CScreen::GetCursorXYPosition(float* px, float* py) { D3DXVECTOR3 v3Eye = CCameraManager::Instance().GetCurrentCamera()->GetEye(); TPosition posVertices[4]; posVertices[0] = TPosition(v3Eye.x-90000000.0f, v3Eye.y+90000000.0f, 0.0f); posVertices[1] = TPosition(v3Eye.x-90000000.0f, v3Eye.y-90000000.0f, 0.0f); posVertices[2] = TPosition(v3Eye.x+90000000.0f, v3Eye.y+90000000.0f, 0.0f); posVertices[3] = TPosition(v3Eye.x+90000000.0f, v3Eye.y-90000000.0f, 0.0f); static const WORD sc_awFillRectIndices[6] = { 0, 2, 1, 2, 3, 1, }; float u, v, t; for (int i = 0; i < 2; ++i) { if (IntersectTriangle(ms_vtPickRayOrig, ms_vtPickRayDir, posVertices[sc_awFillRectIndices[i*3+0]], posVertices[sc_awFillRectIndices[i*3+1]], posVertices[sc_awFillRectIndices[i*3+2]], &u, &v, &t)) { *px = ms_vtPickRayOrig.x + ms_vtPickRayDir.x * t; *py = ms_vtPickRayOrig.y + ms_vtPickRayDir.y * t; return true; } } return false; } bool CScreen::GetCursorZPosition(float* pz) { D3DXVECTOR3 v3Eye = CCameraManager::Instance().GetCurrentCamera()->GetEye(); TPosition posVertices[4]; posVertices[0] = TPosition(v3Eye.x-90000000.0f, 0.0f, v3Eye.z+90000000.0f); posVertices[1] = TPosition(v3Eye.x-90000000.0f, 0.0f, v3Eye.z-90000000.0f); posVertices[2] = TPosition(v3Eye.x+90000000.0f, 0.0f, v3Eye.z+90000000.0f); posVertices[3] = TPosition(v3Eye.x+90000000.0f, 0.0f, v3Eye.z-90000000.0f); static const WORD sc_awFillRectIndices[6] = { 0, 2, 1, 2, 3, 1, }; float u, v, t; for (int i = 0; i < 2; ++i) { if (IntersectTriangle(ms_vtPickRayOrig, ms_vtPickRayDir, posVertices[sc_awFillRectIndices[i*3+0]], posVertices[sc_awFillRectIndices[i*3+1]], posVertices[sc_awFillRectIndices[i*3+2]], &u, &v, &t)) { *pz = ms_vtPickRayOrig.z + ms_vtPickRayDir.z * t; return true; } } return false; } void CScreen::GetPickingPosition(float t, float* x, float* y, float* z) { *x = ms_vtPickRayOrig.x + ms_vtPickRayDir.x * t; *y = ms_vtPickRayOrig.y + ms_vtPickRayDir.y * t; *z = ms_vtPickRayOrig.z + ms_vtPickRayDir.z * t; } void CScreen::SetDiffuseColor(DWORD diffuseColor) { ms_diffuseColor = diffuseColor; } void CScreen::SetDiffuseColor(float r, float g, float b, float a) { ms_diffuseColor = GetColor(r, g, b, a); } void CScreen::SetClearColor(float r, float g, float b, float a) { ms_clearColor = GetColor(r, g, b, a); } void CScreen::SetClearDepth(float depth) { ms_clearDepth = depth; } void CScreen::SetClearStencil(DWORD stencil) { ms_clearStencil = stencil; } void CScreen::ClearDepthBuffer() { assert(ms_lpd3dDevice != NULL); ms_lpd3dDevice->Clear(0L, NULL, D3DCLEAR_ZBUFFER, ms_clearColor, ms_clearDepth, ms_clearStencil); } void CScreen::Clear() { assert(ms_lpd3dDevice != NULL); ms_lpd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, ms_clearColor, ms_clearDepth, ms_clearStencil); } BOOL CScreen::IsLostDevice() { if (!ms_lpd3dDevice) return TRUE; IDirect3DDevice9 & rkD3DDev = *ms_lpd3dDevice; HRESULT hrTestCooperativeLevel = rkD3DDev.TestCooperativeLevel(); if (FAILED(hrTestCooperativeLevel)) return TRUE; return FALSE; } BOOL CScreen::RestoreDevice() { if (!ms_lpd3dDevice) return FALSE; UINT iD3DAdapterInfo = ms_iD3DAdapterInfo; IDirect3D9 & rkD3D = *ms_lpd3d; IDirect3DDevice9 & rkD3DDev = *ms_lpd3dDevice; D3DPRESENT_PARAMETERS & rkD3DPP = ms_d3dPresentParameter; D3D_CDisplayModeAutoDetector & rkD3DDetector = ms_kD3DDetector; HRESULT hrTestCooperativeLevel = rkD3DDev.TestCooperativeLevel(); if (FAILED(hrTestCooperativeLevel)) { if (D3DERR_DEVICELOST == hrTestCooperativeLevel) { return FALSE; } if (D3DERR_DEVICENOTRESET == hrTestCooperativeLevel) { D3D_CAdapterInfo* pkD3DAdapterInfo = rkD3DDetector.GetD3DAdapterInfop(ms_iD3DAdapterInfo); if (!pkD3DAdapterInfo) return FALSE; D3DDISPLAYMODE & rkD3DDMDesktop = pkD3DAdapterInfo->GetDesktopD3DDisplayModer(); if (FAILED(rkD3D.GetAdapterDisplayMode(iD3DAdapterInfo, &rkD3DDMDesktop))) return FALSE; rkD3DPP.BackBufferFormat = rkD3DDMDesktop.Format; HRESULT hrReset = rkD3DDev.Reset(&rkD3DPP); if (FAILED(hrReset)) { return FALSE; } STATEMANAGER.SetDefaultState(); } } return TRUE; } bool CScreen::Begin() { assert(ms_lpd3dDevice != NULL); ResetFaceCount(); if (!STATEMANAGER.BeginScene()) { Tracenf("BeginScene FAILED\n"); return false; } return true; } void CScreen::End() { STATEMANAGER.EndScene(); } extern bool g_isBrowserMode; extern RECT g_rcBrowser; void CScreen::Show(HWND hWnd) { assert(ms_lpd3dDevice != NULL); if (g_isBrowserMode) { RECT rcTop={0, 0, ms_d3dPresentParameter.BackBufferWidth, g_rcBrowser.top}; RECT rcBottom={0, g_rcBrowser.bottom, ms_d3dPresentParameter.BackBufferWidth, ms_d3dPresentParameter.BackBufferHeight}; RECT rcLeft={0, g_rcBrowser.top, g_rcBrowser.left, g_rcBrowser.bottom}; RECT rcRight={g_rcBrowser.right, g_rcBrowser.top, ms_d3dPresentParameter.BackBufferWidth, g_rcBrowser.bottom}; ms_lpd3dDevice->Present(&rcTop, &rcTop, hWnd, NULL); ms_lpd3dDevice->Present(&rcBottom, &rcBottom, hWnd, NULL); ms_lpd3dDevice->Present(&rcLeft, &rcLeft, hWnd, NULL); ms_lpd3dDevice->Present(&rcRight, &rcRight, hWnd, NULL); } else { HRESULT hr=ms_lpd3dDevice->Present(NULL, NULL, hWnd, NULL); if (D3DERR_DEVICELOST == hr) RestoreDevice(); } } void CScreen::Show(RECT * pSrcRect) { assert(ms_lpd3dDevice != NULL); ms_lpd3dDevice->Present(pSrcRect, NULL, NULL, NULL); } void CScreen::Show(RECT * pSrcRect, HWND hWnd) { assert(ms_lpd3dDevice != NULL); ms_lpd3dDevice->Present(pSrcRect, NULL, hWnd, NULL); } void CScreen::ProjectPosition(float x, float y, float z, float * pfX, float * pfY) { D3DXVECTOR3 Input(x, y, z); D3DXVECTOR3 Output; D3DXVec3Project(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matWorld); *pfX = Output.x; *pfY = Output.y; } void CScreen::ProjectPosition(float x, float y, float z, float * pfX, float * pfY, float * pfZ) { D3DXVECTOR3 Input(x, y, z); D3DXVECTOR3 Output; D3DXVec3Project(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matWorld); *pfX = Output.x; *pfY = Output.y; *pfZ = Output.z; } void CScreen::UnprojectPosition(float x, float y, float z, float * pfX, float * pfY, float * pfZ) { D3DXVECTOR3 Input(x, y, z); D3DXVECTOR3 Output; D3DXVec3Unproject(&Output, &Input, &ms_Viewport, &ms_matProj, &ms_matView, &ms_matWorld); *pfX = Output.x; *pfY = Output.y; *pfZ = Output.z; } void CScreen::SetColorOperation() { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE); STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); } void CScreen::SetDiffuseOperation() { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); } void CScreen::SetBlendOperation() { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); STATEMANAGER.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); STATEMANAGER.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); STATEMANAGER.SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); } void CScreen::SetOneColorOperation(D3DXCOLOR & rColor) { STATEMANAGER.SetTexture(0, NULL); STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, rColor); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); } void CScreen::SetAddColorOperation(D3DXCOLOR & rColor) { STATEMANAGER.SetRenderState(D3DRS_TEXTUREFACTOR, rColor); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR); STATEMANAGER.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD); } void CScreen::Identity() { STATEMANAGER.SetTransform(D3DTS_WORLD, &ms_matIdentity); } CScreen::CScreen() { } CScreen::~CScreen() { } void CScreen::BuildViewFrustum() { const D3DXVECTOR3& c_rv3Eye=CCameraManager::Instance().GetCurrentCamera()->GetEye(); const D3DXVECTOR3& c_rv3View=CCameraManager::Instance().GetCurrentCamera()->GetView(); ms_frustum.BuildViewFrustum2( ms_matView*ms_matProj, ms_fNearY, ms_fFarY, ms_fFieldOfView, ms_fAspect, c_rv3Eye, c_rv3View); }
[ "davidkm2012@gmail.com" ]
davidkm2012@gmail.com
df1a53295f99ee5f3cb78c07223de4f5b3dfeaf9
12d8ebc3ae6c59de8e2050e35df260d113704ef5
/source/shared/cgdlCStringUtils.cpp
fe3b4f0fde52823b03531aaa379a0a7c2ce9ddb0
[ "MIT" ]
permissive
graveman82/cgdl
46f7b4d61e3cc463d2dc4e31cdcd44808469a259
6418de44aab4e3b98adf197d54401081c2d61f3f
refs/heads/master
2023-08-14T09:34:12.070346
2021-10-13T08:41:41
2021-10-13T08:41:41
415,200,550
0
0
null
null
null
null
UTF-8
C++
false
false
2,077
cpp
/* //----------------------------------------------------------------------------- MIT License Project: CGDL (Common Game Development Library) Copyright (c) 2021 Marat Sungatullin (aka graveman[82], aka MrSung[82]) 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. //----------------------------------------------------------------------------- Purpose: Implementation of C string utils.. Changes (date, description): 2021-10-09 creation from scratch //----------------------------------------------------------------------------- */ #include <stdio.h> #include "shared/cgdlIntegers.h" namespace cgdl { //----------------------------------------------------------------------------- const char* ToCString(SizeU32 n) { static char buf[32] = {0}; sprintf(buf, "%u", n); return &buf[0]; } //----------------------------------------------------------------------------- const char* ToCString(const void* p) { static char buf[32] = {0}; sprintf(buf, "%p", p); return &buf[0]; } } // end of cgdl
[ "MrSungWork" ]
MrSungWork
6ae6993e51d702134ccb6faa3cb240427f5bc72f
9f59296d69ad77f192b24ee64d3e20425e125d28
/Plugins/SceneFusion/Source/SceneFusion/Private/Testing/sfDeleteActivity.h
acafba78fcf5460692db0fd647b94eb96cc47f8e
[]
no_license
Carp3d/SPARAJJ_World
67420f60500f2ca2bdaca627a6b1bc20857a1bc9
7fbb6bb2cc039c855c52f419137fb535d35dd1a9
refs/heads/master
2022-12-18T23:33:34.085627
2020-09-26T18:24:26
2020-09-26T18:24:26
238,057,306
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
#pragma once #include "sfBaseActivity.h" /** * Activity that deletes random actors from the level. */ class sfDeleteActivity : public sfBaseActivity { public: /** * Constructor * * @param const FString& name of activity. * @param float weight the determines how likely this activity is to occur. */ sfDeleteActivity(const FString& name, float weight); /** * Deletes random actors from the level. */ virtual void Start() override; };
[ "57542114+nyxxaltios@users.noreply.github.com" ]
57542114+nyxxaltios@users.noreply.github.com
4bfed7d03d5884b41fc17a7458215896031e4250
47250118d472ff8ae6af5af9d889a7b2206efa5e
/libif2k/old/if2k_win32install_expertmain.cpp
a1b3ce5d2ebb0f345dfe9328328ea4b46ede7073
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
jdkoftinoff/if2kv2
383d043419689a3c7716d2fe20fcb3442e5af2c8
167631c34b684001c2d5b762bdfd3e45e2699cad
refs/heads/master
2016-09-05T16:54:09.544832
2015-04-25T18:30:33
2015-04-25T18:30:33
34,580,580
0
1
null
null
null
null
UTF-8
C++
false
false
2,126
cpp
#if JDK_IS_WIN32 #include "jdk_world.h" #include "jdk_bindir.h" #include "wninstall.h" #include "jdk_string.h" #include "jdk_settings.h" #include "jdk_util.h" #include "jdk_lz.h" #include "jdk_httprequest.h" #include "jdk_dynbuf.h" #include "if2k_config.h" #include "if2k_win32install_expert.h" #include "if2k_win32install_guts.h" int if2k_win32install_expert_main( int argc, char **argv ) { bool old_windows=false; jdk_set_app_name( IF2K_SHORT_SERVICE_NAME " install" ); if( !WNInstall_IsWinNT4() && !WNInstall_IsWin2000() && !WNInstall_IsWinXP() ) { old_windows=true; } if( !if2k_win32_check_old_versions() ) { return false; } jdk_settings_text install_settings; if( argc==1 ) { if( !install_settings.load_file( "settings.txt" ) ) { char msg[4096]; sprintf( msg, "Failed installation - Unable to load file:\n%s", "settings.txt" ); MessageBox( 0, msg, IF2K_TITLE, MB_OK ); return 1; } } if( argc>1 && argv[1][0]!='-' ) { // is the first parameter a url? if( strncmp( argv[1], "http://", 7 )==0 ) { // yes! try load the settings from the specified URL. jdk_dynbuf settings_buf; jdk_http_response_header response_header; if( jdk_http_get( argv[1], &settings_buf, 100*1024, &response_header, 0, false )==200 ) { // got it! now parse it install_settings.load_buf( settings_buf ); } else { char msg[4096]; sprintf( msg, "Failed installation - Unable to load URL:\n%s", argv[1] ); MessageBox( 0, msg, IF2K_TITLE, MB_OK ); return 1; } } else { if( !install_settings.load_file( argv[1] ) ) { char msg[4096]; sprintf( msg, "Failed installation - Unable to load file:\n%s", argv[1] ); MessageBox( 0, msg, IF2K_TITLE, MB_OK ); return 1; } } argc--; argv++; } jdk_set_home_dir( DEFAULT_APP_DIR ); install_settings.set_args(0,argc,argv ); jdk_str<4096> error_reason; if( !if2k_win32install( install_settings, old_windows, false, error_reason ) ) { //MessageBox( 0, "Failed installation", IF2002_TITLE, MB_OK ); return 1; } return 0; } #endif
[ "none@none" ]
none@none
f0e208bd6604aa39c010b0840cfcce73d632e5d1
1c52a71a1d6851842a13ff193771aed24e46318c
/codeforces/722-B/722-B-21096995.cpp
803526be3c3294001f3e502fb890e6719017aab0
[]
no_license
nimxor/competitive_progeamming
d19654b94478aa59ff2103b4433e613f1fdf5ff6
7caf1353a2e8fc3d423cc9711228fbb4fd1e9a97
refs/heads/master
2021-01-19T03:28:52.056161
2017-04-05T14:02:33
2017-04-05T14:02:33
87,314,559
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define mset(m,v) memset(m,v,sizeof(m)) #define pb push_back #define pob pop_back #define pof pop_front #define pf push_front #define mp make_pair #define fi first #define se second #define pi 3.1415926535897932384 #define mod 1000000007 #define sz 64 const ll maxi = 1e17; const int MAXM = 110; const int MAXN = 5e2+5; int main() { int n,i,j,k; cin>>n; int a[n]; for(i=0;i<n;i++){ cin>>a[i]; } string s; cin.ignore(); int ans=0; for(i=0;i<n;i++){ int cn=0; getline(cin,s); for(j=0;j<s.length();j++){ if(s[j]=='a' || s[j]=='e' || s[j]=='i' || s[j]=='o' || s[j]=='u' || s[j]=='y'){ cn++; } } if(cn==a[i]) ans++; } if(ans==n) cout<<"YES\n"; else cout<<"NO\n"; return 0; }
[ "shubhamgupta190496@gmail.com" ]
shubhamgupta190496@gmail.com
f38fd3cc36bd43ecbab1e3fbdc5220fa3e42c2a5
0eef83063c67480b41ec88146fd62ad126b4160b
/3rdparty/glslang/SPIRV/GlslangToSpv.cpp
05165a60c724a035ea2d64b9a39366d2a728bf0a
[ "BSD-2-Clause", "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
Crunkle/bgfx
4d081b7e1d8d10cd914778dd06a0b62afb382f6b
c87d8afd16d676a3f952568e595c17101ed424e8
refs/heads/master
2020-03-25T02:53:16.479256
2018-08-02T22:35:13
2018-08-02T22:35:13
143,311,916
0
0
BSD-2-Clause
2018-08-02T15:17:36
2018-08-02T15:17:35
null
UTF-8
C++
false
false
294,987
cpp
// // Copyright (C) 2014-2016 LunarG, Inc. // Copyright (C) 2015-2016 Google, Inc. // Copyright (C) 2017 ARM Limited. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // Neither the name of 3Dlabs Inc. Ltd. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Visit the nodes in the glslang intermediate tree representation to // translate them to SPIR-V. // #include "spirv.hpp" #include "GlslangToSpv.h" #include "SpvBuilder.h" namespace spv { #include "GLSL.std.450.h" #include "GLSL.ext.KHR.h" #include "GLSL.ext.EXT.h" #ifdef AMD_EXTENSIONS #include "GLSL.ext.AMD.h" #endif #ifdef NV_EXTENSIONS #include "GLSL.ext.NV.h" #endif } #if ENABLE_OPT #include "spirv-tools/optimizer.hpp" #include "message.h" #endif #if ENABLE_OPT using namespace spvtools; #endif // Glslang includes #include "../glslang/MachineIndependent/localintermediate.h" #include "../glslang/MachineIndependent/SymbolTable.h" #include "../glslang/Include/Common.h" #include "../glslang/Include/revision.h" #include <fstream> #include <iomanip> #include <list> #include <map> #include <stack> #include <string> #include <vector> namespace { namespace { class SpecConstantOpModeGuard { public: SpecConstantOpModeGuard(spv::Builder* builder) : builder_(builder) { previous_flag_ = builder->isInSpecConstCodeGenMode(); } ~SpecConstantOpModeGuard() { previous_flag_ ? builder_->setToSpecConstCodeGenMode() : builder_->setToNormalCodeGenMode(); } void turnOnSpecConstantOpMode() { builder_->setToSpecConstCodeGenMode(); } private: spv::Builder* builder_; bool previous_flag_; }; struct OpDecorations { spv::Decoration precision; spv::Decoration noContraction; spv::Decoration nonUniform; }; } // namespace // // The main holder of information for translating glslang to SPIR-V. // // Derives from the AST walking base class. // class TGlslangToSpvTraverser : public glslang::TIntermTraverser { public: TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options); virtual ~TGlslangToSpvTraverser() { } bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*); bool visitBinary(glslang::TVisit, glslang::TIntermBinary*); void visitConstantUnion(glslang::TIntermConstantUnion*); bool visitSelection(glslang::TVisit, glslang::TIntermSelection*); bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*); void visitSymbol(glslang::TIntermSymbol* symbol); bool visitUnary(glslang::TVisit, glslang::TIntermUnary*); bool visitLoop(glslang::TVisit, glslang::TIntermLoop*); bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*); void finishSpv(); void dumpSpv(std::vector<unsigned int>& out); protected: TGlslangToSpvTraverser(TGlslangToSpvTraverser&); TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&); spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier); spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier); spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier); spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration); spv::ImageFormat TranslateImageFormat(const glslang::TType& type); spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const; spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const; spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const; spv::StorageClass TranslateStorageClass(const glslang::TType&); void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType); spv::Id createSpvVariable(const glslang::TIntermSymbol*); spv::Id getSampledType(const glslang::TSampler&); spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&); spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult); void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle); spv::Id convertGlslangToSpvType(const glslang::TType& type); spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&, bool lastBufferBlockMember); bool filterMember(const glslang::TType& member); spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking, const glslang::TQualifier&); void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking, const glslang::TQualifier&, spv::Id); spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim); spv::Id accessChainLoad(const glslang::TType& type); void accessChainStore(const glslang::TType& type, spv::Id rvalue); void multiTypeStore(const glslang::TType&, spv::Id rValue); glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const; int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix); int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix); void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix); void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember); bool isShaderEntryPoint(const glslang::TIntermAggregate* node); bool writableParam(glslang::TStorageQualifier) const; bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam); void makeFunctions(const glslang::TIntermSequence&); void makeGlobalInitializers(const glslang::TIntermSequence&); void visitFunctions(const glslang::TIntermSequence&); void handleFunctionEntry(const glslang::TIntermAggregate* node); void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments); void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments); spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node); spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*); spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true); spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right); spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy); spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy); spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy); spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize); spv::Id makeSmearedConstant(spv::Id constant, int vectorSize); spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy); spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy); spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands); spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy); spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy); spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId); spv::Id getSymbolId(const glslang::TIntermSymbol* node); spv::Id createSpvConstant(const glslang::TIntermTyped&); spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant); bool isTrivialLeaf(const glslang::TIntermTyped* node); bool isTrivial(const glslang::TIntermTyped* node); spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right); #ifdef AMD_EXTENSIONS spv::Id getExtBuiltins(const char* name); #endif void addPre13Extension(const char* ext) { if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3) builder.addExtension(ext); } glslang::SpvOptions& options; spv::Function* shaderEntry; spv::Function* currentFunction; spv::Instruction* entryPoint; int sequenceDepth; spv::SpvBuildLogger* logger; // There is a 1:1 mapping between a spv builder and a module; this is thread safe spv::Builder builder; bool inEntryPoint; bool entryPointTerminated; bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface const glslang::TIntermediate* glslangIntermediate; spv::Id stdBuiltins; std::unordered_map<const char*, spv::Id> extBuiltinMap; std::unordered_map<int, spv::Id> symbolValues; std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer std::unordered_map<std::string, spv::Function*> functionMap; std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount]; // for mapping glslang block indices to spv indices (e.g., due to hidden members): std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; std::stack<bool> breakForLoop; // false means break for switch std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator; }; // // Helper functions for translating glslang representations to SPIR-V enumerants. // // Translate glslang profile to SPIR-V source language. spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile) { switch (source) { case glslang::EShSourceGlsl: switch (profile) { case ENoProfile: case ECoreProfile: case ECompatibilityProfile: return spv::SourceLanguageGLSL; case EEsProfile: return spv::SourceLanguageESSL; default: return spv::SourceLanguageUnknown; } case glslang::EShSourceHlsl: return spv::SourceLanguageHLSL; default: return spv::SourceLanguageUnknown; } } // Translate glslang language (stage) to SPIR-V execution model. spv::ExecutionModel TranslateExecutionModel(EShLanguage stage) { switch (stage) { case EShLangVertex: return spv::ExecutionModelVertex; case EShLangTessControl: return spv::ExecutionModelTessellationControl; case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation; case EShLangGeometry: return spv::ExecutionModelGeometry; case EShLangFragment: return spv::ExecutionModelFragment; case EShLangCompute: return spv::ExecutionModelGLCompute; default: assert(0); return spv::ExecutionModelFragment; } } // Translate glslang sampler type to SPIR-V dimensionality. spv::Dim TranslateDimensionality(const glslang::TSampler& sampler) { switch (sampler.dim) { case glslang::Esd1D: return spv::Dim1D; case glslang::Esd2D: return spv::Dim2D; case glslang::Esd3D: return spv::Dim3D; case glslang::EsdCube: return spv::DimCube; case glslang::EsdRect: return spv::DimRect; case glslang::EsdBuffer: return spv::DimBuffer; case glslang::EsdSubpass: return spv::DimSubpassData; default: assert(0); return spv::Dim2D; } } // Translate glslang precision to SPIR-V precision decorations. spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision) { switch (glslangPrecision) { case glslang::EpqLow: return spv::DecorationRelaxedPrecision; case glslang::EpqMedium: return spv::DecorationRelaxedPrecision; default: return spv::NoPrecision; } } // Translate glslang type to SPIR-V precision decorations. spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type) { return TranslatePrecisionDecoration(type.getQualifier().precision); } // Translate glslang type to SPIR-V block decorations. spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer) { if (type.getBasicType() == glslang::EbtBlock) { switch (type.getQualifier().storage) { case glslang::EvqUniform: return spv::DecorationBlock; case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock; case glslang::EvqVaryingIn: return spv::DecorationBlock; case glslang::EvqVaryingOut: return spv::DecorationBlock; default: assert(0); break; } } return spv::DecorationMax; } // Translate glslang type to SPIR-V memory decorations. void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory) { if (qualifier.coherent) memory.push_back(spv::DecorationCoherent); if (qualifier.volatil) { memory.push_back(spv::DecorationVolatile); memory.push_back(spv::DecorationCoherent); } if (qualifier.restrict) memory.push_back(spv::DecorationRestrict); if (qualifier.readonly) memory.push_back(spv::DecorationNonWritable); if (qualifier.writeonly) memory.push_back(spv::DecorationNonReadable); } // Translate glslang type to SPIR-V layout decorations. spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout) { if (type.isMatrix()) { switch (matrixLayout) { case glslang::ElmRowMajor: return spv::DecorationRowMajor; case glslang::ElmColumnMajor: return spv::DecorationColMajor; default: // opaque layouts don't need a majorness return spv::DecorationMax; } } else { switch (type.getBasicType()) { default: return spv::DecorationMax; break; case glslang::EbtBlock: switch (type.getQualifier().storage) { case glslang::EvqUniform: case glslang::EvqBuffer: switch (type.getQualifier().layoutPacking) { case glslang::ElpShared: return spv::DecorationGLSLShared; case glslang::ElpPacked: return spv::DecorationGLSLPacked; default: return spv::DecorationMax; } case glslang::EvqVaryingIn: case glslang::EvqVaryingOut: assert(type.getQualifier().layoutPacking == glslang::ElpNone); return spv::DecorationMax; default: assert(0); return spv::DecorationMax; } } } } // Translate glslang type to SPIR-V interpolation decorations. // Returns spv::DecorationMax when no decoration // should be applied. spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier) { if (qualifier.smooth) // Smooth decoration doesn't exist in SPIR-V 1.0 return spv::DecorationMax; else if (qualifier.nopersp) return spv::DecorationNoPerspective; else if (qualifier.flat) return spv::DecorationFlat; #ifdef AMD_EXTENSIONS else if (qualifier.explicitInterp) { builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::DecorationExplicitInterpAMD; } #endif else return spv::DecorationMax; } // Translate glslang type to SPIR-V auxiliary storage decorations. // Returns spv::DecorationMax when no decoration // should be applied. spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier) { if (qualifier.patch) return spv::DecorationPatch; else if (qualifier.centroid) return spv::DecorationCentroid; else if (qualifier.sample) { builder.addCapability(spv::CapabilitySampleRateShading); return spv::DecorationSample; } else return spv::DecorationMax; } // If glslang type is invariant, return SPIR-V invariant decoration. spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier) { if (qualifier.invariant) return spv::DecorationInvariant; else return spv::DecorationMax; } // If glslang type is noContraction, return SPIR-V NoContraction decoration. spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier) { if (qualifier.noContraction) return spv::DecorationNoContraction; else return spv::DecorationMax; } // If glslang type is nonUniform, return SPIR-V NonUniform decoration. spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier) { if (qualifier.isNonUniform()) { builder.addExtension("SPV_EXT_descriptor_indexing"); builder.addCapability(spv::CapabilityShaderNonUniformEXT); return spv::DecorationNonUniformEXT; } else return spv::DecorationMax; } // Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate // associated capabilities when required. For some built-in variables, a capability // is generated only when using the variable in an executable instruction, but not when // just declaring a struct member variable with it. This is true for PointSize, // ClipDistance, and CullDistance. spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration) { switch (builtIn) { case glslang::EbvPointSize: // Defer adding the capability until the built-in is actually used. if (! memberDeclaration) { switch (glslangIntermediate->getStage()) { case EShLangGeometry: builder.addCapability(spv::CapabilityGeometryPointSize); break; case EShLangTessControl: case EShLangTessEvaluation: builder.addCapability(spv::CapabilityTessellationPointSize); break; default: break; } } return spv::BuiltInPointSize; // These *Distance capabilities logically belong here, but if the member is declared and // then never used, consumers of SPIR-V prefer the capability not be declared. // They are now generated when used, rather than here when declared. // Potentially, the specification should be more clear what the minimum // use needed is to trigger the capability. // case glslang::EbvClipDistance: if (!memberDeclaration) builder.addCapability(spv::CapabilityClipDistance); return spv::BuiltInClipDistance; case glslang::EbvCullDistance: if (!memberDeclaration) builder.addCapability(spv::CapabilityCullDistance); return spv::BuiltInCullDistance; case glslang::EbvViewportIndex: builder.addCapability(spv::CapabilityMultiViewport); if (glslangIntermediate->getStage() == EShLangVertex || glslangIntermediate->getStage() == EShLangTessControl || glslangIntermediate->getStage() == EShLangTessEvaluation) { builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer); builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT); } return spv::BuiltInViewportIndex; case glslang::EbvSampleId: builder.addCapability(spv::CapabilitySampleRateShading); return spv::BuiltInSampleId; case glslang::EbvSamplePosition: builder.addCapability(spv::CapabilitySampleRateShading); return spv::BuiltInSamplePosition; case glslang::EbvSampleMask: return spv::BuiltInSampleMask; case glslang::EbvLayer: builder.addCapability(spv::CapabilityGeometry); if (glslangIntermediate->getStage() == EShLangVertex || glslangIntermediate->getStage() == EShLangTessControl || glslangIntermediate->getStage() == EShLangTessEvaluation) { builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer); builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT); } return spv::BuiltInLayer; case glslang::EbvPosition: return spv::BuiltInPosition; case glslang::EbvVertexId: return spv::BuiltInVertexId; case glslang::EbvInstanceId: return spv::BuiltInInstanceId; case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex; case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex; case glslang::EbvBaseVertex: addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters); builder.addCapability(spv::CapabilityDrawParameters); return spv::BuiltInBaseVertex; case glslang::EbvBaseInstance: addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters); builder.addCapability(spv::CapabilityDrawParameters); return spv::BuiltInBaseInstance; case glslang::EbvDrawId: addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters); builder.addCapability(spv::CapabilityDrawParameters); return spv::BuiltInDrawIndex; case glslang::EbvPrimitiveId: if (glslangIntermediate->getStage() == EShLangFragment) builder.addCapability(spv::CapabilityGeometry); return spv::BuiltInPrimitiveId; case glslang::EbvFragStencilRef: builder.addExtension(spv::E_SPV_EXT_shader_stencil_export); builder.addCapability(spv::CapabilityStencilExportEXT); return spv::BuiltInFragStencilRefEXT; case glslang::EbvInvocationId: return spv::BuiltInInvocationId; case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner; case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter; case glslang::EbvTessCoord: return spv::BuiltInTessCoord; case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices; case glslang::EbvFragCoord: return spv::BuiltInFragCoord; case glslang::EbvPointCoord: return spv::BuiltInPointCoord; case glslang::EbvFace: return spv::BuiltInFrontFacing; case glslang::EbvFragDepth: return spv::BuiltInFragDepth; case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation; case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups; case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize; case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId; case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId; case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex; case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId; case glslang::EbvSubGroupSize: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupSize; case glslang::EbvSubGroupInvocation: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupLocalInvocationId; case glslang::EbvSubGroupEqMask: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupEqMaskKHR; case glslang::EbvSubGroupGeMask: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupGeMaskKHR; case glslang::EbvSubGroupGtMask: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupGtMaskKHR; case glslang::EbvSubGroupLeMask: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupLeMaskKHR; case glslang::EbvSubGroupLtMask: builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); return spv::BuiltInSubgroupLtMaskKHR; case glslang::EbvNumSubgroups: builder.addCapability(spv::CapabilityGroupNonUniform); return spv::BuiltInNumSubgroups; case glslang::EbvSubgroupID: builder.addCapability(spv::CapabilityGroupNonUniform); return spv::BuiltInSubgroupId; case glslang::EbvSubgroupSize2: builder.addCapability(spv::CapabilityGroupNonUniform); return spv::BuiltInSubgroupSize; case glslang::EbvSubgroupInvocation2: builder.addCapability(spv::CapabilityGroupNonUniform); return spv::BuiltInSubgroupLocalInvocationId; case glslang::EbvSubgroupEqMask2: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); return spv::BuiltInSubgroupEqMask; case glslang::EbvSubgroupGeMask2: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); return spv::BuiltInSubgroupGeMask; case glslang::EbvSubgroupGtMask2: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); return spv::BuiltInSubgroupGtMask; case glslang::EbvSubgroupLeMask2: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); return spv::BuiltInSubgroupLeMask; case glslang::EbvSubgroupLtMask2: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); return spv::BuiltInSubgroupLtMask; #ifdef AMD_EXTENSIONS case glslang::EbvBaryCoordNoPersp: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordNoPerspAMD; case glslang::EbvBaryCoordNoPerspCentroid: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordNoPerspCentroidAMD; case glslang::EbvBaryCoordNoPerspSample: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordNoPerspSampleAMD; case glslang::EbvBaryCoordSmooth: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordSmoothAMD; case glslang::EbvBaryCoordSmoothCentroid: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordSmoothCentroidAMD; case glslang::EbvBaryCoordSmoothSample: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordSmoothSampleAMD; case glslang::EbvBaryCoordPullModel: builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter); return spv::BuiltInBaryCoordPullModelAMD; #endif case glslang::EbvDeviceIndex: addPre13Extension(spv::E_SPV_KHR_device_group); builder.addCapability(spv::CapabilityDeviceGroup); return spv::BuiltInDeviceIndex; case glslang::EbvViewIndex: addPre13Extension(spv::E_SPV_KHR_multiview); builder.addCapability(spv::CapabilityMultiView); return spv::BuiltInViewIndex; #ifdef NV_EXTENSIONS case glslang::EbvViewportMaskNV: if (!memberDeclaration) { builder.addExtension(spv::E_SPV_NV_viewport_array2); builder.addCapability(spv::CapabilityShaderViewportMaskNV); } return spv::BuiltInViewportMaskNV; case glslang::EbvSecondaryPositionNV: if (!memberDeclaration) { builder.addExtension(spv::E_SPV_NV_stereo_view_rendering); builder.addCapability(spv::CapabilityShaderStereoViewNV); } return spv::BuiltInSecondaryPositionNV; case glslang::EbvSecondaryViewportMaskNV: if (!memberDeclaration) { builder.addExtension(spv::E_SPV_NV_stereo_view_rendering); builder.addCapability(spv::CapabilityShaderStereoViewNV); } return spv::BuiltInSecondaryViewportMaskNV; case glslang::EbvPositionPerViewNV: if (!memberDeclaration) { builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes); builder.addCapability(spv::CapabilityPerViewAttributesNV); } return spv::BuiltInPositionPerViewNV; case glslang::EbvViewportMaskPerViewNV: if (!memberDeclaration) { builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes); builder.addCapability(spv::CapabilityPerViewAttributesNV); } return spv::BuiltInViewportMaskPerViewNV; case glslang::EbvFragFullyCoveredNV: builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered); builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT); return spv::BuiltInFullyCoveredEXT; #endif default: return spv::BuiltInMax; } } // Translate glslang image layout format to SPIR-V image format. spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type) { assert(type.getBasicType() == glslang::EbtSampler); // Check for capabilities switch (type.getQualifier().layoutFormat) { case glslang::ElfRg32f: case glslang::ElfRg16f: case glslang::ElfR11fG11fB10f: case glslang::ElfR16f: case glslang::ElfRgba16: case glslang::ElfRgb10A2: case glslang::ElfRg16: case glslang::ElfRg8: case glslang::ElfR16: case glslang::ElfR8: case glslang::ElfRgba16Snorm: case glslang::ElfRg16Snorm: case glslang::ElfRg8Snorm: case glslang::ElfR16Snorm: case glslang::ElfR8Snorm: case glslang::ElfRg32i: case glslang::ElfRg16i: case glslang::ElfRg8i: case glslang::ElfR16i: case glslang::ElfR8i: case glslang::ElfRgb10a2ui: case glslang::ElfRg32ui: case glslang::ElfRg16ui: case glslang::ElfRg8ui: case glslang::ElfR16ui: case glslang::ElfR8ui: builder.addCapability(spv::CapabilityStorageImageExtendedFormats); break; default: break; } // do the translation switch (type.getQualifier().layoutFormat) { case glslang::ElfNone: return spv::ImageFormatUnknown; case glslang::ElfRgba32f: return spv::ImageFormatRgba32f; case glslang::ElfRgba16f: return spv::ImageFormatRgba16f; case glslang::ElfR32f: return spv::ImageFormatR32f; case glslang::ElfRgba8: return spv::ImageFormatRgba8; case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm; case glslang::ElfRg32f: return spv::ImageFormatRg32f; case glslang::ElfRg16f: return spv::ImageFormatRg16f; case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f; case glslang::ElfR16f: return spv::ImageFormatR16f; case glslang::ElfRgba16: return spv::ImageFormatRgba16; case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2; case glslang::ElfRg16: return spv::ImageFormatRg16; case glslang::ElfRg8: return spv::ImageFormatRg8; case glslang::ElfR16: return spv::ImageFormatR16; case glslang::ElfR8: return spv::ImageFormatR8; case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm; case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm; case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm; case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm; case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm; case glslang::ElfRgba32i: return spv::ImageFormatRgba32i; case glslang::ElfRgba16i: return spv::ImageFormatRgba16i; case glslang::ElfRgba8i: return spv::ImageFormatRgba8i; case glslang::ElfR32i: return spv::ImageFormatR32i; case glslang::ElfRg32i: return spv::ImageFormatRg32i; case glslang::ElfRg16i: return spv::ImageFormatRg16i; case glslang::ElfRg8i: return spv::ImageFormatRg8i; case glslang::ElfR16i: return spv::ImageFormatR16i; case glslang::ElfR8i: return spv::ImageFormatR8i; case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui; case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui; case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui; case glslang::ElfR32ui: return spv::ImageFormatR32ui; case glslang::ElfRg32ui: return spv::ImageFormatRg32ui; case glslang::ElfRg16ui: return spv::ImageFormatRg16ui; case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui; case glslang::ElfRg8ui: return spv::ImageFormatRg8ui; case glslang::ElfR16ui: return spv::ImageFormatR16ui; case glslang::ElfR8ui: return spv::ImageFormatR8ui; default: return spv::ImageFormatMax; } } spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const { if (selectionNode.getFlatten()) return spv::SelectionControlFlattenMask; if (selectionNode.getDontFlatten()) return spv::SelectionControlDontFlattenMask; return spv::SelectionControlMaskNone; } spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const { if (switchNode.getFlatten()) return spv::SelectionControlFlattenMask; if (switchNode.getDontFlatten()) return spv::SelectionControlDontFlattenMask; return spv::SelectionControlMaskNone; } // return a non-0 dependency if the dependency argument must be set spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode, unsigned int& dependencyLength) const { spv::LoopControlMask control = spv::LoopControlMaskNone; if (loopNode.getDontUnroll()) control = control | spv::LoopControlDontUnrollMask; if (loopNode.getUnroll()) control = control | spv::LoopControlUnrollMask; if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite) control = control | spv::LoopControlDependencyInfiniteMask; else if (loopNode.getLoopDependency() > 0) { control = control | spv::LoopControlDependencyLengthMask; dependencyLength = loopNode.getLoopDependency(); } return control; } // Translate glslang type to SPIR-V storage class. spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type) { if (type.getQualifier().isPipeInput()) return spv::StorageClassInput; if (type.getQualifier().isPipeOutput()) return spv::StorageClassOutput; if (glslangIntermediate->getSource() != glslang::EShSourceHlsl || type.getQualifier().storage == glslang::EvqUniform) { if (type.getBasicType() == glslang::EbtAtomicUint) return spv::StorageClassAtomicCounter; if (type.containsOpaque()) return spv::StorageClassUniformConstant; } if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) { addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class); return spv::StorageClassStorageBuffer; } if (type.getQualifier().isUniformOrBuffer()) { if (type.getQualifier().layoutPushConstant) return spv::StorageClassPushConstant; if (type.getBasicType() == glslang::EbtBlock) return spv::StorageClassUniform; return spv::StorageClassUniformConstant; } switch (type.getQualifier().storage) { case glslang::EvqShared: return spv::StorageClassWorkgroup; case glslang::EvqGlobal: return spv::StorageClassPrivate; case glslang::EvqConstReadOnly: return spv::StorageClassFunction; case glslang::EvqTemporary: return spv::StorageClassFunction; default: assert(0); break; } return spv::StorageClassFunction; } // Add capabilities pertaining to how an array is indexed. void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType) { if (indexType.getQualifier().isNonUniform()) { // deal with an asserted non-uniform index // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration if (baseType.getBasicType() == glslang::EbtSampler) { if (baseType.getQualifier().hasAttachment()) builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT); else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT); else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT); else if (baseType.isImage()) builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT); else if (baseType.isTexture()) builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT); } else if (baseType.getBasicType() == glslang::EbtBlock) { if (baseType.getQualifier().storage == glslang::EvqBuffer) builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT); else if (baseType.getQualifier().storage == glslang::EvqUniform) builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT); } } else { // assume a dynamically uniform index if (baseType.getBasicType() == glslang::EbtSampler) { if (baseType.getQualifier().hasAttachment()) { builder.addExtension("SPV_EXT_descriptor_indexing"); builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT); } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) { builder.addExtension("SPV_EXT_descriptor_indexing"); builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT); } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) { builder.addExtension("SPV_EXT_descriptor_indexing"); builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT); } } } } // Return whether or not the given type is something that should be tied to a // descriptor set. bool IsDescriptorResource(const glslang::TType& type) { // uniform and buffer blocks are included, unless it is a push_constant if (type.getBasicType() == glslang::EbtBlock) return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant; // non block... // basically samplerXXX/subpass/sampler/texture are all included // if they are the global-scope-class, not the function parameter // (or local, if they ever exist) class. if (type.getBasicType() == glslang::EbtSampler) return type.getQualifier().isUniformOrBuffer(); // None of the above. return false; } void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent) { if (child.layoutMatrix == glslang::ElmNone) child.layoutMatrix = parent.layoutMatrix; if (parent.invariant) child.invariant = true; if (parent.nopersp) child.nopersp = true; #ifdef AMD_EXTENSIONS if (parent.explicitInterp) child.explicitInterp = true; #endif if (parent.flat) child.flat = true; if (parent.centroid) child.centroid = true; if (parent.patch) child.patch = true; if (parent.sample) child.sample = true; if (parent.coherent) child.coherent = true; if (parent.volatil) child.volatil = true; if (parent.restrict) child.restrict = true; if (parent.readonly) child.readonly = true; if (parent.writeonly) child.writeonly = true; } bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier) { // This should list qualifiers that simultaneous satisfy: // - struct members might inherit from a struct declaration // (note that non-block structs don't explicitly inherit, // only implicitly, meaning no decoration involved) // - affect decorations on the struct members // (note smooth does not, and expecting something like volatile // to effect the whole object) // - are not part of the offset/st430/etc or row/column-major layout return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock); } // // Implement the TGlslangToSpvTraverser class. // TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) : TIntermTraverser(true, false, true), options(options), shaderEntry(nullptr), currentFunction(nullptr), sequenceDepth(0), logger(buildLogger), builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger), inEntryPoint(false), entryPointTerminated(false), linkageOnly(false), glslangIntermediate(glslangIntermediate) { spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage()); builder.clearAccessChain(); builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion()); if (options.generateDebugInfo) { builder.setEmitOpLines(); builder.setSourceFile(glslangIntermediate->getSourceFile()); // Set the source shader's text. If for SPV version 1.0, include // a preamble in comments stating the OpModuleProcessed instructions. // Otherwise, emit those as actual instructions. std::string text; const std::vector<std::string>& processes = glslangIntermediate->getProcesses(); for (int p = 0; p < (int)processes.size(); ++p) { if (glslangIntermediate->getSpv().spv < 0x00010100) { text.append("// OpModuleProcessed "); text.append(processes[p]); text.append("\n"); } else builder.addModuleProcessed(processes[p]); } if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0) text.append("#line 1\n"); text.append(glslangIntermediate->getSourceText()); builder.setSourceText(text); } stdBuiltins = builder.import("GLSL.std.450"); builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450); shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str()); entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str()); // Add the source extensions const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions(); for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it) builder.addSourceExtension(it->c_str()); // Add the top-level modes for this shader. if (glslangIntermediate->getXfbMode()) { builder.addCapability(spv::CapabilityTransformFeedback); builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb); } unsigned int mode; switch (glslangIntermediate->getStage()) { case EShLangVertex: builder.addCapability(spv::CapabilityShader); break; case EShLangTessEvaluation: case EShLangTessControl: builder.addCapability(spv::CapabilityTessellation); glslang::TLayoutGeometry primitive; if (glslangIntermediate->getStage() == EShLangTessControl) { builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices()); primitive = glslangIntermediate->getOutputPrimitive(); } else { primitive = glslangIntermediate->getInputPrimitive(); } switch (primitive) { case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break; case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break; case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); switch (glslangIntermediate->getVertexSpacing()) { case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break; case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break; case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); switch (glslangIntermediate->getVertexOrder()) { case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break; case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); if (glslangIntermediate->getPointMode()) builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode); break; case EShLangGeometry: builder.addCapability(spv::CapabilityGeometry); switch (glslangIntermediate->getInputPrimitive()) { case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break; case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break; case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break; case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break; case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations()); switch (glslangIntermediate->getOutputPrimitive()) { case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break; case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break; case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices()); break; case EShLangFragment: builder.addCapability(spv::CapabilityShader); if (glslangIntermediate->getPixelCenterInteger()) builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger); if (glslangIntermediate->getOriginUpperLeft()) builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft); else builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft); if (glslangIntermediate->getEarlyFragmentTests()) builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests); if (glslangIntermediate->getPostDepthCoverage()) { builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage); builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage); builder.addExtension(spv::E_SPV_KHR_post_depth_coverage); } switch(glslangIntermediate->getDepth()) { case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break; case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break; default: mode = spv::ExecutionModeMax; break; } if (mode != spv::ExecutionModeMax) builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode); if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing()) builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing); break; case EShLangCompute: builder.addCapability(spv::CapabilityShader); builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0), glslangIntermediate->getLocalSize(1), glslangIntermediate->getLocalSize(2)); break; default: break; } } // Finish creating SPV, after the traversal is complete. void TGlslangToSpvTraverser::finishSpv() { if (! entryPointTerminated) { builder.setBuildPoint(shaderEntry->getLastBlock()); builder.leaveFunction(); } // finish off the entry-point SPV instruction by adding the Input/Output <id> for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it) entryPoint->addIdOperand(*it); builder.eliminateDeadDecorations(); } // Write the SPV into 'out'. void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); } // // Implement the traversal functions. // // Return true from interior nodes to have the external traversal // continue on to children. Return false if children were // already processed. // // // Symbols can turn into // - uniform/input reads // - output writes // - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain // - something simple that degenerates into the last bullet // void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol) { SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder); if (symbol->getType().getQualifier().isSpecConstant()) spec_constant_op_mode_setter.turnOnSpecConstantOpMode(); // getSymbolId() will set up all the IO decorations on the first call. // Formal function parameters were mapped during makeFunctions(). spv::Id id = getSymbolId(symbol); // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction if (builder.isPointer(id)) { spv::StorageClass sc = builder.getStorageClass(id); if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) { if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) iOSet.insert(id); } } // Only process non-linkage-only nodes for generating actual static uses if (! linkageOnly || symbol->getQualifier().isSpecConstant()) { // Prepare to generate code for the access // L-value chains will be computed left to right. We're on the symbol now, // which is the left-most part of the access chain, so now is "clear" time, // followed by setting the base. builder.clearAccessChain(); // For now, we consider all user variables as being in memory, so they are pointers, // except for // A) R-Value arguments to a function, which are an intermediate object. // See comments in handleUserFunctionCall(). // B) Specialization constants (normal constants don't even come in as a variable), // These are also pure R-values. glslang::TQualifier qualifier = symbol->getQualifier(); if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end()) builder.setAccessChainRValue(id); else builder.setAccessChainLValue(id); } // Process linkage-only nodes for any special additional interface work. if (linkageOnly) { if (glslangIntermediate->getHlslFunctionality1()) { // Map implicit counter buffers to their originating buffers, which should have been // seen by now, given earlier pruning of unused counters, and preservation of order // of declaration. if (symbol->getType().getQualifier().isUniformOrBuffer()) { if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) { // Save possible originating buffers for counter buffers, keyed by // making the potential counter-buffer name. std::string keyName = symbol->getName().c_str(); keyName = glslangIntermediate->addCounterBufferName(keyName); counterOriginator[keyName] = symbol; } else { // Handle a counter buffer, by finding the saved originating buffer. std::string keyName = symbol->getName().c_str(); auto it = counterOriginator.find(keyName); if (it != counterOriginator.end()) { id = getSymbolId(it->second); if (id != spv::NoResult) { spv::Id counterId = getSymbolId(symbol); if (counterId != spv::NoResult) { builder.addExtension("SPV_GOOGLE_hlsl_functionality1"); builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId); } } } } } } } } bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node) { builder.setLine(node->getLoc().line); SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder); if (node->getType().getQualifier().isSpecConstant()) spec_constant_op_mode_setter.turnOnSpecConstantOpMode(); // First, handle special cases switch (node->getOp()) { case glslang::EOpAssign: case glslang::EOpAddAssign: case glslang::EOpSubAssign: case glslang::EOpMulAssign: case glslang::EOpVectorTimesMatrixAssign: case glslang::EOpVectorTimesScalarAssign: case glslang::EOpMatrixTimesScalarAssign: case glslang::EOpMatrixTimesMatrixAssign: case glslang::EOpDivAssign: case glslang::EOpModAssign: case glslang::EOpAndAssign: case glslang::EOpInclusiveOrAssign: case glslang::EOpExclusiveOrAssign: case glslang::EOpLeftShiftAssign: case glslang::EOpRightShiftAssign: // A bin-op assign "a += b" means the same thing as "a = a + b" // where a is evaluated before b. For a simple assignment, GLSL // says to evaluate the left before the right. So, always, left // node then right node. { // get the left l-value, save it away builder.clearAccessChain(); node->getLeft()->traverse(this); spv::Builder::AccessChain lValue = builder.getAccessChain(); // evaluate the right builder.clearAccessChain(); node->getRight()->traverse(this); spv::Id rValue = accessChainLoad(node->getRight()->getType()); if (node->getOp() != glslang::EOpAssign) { // the left is also an r-value builder.setAccessChain(lValue); spv::Id leftRValue = accessChainLoad(node->getLeft()->getType()); // do the operation OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()), TranslateNoContractionDecoration(node->getType().getQualifier()), TranslateNonUniformDecoration(node->getType().getQualifier()) }; rValue = createBinaryOperation(node->getOp(), decorations, convertGlslangToSpvType(node->getType()), leftRValue, rValue, node->getType().getBasicType()); // these all need their counterparts in createBinaryOperation() assert(rValue != spv::NoResult); } // store the result builder.setAccessChain(lValue); multiTypeStore(node->getType(), rValue); // assignments are expressions having an rValue after they are evaluated... builder.clearAccessChain(); builder.setAccessChainRValue(rValue); } return false; case glslang::EOpIndexDirect: case glslang::EOpIndexDirectStruct: { // Get the left part of the access chain. node->getLeft()->traverse(this); // Add the next element in the chain const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst(); if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector() && node->getOp() == glslang::EOpIndexDirect) { // This is essentially a hard-coded vector swizzle of size 1, // so short circuit the access-chain stuff with a swizzle. std::vector<unsigned> swizzle; swizzle.push_back(glslangIndex); builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType())); } else { int spvIndex = glslangIndex; if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) { // This may be, e.g., an anonymous block-member selection, which generally need // index remapping due to hidden members in anonymous blocks. std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()]; assert(remapper.size() > 0); spvIndex = remapper[glslangIndex]; } // normal case for indexing array or structure or block builder.accessChainPush(builder.makeIntConstant(spvIndex)); // Add capabilities here for accessing PointSize and clip/cull distance. // We have deferred generation of associated capabilities until now. if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray()) declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex); } } return false; case glslang::EOpIndexIndirect: { // Structure or array or vector indirection. // Will use native SPIR-V access-chain for struct and array indirection; // matrices are arrays of vectors, so will also work for a matrix. // Will use the access chain's 'component' for variable index into a vector. // This adapter is building access chains left to right. // Set up the access chain to the left. node->getLeft()->traverse(this); // save it so that computing the right side doesn't trash it spv::Builder::AccessChain partial = builder.getAccessChain(); // compute the next index in the chain builder.clearAccessChain(); node->getRight()->traverse(this); spv::Id index = accessChainLoad(node->getRight()->getType()); addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType()); // restore the saved access chain builder.setAccessChain(partial); if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType())); else builder.accessChainPush(index); } return false; case glslang::EOpVectorSwizzle: { node->getLeft()->traverse(this); std::vector<unsigned> swizzle; convertSwizzle(*node->getRight()->getAsAggregate(), swizzle); builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType())); } return false; case glslang::EOpMatrixSwizzle: logger->missingFunctionality("matrix swizzle"); return true; case glslang::EOpLogicalOr: case glslang::EOpLogicalAnd: { // These may require short circuiting, but can sometimes be done as straight // binary operations. The right operand must be short circuited if it has // side effects, and should probably be if it is complex. if (isTrivial(node->getRight()->getAsTyped())) break; // handle below as a normal binary operation // otherwise, we need to do dynamic short circuiting on the right operand spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped()); builder.clearAccessChain(); builder.setAccessChainRValue(result); } return false; default: break; } // Assume generic binary op... // get right operand builder.clearAccessChain(); node->getLeft()->traverse(this); spv::Id left = accessChainLoad(node->getLeft()->getType()); // get left operand builder.clearAccessChain(); node->getRight()->traverse(this); spv::Id right = accessChainLoad(node->getRight()->getType()); // get result OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()), TranslateNoContractionDecoration(node->getType().getQualifier()), TranslateNonUniformDecoration(node->getType().getQualifier()) }; spv::Id result = createBinaryOperation(node->getOp(), decorations, convertGlslangToSpvType(node->getType()), left, right, node->getLeft()->getType().getBasicType()); builder.clearAccessChain(); if (! result) { logger->missingFunctionality("unknown glslang binary operation"); return true; // pick up a child as the place-holder result } else { builder.setAccessChainRValue(result); return false; } } bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node) { builder.setLine(node->getLoc().line); SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder); if (node->getType().getQualifier().isSpecConstant()) spec_constant_op_mode_setter.turnOnSpecConstantOpMode(); spv::Id result = spv::NoResult; // try texturing first result = createImageTextureFunctionCall(node); if (result != spv::NoResult) { builder.clearAccessChain(); builder.setAccessChainRValue(result); return false; // done with this node } // Non-texturing. if (node->getOp() == glslang::EOpArrayLength) { // Quite special; won't want to evaluate the operand. // Currently, the front-end does not allow .length() on an array until it is sized, // except for the last block membeor of an SSBO. // TODO: If this changes, link-time sized arrays might show up here, and need their // size extracted. // Normal .length() would have been constant folded by the front-end. // So, this has to be block.lastMember.length(). // SPV wants "block" and member number as the operands, go get them. glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft(); block->traverse(this); unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst(); spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member); builder.clearAccessChain(); builder.setAccessChainRValue(length); return false; } // Start by evaluating the operand // Does it need a swizzle inversion? If so, evaluation is inverted; // operate first on the swizzle base, then apply the swizzle. spv::Id invertedType = spv::NoType; auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); }; if (node->getOp() == glslang::EOpInterpolateAtCentroid) invertedType = getInvertedSwizzleType(*node->getOperand()); builder.clearAccessChain(); if (invertedType != spv::NoType) node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this); else node->getOperand()->traverse(this); spv::Id operand = spv::NoResult; if (node->getOp() == glslang::EOpAtomicCounterIncrement || node->getOp() == glslang::EOpAtomicCounterDecrement || node->getOp() == glslang::EOpAtomicCounter || node->getOp() == glslang::EOpInterpolateAtCentroid) operand = builder.accessChainGetLValue(); // Special case l-value operands else operand = accessChainLoad(node->getOperand()->getType()); OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()), TranslateNoContractionDecoration(node->getType().getQualifier()), TranslateNonUniformDecoration(node->getType().getQualifier()) }; // it could be a conversion if (! result) result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType()); // if not, then possibly an operation if (! result) result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType()); if (result) { if (invertedType) { result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result); builder.addDecoration(result, decorations.nonUniform); } builder.clearAccessChain(); builder.setAccessChainRValue(result); return false; // done with this node } // it must be a special case, check... switch (node->getOp()) { case glslang::EOpPostIncrement: case glslang::EOpPostDecrement: case glslang::EOpPreIncrement: case glslang::EOpPreDecrement: { // we need the integer value "1" or the floating point "1.0" to add/subtract spv::Id one = 0; if (node->getBasicType() == glslang::EbtFloat) one = builder.makeFloatConstant(1.0F); else if (node->getBasicType() == glslang::EbtDouble) one = builder.makeDoubleConstant(1.0); else if (node->getBasicType() == glslang::EbtFloat16) one = builder.makeFloat16Constant(1.0F); else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8) one = builder.makeInt8Constant(1); else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16) one = builder.makeInt16Constant(1); else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64) one = builder.makeInt64Constant(1); else one = builder.makeIntConstant(1); glslang::TOperator op; if (node->getOp() == glslang::EOpPreIncrement || node->getOp() == glslang::EOpPostIncrement) op = glslang::EOpAdd; else op = glslang::EOpSub; spv::Id result = createBinaryOperation(op, decorations, convertGlslangToSpvType(node->getType()), operand, one, node->getType().getBasicType()); assert(result != spv::NoResult); // The result of operation is always stored, but conditionally the // consumed result. The consumed result is always an r-value. builder.accessChainStore(result); builder.clearAccessChain(); if (node->getOp() == glslang::EOpPreIncrement || node->getOp() == glslang::EOpPreDecrement) builder.setAccessChainRValue(result); else builder.setAccessChainRValue(operand); } return false; case glslang::EOpEmitStreamVertex: builder.createNoResultOp(spv::OpEmitStreamVertex, operand); return false; case glslang::EOpEndStreamPrimitive: builder.createNoResultOp(spv::OpEndStreamPrimitive, operand); return false; default: logger->missingFunctionality("unknown glslang unary"); return true; // pick up operand as placeholder result } } bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node) { SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder); if (node->getType().getQualifier().isSpecConstant()) spec_constant_op_mode_setter.turnOnSpecConstantOpMode(); spv::Id result = spv::NoResult; spv::Id invertedType = spv::NoType; // to use to override the natural type of the node auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); }; // try texturing result = createImageTextureFunctionCall(node); if (result != spv::NoResult) { builder.clearAccessChain(); builder.setAccessChainRValue(result); return false; #ifdef AMD_EXTENSIONS } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) { #else } else if (node->getOp() == glslang::EOpImageStore) { #endif // "imageStore" is a special case, which has no result return false; } glslang::TOperator binOp = glslang::EOpNull; bool reduceComparison = true; bool isMatrix = false; bool noReturnValue = false; bool atomic = false; assert(node->getOp()); spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision()); switch (node->getOp()) { case glslang::EOpSequence: { if (preVisit) ++sequenceDepth; else --sequenceDepth; if (sequenceDepth == 1) { // If this is the parent node of all the functions, we want to see them // early, so all call points have actual SPIR-V functions to reference. // In all cases, still let the traverser visit the children for us. makeFunctions(node->getAsAggregate()->getSequence()); // Also, we want all globals initializers to go into the beginning of the entry point, before // anything else gets there, so visit out of order, doing them all now. makeGlobalInitializers(node->getAsAggregate()->getSequence()); // Initializers are done, don't want to visit again, but functions and link objects need to be processed, // so do them manually. visitFunctions(node->getAsAggregate()->getSequence()); return false; } return true; } case glslang::EOpLinkerObjects: { if (visit == glslang::EvPreVisit) linkageOnly = true; else linkageOnly = false; return true; } case glslang::EOpComma: { // processing from left to right naturally leaves the right-most // lying around in the access chain glslang::TIntermSequence& glslangOperands = node->getSequence(); for (int i = 0; i < (int)glslangOperands.size(); ++i) glslangOperands[i]->traverse(this); return false; } case glslang::EOpFunction: if (visit == glslang::EvPreVisit) { if (isShaderEntryPoint(node)) { inEntryPoint = true; builder.setBuildPoint(shaderEntry->getLastBlock()); currentFunction = shaderEntry; } else { handleFunctionEntry(node); } } else { if (inEntryPoint) entryPointTerminated = true; builder.leaveFunction(); inEntryPoint = false; } return true; case glslang::EOpParameters: // Parameters will have been consumed by EOpFunction processing, but not // the body, so we still visited the function node's children, making this // child redundant. return false; case glslang::EOpFunctionCall: { builder.setLine(node->getLoc().line); if (node->isUserDefined()) result = handleUserFunctionCall(node); // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done if (result) { builder.clearAccessChain(); builder.setAccessChainRValue(result); } else logger->missingFunctionality("missing user function; linker needs to catch that"); return false; } case glslang::EOpConstructMat2x2: case glslang::EOpConstructMat2x3: case glslang::EOpConstructMat2x4: case glslang::EOpConstructMat3x2: case glslang::EOpConstructMat3x3: case glslang::EOpConstructMat3x4: case glslang::EOpConstructMat4x2: case glslang::EOpConstructMat4x3: case glslang::EOpConstructMat4x4: case glslang::EOpConstructDMat2x2: case glslang::EOpConstructDMat2x3: case glslang::EOpConstructDMat2x4: case glslang::EOpConstructDMat3x2: case glslang::EOpConstructDMat3x3: case glslang::EOpConstructDMat3x4: case glslang::EOpConstructDMat4x2: case glslang::EOpConstructDMat4x3: case glslang::EOpConstructDMat4x4: case glslang::EOpConstructIMat2x2: case glslang::EOpConstructIMat2x3: case glslang::EOpConstructIMat2x4: case glslang::EOpConstructIMat3x2: case glslang::EOpConstructIMat3x3: case glslang::EOpConstructIMat3x4: case glslang::EOpConstructIMat4x2: case glslang::EOpConstructIMat4x3: case glslang::EOpConstructIMat4x4: case glslang::EOpConstructUMat2x2: case glslang::EOpConstructUMat2x3: case glslang::EOpConstructUMat2x4: case glslang::EOpConstructUMat3x2: case glslang::EOpConstructUMat3x3: case glslang::EOpConstructUMat3x4: case glslang::EOpConstructUMat4x2: case glslang::EOpConstructUMat4x3: case glslang::EOpConstructUMat4x4: case glslang::EOpConstructBMat2x2: case glslang::EOpConstructBMat2x3: case glslang::EOpConstructBMat2x4: case glslang::EOpConstructBMat3x2: case glslang::EOpConstructBMat3x3: case glslang::EOpConstructBMat3x4: case glslang::EOpConstructBMat4x2: case glslang::EOpConstructBMat4x3: case glslang::EOpConstructBMat4x4: case glslang::EOpConstructF16Mat2x2: case glslang::EOpConstructF16Mat2x3: case glslang::EOpConstructF16Mat2x4: case glslang::EOpConstructF16Mat3x2: case glslang::EOpConstructF16Mat3x3: case glslang::EOpConstructF16Mat3x4: case glslang::EOpConstructF16Mat4x2: case glslang::EOpConstructF16Mat4x3: case glslang::EOpConstructF16Mat4x4: isMatrix = true; // fall through case glslang::EOpConstructFloat: case glslang::EOpConstructVec2: case glslang::EOpConstructVec3: case glslang::EOpConstructVec4: case glslang::EOpConstructDouble: case glslang::EOpConstructDVec2: case glslang::EOpConstructDVec3: case glslang::EOpConstructDVec4: case glslang::EOpConstructFloat16: case glslang::EOpConstructF16Vec2: case glslang::EOpConstructF16Vec3: case glslang::EOpConstructF16Vec4: case glslang::EOpConstructBool: case glslang::EOpConstructBVec2: case glslang::EOpConstructBVec3: case glslang::EOpConstructBVec4: case glslang::EOpConstructInt8: case glslang::EOpConstructI8Vec2: case glslang::EOpConstructI8Vec3: case glslang::EOpConstructI8Vec4: case glslang::EOpConstructUint8: case glslang::EOpConstructU8Vec2: case glslang::EOpConstructU8Vec3: case glslang::EOpConstructU8Vec4: case glslang::EOpConstructInt16: case glslang::EOpConstructI16Vec2: case glslang::EOpConstructI16Vec3: case glslang::EOpConstructI16Vec4: case glslang::EOpConstructUint16: case glslang::EOpConstructU16Vec2: case glslang::EOpConstructU16Vec3: case glslang::EOpConstructU16Vec4: case glslang::EOpConstructInt: case glslang::EOpConstructIVec2: case glslang::EOpConstructIVec3: case glslang::EOpConstructIVec4: case glslang::EOpConstructUint: case glslang::EOpConstructUVec2: case glslang::EOpConstructUVec3: case glslang::EOpConstructUVec4: case glslang::EOpConstructInt64: case glslang::EOpConstructI64Vec2: case glslang::EOpConstructI64Vec3: case glslang::EOpConstructI64Vec4: case glslang::EOpConstructUint64: case glslang::EOpConstructU64Vec2: case glslang::EOpConstructU64Vec3: case glslang::EOpConstructU64Vec4: case glslang::EOpConstructStruct: case glslang::EOpConstructTextureSampler: { builder.setLine(node->getLoc().line); std::vector<spv::Id> arguments; translateArguments(*node, arguments); spv::Id constructed; if (node->getOp() == glslang::EOpConstructTextureSampler) constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments); else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) { std::vector<spv::Id> constituents; for (int c = 0; c < (int)arguments.size(); ++c) constituents.push_back(arguments[c]); constructed = builder.createCompositeConstruct(resultType(), constituents); } else if (isMatrix) constructed = builder.createMatrixConstructor(precision, arguments, resultType()); else constructed = builder.createConstructor(precision, arguments, resultType()); builder.clearAccessChain(); builder.setAccessChainRValue(constructed); return false; } // These six are component-wise compares with component-wise results. // Forward on to createBinaryOperation(), requesting a vector result. case glslang::EOpLessThan: case glslang::EOpGreaterThan: case glslang::EOpLessThanEqual: case glslang::EOpGreaterThanEqual: case glslang::EOpVectorEqual: case glslang::EOpVectorNotEqual: { // Map the operation to a binary binOp = node->getOp(); reduceComparison = false; switch (node->getOp()) { case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break; case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break; default: binOp = node->getOp(); break; } break; } case glslang::EOpMul: // component-wise matrix multiply binOp = glslang::EOpMul; break; case glslang::EOpOuterProduct: // two vectors multiplied to make a matrix binOp = glslang::EOpOuterProduct; break; case glslang::EOpDot: { // for scalar dot product, use multiply glslang::TIntermSequence& glslangOperands = node->getSequence(); if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1) binOp = glslang::EOpMul; break; } case glslang::EOpMod: // when an aggregate, this is the floating-point mod built-in function, // which can be emitted by the one in createBinaryOperation() binOp = glslang::EOpMod; break; case glslang::EOpEmitVertex: case glslang::EOpEndPrimitive: case glslang::EOpBarrier: case glslang::EOpMemoryBarrier: case glslang::EOpMemoryBarrierAtomicCounter: case glslang::EOpMemoryBarrierBuffer: case glslang::EOpMemoryBarrierImage: case glslang::EOpMemoryBarrierShared: case glslang::EOpGroupMemoryBarrier: case glslang::EOpDeviceMemoryBarrier: case glslang::EOpAllMemoryBarrierWithGroupSync: case glslang::EOpDeviceMemoryBarrierWithGroupSync: case glslang::EOpWorkgroupMemoryBarrier: case glslang::EOpWorkgroupMemoryBarrierWithGroupSync: case glslang::EOpSubgroupBarrier: case glslang::EOpSubgroupMemoryBarrier: case glslang::EOpSubgroupMemoryBarrierBuffer: case glslang::EOpSubgroupMemoryBarrierImage: case glslang::EOpSubgroupMemoryBarrierShared: noReturnValue = true; // These all have 0 operands and will naturally finish up in the code below for 0 operands break; case glslang::EOpAtomicAdd: case glslang::EOpAtomicMin: case glslang::EOpAtomicMax: case glslang::EOpAtomicAnd: case glslang::EOpAtomicOr: case glslang::EOpAtomicXor: case glslang::EOpAtomicExchange: case glslang::EOpAtomicCompSwap: atomic = true; break; case glslang::EOpAtomicCounterAdd: case glslang::EOpAtomicCounterSubtract: case glslang::EOpAtomicCounterMin: case glslang::EOpAtomicCounterMax: case glslang::EOpAtomicCounterAnd: case glslang::EOpAtomicCounterOr: case glslang::EOpAtomicCounterXor: case glslang::EOpAtomicCounterExchange: case glslang::EOpAtomicCounterCompSwap: builder.addExtension("SPV_KHR_shader_atomic_counter_ops"); builder.addCapability(spv::CapabilityAtomicStorageOps); atomic = true; break; default: break; } // // See if it maps to a regular operation. // if (binOp != glslang::EOpNull) { glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped(); glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped(); assert(left && right); builder.clearAccessChain(); left->traverse(this); spv::Id leftId = accessChainLoad(left->getType()); builder.clearAccessChain(); right->traverse(this); spv::Id rightId = accessChainLoad(right->getType()); builder.setLine(node->getLoc().line); OpDecorations decorations = { precision, TranslateNoContractionDecoration(node->getType().getQualifier()), TranslateNonUniformDecoration(node->getType().getQualifier()) }; result = createBinaryOperation(binOp, decorations, resultType(), leftId, rightId, left->getType().getBasicType(), reduceComparison); // code above should only make binOp that exists in createBinaryOperation assert(result != spv::NoResult); builder.clearAccessChain(); builder.setAccessChainRValue(result); return false; } // // Create the list of operands. // glslang::TIntermSequence& glslangOperands = node->getSequence(); std::vector<spv::Id> operands; for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) { // special case l-value operands; there are just a few bool lvalue = false; switch (node->getOp()) { case glslang::EOpFrexp: case glslang::EOpModf: if (arg == 1) lvalue = true; break; case glslang::EOpInterpolateAtSample: case glslang::EOpInterpolateAtOffset: #ifdef AMD_EXTENSIONS case glslang::EOpInterpolateAtVertex: #endif if (arg == 0) { lvalue = true; // Does it need a swizzle inversion? If so, evaluation is inverted; // operate first on the swizzle base, then apply the swizzle. if (glslangOperands[0]->getAsOperator() && glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle) invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType()); } break; case glslang::EOpAtomicAdd: case glslang::EOpAtomicMin: case glslang::EOpAtomicMax: case glslang::EOpAtomicAnd: case glslang::EOpAtomicOr: case glslang::EOpAtomicXor: case glslang::EOpAtomicExchange: case glslang::EOpAtomicCompSwap: case glslang::EOpAtomicCounterAdd: case glslang::EOpAtomicCounterSubtract: case glslang::EOpAtomicCounterMin: case glslang::EOpAtomicCounterMax: case glslang::EOpAtomicCounterAnd: case glslang::EOpAtomicCounterOr: case glslang::EOpAtomicCounterXor: case glslang::EOpAtomicCounterExchange: case glslang::EOpAtomicCounterCompSwap: if (arg == 0) lvalue = true; break; case glslang::EOpAddCarry: case glslang::EOpSubBorrow: if (arg == 2) lvalue = true; break; case glslang::EOpUMulExtended: case glslang::EOpIMulExtended: if (arg >= 2) lvalue = true; break; default: break; } builder.clearAccessChain(); if (invertedType != spv::NoType && arg == 0) glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this); else glslangOperands[arg]->traverse(this); if (lvalue) operands.push_back(builder.accessChainGetLValue()); else { builder.setLine(node->getLoc().line); operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType())); } } builder.setLine(node->getLoc().line); if (atomic) { // Handle all atomics result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType()); } else { // Pass through to generic operations. switch (glslangOperands.size()) { case 0: result = createNoArgOperation(node->getOp(), precision, resultType()); break; case 1: { OpDecorations decorations = { precision, TranslateNoContractionDecoration(node->getType().getQualifier()), TranslateNonUniformDecoration(node->getType().getQualifier()) }; result = createUnaryOperation( node->getOp(), decorations, resultType(), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType()); } break; default: result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType()); break; } if (invertedType) result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result); } if (noReturnValue) return false; if (! result) { logger->missingFunctionality("unknown glslang aggregate"); return true; // pick up a child as a placeholder operand } else { builder.clearAccessChain(); builder.setAccessChainRValue(result); return false; } } // This path handles both if-then-else and ?: // The if-then-else has a node type of void, while // ?: has either a void or a non-void node type // // Leaving the result, when not void: // GLSL only has r-values as the result of a :?, but // if we have an l-value, that can be more efficient if it will // become the base of a complex r-value expression, because the // next layer copies r-values into memory to use the access-chain mechanism bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node) { // See if it simple and safe, or required, to execute both sides. // Crucially, side effects must be either semantically required or avoided, // and there are performance trade-offs. // Return true if required or a good idea (and safe) to execute both sides, // false otherwise. const auto bothSidesPolicy = [&]() -> bool { // do we have both sides? if (node->getTrueBlock() == nullptr || node->getFalseBlock() == nullptr) return false; // required? (unless we write additional code to look for side effects // and make performance trade-offs if none are present) if (!node->getShortCircuit()) return true; // if not required to execute both, decide based on performance/practicality... // see if OpSelect can handle it if ((!node->getType().isScalar() && !node->getType().isVector()) || node->getBasicType() == glslang::EbtVoid) return false; assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() && node->getType() == node->getFalseBlock()->getAsTyped()->getType()); // return true if a single operand to ? : is okay for OpSelect const auto operandOkay = [](glslang::TIntermTyped* node) { return node->getAsSymbolNode() || node->getType().getQualifier().isConstant(); }; return operandOkay(node->getTrueBlock() ->getAsTyped()) && operandOkay(node->getFalseBlock()->getAsTyped()); }; spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue // emit the condition before doing anything with selection node->getCondition()->traverse(this); spv::Id condition = accessChainLoad(node->getCondition()->getType()); // Find a way of executing both sides and selecting the right result. const auto executeBothSides = [&]() -> void { // execute both sides node->getTrueBlock()->traverse(this); spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()); node->getFalseBlock()->traverse(this); spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()); builder.setLine(node->getLoc().line); // done if void if (node->getBasicType() == glslang::EbtVoid) return; // emit code to select between trueValue and falseValue // see if OpSelect can handle it if (node->getType().isScalar() || node->getType().isVector()) { // Emit OpSelect for this selection. // smear condition to vector, if necessary (AST is always scalar) if (builder.isVector(trueValue)) condition = builder.smearScalar(spv::NoPrecision, condition, builder.makeVectorType(builder.makeBoolType(), builder.getNumComponents(trueValue))); // OpSelect result = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue); builder.clearAccessChain(); builder.setAccessChainRValue(result); } else { // We need control flow to select the result. // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path. result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType())); // Selection control: const spv::SelectionControlMask control = TranslateSelectionControl(*node); // make an "if" based on the value created by the condition spv::Builder::If ifBuilder(condition, control, builder); // emit the "then" statement builder.createStore(trueValue, result); ifBuilder.makeBeginElse(); // emit the "else" statement builder.createStore(falseValue, result); // finish off the control flow ifBuilder.makeEndIf(); builder.clearAccessChain(); builder.setAccessChainLValue(result); } }; // Execute the one side needed, as per the condition const auto executeOneSide = [&]() { // Always emit control flow. if (node->getBasicType() != glslang::EbtVoid) result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType())); // Selection control: const spv::SelectionControlMask control = TranslateSelectionControl(*node); // make an "if" based on the value created by the condition spv::Builder::If ifBuilder(condition, control, builder); // emit the "then" statement if (node->getTrueBlock() != nullptr) { node->getTrueBlock()->traverse(this); if (result != spv::NoResult) builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result); } if (node->getFalseBlock() != nullptr) { ifBuilder.makeBeginElse(); // emit the "else" statement node->getFalseBlock()->traverse(this); if (result != spv::NoResult) builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result); } // finish off the control flow ifBuilder.makeEndIf(); if (result != spv::NoResult) { builder.clearAccessChain(); builder.setAccessChainLValue(result); } }; // Try for OpSelect (or a requirement to execute both sides) if (bothSidesPolicy()) { SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder); if (node->getType().getQualifier().isSpecConstant()) spec_constant_op_mode_setter.turnOnSpecConstantOpMode(); executeBothSides(); } else executeOneSide(); return false; } bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node) { // emit and get the condition before doing anything with switch node->getCondition()->traverse(this); spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType()); // Selection control: const spv::SelectionControlMask control = TranslateSwitchControl(*node); // browse the children to sort out code segments int defaultSegment = -1; std::vector<TIntermNode*> codeSegments; glslang::TIntermSequence& sequence = node->getBody()->getSequence(); std::vector<int> caseValues; std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) { TIntermNode* child = *c; if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault) defaultSegment = (int)codeSegments.size(); else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) { valueIndexToSegment[caseValues.size()] = (int)codeSegments.size(); caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst()); } else codeSegments.push_back(child); } // handle the case where the last code segment is missing, due to no code // statements between the last case and the end of the switch statement if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) || (int)codeSegments.size() == defaultSegment) codeSegments.push_back(nullptr); // make the switch statement std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks); // emit all the code in the segments breakForLoop.push(false); for (unsigned int s = 0; s < codeSegments.size(); ++s) { builder.nextSwitchSegment(segmentBlocks, s); if (codeSegments[s]) codeSegments[s]->traverse(this); else builder.addSwitchBreak(); } breakForLoop.pop(); builder.endSwitch(segmentBlocks); return false; } void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node) { int nextConst = 0; spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false); builder.clearAccessChain(); builder.setAccessChainRValue(constant); } bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node) { auto blocks = builder.makeNewLoop(); builder.createBranch(&blocks.head); // Loop control: unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite; const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength); // Spec requires back edges to target header blocks, and every header block // must dominate its merge block. Make a header block first to ensure these // conditions are met. By definition, it will contain OpLoopMerge, followed // by a block-ending branch. But we don't want to put any other body/test // instructions in it, since the body/test may have arbitrary instructions, // including merges of its own. builder.setLine(node->getLoc().line); builder.setBuildPoint(&blocks.head); builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength); if (node->testFirst() && node->getTest()) { spv::Block& test = builder.makeNewBlock(); builder.createBranch(&test); builder.setBuildPoint(&test); node->getTest()->traverse(this); spv::Id condition = accessChainLoad(node->getTest()->getType()); builder.createConditionalBranch(condition, &blocks.body, &blocks.merge); builder.setBuildPoint(&blocks.body); breakForLoop.push(true); if (node->getBody()) node->getBody()->traverse(this); builder.createBranch(&blocks.continue_target); breakForLoop.pop(); builder.setBuildPoint(&blocks.continue_target); if (node->getTerminal()) node->getTerminal()->traverse(this); builder.createBranch(&blocks.head); } else { builder.setLine(node->getLoc().line); builder.createBranch(&blocks.body); breakForLoop.push(true); builder.setBuildPoint(&blocks.body); if (node->getBody()) node->getBody()->traverse(this); builder.createBranch(&blocks.continue_target); breakForLoop.pop(); builder.setBuildPoint(&blocks.continue_target); if (node->getTerminal()) node->getTerminal()->traverse(this); if (node->getTest()) { node->getTest()->traverse(this); spv::Id condition = accessChainLoad(node->getTest()->getType()); builder.createConditionalBranch(condition, &blocks.head, &blocks.merge); } else { // TODO: unless there was a break/return/discard instruction // somewhere in the body, this is an infinite loop, so we should // issue a warning. builder.createBranch(&blocks.head); } } builder.setBuildPoint(&blocks.merge); builder.closeLoop(); return false; } bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node) { if (node->getExpression()) node->getExpression()->traverse(this); builder.setLine(node->getLoc().line); switch (node->getFlowOp()) { case glslang::EOpKill: builder.makeDiscard(); break; case glslang::EOpBreak: if (breakForLoop.top()) builder.createLoopExit(); else builder.addSwitchBreak(); break; case glslang::EOpContinue: builder.createLoopContinue(); break; case glslang::EOpReturn: if (node->getExpression()) { const glslang::TType& glslangReturnType = node->getExpression()->getType(); spv::Id returnId = accessChainLoad(glslangReturnType); if (builder.getTypeId(returnId) != currentFunction->getReturnType()) { builder.clearAccessChain(); spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType()); builder.setAccessChainLValue(copyId); multiTypeStore(glslangReturnType, returnId); returnId = builder.createLoad(copyId); } builder.makeReturn(false, returnId); } else builder.makeReturn(false); builder.clearAccessChain(); break; default: assert(0); break; } return false; } spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node) { // First, steer off constants, which are not SPIR-V variables, but // can still have a mapping to a SPIR-V Id. // This includes specialization constants. if (node->getQualifier().isConstant()) { return createSpvConstant(*node); } // Now, handle actual variables spv::StorageClass storageClass = TranslateStorageClass(node->getType()); spv::Id spvType = convertGlslangToSpvType(node->getType()); const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) || node->getType().containsBasicType(glslang::EbtInt16) || node->getType().containsBasicType(glslang::EbtUint16); if (contains16BitType) { switch (storageClass) { case spv::StorageClassInput: case spv::StorageClassOutput: addPre13Extension(spv::E_SPV_KHR_16bit_storage); builder.addCapability(spv::CapabilityStorageInputOutput16); break; case spv::StorageClassPushConstant: addPre13Extension(spv::E_SPV_KHR_16bit_storage); builder.addCapability(spv::CapabilityStoragePushConstant16); break; case spv::StorageClassUniform: addPre13Extension(spv::E_SPV_KHR_16bit_storage); if (node->getType().getQualifier().storage == glslang::EvqBuffer) builder.addCapability(spv::CapabilityStorageUniformBufferBlock16); else builder.addCapability(spv::CapabilityStorageUniform16); break; case spv::StorageClassStorageBuffer: addPre13Extension(spv::E_SPV_KHR_16bit_storage); builder.addCapability(spv::CapabilityStorageUniformBufferBlock16); break; default: break; } } const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) || node->getType().containsBasicType(glslang::EbtUint8); if (contains8BitType) { if (storageClass == spv::StorageClassPushConstant) { builder.addExtension(spv::E_SPV_KHR_8bit_storage); builder.addCapability(spv::CapabilityStoragePushConstant8); } else if (storageClass == spv::StorageClassUniform) { builder.addExtension(spv::E_SPV_KHR_8bit_storage); builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess); if (node->getType().getQualifier().storage == glslang::EvqBuffer) builder.addCapability(spv::CapabilityStorageBuffer8BitAccess); } } const char* name = node->getName().c_str(); if (glslang::IsAnonymous(name)) name = ""; return builder.createVariable(storageClass, spvType, name); } // Return type Id of the sampled type. spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler) { switch (sampler.type) { case glslang::EbtFloat: return builder.makeFloatType(32); #ifdef AMD_EXTENSIONS case glslang::EbtFloat16: builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch); builder.addCapability(spv::CapabilityFloat16ImageAMD); return builder.makeFloatType(16); #endif case glslang::EbtInt: return builder.makeIntType(32); case glslang::EbtUint: return builder.makeUintType(32); default: assert(0); return builder.makeFloatType(32); } } // If node is a swizzle operation, return the type that should be used if // the swizzle base is first consumed by another operation, before the swizzle // is applied. spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node) { if (node.getAsOperator() && node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle) return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType()); else return spv::NoType; } // When inverting a swizzle with a parent op, this function // will apply the swizzle operation to a completed parent operation. spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult) { std::vector<unsigned> swizzle; convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle); return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle); } // Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V. void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle) { const glslang::TIntermSequence& swizzleSequence = node.getSequence(); for (int i = 0; i < (int)swizzleSequence.size(); ++i) swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst()); } // Convert from a glslang type to an SPV type, by calling into a // recursive version of this function. This establishes the inherited // layout state rooted from the top-level type. spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type) { return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false); } // Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id. // explicitLayout can be kept the same throughout the hierarchical recursive walk. // Mutually recursive with convertGlslangStructToSpvType(). spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember) { spv::Id spvType = spv::NoResult; switch (type.getBasicType()) { case glslang::EbtVoid: spvType = builder.makeVoidType(); assert (! type.isArray()); break; case glslang::EbtFloat: spvType = builder.makeFloatType(32); break; case glslang::EbtDouble: spvType = builder.makeFloatType(64); break; case glslang::EbtFloat16: builder.addCapability(spv::CapabilityFloat16); #if AMD_EXTENSIONS if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3) builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float); #endif spvType = builder.makeFloatType(16); break; case glslang::EbtBool: // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is // a 32-bit int where non-0 means true. if (explicitLayout != glslang::ElpNone) spvType = builder.makeUintType(32); else spvType = builder.makeBoolType(); break; case glslang::EbtInt8: builder.addCapability(spv::CapabilityInt8); spvType = builder.makeIntType(8); break; case glslang::EbtUint8: builder.addCapability(spv::CapabilityInt8); spvType = builder.makeUintType(8); break; case glslang::EbtInt16: builder.addCapability(spv::CapabilityInt16); #ifdef AMD_EXTENSIONS if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3) builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16); #endif spvType = builder.makeIntType(16); break; case glslang::EbtUint16: builder.addCapability(spv::CapabilityInt16); #ifdef AMD_EXTENSIONS if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3) builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16); #endif spvType = builder.makeUintType(16); break; case glslang::EbtInt: spvType = builder.makeIntType(32); break; case glslang::EbtUint: spvType = builder.makeUintType(32); break; case glslang::EbtInt64: spvType = builder.makeIntType(64); break; case glslang::EbtUint64: spvType = builder.makeUintType(64); break; case glslang::EbtAtomicUint: builder.addCapability(spv::CapabilityAtomicStorage); spvType = builder.makeUintType(32); break; case glslang::EbtSampler: { const glslang::TSampler& sampler = type.getSampler(); if (sampler.sampler) { // pure sampler spvType = builder.makeSamplerType(); } else { // an image is present, make its type spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms, sampler.image ? 2 : 1, TranslateImageFormat(type)); if (sampler.combined) { // already has both image and sampler, make the combined type spvType = builder.makeSampledImageType(spvType); } } } break; case glslang::EbtStruct: case glslang::EbtBlock: { // If we've seen this struct type, return it const glslang::TTypeList* glslangMembers = type.getStruct(); // Try to share structs for different layouts, but not yet for other // kinds of qualification (primarily not yet including interpolant qualification). if (! HasNonLayoutQualifiers(type, qualifier)) spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers]; if (spvType != spv::NoResult) break; // else, we haven't seen it... if (type.getBasicType() == glslang::EbtBlock) memberRemapper[glslangMembers].resize(glslangMembers->size()); spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier); } break; default: assert(0); break; } if (type.isMatrix()) spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows()); else { // If this variable has a vector element count greater than 1, create a SPIR-V vector if (type.getVectorSize() > 1) spvType = builder.makeVectorType(spvType, type.getVectorSize()); } if (type.isArray()) { int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride // Do all but the outer dimension if (type.getArraySizes()->getNumDims() > 1) { // We need to decorate array strides for types needing explicit layout, except blocks. if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) { // Use a dummy glslang type for querying internal strides of // arrays of arrays, but using just a one-dimensional array. glslang::TType simpleArrayType(type, 0); // deference type of the array while (simpleArrayType.getArraySizes()->getNumDims() > 1) simpleArrayType.getArraySizes()->dereference(); // Will compute the higher-order strides here, rather than making a whole // pile of types and doing repetitive recursion on their contents. stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix); } // make the arrays for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) { spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride); if (stride > 0) builder.addDecoration(spvType, spv::DecorationArrayStride, stride); stride *= type.getArraySizes()->getDimSize(dim); } } else { // single-dimensional array, and don't yet have stride // We need to decorate array strides for types needing explicit layout, except blocks. if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix); } // Do the outer dimension, which might not be known for a runtime-sized array. // (Unsized arrays that survive through linking will be runtime-sized arrays) if (type.isSizedArray()) spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride); else { if (!lastBufferBlockMember) { builder.addExtension("SPV_EXT_descriptor_indexing"); builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT); } spvType = builder.makeRuntimeArray(spvType); } if (stride > 0) builder.addDecoration(spvType, spv::DecorationArrayStride, stride); } return spvType; } // TODO: this functionality should exist at a higher level, in creating the AST // // Identify interface members that don't have their required extension turned on. // bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member) { auto& extensions = glslangIntermediate->getRequestedExtensions(); if (member.getFieldName() == "gl_ViewportMask" && extensions.find("GL_NV_viewport_array2") == extensions.end()) return true; if (member.getFieldName() == "gl_SecondaryViewportMaskNV" && extensions.find("GL_NV_stereo_view_rendering") == extensions.end()) return true; if (member.getFieldName() == "gl_SecondaryPositionNV" && extensions.find("GL_NV_stereo_view_rendering") == extensions.end()) return true; if (member.getFieldName() == "gl_PositionPerViewNV" && extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end()) return true; if (member.getFieldName() == "gl_ViewportMaskPerViewNV" && extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end()) return true; return false; }; // Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id. // explicitLayout can be kept the same throughout the hierarchical recursive walk. // Mutually recursive with convertGlslangToSpvType(). spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type, const glslang::TTypeList* glslangMembers, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier) { // Create a vector of struct types for SPIR-V to consume std::vector<spv::Id> spvMembers; int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks for (int i = 0; i < (int)glslangMembers->size(); i++) { glslang::TType& glslangMember = *(*glslangMembers)[i].type; if (glslangMember.hiddenMember()) { ++memberDelta; if (type.getBasicType() == glslang::EbtBlock) memberRemapper[glslangMembers][i] = -1; } else { if (type.getBasicType() == glslang::EbtBlock) { memberRemapper[glslangMembers][i] = i - memberDelta; if (filterMember(glslangMember)) continue; } // modify just this child's view of the qualifier glslang::TQualifier memberQualifier = glslangMember.getQualifier(); InheritQualifiers(memberQualifier, qualifier); // manually inherit location if (! memberQualifier.hasLocation() && qualifier.hasLocation()) memberQualifier.layoutLocation = qualifier.layoutLocation; // recurse bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer && i == (int)glslangMembers->size() - 1; spvMembers.push_back( convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember)); } } // Make the SPIR-V type spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str()); if (! HasNonLayoutQualifiers(type, qualifier)) structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType; // Decorate it decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType); return spvType; } void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type, const glslang::TTypeList* glslangMembers, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, spv::Id spvType) { // Name and decorate the non-hidden members int offset = -1; int locationOffset = 0; // for use within the members of this struct for (int i = 0; i < (int)glslangMembers->size(); i++) { glslang::TType& glslangMember = *(*glslangMembers)[i].type; int member = i; if (type.getBasicType() == glslang::EbtBlock) { member = memberRemapper[glslangMembers][i]; if (filterMember(glslangMember)) continue; } // modify just this child's view of the qualifier glslang::TQualifier memberQualifier = glslangMember.getQualifier(); InheritQualifiers(memberQualifier, qualifier); // using -1 above to indicate a hidden member if (member < 0) continue; builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str()); builder.addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix)); builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember)); // Add interpolation and auxiliary storage decorations only to // top-level members of Input and Output storage classes if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) { if (type.getBasicType() == glslang::EbtBlock || glslangIntermediate->getSource() == glslang::EShSourceHlsl) { builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier)); builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier)); } } builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier)); if (type.getBasicType() == glslang::EbtBlock && qualifier.storage == glslang::EvqBuffer) { // Add memory decorations only to top-level members of shader storage block std::vector<spv::Decoration> memory; TranslateMemoryDecoration(memberQualifier, memory); for (unsigned int i = 0; i < memory.size(); ++i) builder.addMemberDecoration(spvType, member, memory[i]); } // Location assignment was already completed correctly by the front end, // just track whether a member needs to be decorated. // Ignore member locations if the container is an array, as that's // ill-specified and decisions have been made to not allow this. if (! type.isArray() && memberQualifier.hasLocation()) builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation); if (qualifier.hasLocation()) // track for upcoming inheritance locationOffset += glslangIntermediate->computeTypeLocationSize( glslangMember, glslangIntermediate->getStage()); // component, XFB, others if (glslangMember.getQualifier().hasComponent()) builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent); if (glslangMember.getQualifier().hasXfbOffset()) builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset); else if (explicitLayout != glslang::ElpNone) { // figure out what to do with offset, which is accumulating int nextOffset; updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix); if (offset >= 0) builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset); offset = nextOffset; } if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone) builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix)); // built-in variable decorations spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true); if (builtIn != spv::BuiltInMax) builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn); // nonuniform builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier())); if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) { builder.addExtension("SPV_GOOGLE_hlsl_functionality1"); builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE, memberQualifier.semanticName); } #ifdef NV_EXTENSIONS if (builtIn == spv::BuiltInLayer) { // SPV_NV_viewport_array2 extension if (glslangMember.getQualifier().layoutViewportRelative){ builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV); builder.addCapability(spv::CapabilityShaderViewportMaskNV); builder.addExtension(spv::E_SPV_NV_viewport_array2); } if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){ builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset); builder.addCapability(spv::CapabilityShaderStereoViewNV); builder.addExtension(spv::E_SPV_NV_stereo_view_rendering); } } if (glslangMember.getQualifier().layoutPassthrough) { builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV); builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV); builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough); } #endif } // Decorate the structure builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix)); builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer())); if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) { builder.addCapability(spv::CapabilityGeometryStreams); builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream); } } // Turn the expression forming the array size into an id. // This is not quite trivial, because of specialization constants. // Sometimes, a raw constant is turned into an Id, and sometimes // a specialization constant expression is. spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim) { // First, see if this is sized with a node, meaning a specialization constant: glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim); if (specNode != nullptr) { builder.clearAccessChain(); specNode->traverse(this); return accessChainLoad(specNode->getAsTyped()->getType()); } // Otherwise, need a compile-time (front end) size, get it: int size = arraySizes.getDimSize(dim); assert(size > 0); return builder.makeUintConstant(size); } // Wrap the builder's accessChainLoad to: // - localize handling of RelaxedPrecision // - use the SPIR-V inferred type instead of another conversion of the glslang type // (avoids unnecessary work and possible type punning for structures) // - do conversion of concrete to abstract type spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type) { spv::Id nominalTypeId = builder.accessChainGetInferredType(); spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId); // Need to convert to abstract types when necessary if (type.getBasicType() == glslang::EbtBool) { if (builder.isScalarType(nominalTypeId)) { // Conversion for bool spv::Id boolType = builder.makeBoolType(); if (nominalTypeId != boolType) loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0)); } else if (builder.isVectorType(nominalTypeId)) { // Conversion for bvec int vecSize = builder.getNumTypeComponents(nominalTypeId); spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize); if (nominalTypeId != bvecType) loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize)); } } return loadedId; } // Wrap the builder's accessChainStore to: // - do conversion of concrete to abstract type // // Implicitly uses the existing builder.accessChain as the storage target. void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue) { // Need to convert to abstract types when necessary if (type.getBasicType() == glslang::EbtBool) { spv::Id nominalTypeId = builder.accessChainGetInferredType(); if (builder.isScalarType(nominalTypeId)) { // Conversion for bool spv::Id boolType = builder.makeBoolType(); if (nominalTypeId != boolType) { // keep these outside arguments, for determinant order-of-evaluation spv::Id one = builder.makeUintConstant(1); spv::Id zero = builder.makeUintConstant(0); rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero); } else if (builder.getTypeId(rvalue) != boolType) rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0)); } else if (builder.isVectorType(nominalTypeId)) { // Conversion for bvec int vecSize = builder.getNumTypeComponents(nominalTypeId); spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize); if (nominalTypeId != bvecType) { // keep these outside arguments, for determinant order-of-evaluation spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize); spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize); rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero); } else if (builder.getTypeId(rvalue) != bvecType) rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue, makeSmearedConstant(builder.makeUintConstant(0), vecSize)); } } builder.accessChainStore(rvalue); } // For storing when types match at the glslang level, but not might match at the // SPIR-V level. // // This especially happens when a single glslang type expands to multiple // SPIR-V types, like a struct that is used in a member-undecorated way as well // as in a member-decorated way. // // NOTE: This function can handle any store request; if it's not special it // simplifies to a simple OpStore. // // Implicitly uses the existing builder.accessChain as the storage target. void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue) { // we only do the complex path here if it's an aggregate if (! type.isStruct() && ! type.isArray()) { accessChainStore(type, rValue); return; } // and, it has to be a case of type aliasing spv::Id rType = builder.getTypeId(rValue); spv::Id lValue = builder.accessChainGetLValue(); spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue)); if (lType == rType) { accessChainStore(type, rValue); return; } // Recursively (as needed) copy an aggregate type to a different aggregate type, // where the two types were the same type in GLSL. This requires member // by member copy, recursively. // If an array, copy element by element. if (type.isArray()) { glslang::TType glslangElementType(type, 0); spv::Id elementRType = builder.getContainedTypeId(rType); for (int index = 0; index < type.getOuterArraySize(); ++index) { // get the source member spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index); // set up the target storage builder.clearAccessChain(); builder.setAccessChainLValue(lValue); builder.accessChainPush(builder.makeIntConstant(index)); // store the member multiTypeStore(glslangElementType, elementRValue); } } else { assert(type.isStruct()); // loop over structure members const glslang::TTypeList& members = *type.getStruct(); for (int m = 0; m < (int)members.size(); ++m) { const glslang::TType& glslangMemberType = *members[m].type; // get the source member spv::Id memberRType = builder.getContainedTypeId(rType, m); spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m); // set up the target storage builder.clearAccessChain(); builder.setAccessChainLValue(lValue); builder.accessChainPush(builder.makeIntConstant(m)); // store the member multiTypeStore(glslangMemberType, memberRValue); } } } // Decide whether or not this type should be // decorated with offsets and strides, and if so // whether std140 or std430 rules should be applied. glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const { // has to be a block if (type.getBasicType() != glslang::EbtBlock) return glslang::ElpNone; // has to be a uniform or buffer block if (type.getQualifier().storage != glslang::EvqUniform && type.getQualifier().storage != glslang::EvqBuffer) return glslang::ElpNone; // return the layout to use switch (type.getQualifier().layoutPacking) { case glslang::ElpStd140: case glslang::ElpStd430: return type.getQualifier().layoutPacking; default: return glslang::ElpNone; } } // Given an array type, returns the integer stride required for that array int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout) { int size; int stride; glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor); return stride; } // Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix // when used as a member of an interface block int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout) { glslang::TType elementType; elementType.shallowCopy(matrixType); elementType.clearArraySizes(); int size; int stride; glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor); return stride; } // Given a member type of a struct, realign the current offset for it, and compute // the next (not yet aligned) offset for the next member, which will get aligned // on the next call. // 'currentOffset' should be passed in already initialized, ready to modify, and reflecting // the migration of data from nextOffset -> currentOffset. It should be -1 on the first call. // -1 means a non-forced member offset (no decoration needed). void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout) { // this will get a positive value when deemed necessary nextOffset = -1; // override anything in currentOffset with user-set offset if (memberType.getQualifier().hasOffset()) currentOffset = memberType.getQualifier().layoutOffset; // It could be that current linker usage in glslang updated all the layoutOffset, // in which case the following code does not matter. But, that's not quite right // once cross-compilation unit GLSL validation is done, as the original user // settings are needed in layoutOffset, and then the following will come into play. if (explicitLayout == glslang::ElpNone) { if (! memberType.getQualifier().hasOffset()) currentOffset = -1; return; } // Getting this far means we need explicit offsets if (currentOffset < 0) currentOffset = 0; // Now, currentOffset is valid (either 0, or from a previous nextOffset), // but possibly not yet correctly aligned. int memberSize; int dummyStride; int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor); // Adjust alignment for HLSL rules // TODO: make this consistent in early phases of code: // adjusting this late means inconsistencies with earlier code, which for reflection is an issue // Until reflection is brought in sync with these adjustments, don't apply to $Global, // which is the most likely to rely on reflection, and least likely to rely implicit layouts if (glslangIntermediate->usingHlslOFfsets() && ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) { int dummySize; int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize); if (componentAlignment <= 4) memberAlignment = componentAlignment; } // Bump up to member alignment glslang::RoundToPow2(currentOffset, memberAlignment); // Bump up to vec4 if there is a bad straddle if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset)) glslang::RoundToPow2(currentOffset, 16); nextOffset = currentOffset + memberSize; } void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember) { const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn; switch (glslangBuiltIn) { case glslang::EbvClipDistance: case glslang::EbvCullDistance: case glslang::EbvPointSize: #ifdef NV_EXTENSIONS case glslang::EbvViewportMaskNV: case glslang::EbvSecondaryPositionNV: case glslang::EbvSecondaryViewportMaskNV: case glslang::EbvPositionPerViewNV: case glslang::EbvViewportMaskPerViewNV: #endif // Generate the associated capability. Delegate to TranslateBuiltInDecoration. // Alternately, we could just call this for any glslang built-in, since the // capability already guards against duplicates. TranslateBuiltInDecoration(glslangBuiltIn, false); break; default: // Capabilities were already generated when the struct was declared. break; } } bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node) { return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0; } // Does parameter need a place to keep writes, separate from the original? // Assumes called after originalParam(), which filters out block/buffer/opaque-based // qualifiers such that we should have only in/out/inout/constreadonly here. bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const { assert(qualifier == glslang::EvqIn || qualifier == glslang::EvqOut || qualifier == glslang::EvqInOut || qualifier == glslang::EvqConstReadOnly); return qualifier != glslang::EvqConstReadOnly; } // Is parameter pass-by-original? bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType, bool implicitThisParam) { if (implicitThisParam) // implicit this return true; if (glslangIntermediate->getSource() == glslang::EShSourceHlsl) return paramType.getBasicType() == glslang::EbtBlock; return paramType.containsOpaque() || // sampler, etc. (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO } // Make all the functions, skeletally, without actually visiting their bodies. void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions) { const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) { spv::Decoration paramPrecision = TranslatePrecisionDecoration(type); if (paramPrecision != spv::NoPrecision) decorations.push_back(paramPrecision); TranslateMemoryDecoration(type.getQualifier(), decorations); }; for (int f = 0; f < (int)glslFunctions.size(); ++f) { glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate(); if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction)) continue; // We're on a user function. Set up the basic interface for the function now, // so that it's available to call. Translating the body will happen later. // // Typically (except for a "const in" parameter), an address will be passed to the // function. What it is an address of varies: // // - "in" parameters not marked as "const" can be written to without modifying the calling // argument so that write needs to be to a copy, hence the address of a copy works. // // - "const in" parameters can just be the r-value, as no writes need occur. // // - "out" and "inout" arguments can't be done as pointers to the calling argument, because // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy. std::vector<spv::Id> paramTypes; std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence(); bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName; paramDecorations.resize(parameters.size()); for (int p = 0; p < (int)parameters.size(); ++p) { const glslang::TType& paramType = parameters[p]->getAsTyped()->getType(); spv::Id typeId = convertGlslangToSpvType(paramType); if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0)) typeId = builder.makePointer(TranslateStorageClass(paramType), typeId); else if (writableParam(paramType.getQualifier().storage)) typeId = builder.makePointer(spv::StorageClassFunction, typeId); else rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId()); getParamDecorations(paramDecorations[p], paramType); paramTypes.push_back(typeId); } spv::Block* functionBlock; spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()), convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(), paramTypes, paramDecorations, &functionBlock); if (implicitThis) function->setImplicitThis(); // Track function to emit/call later functionMap[glslFunction->getName().c_str()] = function; // Set the parameter id's for (int p = 0; p < (int)parameters.size(); ++p) { symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p); // give a name too builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str()); } } } // Process all the initializers, while skipping the functions and link objects void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers) { builder.setBuildPoint(shaderEntry->getLastBlock()); for (int i = 0; i < (int)initializers.size(); ++i) { glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate(); if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) { // We're on a top-level node that's not a function. Treat as an initializer, whose // code goes into the beginning of the entry point. initializer->traverse(this); } } } // Process all the functions, while skipping initializers. void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions) { for (int f = 0; f < (int)glslFunctions.size(); ++f) { glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate(); if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects)) node->traverse(this); } } void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node) { // SPIR-V functions should already be in the functionMap from the prepass // that called makeFunctions(). currentFunction = functionMap[node->getName().c_str()]; spv::Block* functionBlock = currentFunction->getEntryBlock(); builder.setBuildPoint(functionBlock); } void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments) { const glslang::TIntermSequence& glslangArguments = node.getSequence(); glslang::TSampler sampler = {}; bool cubeCompare = false; #ifdef AMD_EXTENSIONS bool f16ShadowCompare = false; #endif if (node.isTexture() || node.isImage()) { sampler = glslangArguments[0]->getAsTyped()->getType().getSampler(); cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow; #ifdef AMD_EXTENSIONS f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16; #endif } for (int i = 0; i < (int)glslangArguments.size(); ++i) { builder.clearAccessChain(); glslangArguments[i]->traverse(this); // Special case l-value operands bool lvalue = false; switch (node.getOp()) { case glslang::EOpImageAtomicAdd: case glslang::EOpImageAtomicMin: case glslang::EOpImageAtomicMax: case glslang::EOpImageAtomicAnd: case glslang::EOpImageAtomicOr: case glslang::EOpImageAtomicXor: case glslang::EOpImageAtomicExchange: case glslang::EOpImageAtomicCompSwap: if (i == 0) lvalue = true; break; case glslang::EOpSparseImageLoad: if ((sampler.ms && i == 3) || (! sampler.ms && i == 2)) lvalue = true; break; #ifdef AMD_EXTENSIONS case glslang::EOpSparseTexture: if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2)) lvalue = true; break; case glslang::EOpSparseTextureClamp: if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3)) lvalue = true; break; case glslang::EOpSparseTextureLod: case glslang::EOpSparseTextureOffset: if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3)) lvalue = true; break; #else case glslang::EOpSparseTexture: if ((cubeCompare && i == 3) || (! cubeCompare && i == 2)) lvalue = true; break; case glslang::EOpSparseTextureClamp: if ((cubeCompare && i == 4) || (! cubeCompare && i == 3)) lvalue = true; break; case glslang::EOpSparseTextureLod: case glslang::EOpSparseTextureOffset: if (i == 3) lvalue = true; break; #endif case glslang::EOpSparseTextureFetch: if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2)) lvalue = true; break; case glslang::EOpSparseTextureFetchOffset: if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3)) lvalue = true; break; #ifdef AMD_EXTENSIONS case glslang::EOpSparseTextureLodOffset: case glslang::EOpSparseTextureGrad: case glslang::EOpSparseTextureOffsetClamp: if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4)) lvalue = true; break; case glslang::EOpSparseTextureGradOffset: case glslang::EOpSparseTextureGradClamp: if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5)) lvalue = true; break; case glslang::EOpSparseTextureGradOffsetClamp: if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6)) lvalue = true; break; #else case glslang::EOpSparseTextureLodOffset: case glslang::EOpSparseTextureGrad: case glslang::EOpSparseTextureOffsetClamp: if (i == 4) lvalue = true; break; case glslang::EOpSparseTextureGradOffset: case glslang::EOpSparseTextureGradClamp: if (i == 5) lvalue = true; break; case glslang::EOpSparseTextureGradOffsetClamp: if (i == 6) lvalue = true; break; #endif case glslang::EOpSparseTextureGather: if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2)) lvalue = true; break; case glslang::EOpSparseTextureGatherOffset: case glslang::EOpSparseTextureGatherOffsets: if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3)) lvalue = true; break; #ifdef AMD_EXTENSIONS case glslang::EOpSparseTextureGatherLod: if (i == 3) lvalue = true; break; case glslang::EOpSparseTextureGatherLodOffset: case glslang::EOpSparseTextureGatherLodOffsets: if (i == 4) lvalue = true; break; case glslang::EOpSparseImageLoadLod: if (i == 3) lvalue = true; break; #endif default: break; } if (lvalue) arguments.push_back(builder.accessChainGetLValue()); else arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType())); } } void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments) { builder.clearAccessChain(); node.getOperand()->traverse(this); arguments.push_back(accessChainLoad(node.getOperand()->getType())); } spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node) { if (! node->isImage() && ! node->isTexture()) return spv::NoResult; builder.setLine(node->getLoc().line); // Process a GLSL texturing op (will be SPV image) const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler() : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler(); #ifdef AMD_EXTENSIONS bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate()) ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16 : false; #endif std::vector<spv::Id> arguments; if (node->getAsAggregate()) translateArguments(*node->getAsAggregate(), arguments); else translateArguments(*node->getAsUnaryNode(), arguments); spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision()); spv::Builder::TextureParameters params = { }; params.sampler = arguments[0]; glslang::TCrackedTextureOp cracked; node->crackTexture(sampler, cracked); const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint; // Check for queries if (cracked.query) { // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler)) params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler); switch (node->getOp()) { case glslang::EOpImageQuerySize: case glslang::EOpTextureQuerySize: if (arguments.size() > 1) { params.lod = arguments[1]; return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult); } else return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult); case glslang::EOpImageQuerySamples: case glslang::EOpTextureQuerySamples: return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult); case glslang::EOpTextureQueryLod: params.coords = arguments[1]; return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult); case glslang::EOpTextureQueryLevels: return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult); case glslang::EOpSparseTexelsResident: return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]); default: assert(0); break; } } int components = node->getType().getVectorSize(); if (node->getOp() == glslang::EOpTextureFetch) { // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed. // This will only happen through the HLSL path for operator[], so we do not have to handle e.g. // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic // here around e.g. which ones return scalars or other types. components = 4; } glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components); auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); }; // Check for image functions other than queries if (node->isImage()) { std::vector<spv::Id> operands; auto opIt = arguments.begin(); operands.push_back(*(opIt++)); // Handle subpass operations // TODO: GLSL should change to have the "MS" only on the type rather than the // built-in function. if (cracked.subpass) { // add on the (0,0) coordinate spv::Id zero = builder.makeIntConstant(0); std::vector<spv::Id> comps; comps.push_back(zero); comps.push_back(zero); operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps)); if (sampler.ms) { operands.push_back(spv::ImageOperandsSampleMask); operands.push_back(*(opIt++)); } spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands); builder.setPrecision(result, precision); return result; } operands.push_back(*(opIt++)); #ifdef AMD_EXTENSIONS if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) { #else if (node->getOp() == glslang::EOpImageLoad) { #endif if (sampler.ms) { operands.push_back(spv::ImageOperandsSampleMask); operands.push_back(*opIt); #ifdef AMD_EXTENSIONS } else if (cracked.lod) { builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod); builder.addCapability(spv::CapabilityImageReadWriteLodAMD); operands.push_back(spv::ImageOperandsLodMask); operands.push_back(*opIt); #endif } if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown) builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat); std::vector<spv::Id> result( 1, builder.createOp(spv::OpImageRead, resultType(), operands) ); builder.setPrecision(result[0], precision); // If needed, add a conversion constructor to the proper size. if (components != node->getType().getVectorSize()) result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType())); return result[0]; #ifdef AMD_EXTENSIONS } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) { #else } else if (node->getOp() == glslang::EOpImageStore) { #endif if (sampler.ms) { operands.push_back(*(opIt + 1)); operands.push_back(spv::ImageOperandsSampleMask); operands.push_back(*opIt); #ifdef AMD_EXTENSIONS } else if (cracked.lod) { builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod); builder.addCapability(spv::CapabilityImageReadWriteLodAMD); operands.push_back(*(opIt + 1)); operands.push_back(spv::ImageOperandsLodMask); operands.push_back(*opIt); #endif } else operands.push_back(*opIt); builder.createNoResultOp(spv::OpImageWrite, operands); if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown) builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat); return spv::NoResult; #ifdef AMD_EXTENSIONS } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) { #else } else if (node->getOp() == glslang::EOpSparseImageLoad) { #endif builder.addCapability(spv::CapabilitySparseResidency); if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown) builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat); if (sampler.ms) { operands.push_back(spv::ImageOperandsSampleMask); operands.push_back(*opIt++); #ifdef AMD_EXTENSIONS } else if (cracked.lod) { builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod); builder.addCapability(spv::CapabilityImageReadWriteLodAMD); operands.push_back(spv::ImageOperandsLodMask); operands.push_back(*opIt++); #endif } // Create the return type that was a special structure spv::Id texelOut = *opIt; spv::Id typeId0 = resultType(); spv::Id typeId1 = builder.getDerefTypeId(texelOut); spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1); spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands); // Decode the return type builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut); return builder.createCompositeExtract(resultId, typeId0, 0); } else { // Process image atomic operations // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer, // as the first source operand, is required by SPIR-V atomic operations. operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType()); spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands); std::vector<spv::Id> operands; operands.push_back(pointer); for (; opIt != arguments.end(); ++opIt) operands.push_back(*opIt); return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType()); } } #ifdef AMD_EXTENSIONS // Check for fragment mask functions other than queries if (cracked.fragMask) { assert(sampler.ms); auto opIt = arguments.begin(); std::vector<spv::Id> operands; // Extract the image if necessary if (builder.isSampledImage(params.sampler)) params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler); operands.push_back(params.sampler); ++opIt; if (sampler.isSubpass()) { // add on the (0,0) coordinate spv::Id zero = builder.makeIntConstant(0); std::vector<spv::Id> comps; comps.push_back(zero); comps.push_back(zero); operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps)); } for (; opIt != arguments.end(); ++opIt) operands.push_back(*opIt); spv::Op fragMaskOp = spv::OpNop; if (node->getOp() == glslang::EOpFragmentMaskFetch) fragMaskOp = spv::OpFragmentMaskFetchAMD; else if (node->getOp() == glslang::EOpFragmentFetch) fragMaskOp = spv::OpFragmentFetchAMD; builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask); builder.addCapability(spv::CapabilityFragmentMaskAMD); return builder.createOp(fragMaskOp, resultType(), operands); } #endif // Check for texture functions other than queries bool sparse = node->isSparseTexture(); bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow; // check for bias argument bool bias = false; #ifdef AMD_EXTENSIONS if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) { #else if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) { #endif int nonBiasArgCount = 2; #ifdef AMD_EXTENSIONS if (cracked.gather) ++nonBiasArgCount; // comp argument should be present when bias argument is present if (f16ShadowCompare) ++nonBiasArgCount; #endif if (cracked.offset) ++nonBiasArgCount; #ifdef AMD_EXTENSIONS else if (cracked.offsets) ++nonBiasArgCount; #endif if (cracked.grad) nonBiasArgCount += 2; if (cracked.lodClamp) ++nonBiasArgCount; if (sparse) ++nonBiasArgCount; if ((int)arguments.size() > nonBiasArgCount) bias = true; } // See if the sampler param should really be just the SPV image part if (cracked.fetch) { // a fetch needs to have the image extracted first if (builder.isSampledImage(params.sampler)) params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler); } #ifdef AMD_EXTENSIONS if (cracked.gather) { const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions(); if (bias || cracked.lod || sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) { builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod); builder.addCapability(spv::CapabilityImageGatherBiasLodAMD); } } #endif // set the rest of the arguments params.coords = arguments[1]; int extraArgs = 0; bool noImplicitLod = false; // sort out where Dref is coming from #ifdef AMD_EXTENSIONS if (cubeCompare || f16ShadowCompare) { #else if (cubeCompare) { #endif params.Dref = arguments[2]; ++extraArgs; } else if (sampler.shadow && cracked.gather) { params.Dref = arguments[2]; ++extraArgs; } else if (sampler.shadow) { std::vector<spv::Id> indexes; int dRefComp; if (cracked.proj) dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref" else dRefComp = builder.getNumComponents(params.coords) - 1; indexes.push_back(dRefComp); params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes); } // lod if (cracked.lod) { params.lod = arguments[2 + extraArgs]; ++extraArgs; } else if (glslangIntermediate->getStage() != EShLangFragment) { // we need to invent the default lod for an explicit lod instruction for a non-fragment stage noImplicitLod = true; } // multisample if (sampler.ms) { params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified ++extraArgs; } // gradient if (cracked.grad) { params.gradX = arguments[2 + extraArgs]; params.gradY = arguments[3 + extraArgs]; extraArgs += 2; } // offset and offsets if (cracked.offset) { params.offset = arguments[2 + extraArgs]; ++extraArgs; } else if (cracked.offsets) { params.offsets = arguments[2 + extraArgs]; ++extraArgs; } // lod clamp if (cracked.lodClamp) { params.lodClamp = arguments[2 + extraArgs]; ++extraArgs; } // sparse if (sparse) { params.texelOut = arguments[2 + extraArgs]; ++extraArgs; } // gather component if (cracked.gather && ! sampler.shadow) { // default component is 0, if missing, otherwise an argument if (2 + extraArgs < (int)arguments.size()) { params.component = arguments[2 + extraArgs]; ++extraArgs; } else params.component = builder.makeIntConstant(0); } // bias if (bias) { params.bias = arguments[2 + extraArgs]; ++extraArgs; } // projective component (might not to move) // GLSL: "The texture coordinates consumed from P, not including the last component of P, // are divided by the last component of P." // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all // unused components will appear after all used components." if (cracked.proj) { int projSourceComp = builder.getNumComponents(params.coords) - 1; int projTargetComp; switch (sampler.dim) { case glslang::Esd1D: projTargetComp = 1; break; case glslang::Esd2D: projTargetComp = 2; break; case glslang::EsdRect: projTargetComp = 2; break; default: projTargetComp = projSourceComp; break; } // copy the projective coordinate if we have to if (projTargetComp != projSourceComp) { spv::Id projComp = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp); params.coords = builder.createCompositeInsert(projComp, params.coords, builder.getTypeId(params.coords), projTargetComp); } } std::vector<spv::Id> result( 1, builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params) ); if (components != node->getType().getVectorSize()) result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType())); return result[0]; } spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node) { // Grab the function's pointer from the previously created function spv::Function* function = functionMap[node->getName().c_str()]; if (! function) return 0; const glslang::TIntermSequence& glslangArgs = node->getSequence(); const glslang::TQualifierList& qualifiers = node->getQualifierList(); // See comments in makeFunctions() for details about the semantics for parameter passing. // // These imply we need a four step process: // 1. Evaluate the arguments // 2. Allocate and make copies of in, out, and inout arguments // 3. Make the call // 4. Copy back the results // 1. Evaluate the arguments and their types std::vector<spv::Builder::AccessChain> lValues; std::vector<spv::Id> rValues; std::vector<const glslang::TType*> argTypes; for (int a = 0; a < (int)glslangArgs.size(); ++a) { argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType()); // build l-value builder.clearAccessChain(); glslangArgs[a]->traverse(this); // keep outputs and pass-by-originals as l-values, evaluate others as r-values if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) || writableParam(qualifiers[a])) { // save l-value lValues.push_back(builder.getAccessChain()); } else { // process r-value rValues.push_back(accessChainLoad(*argTypes.back())); } } // 2. Allocate space for anything needing a copy, and if it's "in" or "inout" // copy the original into that space. // // Also, build up the list of actual arguments to pass in for the call int lValueCount = 0; int rValueCount = 0; std::vector<spv::Id> spvArgs; for (int a = 0; a < (int)glslangArgs.size(); ++a) { spv::Id arg; if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) { builder.setAccessChain(lValues[lValueCount]); arg = builder.accessChainGetLValue(); ++lValueCount; } else if (writableParam(qualifiers[a])) { // need space to hold the copy arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param"); if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) { // need to copy the input into output space builder.setAccessChain(lValues[lValueCount]); spv::Id copy = accessChainLoad(*argTypes[a]); builder.clearAccessChain(); builder.setAccessChainLValue(arg); multiTypeStore(*argTypes[a], copy); } ++lValueCount; } else { // process r-value, which involves a copy for a type mismatch if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) { spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg"); builder.clearAccessChain(); builder.setAccessChainLValue(argCopy); multiTypeStore(*argTypes[a], rValues[rValueCount]); arg = builder.createLoad(argCopy); } else arg = rValues[rValueCount]; ++rValueCount; } spvArgs.push_back(arg); } // 3. Make the call. spv::Id result = builder.createFunctionCall(function, spvArgs); builder.setPrecision(result, TranslatePrecisionDecoration(node->getType())); // 4. Copy back out an "out" arguments. lValueCount = 0; for (int a = 0; a < (int)glslangArgs.size(); ++a) { if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) ++lValueCount; else if (writableParam(qualifiers[a])) { if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) { spv::Id copy = builder.createLoad(spvArgs[a]); builder.setAccessChain(lValues[lValueCount]); multiTypeStore(*argTypes[a], copy); } ++lValueCount; } } return result; } // Translate AST operation to SPV operation, already having SPV-based operands/types. spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison) { bool isUnsigned = isTypeUnsignedInt(typeProxy); bool isFloat = isTypeFloat(typeProxy); bool isBool = typeProxy == glslang::EbtBool; spv::Op binOp = spv::OpNop; bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector? bool comparison = false; switch (op) { case glslang::EOpAdd: case glslang::EOpAddAssign: if (isFloat) binOp = spv::OpFAdd; else binOp = spv::OpIAdd; break; case glslang::EOpSub: case glslang::EOpSubAssign: if (isFloat) binOp = spv::OpFSub; else binOp = spv::OpISub; break; case glslang::EOpMul: case glslang::EOpMulAssign: if (isFloat) binOp = spv::OpFMul; else binOp = spv::OpIMul; break; case glslang::EOpVectorTimesScalar: case glslang::EOpVectorTimesScalarAssign: if (isFloat && (builder.isVector(left) || builder.isVector(right))) { if (builder.isVector(right)) std::swap(left, right); assert(builder.isScalar(right)); needMatchingVectors = false; binOp = spv::OpVectorTimesScalar; } else binOp = spv::OpIMul; break; case glslang::EOpVectorTimesMatrix: case glslang::EOpVectorTimesMatrixAssign: binOp = spv::OpVectorTimesMatrix; break; case glslang::EOpMatrixTimesVector: binOp = spv::OpMatrixTimesVector; break; case glslang::EOpMatrixTimesScalar: case glslang::EOpMatrixTimesScalarAssign: binOp = spv::OpMatrixTimesScalar; break; case glslang::EOpMatrixTimesMatrix: case glslang::EOpMatrixTimesMatrixAssign: binOp = spv::OpMatrixTimesMatrix; break; case glslang::EOpOuterProduct: binOp = spv::OpOuterProduct; needMatchingVectors = false; break; case glslang::EOpDiv: case glslang::EOpDivAssign: if (isFloat) binOp = spv::OpFDiv; else if (isUnsigned) binOp = spv::OpUDiv; else binOp = spv::OpSDiv; break; case glslang::EOpMod: case glslang::EOpModAssign: if (isFloat) binOp = spv::OpFMod; else if (isUnsigned) binOp = spv::OpUMod; else binOp = spv::OpSMod; break; case glslang::EOpRightShift: case glslang::EOpRightShiftAssign: if (isUnsigned) binOp = spv::OpShiftRightLogical; else binOp = spv::OpShiftRightArithmetic; break; case glslang::EOpLeftShift: case glslang::EOpLeftShiftAssign: binOp = spv::OpShiftLeftLogical; break; case glslang::EOpAnd: case glslang::EOpAndAssign: binOp = spv::OpBitwiseAnd; break; case glslang::EOpLogicalAnd: needMatchingVectors = false; binOp = spv::OpLogicalAnd; break; case glslang::EOpInclusiveOr: case glslang::EOpInclusiveOrAssign: binOp = spv::OpBitwiseOr; break; case glslang::EOpLogicalOr: needMatchingVectors = false; binOp = spv::OpLogicalOr; break; case glslang::EOpExclusiveOr: case glslang::EOpExclusiveOrAssign: binOp = spv::OpBitwiseXor; break; case glslang::EOpLogicalXor: needMatchingVectors = false; binOp = spv::OpLogicalNotEqual; break; case glslang::EOpLessThan: case glslang::EOpGreaterThan: case glslang::EOpLessThanEqual: case glslang::EOpGreaterThanEqual: case glslang::EOpEqual: case glslang::EOpNotEqual: case glslang::EOpVectorEqual: case glslang::EOpVectorNotEqual: comparison = true; break; default: break; } // handle mapped binary operations (should be non-comparison) if (binOp != spv::OpNop) { assert(comparison == false); if (builder.isMatrix(left) || builder.isMatrix(right)) return createBinaryMatrixOperation(binOp, decorations, typeId, left, right); // No matrix involved; make both operands be the same number of components, if needed if (needMatchingVectors) builder.promoteScalar(decorations.precision, left, right); spv::Id result = builder.createBinOp(binOp, typeId, left, right); builder.addDecoration(result, decorations.noContraction); builder.addDecoration(result, decorations.nonUniform); return builder.setPrecision(result, decorations.precision); } if (! comparison) return 0; // Handle comparison instructions if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual) && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) { spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual); builder.addDecoration(result, decorations.nonUniform); return result; } switch (op) { case glslang::EOpLessThan: if (isFloat) binOp = spv::OpFOrdLessThan; else if (isUnsigned) binOp = spv::OpULessThan; else binOp = spv::OpSLessThan; break; case glslang::EOpGreaterThan: if (isFloat) binOp = spv::OpFOrdGreaterThan; else if (isUnsigned) binOp = spv::OpUGreaterThan; else binOp = spv::OpSGreaterThan; break; case glslang::EOpLessThanEqual: if (isFloat) binOp = spv::OpFOrdLessThanEqual; else if (isUnsigned) binOp = spv::OpULessThanEqual; else binOp = spv::OpSLessThanEqual; break; case glslang::EOpGreaterThanEqual: if (isFloat) binOp = spv::OpFOrdGreaterThanEqual; else if (isUnsigned) binOp = spv::OpUGreaterThanEqual; else binOp = spv::OpSGreaterThanEqual; break; case glslang::EOpEqual: case glslang::EOpVectorEqual: if (isFloat) binOp = spv::OpFOrdEqual; else if (isBool) binOp = spv::OpLogicalEqual; else binOp = spv::OpIEqual; break; case glslang::EOpNotEqual: case glslang::EOpVectorNotEqual: if (isFloat) binOp = spv::OpFOrdNotEqual; else if (isBool) binOp = spv::OpLogicalNotEqual; else binOp = spv::OpINotEqual; break; default: break; } if (binOp != spv::OpNop) { spv::Id result = builder.createBinOp(binOp, typeId, left, right); builder.addDecoration(result, decorations.noContraction); builder.addDecoration(result, decorations.nonUniform); return builder.setPrecision(result, decorations.precision); } return 0; } // // Translate AST matrix operation to SPV operation, already having SPV-based operands/types. // These can be any of: // // matrix * scalar // scalar * matrix // matrix * matrix linear algebraic // matrix * vector // vector * matrix // matrix * matrix componentwise // matrix op matrix op in {+, -, /} // matrix op scalar op in {+, -, /} // scalar op matrix op in {+, -, /} // spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId, spv::Id left, spv::Id right) { bool firstClass = true; // First, handle first-class matrix operations (* and matrix/scalar) switch (op) { case spv::OpFDiv: if (builder.isMatrix(left) && builder.isScalar(right)) { // turn matrix / scalar into a multiply... spv::Id resultType = builder.getTypeId(right); right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right); op = spv::OpMatrixTimesScalar; } else firstClass = false; break; case spv::OpMatrixTimesScalar: if (builder.isMatrix(right)) std::swap(left, right); assert(builder.isScalar(right)); break; case spv::OpVectorTimesMatrix: assert(builder.isVector(left)); assert(builder.isMatrix(right)); break; case spv::OpMatrixTimesVector: assert(builder.isMatrix(left)); assert(builder.isVector(right)); break; case spv::OpMatrixTimesMatrix: assert(builder.isMatrix(left)); assert(builder.isMatrix(right)); break; default: firstClass = false; break; } if (firstClass) { spv::Id result = builder.createBinOp(op, typeId, left, right); builder.addDecoration(result, decorations.noContraction); builder.addDecoration(result, decorations.nonUniform); return builder.setPrecision(result, decorations.precision); } // Handle component-wise +, -, *, %, and / for all combinations of type. // The result type of all of them is the same type as the (a) matrix operand. // The algorithm is to: // - break the matrix(es) into vectors // - smear any scalar to a vector // - do vector operations // - make a matrix out the vector results switch (op) { case spv::OpFAdd: case spv::OpFSub: case spv::OpFDiv: case spv::OpFMod: case spv::OpFMul: { // one time set up... bool leftMat = builder.isMatrix(left); bool rightMat = builder.isMatrix(right); unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right); int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right); spv::Id scalarType = builder.getScalarTypeId(typeId); spv::Id vecType = builder.makeVectorType(scalarType, numRows); std::vector<spv::Id> results; spv::Id smearVec = spv::NoResult; if (builder.isScalar(left)) smearVec = builder.smearScalar(decorations.precision, left, vecType); else if (builder.isScalar(right)) smearVec = builder.smearScalar(decorations.precision, right, vecType); // do each vector op for (unsigned int c = 0; c < numCols; ++c) { std::vector<unsigned int> indexes; indexes.push_back(c); spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec; spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec; spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec); builder.addDecoration(result, decorations.noContraction); builder.addDecoration(result, decorations.nonUniform); results.push_back(builder.setPrecision(result, decorations.precision)); } // put the pieces together spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision); builder.addDecoration(result, decorations.nonUniform); return result; } default: assert(0); return spv::NoResult; } } spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy) { spv::Op unaryOp = spv::OpNop; int extBuiltins = -1; int libCall = -1; bool isUnsigned = isTypeUnsignedInt(typeProxy); bool isFloat = isTypeFloat(typeProxy); switch (op) { case glslang::EOpNegative: if (isFloat) { unaryOp = spv::OpFNegate; if (builder.isMatrixType(typeId)) return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy); } else unaryOp = spv::OpSNegate; break; case glslang::EOpLogicalNot: case glslang::EOpVectorLogicalNot: unaryOp = spv::OpLogicalNot; break; case glslang::EOpBitwiseNot: unaryOp = spv::OpNot; break; case glslang::EOpDeterminant: libCall = spv::GLSLstd450Determinant; break; case glslang::EOpMatrixInverse: libCall = spv::GLSLstd450MatrixInverse; break; case glslang::EOpTranspose: unaryOp = spv::OpTranspose; break; case glslang::EOpRadians: libCall = spv::GLSLstd450Radians; break; case glslang::EOpDegrees: libCall = spv::GLSLstd450Degrees; break; case glslang::EOpSin: libCall = spv::GLSLstd450Sin; break; case glslang::EOpCos: libCall = spv::GLSLstd450Cos; break; case glslang::EOpTan: libCall = spv::GLSLstd450Tan; break; case glslang::EOpAcos: libCall = spv::GLSLstd450Acos; break; case glslang::EOpAsin: libCall = spv::GLSLstd450Asin; break; case glslang::EOpAtan: libCall = spv::GLSLstd450Atan; break; case glslang::EOpAcosh: libCall = spv::GLSLstd450Acosh; break; case glslang::EOpAsinh: libCall = spv::GLSLstd450Asinh; break; case glslang::EOpAtanh: libCall = spv::GLSLstd450Atanh; break; case glslang::EOpTanh: libCall = spv::GLSLstd450Tanh; break; case glslang::EOpCosh: libCall = spv::GLSLstd450Cosh; break; case glslang::EOpSinh: libCall = spv::GLSLstd450Sinh; break; case glslang::EOpLength: libCall = spv::GLSLstd450Length; break; case glslang::EOpNormalize: libCall = spv::GLSLstd450Normalize; break; case glslang::EOpExp: libCall = spv::GLSLstd450Exp; break; case glslang::EOpLog: libCall = spv::GLSLstd450Log; break; case glslang::EOpExp2: libCall = spv::GLSLstd450Exp2; break; case glslang::EOpLog2: libCall = spv::GLSLstd450Log2; break; case glslang::EOpSqrt: libCall = spv::GLSLstd450Sqrt; break; case glslang::EOpInverseSqrt: libCall = spv::GLSLstd450InverseSqrt; break; case glslang::EOpFloor: libCall = spv::GLSLstd450Floor; break; case glslang::EOpTrunc: libCall = spv::GLSLstd450Trunc; break; case glslang::EOpRound: libCall = spv::GLSLstd450Round; break; case glslang::EOpRoundEven: libCall = spv::GLSLstd450RoundEven; break; case glslang::EOpCeil: libCall = spv::GLSLstd450Ceil; break; case glslang::EOpFract: libCall = spv::GLSLstd450Fract; break; case glslang::EOpIsNan: unaryOp = spv::OpIsNan; break; case glslang::EOpIsInf: unaryOp = spv::OpIsInf; break; case glslang::EOpIsFinite: unaryOp = spv::OpIsFinite; break; case glslang::EOpFloatBitsToInt: case glslang::EOpFloatBitsToUint: case glslang::EOpIntBitsToFloat: case glslang::EOpUintBitsToFloat: case glslang::EOpDoubleBitsToInt64: case glslang::EOpDoubleBitsToUint64: case glslang::EOpInt64BitsToDouble: case glslang::EOpUint64BitsToDouble: case glslang::EOpFloat16BitsToInt16: case glslang::EOpFloat16BitsToUint16: case glslang::EOpInt16BitsToFloat16: case glslang::EOpUint16BitsToFloat16: unaryOp = spv::OpBitcast; break; case glslang::EOpPackSnorm2x16: libCall = spv::GLSLstd450PackSnorm2x16; break; case glslang::EOpUnpackSnorm2x16: libCall = spv::GLSLstd450UnpackSnorm2x16; break; case glslang::EOpPackUnorm2x16: libCall = spv::GLSLstd450PackUnorm2x16; break; case glslang::EOpUnpackUnorm2x16: libCall = spv::GLSLstd450UnpackUnorm2x16; break; case glslang::EOpPackHalf2x16: libCall = spv::GLSLstd450PackHalf2x16; break; case glslang::EOpUnpackHalf2x16: libCall = spv::GLSLstd450UnpackHalf2x16; break; case glslang::EOpPackSnorm4x8: libCall = spv::GLSLstd450PackSnorm4x8; break; case glslang::EOpUnpackSnorm4x8: libCall = spv::GLSLstd450UnpackSnorm4x8; break; case glslang::EOpPackUnorm4x8: libCall = spv::GLSLstd450PackUnorm4x8; break; case glslang::EOpUnpackUnorm4x8: libCall = spv::GLSLstd450UnpackUnorm4x8; break; case glslang::EOpPackDouble2x32: libCall = spv::GLSLstd450PackDouble2x32; break; case glslang::EOpUnpackDouble2x32: libCall = spv::GLSLstd450UnpackDouble2x32; break; case glslang::EOpPackInt2x32: case glslang::EOpUnpackInt2x32: case glslang::EOpPackUint2x32: case glslang::EOpUnpackUint2x32: case glslang::EOpPack16: case glslang::EOpPack32: case glslang::EOpPack64: case glslang::EOpUnpack32: case glslang::EOpUnpack16: case glslang::EOpUnpack8: case glslang::EOpPackInt2x16: case glslang::EOpUnpackInt2x16: case glslang::EOpPackUint2x16: case glslang::EOpUnpackUint2x16: case glslang::EOpPackInt4x16: case glslang::EOpUnpackInt4x16: case glslang::EOpPackUint4x16: case glslang::EOpUnpackUint4x16: case glslang::EOpPackFloat2x16: case glslang::EOpUnpackFloat2x16: unaryOp = spv::OpBitcast; break; case glslang::EOpDPdx: unaryOp = spv::OpDPdx; break; case glslang::EOpDPdy: unaryOp = spv::OpDPdy; break; case glslang::EOpFwidth: unaryOp = spv::OpFwidth; break; case glslang::EOpDPdxFine: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpDPdxFine; break; case glslang::EOpDPdyFine: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpDPdyFine; break; case glslang::EOpFwidthFine: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpFwidthFine; break; case glslang::EOpDPdxCoarse: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpDPdxCoarse; break; case glslang::EOpDPdyCoarse: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpDPdyCoarse; break; case glslang::EOpFwidthCoarse: builder.addCapability(spv::CapabilityDerivativeControl); unaryOp = spv::OpFwidthCoarse; break; case glslang::EOpInterpolateAtCentroid: #ifdef AMD_EXTENSIONS if (typeProxy == glslang::EbtFloat16) builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float); #endif builder.addCapability(spv::CapabilityInterpolationFunction); libCall = spv::GLSLstd450InterpolateAtCentroid; break; case glslang::EOpAny: unaryOp = spv::OpAny; break; case glslang::EOpAll: unaryOp = spv::OpAll; break; case glslang::EOpAbs: if (isFloat) libCall = spv::GLSLstd450FAbs; else libCall = spv::GLSLstd450SAbs; break; case glslang::EOpSign: if (isFloat) libCall = spv::GLSLstd450FSign; else libCall = spv::GLSLstd450SSign; break; case glslang::EOpAtomicCounterIncrement: case glslang::EOpAtomicCounterDecrement: case glslang::EOpAtomicCounter: { // Handle all of the atomics in one place, in createAtomicOperation() std::vector<spv::Id> operands; operands.push_back(operand); return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy); } case glslang::EOpBitFieldReverse: unaryOp = spv::OpBitReverse; break; case glslang::EOpBitCount: unaryOp = spv::OpBitCount; break; case glslang::EOpFindLSB: libCall = spv::GLSLstd450FindILsb; break; case glslang::EOpFindMSB: if (isUnsigned) libCall = spv::GLSLstd450FindUMsb; else libCall = spv::GLSLstd450FindSMsb; break; case glslang::EOpBallot: case glslang::EOpReadFirstInvocation: case glslang::EOpAnyInvocation: case glslang::EOpAllInvocations: case glslang::EOpAllInvocationsEqual: #ifdef AMD_EXTENSIONS case glslang::EOpMinInvocations: case glslang::EOpMaxInvocations: case glslang::EOpAddInvocations: case glslang::EOpMinInvocationsNonUniform: case glslang::EOpMaxInvocationsNonUniform: case glslang::EOpAddInvocationsNonUniform: case glslang::EOpMinInvocationsInclusiveScan: case glslang::EOpMaxInvocationsInclusiveScan: case glslang::EOpAddInvocationsInclusiveScan: case glslang::EOpMinInvocationsInclusiveScanNonUniform: case glslang::EOpMaxInvocationsInclusiveScanNonUniform: case glslang::EOpAddInvocationsInclusiveScanNonUniform: case glslang::EOpMinInvocationsExclusiveScan: case glslang::EOpMaxInvocationsExclusiveScan: case glslang::EOpAddInvocationsExclusiveScan: case glslang::EOpMinInvocationsExclusiveScanNonUniform: case glslang::EOpMaxInvocationsExclusiveScanNonUniform: case glslang::EOpAddInvocationsExclusiveScanNonUniform: #endif { std::vector<spv::Id> operands; operands.push_back(operand); return createInvocationsOperation(op, typeId, operands, typeProxy); } case glslang::EOpSubgroupAll: case glslang::EOpSubgroupAny: case glslang::EOpSubgroupAllEqual: case glslang::EOpSubgroupBroadcastFirst: case glslang::EOpSubgroupBallot: case glslang::EOpSubgroupInverseBallot: case glslang::EOpSubgroupBallotBitCount: case glslang::EOpSubgroupBallotInclusiveBitCount: case glslang::EOpSubgroupBallotExclusiveBitCount: case glslang::EOpSubgroupBallotFindLSB: case glslang::EOpSubgroupBallotFindMSB: case glslang::EOpSubgroupAdd: case glslang::EOpSubgroupMul: case glslang::EOpSubgroupMin: case glslang::EOpSubgroupMax: case glslang::EOpSubgroupAnd: case glslang::EOpSubgroupOr: case glslang::EOpSubgroupXor: case glslang::EOpSubgroupInclusiveAdd: case glslang::EOpSubgroupInclusiveMul: case glslang::EOpSubgroupInclusiveMin: case glslang::EOpSubgroupInclusiveMax: case glslang::EOpSubgroupInclusiveAnd: case glslang::EOpSubgroupInclusiveOr: case glslang::EOpSubgroupInclusiveXor: case glslang::EOpSubgroupExclusiveAdd: case glslang::EOpSubgroupExclusiveMul: case glslang::EOpSubgroupExclusiveMin: case glslang::EOpSubgroupExclusiveMax: case glslang::EOpSubgroupExclusiveAnd: case glslang::EOpSubgroupExclusiveOr: case glslang::EOpSubgroupExclusiveXor: case glslang::EOpSubgroupQuadSwapHorizontal: case glslang::EOpSubgroupQuadSwapVertical: case glslang::EOpSubgroupQuadSwapDiagonal: { std::vector<spv::Id> operands; operands.push_back(operand); return createSubgroupOperation(op, typeId, operands, typeProxy); } #ifdef AMD_EXTENSIONS case glslang::EOpMbcnt: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot); libCall = spv::MbcntAMD; break; case glslang::EOpCubeFaceIndex: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader); libCall = spv::CubeFaceIndexAMD; break; case glslang::EOpCubeFaceCoord: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader); libCall = spv::CubeFaceCoordAMD; break; #endif #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartition: builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned); builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV); unaryOp = spv::OpGroupNonUniformPartitionNV; break; #endif default: return 0; } spv::Id id; if (libCall >= 0) { std::vector<spv::Id> args; args.push_back(operand); id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args); } else { id = builder.createUnaryOp(unaryOp, typeId, operand); } builder.addDecoration(id, decorations.noContraction); builder.addDecoration(id, decorations.nonUniform); return builder.setPrecision(id, decorations.precision); } // Create a unary operation on a matrix spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */) { // Handle unary operations vector by vector. // The result type is the same type as the original type. // The algorithm is to: // - break the matrix into vectors // - apply the operation to each vector // - make a matrix out the vector results // get the types sorted out int numCols = builder.getNumColumns(operand); int numRows = builder.getNumRows(operand); spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows); spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows); std::vector<spv::Id> results; // do each vector op for (int c = 0; c < numCols; ++c) { std::vector<unsigned int> indexes; indexes.push_back(c); spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes); spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec); builder.addDecoration(destVec, decorations.noContraction); builder.addDecoration(destVec, decorations.nonUniform); results.push_back(builder.setPrecision(destVec, decorations.precision)); } // put the pieces together spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision); builder.addDecoration(result, decorations.nonUniform); return result; } // For converting integers where both the bitwidth and the signedness could // change, but only do the width change here. The caller is still responsible // for the signedness conversion. spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize) { // Get the result type width, based on the type to convert to. int width = 32; switch(op) { case glslang::EOpConvInt16ToUint8: case glslang::EOpConvIntToUint8: case glslang::EOpConvInt64ToUint8: case glslang::EOpConvUint16ToInt8: case glslang::EOpConvUintToInt8: case glslang::EOpConvUint64ToInt8: width = 8; break; case glslang::EOpConvInt8ToUint16: case glslang::EOpConvIntToUint16: case glslang::EOpConvInt64ToUint16: case glslang::EOpConvUint8ToInt16: case glslang::EOpConvUintToInt16: case glslang::EOpConvUint64ToInt16: width = 16; break; case glslang::EOpConvInt8ToUint: case glslang::EOpConvInt16ToUint: case glslang::EOpConvInt64ToUint: case glslang::EOpConvUint8ToInt: case glslang::EOpConvUint16ToInt: case glslang::EOpConvUint64ToInt: width = 32; break; case glslang::EOpConvInt8ToUint64: case glslang::EOpConvInt16ToUint64: case glslang::EOpConvIntToUint64: case glslang::EOpConvUint8ToInt64: case glslang::EOpConvUint16ToInt64: case glslang::EOpConvUintToInt64: width = 64; break; default: assert(false && "Default missing"); break; } // Get the conversion operation and result type, // based on the target width, but the source type. spv::Id type = spv::NoType; spv::Op convOp = spv::OpNop; switch(op) { case glslang::EOpConvInt8ToUint16: case glslang::EOpConvInt8ToUint: case glslang::EOpConvInt8ToUint64: case glslang::EOpConvInt16ToUint8: case glslang::EOpConvInt16ToUint: case glslang::EOpConvInt16ToUint64: case glslang::EOpConvIntToUint8: case glslang::EOpConvIntToUint16: case glslang::EOpConvIntToUint64: case glslang::EOpConvInt64ToUint8: case glslang::EOpConvInt64ToUint16: case glslang::EOpConvInt64ToUint: convOp = spv::OpSConvert; type = builder.makeIntType(width); break; default: convOp = spv::OpUConvert; type = builder.makeUintType(width); break; } if (vectorSize > 0) type = builder.makeVectorType(type, vectorSize); return builder.createUnaryOp(convOp, type, operand); } spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy) { spv::Op convOp = spv::OpNop; spv::Id zero = 0; spv::Id one = 0; int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0; switch (op) { case glslang::EOpConvInt8ToBool: case glslang::EOpConvUint8ToBool: zero = builder.makeUint8Constant(0); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpINotEqual, destType, operand, zero); case glslang::EOpConvInt16ToBool: case glslang::EOpConvUint16ToBool: zero = builder.makeUint16Constant(0); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpINotEqual, destType, operand, zero); case glslang::EOpConvIntToBool: case glslang::EOpConvUintToBool: zero = builder.makeUintConstant(0); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpINotEqual, destType, operand, zero); case glslang::EOpConvInt64ToBool: case glslang::EOpConvUint64ToBool: zero = builder.makeUint64Constant(0); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpINotEqual, destType, operand, zero); case glslang::EOpConvFloatToBool: zero = builder.makeFloatConstant(0.0F); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero); case glslang::EOpConvDoubleToBool: zero = builder.makeDoubleConstant(0.0); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero); case glslang::EOpConvFloat16ToBool: zero = builder.makeFloat16Constant(0.0F); zero = makeSmearedConstant(zero, vectorSize); return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero); case glslang::EOpConvBoolToFloat: convOp = spv::OpSelect; zero = builder.makeFloatConstant(0.0F); one = builder.makeFloatConstant(1.0F); break; case glslang::EOpConvBoolToDouble: convOp = spv::OpSelect; zero = builder.makeDoubleConstant(0.0); one = builder.makeDoubleConstant(1.0); break; case glslang::EOpConvBoolToFloat16: convOp = spv::OpSelect; zero = builder.makeFloat16Constant(0.0F); one = builder.makeFloat16Constant(1.0F); break; case glslang::EOpConvBoolToInt8: zero = builder.makeInt8Constant(0); one = builder.makeInt8Constant(1); convOp = spv::OpSelect; break; case glslang::EOpConvBoolToUint8: zero = builder.makeUint8Constant(0); one = builder.makeUint8Constant(1); convOp = spv::OpSelect; break; case glslang::EOpConvBoolToInt16: zero = builder.makeInt16Constant(0); one = builder.makeInt16Constant(1); convOp = spv::OpSelect; break; case glslang::EOpConvBoolToUint16: zero = builder.makeUint16Constant(0); one = builder.makeUint16Constant(1); convOp = spv::OpSelect; break; case glslang::EOpConvBoolToInt: case glslang::EOpConvBoolToInt64: if (op == glslang::EOpConvBoolToInt64) zero = builder.makeInt64Constant(0); else zero = builder.makeIntConstant(0); if (op == glslang::EOpConvBoolToInt64) one = builder.makeInt64Constant(1); else one = builder.makeIntConstant(1); convOp = spv::OpSelect; break; case glslang::EOpConvBoolToUint: case glslang::EOpConvBoolToUint64: if (op == glslang::EOpConvBoolToUint64) zero = builder.makeUint64Constant(0); else zero = builder.makeUintConstant(0); if (op == glslang::EOpConvBoolToUint64) one = builder.makeUint64Constant(1); else one = builder.makeUintConstant(1); convOp = spv::OpSelect; break; case glslang::EOpConvInt8ToFloat16: case glslang::EOpConvInt8ToFloat: case glslang::EOpConvInt8ToDouble: case glslang::EOpConvInt16ToFloat16: case glslang::EOpConvInt16ToFloat: case glslang::EOpConvInt16ToDouble: case glslang::EOpConvIntToFloat16: case glslang::EOpConvIntToFloat: case glslang::EOpConvIntToDouble: case glslang::EOpConvInt64ToFloat: case glslang::EOpConvInt64ToDouble: case glslang::EOpConvInt64ToFloat16: convOp = spv::OpConvertSToF; break; case glslang::EOpConvUint8ToFloat16: case glslang::EOpConvUint8ToFloat: case glslang::EOpConvUint8ToDouble: case glslang::EOpConvUint16ToFloat16: case glslang::EOpConvUint16ToFloat: case glslang::EOpConvUint16ToDouble: case glslang::EOpConvUintToFloat16: case glslang::EOpConvUintToFloat: case glslang::EOpConvUintToDouble: case glslang::EOpConvUint64ToFloat: case glslang::EOpConvUint64ToDouble: case glslang::EOpConvUint64ToFloat16: convOp = spv::OpConvertUToF; break; case glslang::EOpConvDoubleToFloat: case glslang::EOpConvFloatToDouble: case glslang::EOpConvDoubleToFloat16: case glslang::EOpConvFloat16ToDouble: case glslang::EOpConvFloatToFloat16: case glslang::EOpConvFloat16ToFloat: convOp = spv::OpFConvert; if (builder.isMatrixType(destType)) return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy); break; case glslang::EOpConvFloat16ToInt8: case glslang::EOpConvFloatToInt8: case glslang::EOpConvDoubleToInt8: case glslang::EOpConvFloat16ToInt16: case glslang::EOpConvFloatToInt16: case glslang::EOpConvDoubleToInt16: case glslang::EOpConvFloat16ToInt: case glslang::EOpConvFloatToInt: case glslang::EOpConvDoubleToInt: case glslang::EOpConvFloat16ToInt64: case glslang::EOpConvFloatToInt64: case glslang::EOpConvDoubleToInt64: convOp = spv::OpConvertFToS; break; case glslang::EOpConvUint8ToInt8: case glslang::EOpConvInt8ToUint8: case glslang::EOpConvUint16ToInt16: case glslang::EOpConvInt16ToUint16: case glslang::EOpConvUintToInt: case glslang::EOpConvIntToUint: case glslang::EOpConvUint64ToInt64: case glslang::EOpConvInt64ToUint64: if (builder.isInSpecConstCodeGenMode()) { // Build zero scalar or vector for OpIAdd. if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) { zero = builder.makeUint8Constant(0); } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) { zero = builder.makeUint16Constant(0); } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) { zero = builder.makeUint64Constant(0); } else { zero = builder.makeUintConstant(0); } zero = makeSmearedConstant(zero, vectorSize); // Use OpIAdd, instead of OpBitcast to do the conversion when // generating for OpSpecConstantOp instruction. return builder.createBinOp(spv::OpIAdd, destType, operand, zero); } // For normal run-time conversion instruction, use OpBitcast. convOp = spv::OpBitcast; break; case glslang::EOpConvFloat16ToUint8: case glslang::EOpConvFloatToUint8: case glslang::EOpConvDoubleToUint8: case glslang::EOpConvFloat16ToUint16: case glslang::EOpConvFloatToUint16: case glslang::EOpConvDoubleToUint16: case glslang::EOpConvFloat16ToUint: case glslang::EOpConvFloatToUint: case glslang::EOpConvDoubleToUint: case glslang::EOpConvFloatToUint64: case glslang::EOpConvDoubleToUint64: case glslang::EOpConvFloat16ToUint64: convOp = spv::OpConvertFToU; break; case glslang::EOpConvInt8ToInt16: case glslang::EOpConvInt8ToInt: case glslang::EOpConvInt8ToInt64: case glslang::EOpConvInt16ToInt8: case glslang::EOpConvInt16ToInt: case glslang::EOpConvInt16ToInt64: case glslang::EOpConvIntToInt8: case glslang::EOpConvIntToInt16: case glslang::EOpConvIntToInt64: case glslang::EOpConvInt64ToInt8: case glslang::EOpConvInt64ToInt16: case glslang::EOpConvInt64ToInt: convOp = spv::OpSConvert; break; case glslang::EOpConvUint8ToUint16: case glslang::EOpConvUint8ToUint: case glslang::EOpConvUint8ToUint64: case glslang::EOpConvUint16ToUint8: case glslang::EOpConvUint16ToUint: case glslang::EOpConvUint16ToUint64: case glslang::EOpConvUintToUint8: case glslang::EOpConvUintToUint16: case glslang::EOpConvUintToUint64: case glslang::EOpConvUint64ToUint8: case glslang::EOpConvUint64ToUint16: case glslang::EOpConvUint64ToUint: convOp = spv::OpUConvert; break; case glslang::EOpConvInt8ToUint16: case glslang::EOpConvInt8ToUint: case glslang::EOpConvInt8ToUint64: case glslang::EOpConvInt16ToUint8: case glslang::EOpConvInt16ToUint: case glslang::EOpConvInt16ToUint64: case glslang::EOpConvIntToUint8: case glslang::EOpConvIntToUint16: case glslang::EOpConvIntToUint64: case glslang::EOpConvInt64ToUint8: case glslang::EOpConvInt64ToUint16: case glslang::EOpConvInt64ToUint: case glslang::EOpConvUint8ToInt16: case glslang::EOpConvUint8ToInt: case glslang::EOpConvUint8ToInt64: case glslang::EOpConvUint16ToInt8: case glslang::EOpConvUint16ToInt: case glslang::EOpConvUint16ToInt64: case glslang::EOpConvUintToInt8: case glslang::EOpConvUintToInt16: case glslang::EOpConvUintToInt64: case glslang::EOpConvUint64ToInt8: case glslang::EOpConvUint64ToInt16: case glslang::EOpConvUint64ToInt: // OpSConvert/OpUConvert + OpBitCast operand = createIntWidthConversion(op, operand, vectorSize); if (builder.isInSpecConstCodeGenMode()) { // Build zero scalar or vector for OpIAdd. switch(op) { case glslang::EOpConvInt16ToUint8: case glslang::EOpConvIntToUint8: case glslang::EOpConvInt64ToUint8: case glslang::EOpConvUint16ToInt8: case glslang::EOpConvUintToInt8: case glslang::EOpConvUint64ToInt8: zero = builder.makeUint8Constant(0); break; case glslang::EOpConvInt8ToUint16: case glslang::EOpConvIntToUint16: case glslang::EOpConvInt64ToUint16: case glslang::EOpConvUint8ToInt16: case glslang::EOpConvUintToInt16: case glslang::EOpConvUint64ToInt16: zero = builder.makeUint16Constant(0); break; case glslang::EOpConvInt8ToUint: case glslang::EOpConvInt16ToUint: case glslang::EOpConvInt64ToUint: case glslang::EOpConvUint8ToInt: case glslang::EOpConvUint16ToInt: case glslang::EOpConvUint64ToInt: zero = builder.makeUintConstant(0); break; case glslang::EOpConvInt8ToUint64: case glslang::EOpConvInt16ToUint64: case glslang::EOpConvIntToUint64: case glslang::EOpConvUint8ToInt64: case glslang::EOpConvUint16ToInt64: case glslang::EOpConvUintToInt64: zero = builder.makeUint64Constant(0); break; default: assert(false && "Default missing"); break; } zero = makeSmearedConstant(zero, vectorSize); // Use OpIAdd, instead of OpBitcast to do the conversion when // generating for OpSpecConstantOp instruction. return builder.createBinOp(spv::OpIAdd, destType, operand, zero); } // For normal run-time conversion instruction, use OpBitcast. convOp = spv::OpBitcast; break; default: break; } spv::Id result = 0; if (convOp == spv::OpNop) return result; if (convOp == spv::OpSelect) { zero = makeSmearedConstant(zero, vectorSize); one = makeSmearedConstant(one, vectorSize); result = builder.createTriOp(convOp, destType, operand, one, zero); } else result = builder.createUnaryOp(convOp, destType, operand); result = builder.setPrecision(result, decorations.precision); builder.addDecoration(result, decorations.nonUniform); return result; } spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize) { if (vectorSize == 0) return constant; spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize); std::vector<spv::Id> components; for (int c = 0; c < vectorSize; ++c) components.push_back(constant); return builder.makeCompositeConstant(vectorTypeId, components); } // For glslang ops that map to SPV atomic opCodes spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy) { spv::Op opCode = spv::OpNop; switch (op) { case glslang::EOpAtomicAdd: case glslang::EOpImageAtomicAdd: case glslang::EOpAtomicCounterAdd: opCode = spv::OpAtomicIAdd; break; case glslang::EOpAtomicCounterSubtract: opCode = spv::OpAtomicISub; break; case glslang::EOpAtomicMin: case glslang::EOpImageAtomicMin: case glslang::EOpAtomicCounterMin: opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin; break; case glslang::EOpAtomicMax: case glslang::EOpImageAtomicMax: case glslang::EOpAtomicCounterMax: opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax; break; case glslang::EOpAtomicAnd: case glslang::EOpImageAtomicAnd: case glslang::EOpAtomicCounterAnd: opCode = spv::OpAtomicAnd; break; case glslang::EOpAtomicOr: case glslang::EOpImageAtomicOr: case glslang::EOpAtomicCounterOr: opCode = spv::OpAtomicOr; break; case glslang::EOpAtomicXor: case glslang::EOpImageAtomicXor: case glslang::EOpAtomicCounterXor: opCode = spv::OpAtomicXor; break; case glslang::EOpAtomicExchange: case glslang::EOpImageAtomicExchange: case glslang::EOpAtomicCounterExchange: opCode = spv::OpAtomicExchange; break; case glslang::EOpAtomicCompSwap: case glslang::EOpImageAtomicCompSwap: case glslang::EOpAtomicCounterCompSwap: opCode = spv::OpAtomicCompareExchange; break; case glslang::EOpAtomicCounterIncrement: opCode = spv::OpAtomicIIncrement; break; case glslang::EOpAtomicCounterDecrement: opCode = spv::OpAtomicIDecrement; break; case glslang::EOpAtomicCounter: opCode = spv::OpAtomicLoad; break; default: assert(0); break; } if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64) builder.addCapability(spv::CapabilityInt64Atomics); // Sort out the operands // - mapping from glslang -> SPV // - there are extra SPV operands with no glslang source // - compare-exchange swaps the value and comparator // - compare-exchange has an extra memory semantics // - EOpAtomicCounterDecrement needs a post decrement std::vector<spv::Id> spvAtomicOperands; // hold the spv operands auto opIt = operands.begin(); // walk the glslang operands spvAtomicOperands.push_back(*(opIt++)); spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope? spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics? if (opCode == spv::OpAtomicCompareExchange) { // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL // differs from that in SPIR-V. Hence, special processing is required. spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); spvAtomicOperands.push_back(*(opIt + 1)); spvAtomicOperands.push_back(*opIt); opIt += 2; } // Add the rest of the operands, skipping any that were dealt with above. for (; opIt != operands.end(); ++opIt) spvAtomicOperands.push_back(*opIt); spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands); // GLSL and HLSL atomic-counter decrement return post-decrement value, // while SPIR-V returns pre-decrement value. Translate between these semantics. if (op == glslang::EOpAtomicCounterDecrement) resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1)); return resultId; } // Create group invocation operations. spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy) { bool isUnsigned = isTypeUnsignedInt(typeProxy); bool isFloat = isTypeFloat(typeProxy); spv::Op opCode = spv::OpNop; std::vector<spv::Id> spvGroupOperands; spv::GroupOperation groupOperation = spv::GroupOperationMax; if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation || op == glslang::EOpReadInvocation) { builder.addExtension(spv::E_SPV_KHR_shader_ballot); builder.addCapability(spv::CapabilitySubgroupBallotKHR); } else if (op == glslang::EOpAnyInvocation || op == glslang::EOpAllInvocations || op == glslang::EOpAllInvocationsEqual) { builder.addExtension(spv::E_SPV_KHR_subgroup_vote); builder.addCapability(spv::CapabilitySubgroupVoteKHR); } else { builder.addCapability(spv::CapabilityGroups); #ifdef AMD_EXTENSIONS if (op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform || op == glslang::EOpMinInvocationsInclusiveScanNonUniform || op == glslang::EOpMaxInvocationsInclusiveScanNonUniform || op == glslang::EOpAddInvocationsInclusiveScanNonUniform || op == glslang::EOpMinInvocationsExclusiveScanNonUniform || op == glslang::EOpMaxInvocationsExclusiveScanNonUniform || op == glslang::EOpAddInvocationsExclusiveScanNonUniform) builder.addExtension(spv::E_SPV_AMD_shader_ballot); #endif spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup)); #ifdef AMD_EXTENSIONS switch (op) { case glslang::EOpMinInvocations: case glslang::EOpMaxInvocations: case glslang::EOpAddInvocations: case glslang::EOpMinInvocationsNonUniform: case glslang::EOpMaxInvocationsNonUniform: case glslang::EOpAddInvocationsNonUniform: groupOperation = spv::GroupOperationReduce; spvGroupOperands.push_back(groupOperation); break; case glslang::EOpMinInvocationsInclusiveScan: case glslang::EOpMaxInvocationsInclusiveScan: case glslang::EOpAddInvocationsInclusiveScan: case glslang::EOpMinInvocationsInclusiveScanNonUniform: case glslang::EOpMaxInvocationsInclusiveScanNonUniform: case glslang::EOpAddInvocationsInclusiveScanNonUniform: groupOperation = spv::GroupOperationInclusiveScan; spvGroupOperands.push_back(groupOperation); break; case glslang::EOpMinInvocationsExclusiveScan: case glslang::EOpMaxInvocationsExclusiveScan: case glslang::EOpAddInvocationsExclusiveScan: case glslang::EOpMinInvocationsExclusiveScanNonUniform: case glslang::EOpMaxInvocationsExclusiveScanNonUniform: case glslang::EOpAddInvocationsExclusiveScanNonUniform: groupOperation = spv::GroupOperationExclusiveScan; spvGroupOperands.push_back(groupOperation); break; default: break; } #endif } for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) spvGroupOperands.push_back(*opIt); switch (op) { case glslang::EOpAnyInvocation: opCode = spv::OpSubgroupAnyKHR; break; case glslang::EOpAllInvocations: opCode = spv::OpSubgroupAllKHR; break; case glslang::EOpAllInvocationsEqual: opCode = spv::OpSubgroupAllEqualKHR; break; case glslang::EOpReadInvocation: opCode = spv::OpSubgroupReadInvocationKHR; if (builder.isVectorType(typeId)) return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands); break; case glslang::EOpReadFirstInvocation: opCode = spv::OpSubgroupFirstInvocationKHR; break; case glslang::EOpBallot: { // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow: // // result = Bitcast(SubgroupBallotKHR(Predicate).xy) // spv::Id uintType = builder.makeUintType(32); spv::Id uvec4Type = builder.makeVectorType(uintType, 4); spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands); std::vector<spv::Id> components; components.push_back(builder.createCompositeExtract(result, uintType, 0)); components.push_back(builder.createCompositeExtract(result, uintType, 1)); spv::Id uvec2Type = builder.makeVectorType(uintType, 2); return builder.createUnaryOp(spv::OpBitcast, typeId, builder.createCompositeConstruct(uvec2Type, components)); } #ifdef AMD_EXTENSIONS case glslang::EOpMinInvocations: case glslang::EOpMaxInvocations: case glslang::EOpAddInvocations: case glslang::EOpMinInvocationsInclusiveScan: case glslang::EOpMaxInvocationsInclusiveScan: case glslang::EOpAddInvocationsInclusiveScan: case glslang::EOpMinInvocationsExclusiveScan: case glslang::EOpMaxInvocationsExclusiveScan: case glslang::EOpAddInvocationsExclusiveScan: if (op == glslang::EOpMinInvocations || op == glslang::EOpMinInvocationsInclusiveScan || op == glslang::EOpMinInvocationsExclusiveScan) { if (isFloat) opCode = spv::OpGroupFMin; else { if (isUnsigned) opCode = spv::OpGroupUMin; else opCode = spv::OpGroupSMin; } } else if (op == glslang::EOpMaxInvocations || op == glslang::EOpMaxInvocationsInclusiveScan || op == glslang::EOpMaxInvocationsExclusiveScan) { if (isFloat) opCode = spv::OpGroupFMax; else { if (isUnsigned) opCode = spv::OpGroupUMax; else opCode = spv::OpGroupSMax; } } else { if (isFloat) opCode = spv::OpGroupFAdd; else opCode = spv::OpGroupIAdd; } if (builder.isVectorType(typeId)) return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands); break; case glslang::EOpMinInvocationsNonUniform: case glslang::EOpMaxInvocationsNonUniform: case glslang::EOpAddInvocationsNonUniform: case glslang::EOpMinInvocationsInclusiveScanNonUniform: case glslang::EOpMaxInvocationsInclusiveScanNonUniform: case glslang::EOpAddInvocationsInclusiveScanNonUniform: case glslang::EOpMinInvocationsExclusiveScanNonUniform: case glslang::EOpMaxInvocationsExclusiveScanNonUniform: case glslang::EOpAddInvocationsExclusiveScanNonUniform: if (op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMinInvocationsInclusiveScanNonUniform || op == glslang::EOpMinInvocationsExclusiveScanNonUniform) { if (isFloat) opCode = spv::OpGroupFMinNonUniformAMD; else { if (isUnsigned) opCode = spv::OpGroupUMinNonUniformAMD; else opCode = spv::OpGroupSMinNonUniformAMD; } } else if (op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpMaxInvocationsInclusiveScanNonUniform || op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) { if (isFloat) opCode = spv::OpGroupFMaxNonUniformAMD; else { if (isUnsigned) opCode = spv::OpGroupUMaxNonUniformAMD; else opCode = spv::OpGroupSMaxNonUniformAMD; } } else { if (isFloat) opCode = spv::OpGroupFAddNonUniformAMD; else opCode = spv::OpGroupIAddNonUniformAMD; } if (builder.isVectorType(typeId)) return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands); break; #endif default: logger->missingFunctionality("invocation operation"); return spv::NoResult; } assert(opCode != spv::OpNop); return builder.createOp(opCode, typeId, spvGroupOperands); } // Create group invocation operations on a vector spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands) { #ifdef AMD_EXTENSIONS assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin || op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax || op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast || op == spv::OpSubgroupReadInvocationKHR || op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD || op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD || op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD); #else assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin || op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax || op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast || op == spv::OpSubgroupReadInvocationKHR); #endif // Handle group invocation operations scalar by scalar. // The result type is the same type as the original type. // The algorithm is to: // - break the vector into scalars // - apply the operation to each scalar // - make a vector out the scalar results // get the types sorted out int numComponents = builder.getNumComponents(operands[0]); spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0])); std::vector<spv::Id> results; // do each scalar op for (int comp = 0; comp < numComponents; ++comp) { std::vector<unsigned int> indexes; indexes.push_back(comp); spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes); std::vector<spv::Id> spvGroupOperands; if (op == spv::OpSubgroupReadInvocationKHR) { spvGroupOperands.push_back(scalar); spvGroupOperands.push_back(operands[1]); } else if (op == spv::OpGroupBroadcast) { spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup)); spvGroupOperands.push_back(scalar); spvGroupOperands.push_back(operands[1]); } else { spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup)); spvGroupOperands.push_back(groupOperation); spvGroupOperands.push_back(scalar); } results.push_back(builder.createOp(op, scalarType, spvGroupOperands)); } // put the pieces together return builder.createCompositeConstruct(typeId, results); } // Create subgroup invocation operations. spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy) { // Add the required capabilities. switch (op) { case glslang::EOpSubgroupElect: builder.addCapability(spv::CapabilityGroupNonUniform); break; case glslang::EOpSubgroupAll: case glslang::EOpSubgroupAny: case glslang::EOpSubgroupAllEqual: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformVote); break; case glslang::EOpSubgroupBroadcast: case glslang::EOpSubgroupBroadcastFirst: case glslang::EOpSubgroupBallot: case glslang::EOpSubgroupInverseBallot: case glslang::EOpSubgroupBallotBitExtract: case glslang::EOpSubgroupBallotBitCount: case glslang::EOpSubgroupBallotInclusiveBitCount: case glslang::EOpSubgroupBallotExclusiveBitCount: case glslang::EOpSubgroupBallotFindLSB: case glslang::EOpSubgroupBallotFindMSB: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformBallot); break; case glslang::EOpSubgroupShuffle: case glslang::EOpSubgroupShuffleXor: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformShuffle); break; case glslang::EOpSubgroupShuffleUp: case glslang::EOpSubgroupShuffleDown: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative); break; case glslang::EOpSubgroupAdd: case glslang::EOpSubgroupMul: case glslang::EOpSubgroupMin: case glslang::EOpSubgroupMax: case glslang::EOpSubgroupAnd: case glslang::EOpSubgroupOr: case glslang::EOpSubgroupXor: case glslang::EOpSubgroupInclusiveAdd: case glslang::EOpSubgroupInclusiveMul: case glslang::EOpSubgroupInclusiveMin: case glslang::EOpSubgroupInclusiveMax: case glslang::EOpSubgroupInclusiveAnd: case glslang::EOpSubgroupInclusiveOr: case glslang::EOpSubgroupInclusiveXor: case glslang::EOpSubgroupExclusiveAdd: case glslang::EOpSubgroupExclusiveMul: case glslang::EOpSubgroupExclusiveMin: case glslang::EOpSubgroupExclusiveMax: case glslang::EOpSubgroupExclusiveAnd: case glslang::EOpSubgroupExclusiveOr: case glslang::EOpSubgroupExclusiveXor: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformArithmetic); break; case glslang::EOpSubgroupClusteredAdd: case glslang::EOpSubgroupClusteredMul: case glslang::EOpSubgroupClusteredMin: case glslang::EOpSubgroupClusteredMax: case glslang::EOpSubgroupClusteredAnd: case glslang::EOpSubgroupClusteredOr: case glslang::EOpSubgroupClusteredXor: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformClustered); break; case glslang::EOpSubgroupQuadBroadcast: case glslang::EOpSubgroupQuadSwapHorizontal: case glslang::EOpSubgroupQuadSwapVertical: case glslang::EOpSubgroupQuadSwapDiagonal: builder.addCapability(spv::CapabilityGroupNonUniform); builder.addCapability(spv::CapabilityGroupNonUniformQuad); break; #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedAdd: case glslang::EOpSubgroupPartitionedMul: case glslang::EOpSubgroupPartitionedMin: case glslang::EOpSubgroupPartitionedMax: case glslang::EOpSubgroupPartitionedAnd: case glslang::EOpSubgroupPartitionedOr: case glslang::EOpSubgroupPartitionedXor: case glslang::EOpSubgroupPartitionedInclusiveAdd: case glslang::EOpSubgroupPartitionedInclusiveMul: case glslang::EOpSubgroupPartitionedInclusiveMin: case glslang::EOpSubgroupPartitionedInclusiveMax: case glslang::EOpSubgroupPartitionedInclusiveAnd: case glslang::EOpSubgroupPartitionedInclusiveOr: case glslang::EOpSubgroupPartitionedInclusiveXor: case glslang::EOpSubgroupPartitionedExclusiveAdd: case glslang::EOpSubgroupPartitionedExclusiveMul: case glslang::EOpSubgroupPartitionedExclusiveMin: case glslang::EOpSubgroupPartitionedExclusiveMax: case glslang::EOpSubgroupPartitionedExclusiveAnd: case glslang::EOpSubgroupPartitionedExclusiveOr: case glslang::EOpSubgroupPartitionedExclusiveXor: builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned); builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV); break; #endif default: assert(0 && "Unhandled subgroup operation!"); } const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64; const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble; const bool isBool = typeProxy == glslang::EbtBool; spv::Op opCode = spv::OpNop; // Figure out which opcode to use. switch (op) { case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break; case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break; case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break; case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break; case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break; case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break; case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break; case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break; case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break; case glslang::EOpSubgroupBallotBitCount: case glslang::EOpSubgroupBallotInclusiveBitCount: case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break; case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break; case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break; case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break; case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break; case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break; case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break; case glslang::EOpSubgroupAdd: case glslang::EOpSubgroupInclusiveAdd: case glslang::EOpSubgroupExclusiveAdd: case glslang::EOpSubgroupClusteredAdd: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedAdd: case glslang::EOpSubgroupPartitionedInclusiveAdd: case glslang::EOpSubgroupPartitionedExclusiveAdd: #endif if (isFloat) { opCode = spv::OpGroupNonUniformFAdd; } else { opCode = spv::OpGroupNonUniformIAdd; } break; case glslang::EOpSubgroupMul: case glslang::EOpSubgroupInclusiveMul: case glslang::EOpSubgroupExclusiveMul: case glslang::EOpSubgroupClusteredMul: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedMul: case glslang::EOpSubgroupPartitionedInclusiveMul: case glslang::EOpSubgroupPartitionedExclusiveMul: #endif if (isFloat) { opCode = spv::OpGroupNonUniformFMul; } else { opCode = spv::OpGroupNonUniformIMul; } break; case glslang::EOpSubgroupMin: case glslang::EOpSubgroupInclusiveMin: case glslang::EOpSubgroupExclusiveMin: case glslang::EOpSubgroupClusteredMin: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedMin: case glslang::EOpSubgroupPartitionedInclusiveMin: case glslang::EOpSubgroupPartitionedExclusiveMin: #endif if (isFloat) { opCode = spv::OpGroupNonUniformFMin; } else if (isUnsigned) { opCode = spv::OpGroupNonUniformUMin; } else { opCode = spv::OpGroupNonUniformSMin; } break; case glslang::EOpSubgroupMax: case glslang::EOpSubgroupInclusiveMax: case glslang::EOpSubgroupExclusiveMax: case glslang::EOpSubgroupClusteredMax: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedMax: case glslang::EOpSubgroupPartitionedInclusiveMax: case glslang::EOpSubgroupPartitionedExclusiveMax: #endif if (isFloat) { opCode = spv::OpGroupNonUniformFMax; } else if (isUnsigned) { opCode = spv::OpGroupNonUniformUMax; } else { opCode = spv::OpGroupNonUniformSMax; } break; case glslang::EOpSubgroupAnd: case glslang::EOpSubgroupInclusiveAnd: case glslang::EOpSubgroupExclusiveAnd: case glslang::EOpSubgroupClusteredAnd: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedAnd: case glslang::EOpSubgroupPartitionedInclusiveAnd: case glslang::EOpSubgroupPartitionedExclusiveAnd: #endif if (isBool) { opCode = spv::OpGroupNonUniformLogicalAnd; } else { opCode = spv::OpGroupNonUniformBitwiseAnd; } break; case glslang::EOpSubgroupOr: case glslang::EOpSubgroupInclusiveOr: case glslang::EOpSubgroupExclusiveOr: case glslang::EOpSubgroupClusteredOr: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedOr: case glslang::EOpSubgroupPartitionedInclusiveOr: case glslang::EOpSubgroupPartitionedExclusiveOr: #endif if (isBool) { opCode = spv::OpGroupNonUniformLogicalOr; } else { opCode = spv::OpGroupNonUniformBitwiseOr; } break; case glslang::EOpSubgroupXor: case glslang::EOpSubgroupInclusiveXor: case glslang::EOpSubgroupExclusiveXor: case glslang::EOpSubgroupClusteredXor: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedXor: case glslang::EOpSubgroupPartitionedInclusiveXor: case glslang::EOpSubgroupPartitionedExclusiveXor: #endif if (isBool) { opCode = spv::OpGroupNonUniformLogicalXor; } else { opCode = spv::OpGroupNonUniformBitwiseXor; } break; case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break; case glslang::EOpSubgroupQuadSwapHorizontal: case glslang::EOpSubgroupQuadSwapVertical: case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break; default: assert(0 && "Unhandled subgroup operation!"); } std::vector<spv::Id> spvGroupOperands; // Every operation begins with the Execution Scope operand. spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup)); // Next, for all operations that use a Group Operation, push that as an operand. switch (op) { default: break; case glslang::EOpSubgroupBallotBitCount: case glslang::EOpSubgroupAdd: case glslang::EOpSubgroupMul: case glslang::EOpSubgroupMin: case glslang::EOpSubgroupMax: case glslang::EOpSubgroupAnd: case glslang::EOpSubgroupOr: case glslang::EOpSubgroupXor: spvGroupOperands.push_back(spv::GroupOperationReduce); break; case glslang::EOpSubgroupBallotInclusiveBitCount: case glslang::EOpSubgroupInclusiveAdd: case glslang::EOpSubgroupInclusiveMul: case glslang::EOpSubgroupInclusiveMin: case glslang::EOpSubgroupInclusiveMax: case glslang::EOpSubgroupInclusiveAnd: case glslang::EOpSubgroupInclusiveOr: case glslang::EOpSubgroupInclusiveXor: spvGroupOperands.push_back(spv::GroupOperationInclusiveScan); break; case glslang::EOpSubgroupBallotExclusiveBitCount: case glslang::EOpSubgroupExclusiveAdd: case glslang::EOpSubgroupExclusiveMul: case glslang::EOpSubgroupExclusiveMin: case glslang::EOpSubgroupExclusiveMax: case glslang::EOpSubgroupExclusiveAnd: case glslang::EOpSubgroupExclusiveOr: case glslang::EOpSubgroupExclusiveXor: spvGroupOperands.push_back(spv::GroupOperationExclusiveScan); break; case glslang::EOpSubgroupClusteredAdd: case glslang::EOpSubgroupClusteredMul: case glslang::EOpSubgroupClusteredMin: case glslang::EOpSubgroupClusteredMax: case glslang::EOpSubgroupClusteredAnd: case glslang::EOpSubgroupClusteredOr: case glslang::EOpSubgroupClusteredXor: spvGroupOperands.push_back(spv::GroupOperationClusteredReduce); break; #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedAdd: case glslang::EOpSubgroupPartitionedMul: case glslang::EOpSubgroupPartitionedMin: case glslang::EOpSubgroupPartitionedMax: case glslang::EOpSubgroupPartitionedAnd: case glslang::EOpSubgroupPartitionedOr: case glslang::EOpSubgroupPartitionedXor: spvGroupOperands.push_back(spv::GroupOperationPartitionedReduceNV); break; case glslang::EOpSubgroupPartitionedInclusiveAdd: case glslang::EOpSubgroupPartitionedInclusiveMul: case glslang::EOpSubgroupPartitionedInclusiveMin: case glslang::EOpSubgroupPartitionedInclusiveMax: case glslang::EOpSubgroupPartitionedInclusiveAnd: case glslang::EOpSubgroupPartitionedInclusiveOr: case glslang::EOpSubgroupPartitionedInclusiveXor: spvGroupOperands.push_back(spv::GroupOperationPartitionedInclusiveScanNV); break; case glslang::EOpSubgroupPartitionedExclusiveAdd: case glslang::EOpSubgroupPartitionedExclusiveMul: case glslang::EOpSubgroupPartitionedExclusiveMin: case glslang::EOpSubgroupPartitionedExclusiveMax: case glslang::EOpSubgroupPartitionedExclusiveAnd: case glslang::EOpSubgroupPartitionedExclusiveOr: case glslang::EOpSubgroupPartitionedExclusiveXor: spvGroupOperands.push_back(spv::GroupOperationPartitionedExclusiveScanNV); break; #endif } // Push back the operands next. for (auto opIt : operands) { spvGroupOperands.push_back(opIt); } // Some opcodes have additional operands. switch (op) { default: break; case glslang::EOpSubgroupQuadSwapHorizontal: spvGroupOperands.push_back(builder.makeUintConstant(0)); break; case glslang::EOpSubgroupQuadSwapVertical: spvGroupOperands.push_back(builder.makeUintConstant(1)); break; case glslang::EOpSubgroupQuadSwapDiagonal: spvGroupOperands.push_back(builder.makeUintConstant(2)); break; } return builder.createOp(opCode, typeId, spvGroupOperands); } spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy) { bool isUnsigned = isTypeUnsignedInt(typeProxy); bool isFloat = isTypeFloat(typeProxy); spv::Op opCode = spv::OpNop; int extBuiltins = -1; int libCall = -1; size_t consumedOperands = operands.size(); spv::Id typeId0 = 0; if (consumedOperands > 0) typeId0 = builder.getTypeId(operands[0]); spv::Id typeId1 = 0; if (consumedOperands > 1) typeId1 = builder.getTypeId(operands[1]); spv::Id frexpIntType = 0; switch (op) { case glslang::EOpMin: if (isFloat) libCall = spv::GLSLstd450FMin; else if (isUnsigned) libCall = spv::GLSLstd450UMin; else libCall = spv::GLSLstd450SMin; builder.promoteScalar(precision, operands.front(), operands.back()); break; case glslang::EOpModf: libCall = spv::GLSLstd450Modf; break; case glslang::EOpMax: if (isFloat) libCall = spv::GLSLstd450FMax; else if (isUnsigned) libCall = spv::GLSLstd450UMax; else libCall = spv::GLSLstd450SMax; builder.promoteScalar(precision, operands.front(), operands.back()); break; case glslang::EOpPow: libCall = spv::GLSLstd450Pow; break; case glslang::EOpDot: opCode = spv::OpDot; break; case glslang::EOpAtan: libCall = spv::GLSLstd450Atan2; break; case glslang::EOpClamp: if (isFloat) libCall = spv::GLSLstd450FClamp; else if (isUnsigned) libCall = spv::GLSLstd450UClamp; else libCall = spv::GLSLstd450SClamp; builder.promoteScalar(precision, operands.front(), operands[1]); builder.promoteScalar(precision, operands.front(), operands[2]); break; case glslang::EOpMix: if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) { assert(isFloat); libCall = spv::GLSLstd450FMix; } else { opCode = spv::OpSelect; std::swap(operands.front(), operands.back()); } builder.promoteScalar(precision, operands.front(), operands.back()); break; case glslang::EOpStep: libCall = spv::GLSLstd450Step; builder.promoteScalar(precision, operands.front(), operands.back()); break; case glslang::EOpSmoothStep: libCall = spv::GLSLstd450SmoothStep; builder.promoteScalar(precision, operands[0], operands[2]); builder.promoteScalar(precision, operands[1], operands[2]); break; case glslang::EOpDistance: libCall = spv::GLSLstd450Distance; break; case glslang::EOpCross: libCall = spv::GLSLstd450Cross; break; case glslang::EOpFaceForward: libCall = spv::GLSLstd450FaceForward; break; case glslang::EOpReflect: libCall = spv::GLSLstd450Reflect; break; case glslang::EOpRefract: libCall = spv::GLSLstd450Refract; break; case glslang::EOpInterpolateAtSample: #ifdef AMD_EXTENSIONS if (typeProxy == glslang::EbtFloat16) builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float); #endif builder.addCapability(spv::CapabilityInterpolationFunction); libCall = spv::GLSLstd450InterpolateAtSample; break; case glslang::EOpInterpolateAtOffset: #ifdef AMD_EXTENSIONS if (typeProxy == glslang::EbtFloat16) builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float); #endif builder.addCapability(spv::CapabilityInterpolationFunction); libCall = spv::GLSLstd450InterpolateAtOffset; break; case glslang::EOpAddCarry: opCode = spv::OpIAddCarry; typeId = builder.makeStructResultType(typeId0, typeId0); consumedOperands = 2; break; case glslang::EOpSubBorrow: opCode = spv::OpISubBorrow; typeId = builder.makeStructResultType(typeId0, typeId0); consumedOperands = 2; break; case glslang::EOpUMulExtended: opCode = spv::OpUMulExtended; typeId = builder.makeStructResultType(typeId0, typeId0); consumedOperands = 2; break; case glslang::EOpIMulExtended: opCode = spv::OpSMulExtended; typeId = builder.makeStructResultType(typeId0, typeId0); consumedOperands = 2; break; case glslang::EOpBitfieldExtract: if (isUnsigned) opCode = spv::OpBitFieldUExtract; else opCode = spv::OpBitFieldSExtract; break; case glslang::EOpBitfieldInsert: opCode = spv::OpBitFieldInsert; break; case glslang::EOpFma: libCall = spv::GLSLstd450Fma; break; case glslang::EOpFrexp: { libCall = spv::GLSLstd450FrexpStruct; assert(builder.isPointerType(typeId1)); typeId1 = builder.getContainedTypeId(typeId1); int width = builder.getScalarTypeWidth(typeId1); #ifdef AMD_EXTENSIONS if (width == 16) // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16); #endif if (builder.getNumComponents(operands[0]) == 1) frexpIntType = builder.makeIntegerType(width, true); else frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0])); typeId = builder.makeStructResultType(typeId0, frexpIntType); consumedOperands = 1; } break; case glslang::EOpLdexp: libCall = spv::GLSLstd450Ldexp; break; case glslang::EOpReadInvocation: return createInvocationsOperation(op, typeId, operands, typeProxy); case glslang::EOpSubgroupBroadcast: case glslang::EOpSubgroupBallotBitExtract: case glslang::EOpSubgroupShuffle: case glslang::EOpSubgroupShuffleXor: case glslang::EOpSubgroupShuffleUp: case glslang::EOpSubgroupShuffleDown: case glslang::EOpSubgroupClusteredAdd: case glslang::EOpSubgroupClusteredMul: case glslang::EOpSubgroupClusteredMin: case glslang::EOpSubgroupClusteredMax: case glslang::EOpSubgroupClusteredAnd: case glslang::EOpSubgroupClusteredOr: case glslang::EOpSubgroupClusteredXor: case glslang::EOpSubgroupQuadBroadcast: #ifdef NV_EXTENSIONS case glslang::EOpSubgroupPartitionedAdd: case glslang::EOpSubgroupPartitionedMul: case glslang::EOpSubgroupPartitionedMin: case glslang::EOpSubgroupPartitionedMax: case glslang::EOpSubgroupPartitionedAnd: case glslang::EOpSubgroupPartitionedOr: case glslang::EOpSubgroupPartitionedXor: case glslang::EOpSubgroupPartitionedInclusiveAdd: case glslang::EOpSubgroupPartitionedInclusiveMul: case glslang::EOpSubgroupPartitionedInclusiveMin: case glslang::EOpSubgroupPartitionedInclusiveMax: case glslang::EOpSubgroupPartitionedInclusiveAnd: case glslang::EOpSubgroupPartitionedInclusiveOr: case glslang::EOpSubgroupPartitionedInclusiveXor: case glslang::EOpSubgroupPartitionedExclusiveAdd: case glslang::EOpSubgroupPartitionedExclusiveMul: case glslang::EOpSubgroupPartitionedExclusiveMin: case glslang::EOpSubgroupPartitionedExclusiveMax: case glslang::EOpSubgroupPartitionedExclusiveAnd: case glslang::EOpSubgroupPartitionedExclusiveOr: case glslang::EOpSubgroupPartitionedExclusiveXor: #endif return createSubgroupOperation(op, typeId, operands, typeProxy); #ifdef AMD_EXTENSIONS case glslang::EOpSwizzleInvocations: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot); libCall = spv::SwizzleInvocationsAMD; break; case glslang::EOpSwizzleInvocationsMasked: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot); libCall = spv::SwizzleInvocationsMaskedAMD; break; case glslang::EOpWriteInvocation: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot); libCall = spv::WriteInvocationAMD; break; case glslang::EOpMin3: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax); if (isFloat) libCall = spv::FMin3AMD; else { if (isUnsigned) libCall = spv::UMin3AMD; else libCall = spv::SMin3AMD; } break; case glslang::EOpMax3: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax); if (isFloat) libCall = spv::FMax3AMD; else { if (isUnsigned) libCall = spv::UMax3AMD; else libCall = spv::SMax3AMD; } break; case glslang::EOpMid3: extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax); if (isFloat) libCall = spv::FMid3AMD; else { if (isUnsigned) libCall = spv::UMid3AMD; else libCall = spv::SMid3AMD; } break; case glslang::EOpInterpolateAtVertex: if (typeProxy == glslang::EbtFloat16) builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float); extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter); libCall = spv::InterpolateAtVertexAMD; break; #endif default: return 0; } spv::Id id = 0; if (libCall >= 0) { // Use an extended instruction from the standard library. // Construct the call arguments, without modifying the original operands vector. // We might need the remaining arguments, e.g. in the EOpFrexp case. std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands); id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments); } else { switch (consumedOperands) { case 0: // should all be handled by visitAggregate and createNoArgOperation assert(0); return 0; case 1: // should all be handled by createUnaryOperation assert(0); return 0; case 2: id = builder.createBinOp(opCode, typeId, operands[0], operands[1]); break; default: // anything 3 or over doesn't have l-value operands, so all should be consumed assert(consumedOperands == operands.size()); id = builder.createOp(opCode, typeId, operands); break; } } // Decode the return types that were structures switch (op) { case glslang::EOpAddCarry: case glslang::EOpSubBorrow: builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]); id = builder.createCompositeExtract(id, typeId0, 0); break; case glslang::EOpUMulExtended: case glslang::EOpIMulExtended: builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]); builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]); break; case glslang::EOpFrexp: { assert(operands.size() == 2); if (builder.isFloatType(builder.getScalarTypeId(typeId1))) { // "exp" is floating-point type (from HLSL intrinsic) spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1); member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1); builder.createStore(member1, operands[1]); } else // "exp" is integer type (from GLSL built-in function) builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]); id = builder.createCompositeExtract(id, typeId0, 0); } break; default: break; } return builder.setPrecision(id, precision); } // Intrinsics with no arguments (or no return value, and no precision). spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId) { // TODO: get the barrier operands correct switch (op) { case glslang::EOpEmitVertex: builder.createNoResultOp(spv::OpEmitVertex); return 0; case glslang::EOpEndPrimitive: builder.createNoResultOp(spv::OpEndPrimitive); return 0; case glslang::EOpBarrier: if (glslangIntermediate->getStage() == EShLangTessControl) { builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone); // TODO: prefer the following, when available: // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch, // spv::MemorySemanticsPatchMask | // spv::MemorySemanticsAcquireReleaseMask); } else { builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask); } return 0; case glslang::EOpMemoryBarrier: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpMemoryBarrierAtomicCounter: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpMemoryBarrierBuffer: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpMemoryBarrierImage: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpMemoryBarrierShared: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpGroupMemoryBarrier: builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpAllMemoryBarrierWithGroupSync: builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsAllMemory | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpDeviceMemoryBarrier: builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpDeviceMemoryBarrierWithGroupSync: builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpWorkgroupMemoryBarrier: builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpWorkgroupMemoryBarrierWithGroupSync: builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return 0; case glslang::EOpSubgroupBarrier: builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory | spv::MemorySemanticsAcquireReleaseMask); return spv::NoResult; case glslang::EOpSubgroupMemoryBarrier: builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory | spv::MemorySemanticsAcquireReleaseMask); return spv::NoResult; case glslang::EOpSubgroupMemoryBarrierBuffer: builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return spv::NoResult; case glslang::EOpSubgroupMemoryBarrierImage: builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return spv::NoResult; case glslang::EOpSubgroupMemoryBarrierShared: builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask); return spv::NoResult; case glslang::EOpSubgroupElect: { std::vector<spv::Id> operands; return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid); } #ifdef AMD_EXTENSIONS case glslang::EOpTime: { std::vector<spv::Id> args; // Dummy arguments spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args); return builder.setPrecision(id, precision); } #endif default: logger->missingFunctionality("unknown operation with no arguments"); return 0; } } spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol) { auto iter = symbolValues.find(symbol->getId()); spv::Id id; if (symbolValues.end() != iter) { id = iter->second; return id; } // it was not found, create it id = createSpvVariable(symbol); symbolValues[symbol->getId()] = id; if (symbol->getBasicType() != glslang::EbtBlock) { builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType())); builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier())); builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier())); if (symbol->getType().getQualifier().hasSpecConstantId()) builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId); if (symbol->getQualifier().hasIndex()) builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex); if (symbol->getQualifier().hasComponent()) builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent); // atomic counters use this: if (symbol->getQualifier().hasOffset()) builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset); } if (symbol->getQualifier().hasLocation()) builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation); builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier())); if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) { builder.addCapability(spv::CapabilityGeometryStreams); builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream); } if (symbol->getQualifier().hasSet()) builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet); else if (IsDescriptorResource(symbol->getType())) { // default to 0 builder.addDecoration(id, spv::DecorationDescriptorSet, 0); } if (symbol->getQualifier().hasBinding()) builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding); if (symbol->getQualifier().hasAttachment()) builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment); if (glslangIntermediate->getXfbMode()) { builder.addCapability(spv::CapabilityTransformFeedback); if (symbol->getQualifier().hasXfbStride()) builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride); if (symbol->getQualifier().hasXfbBuffer()) { builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer); unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer); if (stride != glslang::TQualifier::layoutXfbStrideEnd) builder.addDecoration(id, spv::DecorationXfbStride, stride); } if (symbol->getQualifier().hasXfbOffset()) builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset); } if (symbol->getType().isImage()) { std::vector<spv::Decoration> memory; TranslateMemoryDecoration(symbol->getType().getQualifier(), memory); for (unsigned int i = 0; i < memory.size(); ++i) builder.addDecoration(id, memory[i]); } // built-in variable decorations spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false); if (builtIn != spv::BuiltInMax) builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn); // nonuniform builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier())); #ifdef NV_EXTENSIONS if (builtIn == spv::BuiltInSampleMask) { spv::Decoration decoration; // GL_NV_sample_mask_override_coverage extension if (glslangIntermediate->getLayoutOverrideCoverage()) decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV; else decoration = (spv::Decoration)spv::DecorationMax; builder.addDecoration(id, decoration); if (decoration != spv::DecorationMax) { builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage); } } else if (builtIn == spv::BuiltInLayer) { // SPV_NV_viewport_array2 extension if (symbol->getQualifier().layoutViewportRelative) { builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV); builder.addCapability(spv::CapabilityShaderViewportMaskNV); builder.addExtension(spv::E_SPV_NV_viewport_array2); } if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) { builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset); builder.addCapability(spv::CapabilityShaderStereoViewNV); builder.addExtension(spv::E_SPV_NV_stereo_view_rendering); } } if (symbol->getQualifier().layoutPassthrough) { builder.addDecoration(id, spv::DecorationPassthroughNV); builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV); builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough); } #endif if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) { builder.addExtension("SPV_GOOGLE_hlsl_functionality1"); builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE, symbol->getType().getQualifier().semanticName); } return id; } // Make a full tree of instructions to build a SPIR-V specialization constant, // or regular constant if possible. // // TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though // // Recursively walk the nodes. The nodes form a tree whose leaves are // regular constants, which themselves are trees that createSpvConstant() // recursively walks. So, this function walks the "top" of the tree: // - emit specialization constant-building instructions for specConstant // - when running into a non-spec-constant, switch to createSpvConstant() spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node) { assert(node.getQualifier().isConstant()); // Handle front-end constants first (non-specialization constants). if (! node.getQualifier().specConstant) { // hand off to the non-spec-constant path assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr); int nextConst = 0; return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false); } // We now know we have a specialization constant to build // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants, // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ... if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) { std::vector<spv::Id> dimConstId; for (int dim = 0; dim < 3; ++dim) { bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet); dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst)); if (specConst) { builder.addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim)); } } return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true); } // An AST node labelled as specialization constant should be a symbol node. // Its initializer should either be a sub tree with constant nodes, or a constant union array. if (auto* sn = node.getAsSymbolNode()) { if (auto* sub_tree = sn->getConstSubtree()) { // Traverse the constant constructor sub tree like generating normal run-time instructions. // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard // will set the builder into spec constant op instruction generating mode. sub_tree->traverse(this); return accessChainLoad(sub_tree->getType()); } else if (auto* const_union_array = &sn->getConstArray()){ int nextConst = 0; spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true); builder.addName(id, sn->getName().c_str()); return id; } } // Neither a front-end constant node, nor a specialization constant node with constant union array or // constant sub tree as initializer. logger->missingFunctionality("Neither a front-end constant nor a spec constant."); exit(1); return spv::NoResult; } // Use 'consts' as the flattened glslang source of scalar constants to recursively // build the aggregate SPIR-V constant. // // If there are not enough elements present in 'consts', 0 will be substituted; // an empty 'consts' can be used to create a fully zeroed SPIR-V constant. // spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant) { // vector of constants for SPIR-V std::vector<spv::Id> spvConsts; // Type is used for struct and array constants spv::Id typeId = convertGlslangToSpvType(glslangType); if (glslangType.isArray()) { glslang::TType elementType(glslangType, 0); for (int i = 0; i < glslangType.getOuterArraySize(); ++i) spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false)); } else if (glslangType.isMatrix()) { glslang::TType vectorType(glslangType, 0); for (int col = 0; col < glslangType.getMatrixCols(); ++col) spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false)); } else if (glslangType.getStruct()) { glslang::TVector<glslang::TTypeLoc>::const_iterator iter; for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter) spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false)); } else if (glslangType.getVectorSize() > 1) { for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) { bool zero = nextConst >= consts.size(); switch (glslangType.getBasicType()) { case glslang::EbtInt8: spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const())); break; case glslang::EbtUint8: spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const())); break; case glslang::EbtInt16: spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const())); break; case glslang::EbtUint16: spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const())); break; case glslang::EbtInt: spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst())); break; case glslang::EbtUint: spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst())); break; case glslang::EbtInt64: spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const())); break; case glslang::EbtUint64: spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const())); break; case glslang::EbtFloat: spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst())); break; case glslang::EbtDouble: spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst())); break; case glslang::EbtFloat16: spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst())); break; case glslang::EbtBool: spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst())); break; default: assert(0); break; } ++nextConst; } } else { // we have a non-aggregate (scalar) constant bool zero = nextConst >= consts.size(); spv::Id scalar = 0; switch (glslangType.getBasicType()) { case glslang::EbtInt8: scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant); break; case glslang::EbtUint8: scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant); break; case glslang::EbtInt16: scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant); break; case glslang::EbtUint16: scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant); break; case glslang::EbtInt: scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant); break; case glslang::EbtUint: scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant); break; case glslang::EbtInt64: scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant); break; case glslang::EbtUint64: scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant); break; case glslang::EbtFloat: scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant); break; case glslang::EbtDouble: scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant); break; case glslang::EbtFloat16: scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant); break; case glslang::EbtBool: scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant); break; default: assert(0); break; } ++nextConst; return scalar; } return builder.makeCompositeConstant(typeId, spvConsts); } // Return true if the node is a constant or symbol whose reading has no // non-trivial observable cost or effect. bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node) { // don't know what this is if (node == nullptr) return false; // a constant is safe if (node->getAsConstantUnion() != nullptr) return true; // not a symbol means non-trivial if (node->getAsSymbolNode() == nullptr) return false; // a symbol, depends on what's being read switch (node->getType().getQualifier().storage) { case glslang::EvqTemporary: case glslang::EvqGlobal: case glslang::EvqIn: case glslang::EvqInOut: case glslang::EvqConst: case glslang::EvqConstReadOnly: case glslang::EvqUniform: return true; default: return false; } } // A node is trivial if it is a single operation with no side effects. // HLSL (and/or vectors) are always trivial, as it does not short circuit. // Otherwise, error on the side of saying non-trivial. // Return true if trivial. bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node) { if (node == nullptr) return false; // count non scalars as trivial, as well as anything coming from HLSL if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl) return true; // symbols and constants are trivial if (isTrivialLeaf(node)) return true; // otherwise, it needs to be a simple operation or one or two leaf nodes // not a simple operation const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode(); const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode(); if (binaryNode == nullptr && unaryNode == nullptr) return false; // not on leaf nodes if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight()))) return false; if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) { return false; } switch (node->getAsOperator()->getOp()) { case glslang::EOpLogicalNot: case glslang::EOpConvIntToBool: case glslang::EOpConvUintToBool: case glslang::EOpConvFloatToBool: case glslang::EOpConvDoubleToBool: case glslang::EOpEqual: case glslang::EOpNotEqual: case glslang::EOpLessThan: case glslang::EOpGreaterThan: case glslang::EOpLessThanEqual: case glslang::EOpGreaterThanEqual: case glslang::EOpIndexDirect: case glslang::EOpIndexDirectStruct: case glslang::EOpLogicalXor: case glslang::EOpAny: case glslang::EOpAll: return true; default: return false; } } // Emit short-circuiting code, where 'right' is never evaluated unless // the left side is true (for &&) or false (for ||). spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right) { spv::Id boolTypeId = builder.makeBoolType(); // emit left operand builder.clearAccessChain(); left.traverse(this); spv::Id leftId = accessChainLoad(left.getType()); // Operands to accumulate OpPhi operands std::vector<spv::Id> phiOperands; // accumulate left operand's phi information phiOperands.push_back(leftId); phiOperands.push_back(builder.getBuildPoint()->getId()); // Make the two kinds of operation symmetric with a "!" // || => emit "if (! left) result = right" // && => emit "if ( left) result = right" // // TODO: this runtime "not" for || could be avoided by adding functionality // to 'builder' to have an "else" without an "then" if (op == glslang::EOpLogicalOr) leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId); // make an "if" based on the left value spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder); // emit right operand as the "then" part of the "if" builder.clearAccessChain(); right.traverse(this); spv::Id rightId = accessChainLoad(right.getType()); // accumulate left operand's phi information phiOperands.push_back(rightId); phiOperands.push_back(builder.getBuildPoint()->getId()); // finish the "if" ifBuilder.makeEndIf(); // phi together the two results return builder.createOp(spv::OpPhi, boolTypeId, phiOperands); } #ifdef AMD_EXTENSIONS // Return type Id of the imported set of extended instructions corresponds to the name. // Import this set if it has not been imported yet. spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name) { if (extBuiltinMap.find(name) != extBuiltinMap.end()) return extBuiltinMap[name]; else { builder.addExtension(name); spv::Id extBuiltins = builder.import(name); extBuiltinMap[name] = extBuiltins; return extBuiltins; } } #endif }; // end anonymous namespace namespace glslang { void GetSpirvVersion(std::string& version) { const int bufSize = 100; char buf[bufSize]; snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision); version = buf; } // For low-order part of the generator's magic number. Bump up // when there is a change in the style (e.g., if SSA form changes, // or a different instruction sequence to do something gets used). int GetSpirvGeneratorVersion() { // return 1; // start // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V // return 3; // change/correct barrier-instruction operands, to match memory model group decisions // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component // return 5; // make OpArrayLength result type be an int with signedness of 0 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code, // versions 4 and 6 each generate OpArrayLength as it has long been done return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent } // Write SPIR-V out to a binary file void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName) { std::ofstream out; out.open(baseName, std::ios::binary | std::ios::out); if (out.fail()) printf("ERROR: Failed to open file: %s\n", baseName); for (int i = 0; i < (int)spirv.size(); ++i) { unsigned int word = spirv[i]; out.write((const char*)&word, 4); } out.close(); } // Write SPIR-V out to a text file with 32-bit hexadecimal words void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName) { std::ofstream out; out.open(baseName, std::ios::binary | std::ios::out); if (out.fail()) printf("ERROR: Failed to open file: %s\n", baseName); out << "\t// " << glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL << std::endl; if (varName != nullptr) { out << "\t #pragma once" << std::endl; out << "const uint32_t " << varName << "[] = {" << std::endl; } const int WORDS_PER_LINE = 8; for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) { out << "\t"; for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) { const unsigned int word = spirv[i + j]; out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word; if (i + j + 1 < (int)spirv.size()) { out << ","; } } out << std::endl; } if (varName != nullptr) { out << "};"; } out.close(); } // // Set up the glslang traversal // void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options) { spv::SpvBuildLogger logger; GlslangToSpv(intermediate, spirv, &logger, options); } void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger, SpvOptions* options) { TIntermNode* root = intermediate.getTreeRoot(); if (root == 0) return; glslang::SpvOptions defaultOptions; if (options == nullptr) options = &defaultOptions; glslang::GetThreadPoolAllocator().push(); TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options); root->traverse(&it); it.finishSpv(); it.dumpSpv(spirv); #if ENABLE_OPT // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan // eg. forward and remove memory writes of opaque types. if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) { spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2; spvtools::Optimizer optimizer(target_env); optimizer.SetMessageConsumer([](spv_message_level_t level, const char* source, const spv_position_t& position, const char* message) { std::cerr << StringifyMessage(level, source, position, message) << std::endl; }); optimizer.RegisterPass(CreateMergeReturnPass()); optimizer.RegisterPass(CreateInlineExhaustivePass()); optimizer.RegisterPass(CreateEliminateDeadFunctionsPass()); optimizer.RegisterPass(CreateScalarReplacementPass()); optimizer.RegisterPass(CreateLocalAccessChainConvertPass()); optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass()); optimizer.RegisterPass(CreateLocalSingleStoreElimPass()); optimizer.RegisterPass(CreateSimplificationPass()); optimizer.RegisterPass(CreateAggressiveDCEPass()); optimizer.RegisterPass(CreateDeadInsertElimPass()); optimizer.RegisterPass(CreateAggressiveDCEPass()); optimizer.RegisterPass(CreateDeadBranchElimPass()); optimizer.RegisterPass(CreateBlockMergePass()); optimizer.RegisterPass(CreateLocalMultiStoreElimPass()); optimizer.RegisterPass(CreateIfConversionPass()); optimizer.RegisterPass(CreateSimplificationPass()); optimizer.RegisterPass(CreateAggressiveDCEPass()); optimizer.RegisterPass(CreateDeadInsertElimPass()); if (options->optimizeSize) { optimizer.RegisterPass(CreateRedundancyEliminationPass()); // TODO(greg-lunarg): Add this when AMD driver issues are resolved // optimizer.RegisterPass(CreateCommonUniformElimPass()); } optimizer.RegisterPass(CreateAggressiveDCEPass()); optimizer.RegisterPass(CreateCFGCleanupPass()); optimizer.RegisterLegalizationPasses(); if (!optimizer.Run(spirv.data(), spirv.size(), &spirv)) return; } #endif glslang::GetThreadPoolAllocator().pop(); } }; // end namespace glslang
[ "branimirkaradzic@gmail.com" ]
branimirkaradzic@gmail.com
79535cf2db93e0614a056a4cdee42143c6d36941
84b74c86448c41b85d9d8ab3fa008798277f7cee
/src/v2/model/boorusite.cpp
65369f7cef2652ccfb272cf8e578f6c9e87cc5d1
[]
no_license
glade0lus/QBooru
41c253142b62d732db43d7faf98c716b04b142f3
76f9079df54b0aaf9cb2ff4625a0fcaff101e860
refs/heads/master
2021-07-10T04:40:13.725663
2018-11-21T21:02:47
2018-11-21T21:02:47
91,212,932
1
1
null
2021-04-02T18:06:37
2017-05-14T01:39:07
C++
UTF-8
C++
false
false
1,957
cpp
#include "boorusite.h" BooruSite::BooruSite() { } BooruSite::BooruSite(Json::Value obj) { init(obj["name"].asString(), API::getAPIFromID(obj["api"].asInt()), obj["url_main"].asString(), obj["url_search"].asString(), obj["url_show"].asString(), obj["url_login"].asString(), obj["login_required"].asBool()); } BooruSite::BooruSite(std::string name, std::string url, int type_id) { init(name,url,API::getAPIFromID(type_id)); } BooruSite::BooruSite(std::string name, std::string url, API *api) { init(name,url,api); } BooruSite::BooruSite(std::string name, API *api, std::string url_main, std::string url_search, std::string url_show, std::string url_login, bool login_required) { init(name, api, url_main, url_search, url_show, url_login, login_required); } void BooruSite::init(std::string name, std::string url, API *api){ std::string url_main = url; std::string url_search = url + api->getSearchUrl(); std::string url_show = url + api->getPostsUrl(); std::string url_login = url + api->getLoginUrl(); init(name, api, url_main, url_search, url_show, url_login, login_required); } void BooruSite::init(std::string name, API *api, std::string url_main, std::string url_search, std::string url_show, std::string url_login, bool login_required){ this->name = name; this->api = api; this->url_main = url_main; this->url_search = url_search; this->url_show = url_show; this->url_login = url_login; this->login_required = login_required; } std::string BooruSite::getName(){ return this->name; } std::string BooruSite::getMainUrl(){ return this->url_main; } std::string BooruSite::getSearchUrl(){ return this->url_search; } std::string BooruSite::getShowUrl(){ return this->url_show; } std::string BooruSite::getLoginUrl(){ return this->url_login; } bool BooruSite::needsLogin(){ return this->login_required; } API* BooruSite::getAPI(){ return this->api; }
[ "florent.uguet@gmail.com" ]
florent.uguet@gmail.com
23ab48973f6d1c81a75cc3817db554141c39e383
5a87eaac41c3341c52fb01f347eb991b9aaffe95
/apue/chapter8/8.10.1.cpp
277574cfe5939b8d1b3b640faea280a55c9d0663
[]
no_license
TTLIUJJ/MyLearning
031cd457379a403a526478048604ccf00308b0fb
1682796cb9f8da59e6c87e6e015aa4e12bbeab2a
refs/heads/master
2021-01-17T17:48:21.252858
2017-03-25T15:10:48
2017-03-25T15:10:48
70,613,108
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
#include <iostream> #include <sys/wait.h> #include "apue.h" using namespace std; char *env_init[] = {"USER=unknown", "PATH/tmp", "NULL"}; int main() { pid_t pid; if((pid = fork()) < 0){ cerr << "Fork() Error" << endl; return -1; } else if(pid == 0){ if(execle("/bin/echo", "echo", "myargl", "My Arg2", (char*)0, env_init) < 0){ cerr << "Execle() Error" << endl; return -1; } } if(wait(pid, NULL, 0) < 0){ cerr << "Wait() Error" << endl; return -1; } if((pid = fork()) < 0){ cerr << "Fork2() Error" << endl; return -1; } else if(pid == 0){ if(execlp("echo", "echo", "only 1 arg", (char*)0) < 0){ cerr << "Execlp() Error" << endl; return -1; } } return 0; ]
[ "TTLIUJJ@GMAIL.COM" ]
TTLIUJJ@GMAIL.COM
60f8bf90b4145b774e27932d1f634ae482d31942
c7f3db94cc3d69cd9a2ae24aa3c69cd767b28672
/must_rma/src/externals/GTI/modules/comm-strategy/CStratSimpleUp.h
5380a152230b0ab9a2aec1200985f873fe3dd6a0
[]
no_license
RWTH-HPC/must-rma-correctness22-supplemental
10683ff20339098a45a35301dbee6b31d74efaec
04cb9fe5f0dcb05ea67880209accf19c5e0dda25
refs/heads/main
2023-04-14T20:48:36.684589
2022-08-10T20:28:43
2022-11-18T03:33:05
523,105,966
0
0
null
null
null
null
UTF-8
C++
false
false
3,640
h
/* This file is part of GTI (Generic Tool Infrastructure) * * Copyright (C) * 2008-2019 ZIH, Technische Universitaet Dresden, Federal Republic of Germany * 2008-2019 Lawrence Livermore National Laboratories, United States of America * 2013-2019 RWTH Aachen University, Federal Republic of Germany * * See the LICENSE file in the package base directory for details */ /** * @file CStratSimpleUp.h * Simple implementation for the I_CommStrategyUp interface. * * Provides the interface functionality with a simple implementation. * * @author Tobias Hilbrich * @date 16.04.2009 */ #include "GtiDefines.h" #include "GtiEnums.h" #include "GtiTypes.h" #include "I_CommStrategyUp.h" #include "I_CommProtocol.h" #include "ModuleBase.h" #include "CStratQueue.h" #ifndef CSTRAT_SIMPLE_UP_H #define CSTRAT_SIMPLE_UP_H namespace gti { /** * Simple implementation of upwards strategy. * Properties: * - no aggregation * - uses ssend to send * - waits for an acknowledgment in the send */ class CStratSimpleUp : public ModuleBase<CStratSimpleUp, CStratUpQueue> { protected: /** The communication protocol. */ I_CommProtocol *protocol; unsigned int myRequest; uint64_t myBuf[2]; bool myGotPing; std::list<std::pair<uint64_t, uint64_t*> > myMsgQueue; /**< Queue of messages that where received when waiting for an acknowledgment*/ static const uint64_t myTokenShutdownSync; static const uint64_t myTokenMessage; static const uint64_t myTokenAck; public: /** * Constructor. * @ref ModConf see for details on module configuration. * @param instanceName name of the module instance. */ CStratSimpleUp (const char* instanceName); /** * Destructor. */ ~CStratSimpleUp (void); /** * @see I_CommStrategyUp::getPlaceId */ GTI_RETURN getPlaceId (uint64_t* outPlaceId); /** * @see I_CommStrategyUp::shutdown */ GTI_RETURN shutdown ( GTI_FLUSH_TYPE flush_behavior, GTI_SYNC_TYPE sync_behavior ); /** * @see I_CommStrategyUp::send */ GTI_RETURN send ( void* buf, uint64_t num_bytes, void* free_data, GTI_RETURN (*buf_free_function) (void* free_data, uint64_t num_bytes, void* buf) ); /** * @see I_CommStrategyUp::test */ GTI_RETURN test ( int* out_flag, uint64_t* out_num_bytes, void** out_buf, void** out_free_data, GTI_RETURN (**out_buf_free_function) (void* free_data, uint64_t num_bytes, void* buf) ); /** * @see I_CommStrategyUp::wait */ GTI_RETURN wait ( uint64_t* out_num_bytes, void** out_buf, void** out_free_data, GTI_RETURN (**out_buf_free_function) (void* free_data, uint64_t num_bytes, void* buf) ); /** * @see I_CommStrategyUp::raisePanic */ GTI_RETURN raisePanic ( void ); /** * @see I_PanicListener::flush */ GTI_RETURN flush ( void ); /** * @see I_PanicListener::flushAndSetImmediate */ GTI_RETURN flushAndSetImmediate (void); }; } #endif /* CSTRAT_SIMPLE_UP_H */
[ "schwitanski@itc.rwth-aachen.de" ]
schwitanski@itc.rwth-aachen.de
21aa6c63cfb2d5ce974065e1da2558e6a3a5bcee
d4d4e9c9b22bdbc7af03e79af3559e6effe4f63e
/CodeJam/qualification_round/b.cpp
ae9d32afacc12b68073d7ae9b42f7efd1e45645f
[]
no_license
deeepeshthakur/CodeFiles
ea8d9c4a2b7a21c853ba8fc953c532e74576a791
3c9f08770a2628fa6eaef28fff212bfa1db96d16
refs/heads/master
2021-07-09T20:08:30.258607
2020-07-06T03:50:57
2020-07-06T03:50:57
160,020,105
2
1
null
2020-07-06T03:44:02
2018-12-02T06:26:50
C++
UTF-8
C++
false
false
1,290
cpp
#include<bits/stdc++.h> #define F first #define S second #define pb push_back #define mp make_pair #define full(a) a.begin(),a.end() #define rfull(a) a.rbegin(),a.rend() using namespace std; const double pi=acos(-1.0); const double pii=2*pi; const double eps=1e-6; const long long MOD=1e9+7; void solve(int test_case){ string s; cin>>s; vector<int> a(s.size(),0); vector<pair<int,int>> br(a.size(),{0,0}); for(int i=0;i<s.size();i++) a[i]=int(s[i]-'0'); int n=a.size(); for(int x=9;x>=1;x--){ for(int i=0;i<n;i++){ if(a[i]==x){ int j=i; while(j+1<n && a[i]==a[j+1]){ j++; } br[i].first++; br[j].second++; for(int k=i;k<=j;k++){ a[k]--; } i=j; } } } cout<<"Case #"<<test_case<<": "; for(int i=0;i<n;i++){ for(int j=0;j<br[i].first;j++){ cout<<"("; } cout<<s[i]; for(int j=0;j<br[i].second;j++){ cout<<")"; } } cout<<"\n"; } int main(){ std::ios::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); int t; cin >> t; for(int i=1;i<=t;i++){ solve(i); } return 0; }
[ "deeepeshthakur@gmail.com" ]
deeepeshthakur@gmail.com
8e4fa644aef79e934c3284c88254d1a38bbb4398
dbe71f422219752454925871cf27df8c84da312d
/cpp01.cpp
07806c26f98811e8dc41d8a2771b38cdda7be553
[]
no_license
tsp1998/CPP
8e1ee8f2ea746416123db23bcdfca3827960ffbf
44d110574a84032bcdfe3c2ee9f09bb7b060d21d
refs/heads/master
2023-03-27T22:07:15.887860
2021-03-28T07:00:21
2021-03-28T07:00:21
326,348,172
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
//show the output /* Tandale Shubham Parmeshwar Programmer SKNSCOE,Korti Email-tsp@outlook.in */ #include <iostream> using namespace std; public class s { s1() { cout << "hello" << "this is Java programming" << endl; } int main() { s o; o.s1(); }
[ "shubham.tandale@qualitiasoft.com" ]
shubham.tandale@qualitiasoft.com
98c32412e2567ea896497aaa75d950632d16555a
636394fc4967123179dd2dc935f437e735c6d38a
/export/windows/obj/src/flixel/input/FlxSwipe.cpp
b26e49be9df85378d854340fcd5f7b7d75b70c3d
[ "MIT" ]
permissive
arturspon/zombie-killer
865e6ef3bdb47408f9bfea9016f61bf19b2559c7
07848c5006916e9079537a3d703ffe3740afaa5a
refs/heads/master
2021-07-18T16:44:26.556092
2019-05-04T13:56:08
2019-05-04T13:56:08
181,805,463
0
1
MIT
2021-07-16T23:18:46
2019-04-17T02:50:10
C++
UTF-8
C++
false
true
12,798
cpp
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxGame #include <flixel/FlxGame.h> #endif #ifndef INCLUDED_flixel_input_FlxSwipe #include <flixel/input/FlxSwipe.h> #endif #ifndef INCLUDED_flixel_math_FlxPoint #include <flixel/math/FlxPoint.h> #endif #ifndef INCLUDED_flixel_util_FlxPool_flixel_util_LabelValuePair #include <flixel/util/FlxPool_flixel_util_LabelValuePair.h> #endif #ifndef INCLUDED_flixel_util_FlxStringUtil #include <flixel/util/FlxStringUtil.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_flixel_util_IFlxPool #include <flixel/util/IFlxPool.h> #endif #ifndef INCLUDED_flixel_util_IFlxPooled #include <flixel/util/IFlxPooled.h> #endif #ifndef INCLUDED_flixel_util_LabelValuePair #include <flixel/util/LabelValuePair.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectContainer #include <openfl/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_Sprite #include <openfl/display/Sprite.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_223f15e5be8ee429_29_new,"flixel.input.FlxSwipe","new",0xecc12d70,"flixel.input.FlxSwipe.new","flixel/input/FlxSwipe.hx",29,0xe38cac7e) HX_LOCAL_STACK_FRAME(_hx_pos_223f15e5be8ee429_39_toString,"flixel.input.FlxSwipe","toString",0xb726199c,"flixel.input.FlxSwipe.toString","flixel/input/FlxSwipe.hx",39,0xe38cac7e) HX_LOCAL_STACK_FRAME(_hx_pos_223f15e5be8ee429_50_get_distance,"flixel.input.FlxSwipe","get_distance",0xd139c82e,"flixel.input.FlxSwipe.get_distance","flixel/input/FlxSwipe.hx",50,0xe38cac7e) HX_LOCAL_STACK_FRAME(_hx_pos_223f15e5be8ee429_55_get_angle,"flixel.input.FlxSwipe","get_angle",0xc834293a,"flixel.input.FlxSwipe.get_angle","flixel/input/FlxSwipe.hx",55,0xe38cac7e) HX_LOCAL_STACK_FRAME(_hx_pos_223f15e5be8ee429_60_get_duration,"flixel.input.FlxSwipe","get_duration",0x79ce444d,"flixel.input.FlxSwipe.get_duration","flixel/input/FlxSwipe.hx",60,0xe38cac7e) namespace flixel{ namespace input{ void FlxSwipe_obj::__construct(int ID, ::flixel::math::FlxPoint StartPosition, ::flixel::math::FlxPoint EndPosition,int StartTimeInTicks){ HX_STACKFRAME(&_hx_pos_223f15e5be8ee429_29_new) HXLINE( 30) this->ID = ID; HXLINE( 31) this->startPosition = StartPosition; HXLINE( 32) this->endPosition = EndPosition; HXLINE( 33) this->_startTimeInTicks = StartTimeInTicks; HXLINE( 34) this->_endTimeInTicks = ::flixel::FlxG_obj::game->ticks; } Dynamic FlxSwipe_obj::__CreateEmpty() { return new FlxSwipe_obj; } void *FlxSwipe_obj::_hx_vtable = 0; Dynamic FlxSwipe_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< FlxSwipe_obj > _hx_result = new FlxSwipe_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3]); return _hx_result; } bool FlxSwipe_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x25d95576; } ::String FlxSwipe_obj::toString(){ HX_STACKFRAME(&_hx_pos_223f15e5be8ee429_39_toString) HXLINE( 40) ::Dynamic value = this->ID; HXDLIN( 40) ::flixel::util::LabelValuePair _this = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 40) _this->label = HX_("ID",db,3f,00,00); HXDLIN( 40) _this->value = value; HXLINE( 41) ::Dynamic value1 = this->startPosition; HXDLIN( 41) ::flixel::util::LabelValuePair _this1 = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 41) _this1->label = HX_("start",62,74,0b,84); HXDLIN( 41) _this1->value = value1; HXLINE( 42) ::Dynamic value2 = this->endPosition; HXDLIN( 42) ::flixel::util::LabelValuePair _this2 = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 42) _this2->label = HX_("end",db,03,4d,00); HXDLIN( 42) _this2->value = value2; HXLINE( 43) Float dx = (this->startPosition->x - this->endPosition->x); HXDLIN( 43) Float dy = (this->startPosition->y - this->endPosition->y); HXDLIN( 43) ::Dynamic value3 = ::Math_obj::sqrt(((dx * dx) + (dy * dy))); HXDLIN( 43) ::flixel::util::LabelValuePair _this3 = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 43) _this3->label = HX_("distance",35,93,f9,6b); HXDLIN( 43) _this3->value = value3; HXLINE( 44) ::Dynamic value4 = this->startPosition->angleBetween(this->endPosition); HXDLIN( 44) ::flixel::util::LabelValuePair _this4 = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 44) _this4->label = HX_("angle",d3,43,e2,22); HXDLIN( 44) _this4->value = value4; HXLINE( 45) ::Dynamic value5 = (( (Float)((this->_endTimeInTicks - this->_startTimeInTicks)) ) / ( (Float)(1000) )); HXDLIN( 45) ::flixel::util::LabelValuePair _this5 = ::flixel::util::LabelValuePair_obj::_pool->get(); HXDLIN( 45) _this5->label = HX_("duration",54,0f,8e,14); HXDLIN( 45) _this5->value = value5; HXLINE( 39) return ::flixel::util::FlxStringUtil_obj::getDebugString(::Array_obj< ::Dynamic>::__new(6)->init(0,_this)->init(1,_this1)->init(2,_this2)->init(3,_this3)->init(4,_this4)->init(5,_this5)); } HX_DEFINE_DYNAMIC_FUNC0(FlxSwipe_obj,toString,return ) Float FlxSwipe_obj::get_distance(){ HX_STACKFRAME(&_hx_pos_223f15e5be8ee429_50_get_distance) HXDLIN( 50) Float dx = (this->startPosition->x - this->endPosition->x); HXDLIN( 50) Float dy = (this->startPosition->y - this->endPosition->y); HXDLIN( 50) return ::Math_obj::sqrt(((dx * dx) + (dy * dy))); } HX_DEFINE_DYNAMIC_FUNC0(FlxSwipe_obj,get_distance,return ) Float FlxSwipe_obj::get_angle(){ HX_STACKFRAME(&_hx_pos_223f15e5be8ee429_55_get_angle) HXDLIN( 55) return this->startPosition->angleBetween(this->endPosition); } HX_DEFINE_DYNAMIC_FUNC0(FlxSwipe_obj,get_angle,return ) Float FlxSwipe_obj::get_duration(){ HX_STACKFRAME(&_hx_pos_223f15e5be8ee429_60_get_duration) HXDLIN( 60) return (( (Float)((this->_endTimeInTicks - this->_startTimeInTicks)) ) / ( (Float)(1000) )); } HX_DEFINE_DYNAMIC_FUNC0(FlxSwipe_obj,get_duration,return ) hx::ObjectPtr< FlxSwipe_obj > FlxSwipe_obj::__new(int ID, ::flixel::math::FlxPoint StartPosition, ::flixel::math::FlxPoint EndPosition,int StartTimeInTicks) { hx::ObjectPtr< FlxSwipe_obj > __this = new FlxSwipe_obj(); __this->__construct(ID,StartPosition,EndPosition,StartTimeInTicks); return __this; } hx::ObjectPtr< FlxSwipe_obj > FlxSwipe_obj::__alloc(hx::Ctx *_hx_ctx,int ID, ::flixel::math::FlxPoint StartPosition, ::flixel::math::FlxPoint EndPosition,int StartTimeInTicks) { FlxSwipe_obj *__this = (FlxSwipe_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(FlxSwipe_obj), true, "flixel.input.FlxSwipe")); *(void **)__this = FlxSwipe_obj::_hx_vtable; __this->__construct(ID,StartPosition,EndPosition,StartTimeInTicks); return __this; } FlxSwipe_obj::FlxSwipe_obj() { } void FlxSwipe_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(FlxSwipe); HX_MARK_MEMBER_NAME(ID,"ID"); HX_MARK_MEMBER_NAME(startPosition,"startPosition"); HX_MARK_MEMBER_NAME(endPosition,"endPosition"); HX_MARK_MEMBER_NAME(_startTimeInTicks,"_startTimeInTicks"); HX_MARK_MEMBER_NAME(_endTimeInTicks,"_endTimeInTicks"); HX_MARK_END_CLASS(); } void FlxSwipe_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ID,"ID"); HX_VISIT_MEMBER_NAME(startPosition,"startPosition"); HX_VISIT_MEMBER_NAME(endPosition,"endPosition"); HX_VISIT_MEMBER_NAME(_startTimeInTicks,"_startTimeInTicks"); HX_VISIT_MEMBER_NAME(_endTimeInTicks,"_endTimeInTicks"); } hx::Val FlxSwipe_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"ID") ) { return hx::Val( ID ); } break; case 5: if (HX_FIELD_EQ(inName,"angle") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_angle() ); } break; case 8: if (HX_FIELD_EQ(inName,"distance") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_distance() ); } if (HX_FIELD_EQ(inName,"duration") ) { if (inCallProp == hx::paccAlways) return hx::Val( get_duration() ); } if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"get_angle") ) { return hx::Val( get_angle_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"endPosition") ) { return hx::Val( endPosition ); } break; case 12: if (HX_FIELD_EQ(inName,"get_distance") ) { return hx::Val( get_distance_dyn() ); } if (HX_FIELD_EQ(inName,"get_duration") ) { return hx::Val( get_duration_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"startPosition") ) { return hx::Val( startPosition ); } break; case 15: if (HX_FIELD_EQ(inName,"_endTimeInTicks") ) { return hx::Val( _endTimeInTicks ); } break; case 17: if (HX_FIELD_EQ(inName,"_startTimeInTicks") ) { return hx::Val( _startTimeInTicks ); } } return super::__Field(inName,inCallProp); } hx::Val FlxSwipe_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"ID") ) { ID=inValue.Cast< int >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"endPosition") ) { endPosition=inValue.Cast< ::flixel::math::FlxPoint >(); return inValue; } break; case 13: if (HX_FIELD_EQ(inName,"startPosition") ) { startPosition=inValue.Cast< ::flixel::math::FlxPoint >(); return inValue; } break; case 15: if (HX_FIELD_EQ(inName,"_endTimeInTicks") ) { _endTimeInTicks=inValue.Cast< int >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"_startTimeInTicks") ) { _startTimeInTicks=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void FlxSwipe_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("ID",db,3f,00,00)); outFields->push(HX_("startPosition",2b,03,b6,cf)); outFields->push(HX_("endPosition",a4,33,b9,82)); outFields->push(HX_("distance",35,93,f9,6b)); outFields->push(HX_("angle",d3,43,e2,22)); outFields->push(HX_("duration",54,0f,8e,14)); outFields->push(HX_("_startTimeInTicks",e1,34,b7,36)); outFields->push(HX_("_endTimeInTicks",48,30,b2,c2)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo FlxSwipe_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(FlxSwipe_obj,ID),HX_("ID",db,3f,00,00)}, {hx::fsObject /* ::flixel::math::FlxPoint */ ,(int)offsetof(FlxSwipe_obj,startPosition),HX_("startPosition",2b,03,b6,cf)}, {hx::fsObject /* ::flixel::math::FlxPoint */ ,(int)offsetof(FlxSwipe_obj,endPosition),HX_("endPosition",a4,33,b9,82)}, {hx::fsInt,(int)offsetof(FlxSwipe_obj,_startTimeInTicks),HX_("_startTimeInTicks",e1,34,b7,36)}, {hx::fsInt,(int)offsetof(FlxSwipe_obj,_endTimeInTicks),HX_("_endTimeInTicks",48,30,b2,c2)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *FlxSwipe_obj_sStaticStorageInfo = 0; #endif static ::String FlxSwipe_obj_sMemberFields[] = { HX_("ID",db,3f,00,00), HX_("startPosition",2b,03,b6,cf), HX_("endPosition",a4,33,b9,82), HX_("_startTimeInTicks",e1,34,b7,36), HX_("_endTimeInTicks",48,30,b2,c2), HX_("toString",ac,d0,6e,38), HX_("get_distance",3e,47,13,21), HX_("get_angle",2a,a0,8b,66), HX_("get_duration",5d,c3,a7,c9), ::String(null()) }; hx::Class FlxSwipe_obj::__mClass; void FlxSwipe_obj::__register() { FlxSwipe_obj _hx_dummy; FlxSwipe_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("flixel.input.FlxSwipe",7e,f5,e9,ec); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(FlxSwipe_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< FlxSwipe_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = FlxSwipe_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = FlxSwipe_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace flixel } // end namespace input
[ "artursponchi@gmail.com" ]
artursponchi@gmail.com
2869f8c6a07b3a7ae848495111ed78acbcb3a33e
3122ac39f1ce0a882b48293a77195476299c2a3b
/clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIBranchImpllinks.h
1ff159f7cd9af6fe72d385fbf5fead171f8a7ed8
[ "MIT" ]
permissive
miao1007/swaggy-jenkins
4e6fe28470eda2428cbc584dcd365a21caa606ef
af79438c120dd47702b50d51c42548b4db7fd109
refs/heads/master
2020-08-30T16:50:27.474383
2019-04-10T13:47:17
2019-04-10T13:47:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,565
h
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.1.1 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIBranchImpllinks.h * * */ #ifndef OAIBranchImpllinks_H #define OAIBranchImpllinks_H #include <QJsonObject> #include "OAILink.h" #include <QString> #include "OAIObject.h" namespace OpenAPI { class OAIBranchImpllinks: public OAIObject { public: OAIBranchImpllinks(); OAIBranchImpllinks(QString json); ~OAIBranchImpllinks() override; void init(); QString asJson () const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; OAILink getSelf() const; void setSelf(const OAILink &self); OAILink getActions() const; void setActions(const OAILink &actions); OAILink getRuns() const; void setRuns(const OAILink &runs); OAILink getQueue() const; void setQueue(const OAILink &queue); QString getClass() const; void setClass(const QString &_class); virtual bool isSet() const override; private: OAILink self; bool m_self_isSet; OAILink actions; bool m_actions_isSet; OAILink runs; bool m_runs_isSet; OAILink queue; bool m_queue_isSet; QString _class; bool m__class_isSet; }; } #endif // OAIBranchImpllinks_H
[ "cliffano@gmail.com" ]
cliffano@gmail.com
455a32c061addc02b2803abe03f6846d799ea549
1f77f63fc4bcf538fc892f6a5ba54058367ed0e5
/src/csalt/src/userfunutils/BoundData.cpp
d3d5a4c31ec4da8e400840b0320e0a626f453dc9
[ "Apache-2.0" ]
permissive
ChristopherRabotin/GMAT
5f8211051b620562947443796fa85c80aed5a7cf
829b7c2c3c7ea73d759c338e7051f92f4f2f6f43
refs/heads/GMAT-2020a
2022-05-21T07:01:48.435641
2022-05-09T17:28:07
2022-05-09T17:28:07
84,392,259
24
10
Apache-2.0
2022-05-11T03:48:44
2017-03-09T03:09:20
C++
UTF-8
C++
false
false
12,207
cpp
//------------------------------------------------------------------------------ // BoundData //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Author: Wendy Shoan / NASA // Created: 2016.01.05 // /** * From original MATLAB prototype: * Author: S. Hughes. steven.p.hughes@nasa.gov */ //------------------------------------------------------------------------------ #include "BoundData.hpp" //------------------------------------------------------------------------------ // public methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // default constructor //------------------------------------------------------------------------------ BoundData::BoundData() { emptyBoundVector.SetSize(1); emptyBoundVector(0) = 0.0; } //------------------------------------------------------------------------------ // copy constructor //------------------------------------------------------------------------------ BoundData::BoundData(const BoundData &copy) { if (copy.stateLowerBound.IsSized()) stateLowerBound = copy.stateLowerBound; if (copy.stateUpperBound.IsSized()) stateUpperBound = copy.stateUpperBound; if (copy.controlLowerBound.IsSized()) controlLowerBound = copy.controlLowerBound; if (copy.controlUpperBound.IsSized()) controlUpperBound = copy.controlUpperBound; if (copy.timeLowerBound.IsSized()) timeLowerBound = copy.timeLowerBound; if (copy.timeUpperBound.IsSized()) timeUpperBound = copy.timeUpperBound; if (copy.staticLowerBound.IsSized()) staticLowerBound = copy.staticLowerBound; if (copy.staticUpperBound.IsSized()) staticUpperBound = copy.staticUpperBound; if (copy.emptyBoundVector.IsSized()) emptyBoundVector = copy.emptyBoundVector; } //------------------------------------------------------------------------------ // operator= //------------------------------------------------------------------------------ BoundData& BoundData::operator=(const BoundData &copy) { if (&copy == this) return *this; if (copy.stateLowerBound.IsSized()) stateLowerBound = copy.stateLowerBound; if (copy.stateUpperBound.IsSized()) stateUpperBound = copy.stateUpperBound; if (copy.controlLowerBound.IsSized()) controlLowerBound = copy.controlLowerBound; if (copy.controlUpperBound.IsSized()) controlUpperBound = copy.controlUpperBound; if (copy.timeLowerBound.IsSized()) timeLowerBound = copy.timeLowerBound; if (copy.timeUpperBound.IsSized()) timeUpperBound = copy.timeUpperBound; if (copy.staticLowerBound.IsSized()) staticLowerBound = copy.staticLowerBound; if (copy.staticUpperBound.IsSized()) staticUpperBound = copy.staticUpperBound; if (copy.emptyBoundVector.IsSized()) emptyBoundVector = copy.emptyBoundVector; return *this; } //------------------------------------------------------------------------------ // destructor //------------------------------------------------------------------------------ BoundData::~BoundData() { // nothing to do here } //------------------------------------------------------------------------------ // Set methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // void SetStateLowerBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the state lower bound. * * @param <bound> the input state lower bound value */ //------------------------------------------------------------------------------ void BoundData::SetStateLowerBound(const Rvector &bound) { if (bound.IsSized()) stateLowerBound = bound; } //------------------------------------------------------------------------------ // void SetStateUpperBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the state upper bound. * * @param <bound> the input state upper bound value */ //------------------------------------------------------------------------------ void BoundData::SetStateUpperBound(const Rvector &bound) { if (bound.IsSized()) stateUpperBound = bound; } //------------------------------------------------------------------------------ // void SetControlLowerBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the control lower bound. * * @param <bound> the input control lower bound value */ //------------------------------------------------------------------------------ void BoundData::SetControlLowerBound(const Rvector &bound) { if (bound.IsSized()) controlLowerBound = bound; } //------------------------------------------------------------------------------ // void SetControlUpperBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the control upper bound. * * @param <bound> the input control upper bound value */ //------------------------------------------------------------------------------ void BoundData::SetControlUpperBound(const Rvector &bound) { if (bound.IsSized()) controlUpperBound = bound; } //------------------------------------------------------------------------------ // void SetTimeLowerBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the time lower bound. * * @param <bound> the input time lower bound value */ //------------------------------------------------------------------------------ void BoundData::SetTimeLowerBound(const Rvector &bound) { if (bound.IsSized()) timeLowerBound = bound; } //------------------------------------------------------------------------------ // void SetTimeUpperBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the time upper bound. * * @param <bound> the input time upper bound value */ //------------------------------------------------------------------------------ void BoundData::SetTimeUpperBound(const Rvector &bound) { if (bound.IsSized()) timeUpperBound = bound; } //------------------------------------------------------------------------------ // void SetStaticLowerBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the static lower bound. * * @param <bound> the input static lower bound value */ //------------------------------------------------------------------------------ void BoundData::SetStaticLowerBound(const Rvector &bound) { if (bound.IsSized()) staticLowerBound = bound; } //------------------------------------------------------------------------------ // void SetStaticUpperBound(const Rvector &bound) //------------------------------------------------------------------------------ /** * This method sets the static upper bound. * * @param <bound> the input static upper bound value */ //------------------------------------------------------------------------------ void BoundData::SetStaticUpperBound(const Rvector &bound) { if (bound.IsSized()) staticUpperBound = bound; } //------------------------------------------------------------------------------ // Get methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // const Rvector& GetStateLowerBound() //------------------------------------------------------------------------------ /** * This method returns the state lower bound. * * @return the state lower bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetStateLowerBound() { return stateLowerBound; } //------------------------------------------------------------------------------ // const Rvector& GetStateUpperBound() //------------------------------------------------------------------------------ /** * This method returns the state upper bound. * * @return the state upper bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetStateUpperBound() { return stateUpperBound; } //------------------------------------------------------------------------------ // const Rvector& GetControlLowerBound() //------------------------------------------------------------------------------ /** * This method returns the control lower bound. * * @return the control lower bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetControlLowerBound() { if (controlLowerBound.IsSized() == true) return controlLowerBound; else return emptyBoundVector; } //------------------------------------------------------------------------------ // const Rvector& GetControlUpperBound() //------------------------------------------------------------------------------ /** * This method returns the control upper bound. * * @return the control upper bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetControlUpperBound() { if (controlUpperBound.IsSized() == true) return controlUpperBound; else return emptyBoundVector; } //------------------------------------------------------------------------------ // const Rvector& GetTimeLowerBound() //------------------------------------------------------------------------------ /** * This method returns the time lower bound. * * @return the time lower bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetTimeLowerBound() { return timeLowerBound; } //------------------------------------------------------------------------------ // const Rvector& GetTimeUpperBound() //------------------------------------------------------------------------------ /** * This method returns the time upper bound. * * @return the time upper bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetTimeUpperBound() { return timeUpperBound; } //------------------------------------------------------------------------------ // const Rvector& GetStaticLowerBound() //------------------------------------------------------------------------------ /** * This method returns the static lower bound. * * @return the static lower bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetStaticLowerBound() { if (staticLowerBound.IsSized() == true) return staticLowerBound; else return emptyBoundVector; } //------------------------------------------------------------------------------ // const Rvector& GetStaticUpperBound() //------------------------------------------------------------------------------ /** * This method returns the state upper bound. * * @return the state upper bound vector */ //------------------------------------------------------------------------------ const Rvector& BoundData::GetStaticUpperBound() { if (staticUpperBound.IsSized() == true) return staticUpperBound; else return emptyBoundVector; return staticUpperBound; } //------------------------------------------------------------------------------ // protected methods //------------------------------------------------------------------------------ // none
[ "christopher.rabotin@gmail.com" ]
christopher.rabotin@gmail.com
52ffd96ebd6bf457225a6c148c49c357930f38ea
33d88cf70ad9f56d2833b150b932ab07d08e9b6e
/graphs/cheapest_flights_within_k_stops.cpp
89c03b76e32408a14e0a4a43a9bc9cf9b650df86
[]
no_license
sanyamdtu/interview_questions
386c33fd8a72ff22a73cfb4c3b1d4d730695cc63
157880e9d83009db455eec1a370010ea7b494ea0
refs/heads/main
2023-08-14T21:43:26.330843
2021-10-02T06:18:46
2021-10-02T06:18:46
315,205,280
0
0
null
null
null
null
UTF-8
C++
false
false
884
cpp
class Solution { public: struct comp { bool operator()(vector<int> &a, vector<int> &b) { return (a[0] > b[0]); } }; int findCheapestPrice(int n, vector<vector<int>> &arr, int u, int v, int k) { vector<vector<pair<int, int>>> g(n); for (auto i : arr) g[i[0]].push_back({i[1], i[2]}); priority_queue<vector<int>, vector<vector<int>>, comp> s; s.push({0, u, k + 1}); while (!s.empty()) { auto a = s.top(); s.pop(); int node = a[1], price = a[0], stops = a[2]; if (node == v) return price; if (a[2] <= 0) continue; for (auto i : g[node]) { s.push({price + i.second, i.first, stops - 1}); } } return -1; } };
[ "sanyamexam@gmail.com" ]
sanyamexam@gmail.com
3c9ad27907604e4e20c6db4d867861cbbb59b24f
6e6d9526d20b54522f152519ecf0167622219006
/docker/Distributed-Mining/gen-cpp/WorkerService_types.h
57d2527ddf6987f0f4593f075e2dacf19d5d3897
[]
no_license
dream-lab/DiPETrans
a46bc94d25da14cd8bf7563e9967ef146ff003ea
1d0b1a6849e55643a23f089323def42fa6e6b09d
refs/heads/master
2023-03-09T20:12:43.692829
2021-02-21T10:24:09
2021-02-21T10:24:09
null
0
0
null
null
null
null
UTF-8
C++
false
true
1,454
h
/** * Autogenerated by Thrift Compiler (0.12.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #ifndef WorkerService_TYPES_H #define WorkerService_TYPES_H #include <iosfwd> #include <thrift/Thrift.h> #include <thrift/TApplicationException.h> #include <thrift/TBase.h> #include <thrift/protocol/TProtocol.h> #include <thrift/transport/TTransport.h> #include <thrift/stdcxx.h> #include "SharedService_types.h" #include "MasterService_types.h" namespace WorkerService { class result; class result : public virtual ::apache::thrift::TBase { public: result(const result&); result& operator=(const result&); result() : number(0), nonce(0) { } virtual ~result() throw(); int32_t number; int64_t nonce; void __set_number(const int32_t val); void __set_nonce(const int64_t val); bool operator == (const result & rhs) const { if (!(number == rhs.number)) return false; if (!(nonce == rhs.nonce)) return false; return true; } bool operator != (const result &rhs) const { return !(*this == rhs); } bool operator < (const result & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; virtual void printTo(std::ostream& out) const; }; void swap(result &a, result &b); std::ostream& operator<<(std::ostream& out, const result& obj); } // namespace #endif
[ "skmonga.hbk@gmail.com" ]
skmonga.hbk@gmail.com
dce6de421c539ef9246017f9d84b0a99a2b96e57
f44a83522f95801a5609ae527396a50ea9c713e7
/practise/lcs.cpp
6f425f30e480b132e91f2f3270bc90b5114d63c5
[]
no_license
ngk123/algorithms
c89e021ee258dc7762f6b73b67a64b92f9bd5bcb
7e2bcc9b62a885f5a86ba121fe5a22badb4f9c05
refs/heads/master
2021-01-20T00:27:21.185896
2017-04-23T08:58:42
2017-04-23T08:58:42
89,129,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,697
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> #include <string.h> #include <string> using namespace std; int lcs(int t,string str1,string str2, int len1, int len2) { int lcsTemp[len1+1][len2+1]; int i,j,idx; int count=0; string answer[1002]; int idx1[1002],idx2[1002]; for(i=0;i<=len1;i++) { for(j=0;j<=len2;j++) { if(i==0||j==0) { lcsTemp[i][j]=0; } else if(str1[i-1]==str2[j-1]) { lcsTemp[i][j]=lcsTemp[i-1][j-1]+1; if(lcsTemp[i][j]>count) { answer[count]=str1[i-1]; idx1[count]=i; idx2[count]=j; count++; } } else { lcsTemp[i][j]=max(lcsTemp[i-1][j],lcsTemp[i][j-1]); } } } if(count<2) { cout<<"case "<<t<<" N"<<endl; } else { cout<<"case "<<t<<" Y"<<endl; cout<<count<<endl; for(i=0;i<count;i++) { cout<<answer[i]<<" "<<idx1[i]<<" "<<idx2[i]<<endl; } } return lcsTemp[len1][len2]; } int main () { int T,n,k,i,j,len1,len2,ans; cin>>T; for(k=0;k<T;k++) { string str1, str2; cin>>len1>>str1>>len2>>str2; //len1=str1.size(); //len2=str2.size(); //cout<<"len1:"<<len1<<" len2:"<<len2<<endl; ans=lcs(k+1,str1, str2, len1, len2) ; // cout<<"lcs :"<<ans<<endl; } return 0; }
[ "khadenilesh92@gmail.com" ]
khadenilesh92@gmail.com
ad5718acc0318347b15f60abe93019ed6bb2f808
395d1860e82bc75ccc04b91c4b9a8fa46276d9bb
/Source/Animation/Animation/Playback/Multithreaded/SampleAndCombine/hkaAnimationSampleAndCombineJobs.h
4e666c155c464fc47e6549bde2e71a62ced25928
[]
no_license
Hakhyun-Kim/projectanarchy
28ba7370050000a12e4305faa11d5deb77c330a1
ccea719afcb03967a68a169730b59e8a8a6c45f8
refs/heads/master
2021-06-03T04:41:22.814866
2013-11-07T07:21:03
2013-11-07T07:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,958
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_ANIMATION_SAMPLE_AND_COMBINE_JOBS_H #define HK_ANIMATION_SAMPLE_AND_COMBINE_JOBS_H #include <Common/Base/Thread/Semaphore/hkSemaphoreBusyWait.h> #include <Common/Base/Thread/JobQueue/hkJobQueue.h> #include <Animation/Animation/Playback/Multithreaded/hkaAnimationJobs.h> #include <Animation/Animation/Animation/hkaAnimationBinding.h> #include <Animation/Animation/Animation/hkaAnimation.h> #include <Animation/Animation/Animation/Quantized/hkaQuantizedAnimation.h> #include <Animation/Animation/Playback/Multithreaded/hkaJobDoneNotifier.h> #include <Animation/Animation/Rig/hkaSkeleton.h> class hkaAnimatedSkeleton; class hkaQuantizedAnimation; class hkaAnimationSampleAndCombineJobBase : public hkJob { public: /// Types enum. enum JobSubType { /// Sample only (no blending) ANIMATION_SAMPLE_AND_COMBINE_JOB_SAMPLE_ONLY, /// Sample and combine (blending) ANIMATION_SAMPLE_AND_COMBINE_JOB_SAMPLE_AND_COMBINE, /// Sample and combine (quantized) ANIMATION_SAMPLE_AND_COMBINE_JOB_QUANTIZED_SAMPLE_AND_COMBINE, // just a marker marking the end of the animation job id range ANIMATION_SAMPLE_AND_COMBINE_JOB_END }; HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaAnimationSampleAndCombineJobBase ); protected: HK_FORCE_INLINE hkaAnimationSampleAndCombineJobBase( JobSubType type, hkUint16 size ); public: /// The buffer allowable/available for decompressing data. You can use getMaxSizeOfCombinedDataChunks() to ensure this is large enough. hkUint32 m_bufferSize; /// Notifies via a semaphore or flag that the job is done. hkaJobDoneNotifier m_jobDoneNotifier; }; /// A job which samples a set of animations. /// If more than one animation is specified then DMA cost is hidden through double buffering. class hkaAnimationSampleOnlyJob : public hkaAnimationSampleAndCombineJobBase { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaAnimationSampleOnlyJob ); HK_FORCE_INLINE hkaAnimationSampleOnlyJob(); HK_FORCE_INLINE ~hkaAnimationSampleOnlyJob() {} #if !defined(HK_PLATFORM_SPU) inline hkBool isValid() const; // Only exists on PPU for error checking #endif /// Helper structure for data needed to sample a single animation struct AnimationData { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaAnimationSampleOnlyJob::AnimationData ); /// Constructor. #if !defined(HK_PLATFORM_SPU) HK_FORCE_INLINE AnimationData(); // Only exists on PPU for error checking HK_FORCE_INLINE ~AnimationData() {} #endif /// Init all members. HK_FORCE_INLINE void init(); #if !defined(HK_PLATFORM_SPU) /// Test if all members are valid (alignment, size etc.). inline hkBool isValid() const; // Only exists on PPU for error checking #endif // Sample inputs /// The frame number such that local time for the sample is between m_frameIndex and m_frameIndex+1. HK_ALIGN16(hkUint32 m_frameIndex); /// The delta between frames, in range [0,1). You can use getFrameAndDelta() to calculate this and m_frameIndex for a given time. hkReal m_frameDelta; /// The highest transform track to sample to - used for LOD sampling. hkUint32 m_maxTransformTrack; /// The highest float track to sample to - used for LOD sampling. hkUint32 m_maxFloatTrack; // Animation Data /// Pointer to original animated skeleton - used only in shared memory architectures, otherwise ignored. const hkaAnimation* m_animationOnCPU; /// The type of animation data stored in the chunks hkaAnimation::AnimationType m_animationType; /// The static animation data required to sample at 'localTime', given by m_frameIndex and m_frameDelta. hkaAnimation::DataChunk m_chunks[HK_MAX_NUM_DATA_CHUNKS]; /// The number of chunks that contain valid data. int m_numValidChunks; // Output Data /// The transform/bone results are placed in this buffer in main memory. hkQsTransform* m_poseOut; /// The float results are placed in this buffer in main memory. hkReal* m_floatSlotsOut; }; // Animation Data /// The array of animations to sample. AnimationData* m_animData; /// The number of animations to sample. int m_numAnims; }; /// A job which does all the decompression and blending for an animated skeleton class hkaAnimationSampleAndCombineJob : public hkaAnimationSampleAndCombineJobBase { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaAnimationSampleAndCombineJob); HK_FORCE_INLINE hkaAnimationSampleAndCombineJob(); HK_FORCE_INLINE ~hkaAnimationSampleAndCombineJob() {} #if !defined(HK_PLATFORM_SPU) inline hkBool isValid() const; #endif public: /// Helper structure for data needed to sample and blend a single animation control. struct ControlData { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaAnimationSampleAndCombineJob::ControlData); #if !defined(HK_PLATFORM_SPU) HK_FORCE_INLINE ControlData(); // Only exists on PPU for error checking HK_FORCE_INLINE ~ControlData() {} #endif HK_FORCE_INLINE void init(); #if !defined(HK_PLATFORM_SPU) inline hkBool isValid() const; // Only exists on PPU for error checking #endif /// The frame number such that local time for the sample is between m_frameIndex and m_frameIndex+1. HK_ALIGN16(hkUint32 m_frameIndex); /// The delta between frames, in range [0,1). You can use getFrameAndDelta() to calculate this and m_frameIndex for a given time. hkReal m_frameDelta; /// The master weight for blending this animation. hkReal m_weight; /// The binding for this animation. hkaAnimationBinding m_binding; /// The type of animation data stored in the chunks. hkaAnimation::AnimationType m_animationType; /// The animation data required to sample at 'localTime', given by m_frameIndex and m_frameDelta hkaAnimation::DataChunk m_chunks[HK_MAX_NUM_DATA_CHUNKS]; /// The number of chunks that contain valid data. hkInt32 m_numValidChunks; /// The per track weights for this control. const hkUint8* m_transformTrackWeights; /// Set to 0 if no per track weight are required. hkInt32 m_numTransformTrackWeights; /// The per track weights for this control const hkUint8* m_floatTrackWeights; /// Set to 0 if no per track weight are required. hkInt32 m_numFloatTrackWeights; }; // Sample inputs /// Pointer to original animated skeleton - used only in shared memory architectures, otherwise ignored. const hkaAnimatedSkeleton* m_animatedSkeletonOnCPU; /// Point to the reference pose or HK_NULL for no filling. hkQsTransform* m_referencePose; /// The fill threshold (see hkaAnimatedSkeleton). hkReal m_referencePoseWeightThreshold; /// The total number of bones in the output skeleton - used only if local-to-model space conversion is required. hkUint32 m_numSkeletonBones; /// The parent indices array - used only if local-to-model space conversion is required. const hkInt16* m_parentIndices; /// The highest number of bones to sample. hkUint32 m_maxBone; /// The highest number of float slots to sample. hkUint32 m_maxFloatSlot; // Animation Control Data /// Note: The control data here is expected to be ordered by blend hint. Normal blending comes first followed by additive. ControlData* m_animationControls; /// Number of controls. hkUint32 m_numAnimationControls; /// Required to aid reserving of stack space for track sample data. hkUint16 m_maxTransformTracksInAllAnimations; /// Required to aid reserving of stack space for track sample data. hkUint16 m_maxFloatTracksInAllAnimations; // Output Data /// The transform/bone results are placed in this buffer in main memory. If m_parentIndices == HK_NULL, these are in local space, otherwise they are in model space. hkQsTransform* m_poseOut; /// The float results are placed in this buffer in main memory. hkReal* m_floatSlotsOut; /// The partitions in the hkaSkeleton const hkaSkeleton::Partition* m_partitions; /// The number of partitions in the partition list hkInt16 m_numPartitions; }; /// A job which samples and blends a set of hkaQuantizedAnimation instances. /// The job consists of an array of QuantizedAnimationEntry describing each animation, local sampling time, blend weight, etc. class hkaQuantizedSampleAndCombineJob : public hkaAnimationSampleAndCombineJobBase { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIMATION, hkaQuantizedSampleAndCombineJob ); enum PerJobBlendFlags { SLERP = 1, ///< If set, slerp blended rotations. Otherwise lerp blended rotations. NORMALIZE = 2 ///< If set the resulting pose is normalized after blending (required if using lerp). }; HK_FORCE_INLINE hkaQuantizedSampleAndCombineJob(); HK_FORCE_INLINE ~hkaQuantizedSampleAndCombineJob() {} /// Descriptor for sampling and blending a single hkaQuantizedAnimation animation. /// The hkaQuantizedSampleAndCombineJob has an array of these struct QuantizedAnimationEntry { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_ANIM_RUNTIME,hkaQuantizedSampleAndCombineJob::QuantizedAnimationEntry); enum BlendFlags { ADDITIVE = 1, ///< If set, this animation is blended additively SUBTRACTIVE = 2, ///< If set, this animation is blended subtractively (cannot be both additive and subtractive) MIRRORED = 4, ///< If set, this animation is mirrored before blending PARTITIONS = 8 ///< If set, this animation will be expanded from partition space to full pose before blending }; /// Initializes the m_animData and m_numAnimData members from a given hkaQuantizedAnimation HK_FORCE_INLINE void setAnimData( const hkaQuantizedAnimation* anim ); /// Data descriptor for an hkaQuantizedAnimation instance. // Initialize these by calling setAnimData() above. const hkUint8* m_animData; hkUint32 m_numAnimData; /// Local time for sampling and blend weight. /// See Animation/Playback/Utilities/hkaBlender.h for a description of how blend weights are used hkReal m_sampleTime; hkReal m_weight; // Per bone weights (may be null, otherwise must be numBones in size and 16 byte aligned) hkReal* m_perBoneWeights; hkReal* m_perFloatWeights; // Partition indices (may be null if there are no partitions const hkInt16* m_partitionIndices; hkInt16 m_numPartitionIndices; /// Per animation blend flags hkUint32 m_flags; }; // // Input data // /// Animation blend list hkUint32 m_numAnimations; QuantizedAnimationEntry* m_animations; /// Skeleton description. /// These values should be copied directly from the hkaSkeleton instance for this character. hkUint32 m_numBones; hkUint32 m_numFloats; const hkQsTransform* m_referenceBones; const hkReal* m_referenceFloats; const hkInt16* m_parentIndices; ///< Set to HK_NULL to keep results in local space. Otherwise results are converted to model space. /// Options applied to all animations. See hkaQuantizedAnimation.h for further information. /// Weight below which animations are ignored (not blended). hkReal m_minimumWeight; hkReal m_frameSteppingTolerance; ///< Tolerance to which animations snap to the nearest frame rather than interpolate between frames hkUint32 m_flags; ///< Per-job blend flags /// Mirroring data (optional if not using mirroring). /// Set to hkaMirroredSkeleton::getBonePairMap() const hkInt16* m_mirroredBonePairMap; const hkQuaternion* m_mirroredBoneInvariants; ///< Set to hkaMirroredSkeleton::getInvariants() // Partitioning data (optional if not using partitions). /// Set to hkaSkeleton::m_parititons const hkaSkeleton::Partition* m_partitions; hkInt16 m_numPartitions; ///< Set to m_partitions::getSize() // // Output data // /// Output arrays. Must be large enough to hold the result. /// The transform/bone results are placed in this buffer in main memory. If m_parentIndices == HK_NULL, these are in local space, otherwise they are in model space. hkQsTransform* m_bonesOut; hkReal* m_floatsOut; ///< The float results are placed in this buffer in main memory. hkReal* m_boneWeightsOut; ///< The weight results are placed in this buffer in main memory (may be HK_NULL if not needed). hkReal* m_floatWeightsOut; ///< The weight results are placed in this buffer in main memory (may be HK_NULL if not needed). }; #include <Animation/Animation/Playback/Multithreaded/SampleAndCombine/hkaAnimationSampleAndCombineJobs.inl> #endif // HK_ANIMATION_SAMPLE_AND_COMBINE_JOBS_H /* * Havok SDK - Base file, BUILD(#20131019) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "joel.van.eenwyk@havok.com" ]
joel.van.eenwyk@havok.com
dc86cfb44168ecb489ad68e0f11fd34660d4658b
37221af35b41dcd209e7ec076c50047cb35af348
/app/src/main/cpp/vins_system/system.cc
1c8a943a567beea6f605a64a2fa221292867c41c
[]
no_license
euwen/VINS_Honor
e08e3b433eda3f7ba0c94f1dcc6a5287d784e816
d13bf81ec407325c0078fac57ce8ae30d546eea1
refs/heads/master
2022-10-03T21:59:12.451488
2020-06-04T14:34:40
2020-06-04T14:34:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,676
cc
#include "system.h" System* System::instance = nullptr; ASensorEventQueue* System::accSensorEventQueue = nullptr; ASensorEventQueue* System::gyrSensorEventQueue = nullptr; System::System() { //LOGI("System Constructor"); this->instance = this; } System::~System() { LOGI("System Destructor"); } void System::Init() { isCapturing = false; bStart_backend = true; bool deviceCheck = SetParameters( DeviceType::Honor20 ); if ( !deviceCheck ) { LOGE( "Device Not Supported!" ); } trackerData[0].readIntrinsicParameter(); estimator.setParameter(); thd_BackEnd = std::thread( &System::ProcessBackEnd, this ); ImuStartUpdate(); isCapturing = true; LOGI( " VINS System Parameters were Initialized Successfuly!" ); } // 对IMU和图像数据进行对齐对其并组合 pair< vector<IMU>, IMG >,返回 vector< pair< vector<IMU>, IMG > > // 一帧IMG数据对应多帧IMU数据, 即[i, j]图像时刻中的所有图像和IMU数据, 取对齐好的第j帧图像和[i ,j]帧图像间的所有IMU数据进行组合 std::vector< std::pair< std::vector<ImuConstPtr>, ImgConstPtr > > System::GetMeasurements() { std::vector< std::pair< std::vector<ImuConstPtr>, ImgConstPtr > > measurements; while (true) { // 直到把imu_buf和feature_buf中的图像数据和IMU数据取完,才能够跳出此函数 if ( imu_buf.empty() || feature_buf.empty() ) return measurements; // imu_buf和feature_buf中数据的时间戳从front到back是递增的 // imu_buf队尾处IMU数据时间戳大于feature_buf队首处图像数据,跳过此if语句 if ( !(imu_buf.back()->header > feature_buf.front()->header + estimator.td) ) { // imu_buf : ... t2 t3 t4 t5 t6 t7 (no imu data) // feature_buf : ... t12 -- -- -- -- t17 ... // 这种情况应该继续等待获取更多的IMU测量数据, 只允许出现在处理的开始阶段 LOGI("wait for imu, only should happen at the beginning"); sum_of_wait++; return measurements; } // imu_buf队首处IMU数据的时间戳小于feature_buf队首处图像数据,跳过此if语句 if ( !(imu_buf.front()->header < feature_buf.front()->header + estimator.td) ) { // imu_buf : ... t4 t5 t6 t7 t8 t9 ... // feature_buf : ... t1 -- -- -- -- t6 ... // 这种情况应该将旧的图像数据pop出队列,只允许出现在处理的开始阶段 LOGI("throw img, only should happen at the beginning"); feature_buf.pop(); continue; } // imu_buf : ... t2 t3 t4 t5 t6 t7 ... // feature_buf : ... t4 -- -- -- -- t9 ... // 取出feature_buf队首处图像数据,并移出队列 ImgConstPtr img_msg = feature_buf.front(); feature_buf.pop(); // 取出imu_buf中所有时间戳小于img_msg的IMU数据,并移出队列 // 图像数据(img_msg),对应多组在时间戳内的imu数据,然后塞入measurements std::vector<ImuConstPtr> IMUs; while ( imu_buf.front()->header < img_msg->header + estimator.td ) { IMUs.emplace_back(imu_buf.front()); imu_buf.pop(); } // !!!这里把下一帧IMU数据也放进去了,但没有pop出队列 // !!!因此当前帧图像和下一帧图像会共用这一帧IMU数据(第一个时间戳大于当前帧图像时间戳的IMU数据) IMUs.emplace_back(imu_buf.front()); if (IMUs.empty()) LOGE( "NO IMU Between Two Image!" ); measurements.emplace_back(IMUs, img_msg); } return measurements; } void System::ProcessBackEnd() { // 线程循环等待接收对齐好的IMU和图像数据 while (bStart_backend) { //LOGI( "Thread thd_BackEnd, Function ProcessBackEnd..." ); // getMeasurements() 对IMU和图像数据进行对齐对其并组合 vector< pair< vector<IMU>, IMG > > // 一帧IMG数据对应多帧IMU数据, 即[i, j]图像时刻中的所有图像和IMU数据, 取对齐好的第j帧图像和[i ,j]帧图像间的所有IMU数据进行组合 std::vector< std::pair< std::vector<ImuConstPtr>, ImgConstPtr > > measurements; std::unique_lock<std::mutex> lk(m_buf); con.wait(lk, [&] { return (measurements = GetMeasurements()).size() != 0; }); lk.unlock(); m_estimator.lock(); // 遍历刚刚获取的IMU和图像数据 for (auto &measurement : measurements) { auto img_msg = measurement.second; double dx = 0, dy = 0, dz = 0, rx = 0, ry = 0, rz = 0; // 遍历刚刚获取的这一段IMU数据,并递推求解这一段时间末尾时刻(即图像帧时刻)对应的预积分量和运动模型积分得到的状态估计量 for (auto &imu_msg : measurement.first) { double t = imu_msg->header; double img_t = img_msg->header + estimator.td; // IMU数据时间戳早于图像数据 // 一般仿真数据集中 getMeasurements() 返回的结果是IMU数据时间戳早于图像数据 if (t <= img_t) { if (current_time < 0) current_time = t; // dt 是两个IMU时刻之间的时间间隔 double dt = t - current_time; assert(dt >= 0); current_time = t; dx = imu_msg->linear_acceleration.x(); dy = imu_msg->linear_acceleration.y(); dz = imu_msg->linear_acceleration.z(); rx = imu_msg->angular_velocity.x(); ry = imu_msg->angular_velocity.y(); rz = imu_msg->angular_velocity.z(); // 对获取的IMU数据进行处理: 预积分更新, 运动模型更新 estimator.processIMU(dt, Vector3d(dx, dy, dz), Vector3d(rx, ry, rz)); //LOGI( "imu: dt:%f a: %f %f %f w: %f %f %f\n",dt, dx, dy, dz, rx, ry, rz ); } // IMU数据时间戳晚于图像数据 // 考虑鲁棒性,实际情况中还是会有两传感器(IMU和相机)的数据谁先收到和后收到的问题 // 通常的一种情况是,两传感器时钟系统不同步且无规律可言,此时一帧图像的时间戳在两个IMU时刻之间 // 那么就需要采用插值的方法,来对齐IMU和图像的位姿(四元数球面插值)和速度(单线性插值) else { double dt_1 = img_t - current_time; double dt_2 = t - img_t; current_time = img_t; assert(dt_1 >= 0); assert(dt_2 >= 0); assert(dt_1 + dt_2 > 0); double w1 = dt_2 / (dt_1 + dt_2); double w2 = dt_1 / (dt_1 + dt_2); dx = w1 * dx + w2 * imu_msg->linear_acceleration.x(); dy = w1 * dy + w2 * imu_msg->linear_acceleration.y(); dz = w1 * dz + w2 * imu_msg->linear_acceleration.z(); rx = w1 * rx + w2 * imu_msg->angular_velocity.x(); ry = w1 * ry + w2 * imu_msg->angular_velocity.y(); rz = w1 * rz + w2 * imu_msg->angular_velocity.z(); estimator.processIMU(dt_1, Vector3d(dx, dy, dz), Vector3d(rx, ry, rz)); //LOGI( "dimu: dt:%f a: %f %f %f w: %f %f %f\n",dt_1, dx, dy, dz, rx, ry, rz ); } } LOGI( "Processing vision data with stamp %f \n", img_msg->header ); std::map< int, std::vector< std::pair< int, Eigen::Matrix<double, 7, 1> > > > image; // 遍历并获取这一帧图像数据中的每一个特征点信息,并存储到map数组 image 中 for (unsigned int i = 0; i < img_msg->points.size(); i++) { int v = img_msg->id_of_point[i] + 0.5; int feature_id = v / NUM_OF_CAM; int camera_id = v % NUM_OF_CAM; // 特征点去畸变校正后且在相机系归一化平面的坐标 double x = img_msg->points[i].x(); double y = img_msg->points[i].y(); double z = img_msg->points[i].z(); // 特征点像素系坐标 double p_u = img_msg->u_of_point[i]; double p_v = img_msg->v_of_point[i]; // 特征点速度 double velocity_x = img_msg->velocity_x_of_point[i]; double velocity_y = img_msg->velocity_y_of_point[i]; assert(z == 1); Eigen::Matrix<double, 7, 1> xyz_uv_velocity; xyz_uv_velocity << x, y, z, p_u, p_v, velocity_x, velocity_y; image[feature_id].emplace_back(camera_id, xyz_uv_velocity); //LOGI( "dimg: point_3d: %f %f %f point_2d: %f %f velocity: %f %f \n",x, y, z, p_u, p_v, velocity_x, velocity_y ); } // 对获取的这一帧图像数据进行处理: VIO初始化, 视觉特征三角化, BA非线性优化 estimator.processImage(image, img_msg->header); if ( estimator.solver_flag == Estimator::SolverFlag::NON_LINEAR ) { Vector3d p_wi; Quaterniond q_wi; q_wi = Quaterniond(estimator.Rs[WINDOW_SIZE]); p_wi = estimator.Ps[WINDOW_SIZE]; double dStamp = estimator.Headers[WINDOW_SIZE]; //LOGI( "Timestamp: %f, Optimized location: %f, %f, %f", dStamp, p_wi.x(), p_wi.y(), p_wi.z() ); } // Update Android UI Information ShowInputView(); } m_estimator.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); LOGI("Thread thd_BackEnd iteration done"); } } void System::ImageStartUpdate(cv::Mat& image, double imgTimestamp, bool isScreenRotated) { if ( isCapturing ) { // 跳过第零帧 if (!init_feature) { LOGI( "1 PubImageData skip the first detected feature, which doesn't contain optical flow speed" ); init_feature = 1; return; } // 判断是否是第一帧图像 if(first_image_flag) { LOGI( "Init the first image" ); first_image_flag = false; first_image_time = imgTimestamp; last_image_time = imgTimestamp; return; } // detect unstable camera stream // 判断时间间隔,有问题(当前帧距上一帧发布时间久远,或当前帧时间戳早于上一帧)则 restart 重启 if (imgTimestamp - last_image_time > 1.0 || imgTimestamp < last_image_time) { LOGI( "image discontinue! reset the feature tracker!" ); first_image_flag = true; last_image_time = 0.0; pub_count = 1; return; } last_image_time = imgTimestamp; // frequency control // FREQ, frequence (Hz) of publish tracking result. At least 10Hz for good estimation. // If set FREQ == 0, the frequence will be same as raw image // 通过控制间隔时间 (img_msg->header.stamp.toSec() - first_image_time) 内的发布次数 pub_count // 来控制图像跟踪的发布频率不超过 FREQ (Hz) if ( round( 1.0 * pub_count / (imgTimestamp - first_image_time) ) <= FREQ) { PUB_THIS_FRAME = true; // reset the frequency control if (abs(1.0 * pub_count / (imgTimestamp - first_image_time) - FREQ) < 0.01 * FREQ) { first_image_time = imgTimestamp; pub_count = 0; } } else PUB_THIS_FRAME = false; // 单目 读取图像数据并进行特征跟踪处理 //LOGI( "Start to process image via feature tracker!" ); cv::cvtColor( image, image, cv::COLOR_BGRA2GRAY ); trackerData[0].readImage(image, imgTimestamp); cv::cvtColor( image, image, cv::COLOR_GRAY2BGRA ); for ( unsigned int i = 0;; i++ ) { bool completed = false; for (int j = 0; j < NUM_OF_CAM; j++) // 单目 更新当前帧图像特征点的全局ID if (j != 1 || !STEREO_TRACK) completed |= trackerData[j].updateID(i); // 遍历完整个ids之后才会break,即updateID()返回false使completed = false 时才会break if (!completed) break; } // PUB_THIS_FRAME=1 封装该帧图像特征点信息并发布 if (PUB_THIS_FRAME) { pub_count++; std::shared_ptr<IMG_MSG> feature_points( new IMG_MSG() ); feature_points->header = imgTimestamp; vector<set<int>> hash_ids(NUM_OF_CAM); for (int i = 0; i < NUM_OF_CAM; i++) { auto &un_pts = trackerData[i].cur_un_pts; // 特征点去畸变校正后且在相机系归一化平面的坐标 auto &cur_pts = trackerData[i].cur_pts; // 特征点像素坐标 auto &ids = trackerData[i].ids; auto &pts_velocity = trackerData[i].pts_velocity; for (unsigned int j = 0; j < ids.size(); j++) { if (trackerData[i].track_cnt[j] > 1) { int p_id = ids[j]; hash_ids[i].insert(p_id); double x = un_pts[j].x; double y = un_pts[j].y; double z = 1; // 图像特征点信息封装 feature_points->points.push_back( Vector3d( x, y, z ) ); feature_points->id_of_point.push_back( p_id * NUM_OF_CAM + i ); feature_points->u_of_point.push_back( cur_pts[j].x ); feature_points->v_of_point.push_back( cur_pts[j].y ); // 图像特征点的移动速度(x,y方向单位时间内移动了多少个像素) // 这个主要是用于IMU数据与图像数据的时间戳自动对齐(参考秦通18年IROS Paper) feature_points->velocity_x_of_point.push_back( pts_velocity[j].x ); feature_points->velocity_y_of_point.push_back( pts_velocity[j].y ); } } } // skip the first image; since no optical speed on frist image if (!init_pub) { init_pub = 1; } else { m_buf.lock(); // 前端特征点追踪结果 feature_points 最终存储到队列 System::feature_buf 中 feature_buf.push( feature_points ); m_buf.unlock(); con.notify_one(); } } if ( SHOW_TRACK ) { // 根据特征点被追踪的次数,显示其颜色,越红表示这个特征点看到的越久,一幅图像要是大部分特征点是蓝色,前端tracker效果很差了,估计要挂了 for (unsigned int j = 0; j < trackerData[0].cur_pts.size(); j++) { double len = min( 1.0, 1.0 * trackerData[0].track_cnt[j] / WINDOW_SIZE ); cv::circle( image, trackerData[0].cur_pts[j], 2, cv::Scalar(255 * (1 - len), 0, 255 * len), 2 ); } } // 绘制并显示轨迹 // if ( estimator.solver_flag == Estimator::SolverFlag::NON_LINEAR ) { estimator.drawresult.pose.clear(); estimator.drawresult.pose = estimator.visual_poses; estimator.drawresult.origin_w[0] = (float)estimator.correct_Ps[0][0]; estimator.drawresult.origin_w[1] = (float)estimator.correct_Ps[0][1]; //LOGI( "Start to draw trajectory!" ); estimator.drawresult.Reprojection( estimator.image_show, estimator.visual_point_cloud, estimator.correct_Rs, estimator.correct_Ps ); //LOGI( "Start to show trajectory!" ); cv::Mat tmp2 = estimator.image_show; cv::Mat down_origin_image; cv::resize(image, down_origin_image, cv::Size(200, 150)); // 宽 200, 高 150 cv::cvtColor(down_origin_image, down_origin_image, cv::COLOR_BGRA2BGR); cv::Mat imageROI; imageROI = tmp2( cv::Rect( 10, ROW - down_origin_image.rows- 10, down_origin_image.cols, down_origin_image.rows ) ); down_origin_image.copyTo(imageROI); cv::cvtColor(tmp2, image, cv::COLOR_BGR2BGRA); // } } else { LOGI( "Not Caputuring!" ); } } void System::ImuStartUpdate() { // Get a reference to the sensor manager ASensorManager *sensorManager = ASensorManager_getInstance(); assert( sensorManager != NULL ); ALooper* looper = ALooper_forThread(); if( looper == NULL ) looper = ALooper_prepare( ALOOPER_PREPARE_ALLOW_NON_CALLBACKS ); assert(looper != NULL); // Creates a new sensor event queue and associate it with a looper accSensorEventQueue = ASensorManager_createEventQueue( sensorManager, looper, LOOPER_ID_USER, NULL, NULL ); assert( accSensorEventQueue != NULL ); // Returns the default sensor for the given type const ASensor *accelerometer = ASensorManager_getDefaultSensor( sensorManager, ASENSOR_TYPE_ACCELEROMETER ); assert( accelerometer != NULL ); auto status = ASensorEventQueue_enableSensor( accSensorEventQueue, accelerometer ); assert(status >= 0); status = ASensorEventQueue_setEventRate( accSensorEventQueue, accelerometer, SENSOR_REFRESH_PERIOD_US ); assert(status >= 0); gyrSensorEventQueue = ASensorManager_createEventQueue( sensorManager, looper, LOOPER_ID_USER, ProcessASensorEventsCallback, NULL); assert( gyrSensorEventQueue != NULL ); const ASensor *gyroscope = ASensorManager_getDefaultSensor( sensorManager, ASENSOR_TYPE_GYROSCOPE ); assert( gyroscope != NULL ); status = ASensorEventQueue_enableSensor( gyrSensorEventQueue, gyroscope ); assert(status >= 0); status = ASensorEventQueue_setEventRate( gyrSensorEventQueue, gyroscope, SENSOR_REFRESH_PERIOD_US ); assert(status >= 0); LOGI("IMU EventQueues Initialized and Started!"); } int System::ProcessASensorEventsCallback(int fd, int events, void* data) { static ASensorEvent accSensorEvent; ASensorEvent gyrSensorEvent; static double accTimestamp = -1.0; //LOGI( "Start to Update IMU Data!" ); // Retrieve pending events in sensor event queue // Retrieve next available events from the queue to a specified event array while ( ASensorEventQueue_getEvents(gyrSensorEventQueue, &gyrSensorEvent, 1) > 0 ) { //LOGI( "Retrieve pending events in sensor event queue" ); assert( gyrSensorEvent.type == ASENSOR_TYPE_GYROSCOPE ); double gyrTimestamp = gyrSensorEvent.timestamp / 1000000000.0; assert( gyrTimestamp > 0 ); IMU_MSG gyr_msg; gyr_msg.header = gyrTimestamp; gyr_msg.angular_velocity << gyrSensorEvent.uncalibrated_gyro.x_uncalib, gyrSensorEvent.uncalibrated_gyro.y_uncalib, gyrSensorEvent.uncalibrated_gyro.z_uncalib; //LOGI( "Filtering Gyroscope Data!" ); if ( instance->gyr_buf.size() == 0 ) { instance->gyr_buf.push_back( gyr_msg ); instance->gyr_buf.push_back( gyr_msg ); continue; } else if ( gyr_msg.header <= instance->gyr_buf[1].header ) { continue; } else { instance->gyr_buf[0] = instance->gyr_buf[1]; instance->gyr_buf[1] = gyr_msg; } // wait until gyroscope data is steady if ( instance->imu_prepare < 10 ) { LOGI( "Wait Until Gyroscope Data is Steady!" ); instance->imu_prepare++; continue; } while ( accTimestamp < instance->gyr_buf[0].header ) { ssize_t accEventNumbers; while ( (accEventNumbers = ASensorEventQueue_getEvents( accSensorEventQueue, &accSensorEvent, 1 )) == 0 ) { std::this_thread::sleep_for( std::chrono::milliseconds(1) ); } assert( accEventNumbers == 1 ); assert( accSensorEvent.type == ASENSOR_TYPE_ACCELEROMETER ); accTimestamp = accSensorEvent.timestamp / 1000000000.0; std::shared_ptr<IMU_MSG> acc_msg(new IMU_MSG()); acc_msg->header = accTimestamp; acc_msg->linear_acceleration << accSensorEvent.acceleration.x, accSensorEvent.acceleration.y, accSensorEvent.acceleration.z; instance->cur_acc = acc_msg; } if ( instance->gyr_buf[1].header < accTimestamp ) { LOGE("Have to Wait for Fitting Gyroscope Event!"); continue; } // 插值 //LOGI( "Interpolation Between Gyroscope and Accelerometer" ); std::shared_ptr<IMU_MSG> imu_msg(new IMU_MSG()); if ( instance->cur_acc->header >= instance->gyr_buf[0].header && instance->cur_acc->header < instance->gyr_buf[1].header ) { imu_msg->header = instance->cur_acc->header; imu_msg->linear_acceleration = instance->cur_acc->linear_acceleration; imu_msg->angular_velocity = instance->gyr_buf[0].angular_velocity + ( instance->gyr_buf[1].angular_velocity - instance->gyr_buf[0].angular_velocity ) * ( instance->cur_acc->header - instance->gyr_buf[0].header ) / ( instance->gyr_buf[1].header - instance->gyr_buf[0].header ); } else { LOGE( "IMU Data Error, Current Accelerometer Data Error!" ); continue; } instance->m_buf.lock(); instance->imu_buf.push( imu_msg ); instance->m_buf.unlock(); instance->con.notify_one(); } //should return 1 to continue receiving callbacks, or 0 to unregister return 1; } void System::ImuStopUpdate() { ASensorManager *sensorManager = ASensorManager_getInstance(); if ( sensorManager != NULL ) { const ASensor *accelerometer = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_ACCELEROMETER); const ASensor *gyroscope = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_GYROSCOPE); ASensorEventQueue_disableSensor(accSensorEventQueue, accelerometer); ASensorEventQueue_disableSensor(gyrSensorEventQueue, gyroscope); } } void System::ShowInputView() { std::ostringstream oss; m_ui.lock(); float x_view = (float)estimator.correct_Ps[0][0]; float y_view = (float)estimator.correct_Ps[0][1]; float z_view = (float)estimator.correct_Ps[0][2]; LOGI( "XYZ: %f, %f, %f", x_view, y_view, z_view ); oss << "X: "<< x_view; tvXText = oss.str(); oss.str(""); oss.clear(); oss << "Y: "<< y_view; tvYText = oss.str(); oss.str(""); oss.clear(); oss << "Z: "<< z_view; tvZText = oss.str(); oss.str(""); oss.clear(); m_ui.unlock(); }
[ "clearcumt@163.com" ]
clearcumt@163.com
18bd3412d11bd14b3b74bb7ebe01020d52c576ec
6cd5be1764cbbeb29854b43c6970ff832e859d74
/locomoto.h
daf5099a5f9c984f4bfc3de61b65a44de46308a2
[]
no_license
EndianaJones/Robbot
de4d2e9547b185c54df3b0222464b6f869760b07
e98c42a1ac7d1401c5aee18bedfd2a85dee7deba
refs/heads/master
2021-05-06T15:07:05.955361
2017-12-08T05:06:22
2017-12-08T05:06:22
113,533,430
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
h
#ifndef LOCOMOTOR_H_INCLUDED #define LOCOMOTOR_H_INCLUDED #include "std_lib_facilitie.h" using namespace std; class locomotor { private: double part_max_speed; // in MPH double part_power; //in watts int part_battery_comp; string part_name; int part_number; string part_type; //can be Torso, head, Locomotor or battery double part_price; double part_weight; string part_description; public: locomotor(); locomotor(string , int , string , double , double , string , double, double ); //void set_name(); string get_name() const ; //void set_number(int); int get_number() const; // void set_type(string type); string get_type() const; // void set_price(double); double get_price() const; // void set_weight(double); double get_weight() const ; // void set_description(string); string get_description() const; double get_max_speed() const ; double get_power() const; }; #endif // LOCOMOTOR_H_INCLUDED
[ "noreply@github.com" ]
EndianaJones.noreply@github.com
46f6337aa1620c42b287f44605dbcddf8ec5d382
2f078361c5890e46fdebbc85db1649484513f0d9
/UVaProblems/graph_theory/min_span_tree/variants/10048/k.cpp
d6af1951cdf0b60de4481f142b6cb70016e37cc7
[]
no_license
joseg4570/OJ_problems
6bdcb29d8e52ef56024c53f105ed6f00cce60bea
c60d3dc0e569cb5955d7b60b94e9e551a37f0023
refs/heads/master
2021-01-11T10:19:49.866093
2016-10-31T19:33:31
2016-10-31T19:33:31
72,462,656
0
0
null
null
null
null
UTF-8
C++
false
false
1,692
cpp
#include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; #define x first #define y second #define NMAX 105 typedef pair<int,int> ii; typedef pair<int,ii> edge; typedef vector<edge> ve; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vii> graph; graph G; vi visited; vi set; int sp[NMAX][NMAX]; int root; void init(int n) { set.assign(n,0); for(int i=0;i<n;i++) set[i] = i; } int boss(int i) { if(set[i] == i) return i; return set[i] = boss(set[i]); } bool same_set(int i,int j) { return boss(i) == boss(j); } void join_sets(int i,int j) { if(boss(i) != boss(j)) set[boss(i)] = boss(j); } void dfs(int node,int d) { visited[node] = 1; sp[root][node] = d; for(int i=0;i<G[node].size();i++) { int v = G[node][i].x; if(!visited[v]) dfs(v,max(d,G[node][i].y)); } } int main() { cin.tie(0); ios::sync_with_stdio(0); int n,m,q,a,b,n_case; ve e; n_case = 0; while(cin >> n >> m >> q && n) { if(n_case) cout << '\n'; cout << "Case #" << ++n_case << '\n'; if(e.size() < m) e.resize(m); init(n); G.clear(); G.resize(n); for(int i=0;i<m;i++) { cin >> e[i].y.x >> e[i].y.y >> e[i].x; e[i].y.x--,e[i].y.y--; } sort(e.begin(),e.begin()+m); for(int i=0;i<m;i++) { a = e[i].y.x; b = e[i].y.y; if(!same_set(a,b)) { join_sets(a,b); G[a].push_back(make_pair(b,e[i].x)); G[b].push_back(make_pair(a,e[i].x)); } } for(int i=0;i<n;i++) { visited.assign(n,0); root = i; dfs(i,0); } for(int i=0;i<q;i++) { cin >> a >> b; a--,b--; if(!same_set(a,b)) cout << "no path\n"; else cout << sp[a][b] << '\n'; } } return 0; }
[ "joseg4570@gmail.com" ]
joseg4570@gmail.com
74df38e9739d9a07794a89107774767456dc3711
471ab22889d52ff4027dee2902ffc6edfae8e23b
/inference/cc/src/Config.cc
a50c9f6d12faff4e39d35b50c94a630728a7516d
[]
no_license
SunYanCN/etagger
bd664ac83f2fbf8bdc2d66d25442c6d04316f18b
27143071868fce80d71661ccfb6fd83be7f955f6
refs/heads/master
2021-08-28T11:33:01.800372
2021-08-22T10:45:27
2021-08-22T10:45:27
240,457,337
0
0
null
2021-08-22T13:55:46
2020-02-14T08:03:38
Python
UTF-8
C++
false
false
164
cc
#include "Config.h" /* * public methods */ Config::Config() { } Config::Config(int word_length) { this->word_length = word_length; } Config::~Config() { }
[ "hazzling@gmail.com" ]
hazzling@gmail.com
f3d6dc30f1599512b14fb06812f86917a236287c
0fd7bfc4effe067c2887e2e29e08e9bfa4446398
/Source/Plugins/PulsePalOutput/PulsePalOutputEditor.cpp
a5ee04bce64a47463a629a87c12fe4bf1335464c
[]
no_license
priyanjitdey94/plugin-GUI
baf4c17d9a50a8457fb047375f32672b7fa8d4bc
c1665986aac79888515b75a8a851211b1fb4c516
refs/heads/master
2021-01-17T17:54:01.994930
2016-04-07T18:28:27
2016-04-07T18:28:27
53,115,629
1
0
null
2016-03-04T07:17:38
2016-03-04T07:17:38
null
UTF-8
C++
false
false
5,321
cpp
/* ------------------------------------------------------------------ This file is part of the Open Ephys GUI Copyright (C) 2014 Open Ephys ------------------------------------------------------------------ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include "PulsePalOutputEditor.h" #include "PulsePalOutput.h" #include "serial/PulsePal.h" PulsePalOutputEditor::PulsePalOutputEditor(GenericProcessor* parentNode, PulsePal* pp, bool useDefaultParameterEditors=true) : GenericEditor(parentNode, useDefaultParameterEditors), pulsePal(pp) { desiredWidth = 315; for (int i = 1; i < 5; i++) { ChannelTriggerInterface* cti = new ChannelTriggerInterface(pp, (PulsePalOutput*) getProcessor(), i); channelTriggerInterfaces.add(cti); cti->setBounds(10+75*(i-1),30,65,90); addAndMakeVisible(cti); } } PulsePalOutputEditor::~PulsePalOutputEditor() { } void PulsePalOutputEditor::saveCustomParameters(XmlElement* xml) { xml->setAttribute("Type", "PulsePalOutputEditor"); for (int i = 0; i < 4; i++) { XmlElement* outputXml = xml->createNewChildElement("OUTPUTCHANNEL"); outputXml->setAttribute("Number",i); outputXml->setAttribute("Trigger",channelTriggerInterfaces[i]->getTriggerChannel()); outputXml->setAttribute("Gate",channelTriggerInterfaces[i]->getGateChannel()); } } void PulsePalOutputEditor::loadCustomParameters(XmlElement* xml) { forEachXmlChildElement(*xml, xmlNode) { if (xmlNode->hasTagName("OUTPUTCHANNEL")) { int chNum = xmlNode->getIntAttribute("Number"); channelTriggerInterfaces[chNum]->setTriggerChannel(xmlNode->getIntAttribute("Trigger")); channelTriggerInterfaces[chNum]->setGateChannel(xmlNode->getIntAttribute("Gate")); } } } //----------------------------------------------- ChannelTriggerInterface::ChannelTriggerInterface(PulsePal* pp, PulsePalOutput* ppo, int chan) : pulsePal(pp), processor(ppo), isEnabled(true), channelNumber(chan), name(String(chan)) { triggerButton = new UtilityButton("trigger", Font("Small Text", 10, Font::plain)); triggerButton->addListener(this); triggerButton->setRadius(3.0f); triggerButton->setBounds(5,5,55,20); addAndMakeVisible(triggerButton); triggerSelector = new ComboBox(); triggerSelector->setBounds(5,30,55,20); triggerSelector->addListener(this); triggerSelector->addItem("Trig",1); for (int i = 0; i < 10; i++) triggerSelector->addItem(String(i+1),i+2); // start numbering at one for // user-visible channels triggerSelector->setSelectedId(1, dontSendNotification); addAndMakeVisible(triggerSelector); gateSelector = new ComboBox(); gateSelector->setBounds(5,55,55,20); gateSelector->addListener(this); gateSelector->addItem("Gate",1); for (int i = 0; i < 10; i++) gateSelector->addItem(String(i+1),i+2); // start numbering at one for // user-visible channels gateSelector->setSelectedId(1, dontSendNotification); addAndMakeVisible(gateSelector); } ChannelTriggerInterface::~ChannelTriggerInterface() { } void ChannelTriggerInterface::paint(Graphics& g) { g.setColour(Colours::lightgrey); g.fillRoundedRectangle(0,0,getWidth(),getHeight(),4.0f); if (isEnabled) g.setColour(Colours::black); else g.setColour(Colours::grey); g.setFont(Font("Small Text", 10, Font::plain)); g.drawText(name, 5, 80, 200, 10, Justification::left, false); } void ChannelTriggerInterface::buttonClicked(Button* button) { pulsePal->triggerChannel(channelNumber); } void ChannelTriggerInterface::comboBoxChanged(ComboBox* comboBoxThatHasChanged) { //std::cout << "Combo box changed to " << comboBoxThatHasChanged->getSelectedId() << std::endl; if (comboBoxThatHasChanged == triggerSelector) { processor->setParameter(0, channelNumber); processor->setParameter(1, (float) comboBoxThatHasChanged->getSelectedId() - 2); } else if (comboBoxThatHasChanged == gateSelector) { processor->setParameter(0, channelNumber); processor->setParameter(2, (float) comboBoxThatHasChanged->getSelectedId() - 2); } } int ChannelTriggerInterface::getTriggerChannel() { return triggerSelector->getSelectedId(); } int ChannelTriggerInterface::getGateChannel() { return gateSelector->getSelectedId(); } void ChannelTriggerInterface::setTriggerChannel(int chan) { return triggerSelector->setSelectedId(chan); } void ChannelTriggerInterface::setGateChannel(int chan) { return gateSelector->setSelectedId(chan); }
[ "aacuelo@teleco.upv.es" ]
aacuelo@teleco.upv.es
41407c4f5d876dcb8c3043ee6d5af4fc9fe27312
4e49f2b456882ba8643907a196f86b3062004243
/MFCTeeChart/MFCTeeChart/TeeChar/circulargauge.h
7779480bac2b1530fabf25237941c2fa9677cada
[]
no_license
772148702/Artificial-Intelligence
d4616acf13a38658fc38e71874091b4a0596f6ac
3b2c48af7a88adc2d2fab01176db7c811deda1d1
refs/heads/master
2018-08-29T19:14:37.293494
2018-07-06T15:16:10
2018-07-06T15:16:10
108,261,921
0
1
null
null
null
null
UTF-8
C++
false
false
1,739
h
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. // Dispatch interfaces referenced by this interface class CTeeShape; class CFramedBorder; class CGaugePointerRange; class CGaugeSeriesPointer; class CPointer; ///////////////////////////////////////////////////////////////////////////// // CCircularGauge wrapper class class CCircularGauge : public COleDispatchDriver { public: CCircularGauge() {} // Calls COleDispatchDriver default constructor CCircularGauge(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CCircularGauge(const CCircularGauge& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: CTeeShape GetFace(); CFramedBorder GetFrame(); double GetValue(); void SetValue(double newValue); CGaugePointerRange GetGreenLine(); BOOL GetHorizontal(); void SetHorizontal(BOOL bNewValue); double GetMaximum(); void SetMaximum(double newValue); double GetMinimum(); void SetMinimum(double newValue); long GetMinorTickDistance(); void SetMinorTickDistance(long nNewValue); CGaugeSeriesPointer GetMinorTicks(); CGaugePointerRange GetRedLine(); CGaugeSeriesPointer GetTicks(); CGaugeSeriesPointer GetCenter(); BOOL GetCircled(); void SetCircled(BOOL bNewValue); CPointer GetEndPoint(); BOOL GetLabelsInside(); void SetLabelsInside(BOOL bNewValue); BOOL GetRotateLabels(); void SetRotateLabels(BOOL bNewValue); double GetRotationAngle(); void SetRotationAngle(double newValue); double GetTotalAngle(); void SetTotalAngle(double newValue); CGaugeSeriesPointer GetHand(); };
[ "772148702@qq.com" ]
772148702@qq.com
712b4660454db4ed82e181a8b1f73b3f2562a80a
69e201ccaab52f8cdbc8ac3da0634f2cb49fdccf
/cap2/Scopy2.cpp
0047d6390ab744b3b1b69a4b89d77f7bfd648b19
[]
no_license
sebassdc/pensar-cpp
c05dae0da227e827d6ab03115ffe039c1fe2831f
81468397c578c746629ac6707154fd17ebb6f431
refs/heads/master
2020-04-04T17:19:23.033347
2018-11-04T19:18:44
2018-11-04T19:18:44
156,116,148
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
// Copy one file to another, a line at time #include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("Scopy.cpp"); // Open for reading ofstream out("Scopy2.cpp"); // Open for writing string s; while(getline(in, s)) { // Discards newline char out << s << "\n"; // ... must add it back cout << s << "\n"; } }
[ "sebassdc@gmail.com" ]
sebassdc@gmail.com
7493bff9f1160a4db0963f5764de60cb28b891e5
75cc8a6c2e0e19dc8e76cd3bdf6618cb1929e5ec
/leetcode C/leetcode38CountAndSay.cpp
63787697e1d044bffd5b28437249e6a7db27d003
[]
no_license
candyqinlibo/leetcode
859ac3ad40ca4800d4bcc18f5f8ecae167c46e30
6a1709785c67f3c6552760d0b04f19a2384c3961
refs/heads/master
2020-06-04T02:46:55.731991
2015-12-15T10:00:44
2015-12-15T10:00:44
41,775,221
0
0
null
null
null
null
GB18030
C++
false
false
1,541
cpp
// leetcode38CountAndSay.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "string.h" #include "malloc.h" char* countAndSay(int n){ if (n == 1) return "1"; char *cur = (char*)malloc(2*sizeof(char)); char* tmp; cur[0] = '1'; cur[1] = 0; int len, idx, j, count; for (int i = 1; i < n;i++) { len = strlen(cur); tmp = (char*)calloc(len*2+1,sizeof(char)); count = 1; for (idx = 1,j=0;idx < len; idx++) { if (cur[idx] == cur[idx-1]) { count++; } else { tmp[j++] = '0' + count; tmp[j++] = cur[idx - 1]; count = 1; } } tmp[j++] = '0' + count; tmp[j++] = cur[len - 1]; free(cur); cur = tmp; } return cur; } //char* countAndSay(int n) { // if (n < 1) return NULL; // if (n = 1) return "1"; // char* result = (char*)malloc(2*sizeof(char)); // if (result == NULL) return NULL; // result[0] = '1'; // result[1] = '0'; // int key, count,pos; // for (int i = 1; i < n;i++) // { // int length = strlen(result); // char* temp = (char*)malloc((length*2+1)*sizeof(char)); // char* x = result; // //temp = result; // pos = 0; // key = x[0]; // count = 1; // for (int j = 1; j < length;j++) // { // if (x[j] == key) // { // count++; // } // else // { // x[pos++] = count + '0'; // count = 1; // x[pos++] = key + '0'; // key = x[j]; // } // } // temp[pos++] = count + '0'; // temp[pos++] = key + '0'; // temp[pos] = '\0'; // result = temp; // } // return result; //} int main(void) { puts(countAndSay(10)); return 0; }
[ "gao.hzy@unearby.com" ]
gao.hzy@unearby.com
515bb9360b6c181675fa012ed1575fc9f04b32e1
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_7360.cpp
cab72366541fba147452ed11e4c3c91a7e0844b1
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
git diff expect.err output.err ' cat > expect <<EOF boolean: 0 integer: 0 string: (not set) arg 00: --quux EOF test_expect_success 'keep some options as arguments' ' test-parse-options --quux > output 2> output.err && test ! -s output.err && git diff expect output ' test_done
[ "993273596@qq.com" ]
993273596@qq.com
8f400307eebbb349fd0039ec2ae059ae80b5b53c
58fc843305fe9f745677d195ca9c0277a24e77f1
/src/tools/properties.cpp
dd3f5320b23d51ebd725383eae3870cabcc14d35
[ "MIT" ]
permissive
gionellef/occa
61fc79555d027215ab2f2834bf286bf55e5ad8e5
d7fa75a9d5e422f3c80a694acdd2097a10056911
refs/heads/master
2022-08-16T01:32:36.835014
2020-05-22T03:10:25
2020-05-22T03:10:25
265,815,861
0
0
MIT
2020-05-21T10:08:17
2020-05-21T10:08:16
null
UTF-8
C++
false
false
1,382
cpp
#include <occa/io/utils.hpp> #include <occa/tools/properties.hpp> #include <occa/tools/string.hpp> namespace occa { properties::properties() { type = object_; initialized = false; } properties::properties(const properties &other) { type = object_; value_ = other.value_; // Note: "other" might be a json object initialized = other.isInitialized(); } properties::properties(const json &j) { type = object_; value_ = j.value_; initialized = true; } properties::properties(const char *c) : initialized(false) { properties::load(c); } properties::properties(const std::string &s) : initialized(false) { properties::load(s); } properties::~properties() {} bool properties::isInitialized() const { if (!initialized) { initialized = value_.object.size(); } return initialized; } void properties::load(const char *&c) { lex::skipWhitespace(c); loadObject(c); initialized = true; } void properties::load(const std::string &s) { const char *c = s.c_str(); lex::skipWhitespace(c); loadObject(c); initialized = true; } properties properties::read(const std::string &filename) { properties props; props.load(io::read(filename)); return props; } template <> hash_t hash(const properties &props) { return props.hash(); } }
[ "dmed256@gmail.com" ]
dmed256@gmail.com
08028dc2c5306b438ffd197779a8cda0138a253c
d43e19bd4670a90a7a6751b3fb8cf5d479db61a7
/UnrealArcheryShooter/Source/UnrealArcheryShooter/Public/Weapon/Widget/WeaponShopGrid.h
fca8010433f82dfc61e3484469389654d6261e6d
[ "MIT" ]
permissive
Prastiwar/UnrealArcheryShooter
819899a19dacd10c12b6b58f15bc3c3c77f24146
45dd74f762ef413bb857ce8d66d7d8cee9aae564
refs/heads/master
2020-03-29T07:19:06.681474
2018-12-30T17:48:51
2018-12-30T17:48:51
149,660,495
1
1
null
null
null
null
UTF-8
C++
false
false
872
h
// Authored by Tomasz Piowczyk. MIT License. Repository: https://github.com/Prastiwar/UnrealArcheryShooter #pragma once #include "ItemGrid.h" #include "WeaponShop.h" #include "WeaponShopItem.h" #include "WeaponShopGrid.generated.h" class AUnrealArcheryShooterGameMode; UCLASS() class UNREALARCHERYSHOOTER_API UWeaponShopGrid : public UItemGrid { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadOnly) TSubclassOf<AWeaponShop> WeaponShop; UPROPERTY(BlueprintReadOnly, meta = (BindWidget)) class UButton* ExitButton; UFUNCTION(BlueprintCallable) void ExitShop(); UFUNCTION(BlueprintCallable) virtual void BuildGrid() override; protected: virtual void NativeConstruct() override; UFUNCTION(BlueprintCallable) void SetGrid(const TArray<UWeaponShopItem*>& WeaponItems); private: UFUNCTION() void TryExitShop(const bool bBought); };
[ "tomasz.piowczyk@gmail.com" ]
tomasz.piowczyk@gmail.com
b16d43b53c8919aabbffb3652ce3dfb8ab2289dd
88c6f71aa484af0da734b95f417a5dfca1c0ca59
/ComputeArea.cc
710763bdce0e895a6c31e33b90fda760ebf9e5aa
[]
no_license
jas0ns/StupidLeetcode
59025700aec955eb035f919faa13283a83d0abe1
a3540ef5110e9782a9478aeb1945f8b3ee2b2154
refs/heads/master
2021-01-09T20:11:48.663636
2016-08-09T09:43:18
2016-08-09T09:43:18
64,645,959
1
0
null
null
null
null
UTF-8
C++
false
false
511
cc
#include <iostream> using namespace std; class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int l, r, t, b, w, h; if (C < E || A > G) return 0; if (B > H || D < F) return 0; l = A > E ? A - E : E - A; r = C > G ? C - G : G - C; t = D > H ? D - H : H - D; b = B > F ? B - F : F - B; return (r - l) * (t - b); } }; int main(int argc, char **argv) { Solution s; cout << s.computeArea(-3, 0, 3, 4, 0, -1, 9 ,2) << endl; }
[ "jasons_toy@foxmail.com" ]
jasons_toy@foxmail.com
5b691791b2d3c5f476ae686ffc617368fe17ba59
9cfecad20b7d064822f34fd1890c3dfc3abf7eb5
/Prototypes/7 Step/ButtonInteraction/ArduinoClient/LightBarrier.cpp
296117a27742e61bdbd60eaddd545c4ad37aadbf
[]
no_license
hnnswldschtz/DataMatters
bd1dabcc19411ef6ef72d8a8a26bca8b6a31215e
bfaa74f5916bfbef908eea7877156844afa51962
refs/heads/master
2021-01-07T06:50:10.545529
2019-10-01T12:34:21
2019-10-01T12:34:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
#include "LightBarrier.h" LightBarrier::LightBarrier(int pin, int amountHoles){ _lightBarrierPin = pin; pinMode(_lightBarrierPin, INPUT); digitalWrite(_lightBarrierPin, HIGH); _oldValue = digitalRead(_lightBarrierPin); _counter = 0; _notification = amountHoles * 2; } boolean LightBarrier::notification(){ int value = digitalRead(_lightBarrierPin); if(value != _oldValue) { _counter = _counter + 1; _oldValue = value; } } void LightBarrier::setCounter(int newCounter){ _counter = newCounter; } int LightBarrier::getCounter(){ return _counter/_notification; }
[ "christopherheiden9@gmail.com" ]
christopherheiden9@gmail.com
5eb0144f642f8fd9f77f9441707987dc2a53609b
a22df522dda3adafee053a2bb76d2365e7d079a7
/BOOV_PROJECT.cpp
f0d6332bc0f6f1f209d2313c21e923a4719b9dc6
[]
no_license
MoustafaRoushdy/BOOV-Game
907b8b112f7f015c838c8903ee1f88a54e9afe3c
5d3c1134cc5bff3d7fe7178c4954225cb02b346f
refs/heads/main
2023-07-30T18:31:17.682431
2021-09-18T18:57:50
2021-09-18T18:57:50
407,651,923
0
0
null
null
null
null
UTF-8
C++
false
false
1,906
cpp
// BOOVproject.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "BOOV.h" #include <ctime> #include"gorg.h" using namespace std; int main() { srand(static_cast<unsigned>(time(0))); //getting the boov's health int health = 0 ; //getting the boov's shield int shield = 0 ; //run many simulations const int num_of_simulations = 10000; //counting the number of round_survived int BOOV_wins = 0; int gorg_wins = 0; for (int i = 0; i < num_of_simulations; i++) { competitor * oh = new BOOV("oh", 30 , 31); competitor * goorg = new gorg; while (!oh->IsDefeated() && !goorg->IsDefeated()) { goorg->GetAttacked(); if (!goorg->IsDefeated()) oh->GetAttacked(); } if (goorg->IsDefeated()) BOOV_wins++; else gorg_wins++; } double BOOVpct = BOOV_wins / static_cast<double>(num_of_simulations)*100; double gorgpct = gorg_wins / static_cast<double>(num_of_simulations) * 100; cout <<"boov percentage = " << BOOVpct<< endl; cout << "gorg percentage = " << gorgpct << endl; system("PAUSE"); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
[ "noreply@github.com" ]
MoustafaRoushdy.noreply@github.com
bbf3318a23b3f40037ecd8c5e874ec02299f7bd9
0deb58e0bf0241596b381e97d1998dcec8788fa1
/lab07/lab07.cpp
1d505becb5b122e79731c97a3753727fb81ed37d
[]
no_license
botanegg/computationLabs
24f29539002e8e5a02cc3a1c361046ffbd4d658f
ed34f7f74bf4af3b6f7f2ab0dfb99b598ade7949
refs/heads/master
2021-01-02T08:51:32.250142
2017-12-11T16:08:00
2017-12-12T00:39:57
24,266,304
0
1
null
2017-12-12T00:39:58
2014-09-20T15:29:23
C++
UTF-8
C++
false
false
4,038
cpp
#include <iostream> #include <cmath> #include <vector> #include <float.h> using namespace std; //General double f(double x); double a = 0; double b = 3.1415926; //2 double formulaTrapeze(double a, double b, int m); double formulaSimpson(double a, double b, int m); void ruleRunge(); //3 double formulaGauss(double a, double b, int m); int main() { ruleRunge(); cout << "Gauss m = 2: " << formulaGauss(a, b, 2) << endl; cout << "Gauss m = 4: " << formulaGauss(a, b, 4) << endl; cout << "Gauss m = 5: " << formulaGauss(a, b, 5) << endl; cout << "Gauss m = 8: " << formulaGauss(a, b, 8) << endl; return 0; } double f(double x) { return exp(cos(x)) * cos(2 * x); } void ruleRunge() { cout << "I. Runge's rule" << endl; double epsMinusFive = 0.00001; double epsMinusSeven = 0.0000001; double eps = DBL_MAX; int m = 1; double zhDivTwo, zh; //e10-5 while (eps > epsMinusFive) { zh = formulaTrapeze(a, b, m); zhDivTwo = formulaTrapeze(a, b, m * 2); eps = abs((zhDivTwo - zh) / 3); ++m; } cout << "formulaTrapeze" << endl; cout << "Res: " << zhDivTwo << endl; cout << "m: " << m * 2 << endl; cout << "h: " << (b - a) / (m * 2) << endl; cout << "Eps: " << eps << endl << endl; //e10-7 eps = DBL_MAX; m = 1; while (eps > epsMinusSeven) { zh = formulaTrapeze(a, b, m); zhDivTwo = formulaTrapeze(a, b, m * 2); eps = abs((zhDivTwo - zh) / 3); ++m; } cout << "formulaTrapeze" << endl; cout << "Res: " << zhDivTwo << endl; cout << "m: " << m * 2 << endl; cout << "h: " << (b - a) / (m * 2) << endl; cout << "Eps: " << eps << endl << endl; //Simpson eps = DBL_MAX; m = 1; while (eps > epsMinusSeven) { zh = formulaSimpson(a, b, m); zhDivTwo = formulaSimpson(a, b, m * 2); eps = abs((zhDivTwo - zh) / 15); ++m; } cout << "formulaSimpson" << endl; cout << "Res: " << zhDivTwo << endl; cout << "m: " << m * 4 << endl; cout << "h: " << (b - a) / (m * 2) << endl; cout << "Eps: " << eps << endl << endl; } double formulaTrapeze(double a, double b, int m) { double res = 0; double h = (b - a) / m; for (int i = 0; i <= m; ++i) res += f(a + i * h); res = (2 * res - f(a) - f(a + h * m)) * (h / 2); return res; } double formulaSimpson(double a, double b, int m) { double res = 0; double h = (b - a) / (2 * m); res += f(a) + f(a + h * 2 * m); for (int i = 1; i < 2 * m; ++i) { if (i % 2) res += 4 * f(a + i * h); else res += 2 * f(a + i * h); } res *= (b - a) / (6 * m); return res; } double formulaGauss(double a, double b, int m) { vector<vector<double>> t, ag; t.resize(9); ag.resize(9); //2 t[2].resize(2); t[2][0] = -0.577350; t[2][1] = 0.577350; ag[2].resize(2); ag[2][0] = ag[2][1] = 1; //4 t[4].resize(4); t[4][0] = -0.86114; t[4][1] = -0.33998; t[4][2] = 0.33998; t[4][3] = 0.86114; ag[4].resize(4); ag[4][0] = ag[4][3] = 0.34785; ag[4][1] = ag[4][2] = 0.65215; //5 t[5].resize(5); t[5][0] = -0.90618; t[5][1] = -0.538469; t[5][2] = 0; t[5][3] = 0.538469; t[5][4] = 0.90618; ag[5].resize(5); ag[5][0] = ag[5][4] = 0.23693; ag[5][1] = ag[5][3] = 0.47863; ag[5][2] = 0.56889; //8 t[8].resize(8); t[8][0] = -0.96028986; t[8][1] = -0.79666648; t[8][2] = -0.52553242; t[8][3] = -0.18343464; t[8][7] = 0.96028986; t[8][6] = 0.79666648; t[8][5] = 0.52553242; t[8][4] = 0.18343464; ag[8].resize(8); ag[8][0] = ag[8][7] = 0.10122854; ag[8][1] = ag[8][6] = 0.22238103; ag[8][2] = ag[8][5] = 0.31370664; ag[8][3] = ag[8][4] = 0.36268378; double res = 0; for (int i = 0; i < m; ++i) { res += ag[m][i] * f((a + b) / 2 + (b - a) * t[m][i] / 2); } res *= (b - a) / 2; return res; }
[ "botankras@gmail.com" ]
botankras@gmail.com
03456dc0b3fa3d3421b9b5aed6591a2244ab1d84
fb75f312fa0a0a733364dc0f3429a2d5563e3ee3
/SwordToOffer/Interview.cpp
687d18e243984e37b89bbd61e993ad058eb01a34
[]
no_license
neuwyq/GHCXX
2ade656b932eb5f9da3a8f9c57618ad3cb3b8871
eb9f806d250d752be793260993f48fb83bbcd0b2
refs/heads/master
2020-04-09T18:12:17.521607
2018-12-05T10:55:56
2018-12-05T10:55:56
160,504,745
1
0
null
2018-12-05T10:57:46
2018-12-05T10:57:46
null
UTF-8
C++
false
false
4,553
cpp
// // Created by GH on 2018/11/26. // #include "Interview.h" bool duplicate(int numbers[], int length, int *duplicate) { if (numbers == nullptr || length <= 0) return false; for (int i = 0; i < length; ++i) { if (numbers[i] < 0 || numbers[i] >= length) return false; } for (int i = 0; i < length; ++i) { while (numbers[i] != i) { if (numbers[i] == numbers[numbers[i]]) { *duplicate = numbers[i]; return true; } int temp = numbers[i]; numbers[i] = numbers[temp]; numbers[temp] = temp; } } return false; } int getDuplication(const int* numbers, int length) { if (numbers == nullptr || length <= 0) return -1; int start = 1; int end = length - 1; while(start <= end) { int middle = (end + start) / 2; int count = countRange(numbers, length, start, middle); if (end == start) { if (count > 1) return start; else break; } if (count > (middle - start + 1)) end = middle; else start = middle + 1; } return -1; } int countRange(const int* numbers, int length, int start, int end) { if (numbers == nullptr || length <= 0) return 0; int count = 0; for (int i = 0; i < length; ++i) { if (numbers[i] <= end && numbers[i] >= start) ++count; } return count; } bool Find(int matrix[][4], int rows, int columns, int number) { if (matrix == nullptr || rows <= 0 || columns <= 0) return false; for (int i = columns - 1; i >= 0; --i) { for (int j = 0; j < rows; ++j) { if (matrix[j][i] == number) return true; if (matrix[j][i] > number) break; else continue; } ++matrix; } return false; } bool Find(int *matrix, int rows, int columns, int number) { if (matrix == nullptr || rows <=0 || columns <= 0) return false; int row = 0; int column = columns - 1; while(row < rows && column >= 0) { if (matrix[row * columns + column] == number) return true; if (matrix[row * columns + column] > number) --column; else ++row; } return false; } void ReplaceBlank(char string[], int length) { if (string == nullptr || length <= 0) return; int stringLength = 0; int blankCount = 0; while (string[stringLength] != '\0') { if (string[stringLength] == ' ') ++blankCount; ++stringLength; } int newLength = stringLength + blankCount * 2; if (newLength > length) return; int indexp2 = newLength; int indexp1 = stringLength; while (indexp1 != indexp2) { if (string[indexp1] != ' ') { string[indexp2--] = string[indexp1--]; } else { string[indexp2--] = '0'; string[indexp2--] = '2'; string[indexp2--] = '%'; --indexp1; } } } void MergeArray(int *numbers1, int length1, int *numbers2, int length2) { if (numbers1 == nullptr || numbers2 == nullptr || length2 <= 0) return; if (length1 <= 0) { int nb2 = length2 - 1; while (nb2 >= 0) numbers1[nb2] = numbers2[nb2--]; return; } int newLength = length1 + length2 - 1; int nb1 = length1 - 1; int nb2 = length2 - 1; while (newLength >= 0 && nb1 >= 0 && nb2 >= 0) { if (numbers1[nb1] > numbers2[nb2]) numbers1[newLength--] = numbers1[nb1--]; else numbers1[newLength--] = numbers2[nb2--]; } } BinaryTreeNode* ConstructByFM(int *preorder, int *inorder, int length) { if (preorder == nullptr || inorder == nullptr || length <= 0 ) return nullptr; return ConstructByFMCore(preorder, preorder + length - 1, inorder, preorder + length - 1); } BinaryTreeNode* ConstructByFMCore(int *stratPreorder, int *endPreorder, int *stratInorder, int *endInorder) { int rootValue = stratPreorder[0]; BinaryTreeNode* root = new BinaryTreeNode(); root->m_nValue = rootValue; root->m_pLeft = root->m_pRight = nullptr; if (stratPreorder == endPreorder) { if (stratInorder == endInorder && *stratPreorder == *stratInorder) return root; else throw std::exception(); } }
[ "784558153@qq.com" ]
784558153@qq.com
e63f31cc224324b9924c2e79bcf8226813500404
a909df0ba2abf695df4a7d15350312d4c6463c48
/Kattis/simonsays.cpp
0617b4a967b59d72fcf27c9fd4659071fe5bea81
[]
no_license
SayaUrobuchi/uvachan
1dadd767a96bb02c7e9449c48e463847480e98ec
c213f5f3dcfc72376913a21f9abe72988a8127a1
refs/heads/master
2023-07-23T03:59:50.638063
2023-07-16T04:31:23
2023-07-16T04:31:23
94,064,326
0
0
null
null
null
null
UTF-8
C++
false
false
330
cpp
#include <stdio.h> #include <iostream> #include <string> char buf[1048576]; int main() { int n, i; std::string s; while (std::cin >> n) { std::getline(std::cin, s); for (i=0; i<n; i++) { std::getline(std::cin, s); if (sscanf(s.c_str(), "Simon says%[^\n]", buf) == 1) { puts(buf); } } } return 0; }
[ "sa0726866@gmail.com" ]
sa0726866@gmail.com
cbef264a1e0daca1a303d500f768c8538310788a
665b72d4f1751cca0bcb18ec7ed2ba4d413a409b
/steeringseek.h
00f277c6fb2becec55f200208c3f06e32d21df93
[]
no_license
bizcocho-man/utad-ai-pathfinding-navmesh
1645d7a003f13c949dd3bcb65ae909a9c20a4383
c7f2f368861ef411fd14b77c6865265b5a0716c5
refs/heads/master
2022-05-13T21:59:54.268329
2018-01-26T12:22:02
2018-01-26T12:22:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
472
h
#ifndef __STEERINGSEEK_H__ #define __STEERINGSEEK_H__ #include "steering.h" class SteeringSeek : public Steering { public: SteeringSeek(); ~SteeringSeek(); virtual USVec2D GetSteering(Character* character, const USVec2D& target); virtual float GetAngularSteering(Character* character, float targetRotation) { return 0.0f; } virtual void DrawDebug(Character* character); private: USVec2D mVelocity; USVec2D mAcceleration; USVec2D mCharacterPosition; }; #endif
[ "shielderjohn@gmail.com" ]
shielderjohn@gmail.com
75ec73037b18d0fc163f92054be222a916579182
ccc8189650a214778bc9e446d4e1fc76cd1d606c
/src/tasks/spherical_wave/include/parser_spherical_wave.h
dfa52684fa733e9663e722f881684558c2bf5ab8
[]
no_license
PanovaElena/ParallelFourierSolvers2
bc64a9294fbcf879e0d37a0502acf291e2539855
427835108a4c862e2509cf5c9226da3d563a0be9
refs/heads/master
2022-03-09T09:32:30.505699
2020-06-03T14:54:35
2020-06-03T14:54:35
211,049,627
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
h
#pragma once #include <map> #include "task_parser.h" #include "spherical_wave.h" #include "mask.h" #include "filter.h" #include "field_solver.h" class ParserSphericalWave : public TaskParser { public: void help(TaskParameters& p1, Task task) override { TaskParser::help(p1, task); ParametersForSphericalWave& p = static_cast<ParametersForSphericalWave&>(p1); std::cout << "-scx, -scy, -scz set coordinate of source, default value is " << p.source.coord << "\n" << "-somega set frequency of source, default value is " << p.source.omega << "\n" << "-somenv set frequency of envelop for source, default value is " << p.source.omegaEnv << "\n" << "-stime set working time of source, default value is " << p.source.time << "\n" << "-stimest set start time of source, default value is " << p.source.startTime << "\n" << "-swx, -swy, -swz set width of source, default value is " << p.source.width << "\n" << std::endl; } Stat saveArgs(TaskParameters& p, Task task) override { Stat s = TaskParser::saveArgs(p, task); if (s == Stat::ERROR || s == Stat::STOP) return s; ParametersForSphericalWave& params = static_cast<ParametersForSphericalWave&>(p); if (m.find("-scx") != m.end()) params.source.coord.x = std::stod(m.find("-scx")->second); if (m.find("-scy") != m.end()) params.source.coord.y = std::stod(m.find("-scy")->second); if (m.find("-scz") != m.end()) params.source.coord.z = std::stod(m.find("-scz")->second); if (m.find("-swx") != m.end()) params.source.width.x = std::stod(m.find("-swx")->second); if (m.find("-swy") != m.end()) params.source.width.y = std::stod(m.find("-swy")->second); if (m.find("-swz") != m.end()) params.source.width.z = std::stod(m.find("-swz")->second); if (m.find("-somega") != m.end()) params.source.omega = std::stod(m.find("-somega")->second); if (m.find("-somenv") != m.end()) params.source.omegaEnv = std::stod(m.find("-somenv")->second); if (m.find("-stime") != m.end()) params.source.time = std::stod(m.find("-stime")->second); if (m.find("-stimest") != m.end()) params.source.startTime = std::stod(m.find("-stimest")->second); return Stat::OK; } };
[ "alyona-gra98@yandex.ru" ]
alyona-gra98@yandex.ru
cecd75a1da224f7df07b604ee4804c64621ced45
1cd3aa337bf0455bc53847a11d4b97ceaf6eb3e7
/MeanMax/Player.cpp
f9ae0d033e36faad7abe7437528bef9de25e740e
[ "Apache-2.0" ]
permissive
Namerian/CodinGame
2132bf80200856df2f65c0848ee1b12dcf4564a8
e0779f51e5fd2c7823ae38ab361c00533f2e54e5
refs/heads/master
2021-01-19T23:25:16.654681
2018-04-22T22:09:57
2018-04-22T22:09:57
88,977,352
0
0
null
null
null
null
UTF-8
C++
false
false
9,029
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> //============================================================= struct Vehicle { int unitId; int unitType; int player; float mass; int radius; int x; int y; int vx; int vy; int extra; int extra2; bool updated; }; struct MyVehicle : Vehicle { std::string output = "WAIT"; int targetUnitId = -1; }; struct Model { MyVehicle myReaper; MyVehicle myDestroyer; MyVehicle myDoof; std::vector<Vehicle> wrecks; std::vector<Vehicle> tankers; }; //============================================================= //============================================================= double GetFriction(int unitType) { if (unitType == 0) { return 0.2; } return 0; } double ComputeDistance(int ax, int ay, int bx, int by) { double distX = bx - ax; double distY = by - ay; distX *= distX; distY *= distY; return std::sqrt(distX + distY); } Vehicle *GetVehicle(std::vector<Vehicle> &vehicles, int vehicleId) { for (unsigned int i = 0; i < vehicles.size(); i++) { if (vehicles.at(i).unitId == vehicleId) { return &vehicles.at(i); } } return nullptr; } Vehicle *FindNearest(std::vector<Vehicle> &targets, Vehicle &source) { if (targets.size() == 0) { //std::cerr << "FindNearest(): target.size == 0" << std::endl; return nullptr; } else if (targets.size() == 1) { //std::cerr << "FindNearest(): target.size == 1" << std::endl; return &targets.at(0); } int resultIndex = 0; double smallestDistance = ComputeDistance(source.x, source.y, targets.at(0).x, targets.at(0).y); for (unsigned int i = 1; i < targets.size(); i++) { double newDistance = ComputeDistance(source.x, source.y, targets.at(i).x, targets.at(i).y); if (newDistance < smallestDistance) { resultIndex = i; smallestDistance = newDistance; } } return &targets.at(resultIndex); } // void ComputeOutput(MyVehicle &vehicle, int targetX, int targetY) // { // //double distance = ComputeDistance(vehicle.x, vehicle.y, targetX, targetY); // //double friction = GetFriction(vehicle.unitType); // //int directionX = targetX - vehicle.x; // //int directionY = targetY - vehicle.y; // //double length = std::sqrt(directionX * directionX + directionY * directionY); // //directionX = std::round(directionX * (1.0 / length)); // //directionY = std::round(directionY * (1.0 / length)); // vehicle.output = "" + std::to_string(targetX) + " " + std::to_string(targetY) + " 300"; // } //============================================================= //============================================================= void HandleReaper(Model &model) { model.myReaper.output = "0 0 150"; //checking if the target still exists if (model.myReaper.targetUnitId != -1) { Vehicle *target = GetVehicle(model.wrecks, model.myReaper.targetUnitId); if (target == nullptr) { std::cerr << "HandleReaper(): target does not exist anymore: id=" << model.myReaper.targetUnitId << std::endl; model.myReaper.targetUnitId = -1; } } if (model.myReaper.targetUnitId == -1) { Vehicle *target = FindNearest(model.wrecks, model.myReaper); if (target != nullptr) { model.myReaper.targetUnitId = target->unitId; std::cerr << "HandleReaper(): target set: id=" << target->unitId << std::endl; } else { std::cerr << "HandleReaper(): FindNearest() returned null" << std::endl; } } if (model.myReaper.targetUnitId != -1) { Vehicle *target = GetVehicle(model.wrecks, model.myReaper.targetUnitId); if (target == nullptr) { std::cerr << "HandleReaper(): target is null: id=" << model.myReaper.targetUnitId << std::endl; } model.myReaper.output = "" + std::to_string(target->x) + " " + std::to_string(target->y) + " 300"; } } void HandleDestroyer(Model &model) { model.myDestroyer.output = "0 0 150"; } void HandleDoof(Model &model) { model.myDoof.output = "WAIT"; } //============================================================= //============================================================= int main() { Model model; // game loop while (1) { //**************** //pre-input initialization //**************** //marking all wrecks as not updated for (Vehicle &wreck : model.wrecks) { wreck.updated = false; } //**************** //reading input //**************** int myScore; std::cin >> myScore; std::cin.ignore(); int enemyScore1; std::cin >> enemyScore1; std::cin.ignore(); int enemyScore2; std::cin >> enemyScore2; std::cin.ignore(); int myRage; std::cin >> myRage; std::cin.ignore(); int enemyRage1; std::cin >> enemyRage1; std::cin.ignore(); int enemyRage2; std::cin >> enemyRage2; std::cin.ignore(); int unitCount; std::cin >> unitCount; std::cin.ignore(); for (int i = 0; i < unitCount; i++) { int unitId; int unitType; int player; float mass; int radius; int x; int y; int vx; int vy; int extra; int extra2; std::cin >> unitId >> unitType >> player >> mass >> radius >> x >> y >> vx >> vy >> extra >> extra2; std::cin.ignore(); Vehicle *currentVehicle = nullptr; if (player == 0) //reading info about my vehicles { if (unitType == 0) { currentVehicle = &model.myReaper; } else if (unitType == 1) { currentVehicle = &model.myDestroyer; } else if (unitType == 2) { currentVehicle = &model.myDoof; } } else if (unitType == 3) //this is a tanker { currentVehicle = GetVehicle(model.tankers, unitId); if (currentVehicle == nullptr) { model.tankers.push_back(Vehicle()); currentVehicle = &model.tankers.at(model.tankers.size() - 1); } } else if (unitType == 4) //this is a wreck { currentVehicle = GetVehicle(model.wrecks, unitId); if (currentVehicle == nullptr) { model.wrecks.push_back(Vehicle()); currentVehicle = &model.wrecks.at(model.wrecks.size() - 1); } } if (currentVehicle != nullptr) { currentVehicle->unitId = unitId; currentVehicle->unitType = unitType; currentVehicle->player = player; currentVehicle->mass = mass; currentVehicle->radius = radius; currentVehicle->x = x; currentVehicle->y = y; currentVehicle->vx = vx; currentVehicle->vy = vy; currentVehicle->extra = extra; currentVehicle->extra2 = extra2; currentVehicle->updated = true; } } //**************** //post-input initialization //**************** //removing all not updated wrecks int wreckCountA = model.wrecks.size(); model.wrecks.erase(std::remove_if(model.wrecks.begin(), model.wrecks.end(), [&model](const Vehicle &x) { return !x.updated; }), model.wrecks.end()); int wreckCountB = model.wrecks.size(); if (wreckCountA != wreckCountB) { //std::cerr << "wreck count changed from " << wreckCountA << " to " << wreckCountB << std::endl; } //**************** //handling my vehicles //**************** HandleDoof(model); HandleDestroyer(model); HandleReaper(model); //**************** //output //**************** // Write an action using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; //Reaper output std::cout << model.myReaper.output << std::endl; //xx output std::cout << model.myDestroyer.output << std::endl; //xx output std::cout << model.myDoof.output << std::endl; } } //=============================================================
[ "patrickmonville@hotmail.com" ]
patrickmonville@hotmail.com
00dbebcc8462a3e730cf75bb1f07bc95660cc2eb
7e791eccdc4d41ba225a90b3918ba48e356fdd78
/chromium/src/components/arc/ime/arc_ime_bridge.h
65b67f8b7d764cdd1458a6bedfed8c2b52c80dc6
[ "BSD-3-Clause" ]
permissive
WiViClass/cef-3.2623
4e22b763a75e90d10ebf9aa3ea9a48a3d9ccd885
17fe881e9e481ef368d9f26e903e00a6b7bdc018
refs/heads/master
2021-01-25T04:38:14.941623
2017-06-09T07:37:43
2017-06-09T07:37:43
93,824,379
2
1
null
null
null
null
UTF-8
C++
false
false
3,874
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_ARC_IME_ARC_IME_BRIDGE_H_ #define COMPONENTS_ARC_IME_ARC_IME_BRIDGE_H_ #include "base/macros.h" #include "components/arc/ime/arc_ime_ipc_host.h" #include "ui/aura/client/focus_change_observer.h" #include "ui/aura/env_observer.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_tracker.h" #include "ui/base/ime/text_input_client.h" #include "ui/base/ime/text_input_flags.h" #include "ui/base/ime/text_input_type.h" #include "ui/gfx/geometry/rect.h" namespace aura { class Window; } namespace ui { class InputMethod; } namespace arc { class ArcBridgeService; // This class implements ui::TextInputClient and makes ARC windows behave // as a text input target in Chrome OS environment. class ArcImeBridge : public ArcImeIpcHost::Delegate, public aura::EnvObserver, public aura::WindowObserver, public aura::client::FocusChangeObserver, public ui::TextInputClient { public: explicit ArcImeBridge(ArcBridgeService* arc_bridge_service); ~ArcImeBridge() override; // Overridden from aura::EnvObserver: void OnWindowInitialized(aura::Window* new_window) override; // Overridden from aura::WindowObserver: void OnWindowAddedToRootWindow(aura::Window* window) override; // Overridden from aura::client::FocusChangeObserver: void OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) override; // Overridden from ArcImeIpcHost::Delegate: void OnTextInputTypeChanged(ui::TextInputType type) override; void OnCursorRectChanged(const gfx::Rect& rect) override; // Overridden from ui::TextInputClient: void SetCompositionText(const ui::CompositionText& composition) override; void ConfirmCompositionText() override; void ClearCompositionText() override; void InsertText(const base::string16& text) override; void InsertChar(const ui::KeyEvent& event) override; ui::TextInputType GetTextInputType() const override; gfx::Rect GetCaretBounds() const override; // Overridden from ui::TextInputClient (with default implementation): // TODO(kinaba): Support each of these methods to the extent possible in // Android input method API. ui::TextInputMode GetTextInputMode() const override; int GetTextInputFlags() const override; bool CanComposeInline() const override; bool GetCompositionCharacterBounds(uint32_t index, gfx::Rect* rect) const override; bool HasCompositionText() const override; bool GetTextRange(gfx::Range* range) const override; bool GetCompositionTextRange(gfx::Range* range) const override; bool GetSelectionRange(gfx::Range* range) const override; bool SetSelectionRange(const gfx::Range& range) override; bool DeleteRange(const gfx::Range& range) override; bool GetTextFromRange(const gfx::Range& range, base::string16* text) const override; void OnInputMethodChanged() override {} bool ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) override; void ExtendSelectionAndDelete(size_t before, size_t after) override {} void EnsureCaretInRect(const gfx::Rect& rect) override {} bool IsEditCommandEnabled(int command_id) override; void SetEditCommandForNextKeyEvent(int command_id) override {} private: ui::InputMethod* GetInputMethod(); ArcImeIpcHost ipc_host_; ui::TextInputType ime_type_; gfx::Rect cursor_rect_; aura::WindowTracker observing_root_windows_; aura::WindowTracker arc_windows_; aura::WindowTracker focused_arc_window_; DISALLOW_COPY_AND_ASSIGN(ArcImeBridge); }; } // namespace arc #endif // COMPONENTS_ARC_IME_ARC_IME_BRIDGE_H_
[ "1480868058@qq.com" ]
1480868058@qq.com
680a7aa435ceef1e4ab14f8703ba00d4cc2fc5a7
ca0a9c00eda752b70a10a7d449c39593a0a5a8f7
/Arrays/Repeat and Missing number.cpp
5853a669a40392aa3b5553d2349133318a287174
[]
no_license
faizm4765/Problem-Solving-IB-Series
31fc3e254c8bda8d265cc403cd4cf614e75664d7
69610a6350755ac91f5f81d38c90ce46d0cb14c2
refs/heads/master
2023-03-16T20:24:27.400797
2021-02-28T14:02:38
2021-02-28T14:02:38
263,027,964
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
/* You are given a read only array of n integers from 1 to n. Each integer appears exactly once except A which appears twice and B which is missing. Return A and B. */ ---------------------------------------------------------------------------------------------------------------------- vector<int> Solution::repeatedNumber(const vector<int> &A) { long long int len = A.size(); long long int Sum_N = (len * (len+1) ) /2, Sum_NSq = (len * (len +1) *(2*len +1) )/6; long long int missingNumber=0, repeating=0; for(int i=0;i<A.size(); i++){ Sum_N -= (long long int)A[i]; Sum_NSq -= (long long int)A[i]*(long long int)A[i]; } missingNumber = (Sum_N + Sum_NSq/Sum_N)/2; repeating= missingNumber - Sum_N; vector <int> ans; ans.push_back(repeating); ans.push_back(missingNumber); return ans; }
[ "noreply@github.com" ]
faizm4765.noreply@github.com
b7251d896585ff83cb79604c8142d8cca9ad0767
018397d645693256d64c23b8e5e861b523a7181a
/utility/source/shader.cpp
a9f5bb13b63d969d0098207251f5ca093aed7e0d
[ "MIT" ]
permissive
evertonantunes/OpenGLPlayground
9e2934856e4e8140b8887bef4b1b54fb3dba577f
1a7a9caaf81b250b90585dcdc128f6d55e391f7e
refs/heads/master
2020-05-02T14:39:51.554530
2019-05-13T14:40:55
2019-05-13T14:40:55
178,017,602
0
0
null
null
null
null
UTF-8
C++
false
false
3,519
cpp
#include "shader.hpp" #include <iostream> #include <fstream> using namespace application::opengl; Shader::Shader() { _totalShaders=0; _shaders[VERTEX_SHADER]=0; _shaders[FRAGMENT_SHADER]=0; _shaders[GEOMETRY_SHADER]=0; _attributeList.clear(); _uniformLocationList.clear(); } Shader::~Shader() { _attributeList.clear(); _uniformLocationList.clear(); } bool Shader::LoadFromString(GLenum whichShader, const std::string_view source) { if (source.empty()) { return false; } GLuint shader = glCreateShader (whichShader); GLint size = source.size(); const char * ptmp = source.data(); glShaderSource (shader, 1, &ptmp, &size); //check whether the shader loads fine GLint status; glCompileShader (shader); glGetShaderiv (shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *infoLog= new GLchar[infoLogLength]; glGetShaderInfoLog (shader, infoLogLength, NULL, infoLog); std::cerr << "Compile log: " << infoLog << std::endl; delete [] infoLog; } _shaders[_totalShaders++] = shader; return true; } bool Shader::LoadFromFile(GLenum whichShader, const std::string &filename) { std::ifstream fp(filename.c_str(), std::ios_base::in); if(fp) { std::string line, buffer; while(std::getline(fp, line)) { buffer.append(line); buffer.append("\r\n"); } //copy to source return LoadFromString(whichShader, buffer); } else { std::cerr << "Error loading shader: " << filename << std::endl; return false; } } void Shader::CreateAndLinkProgram() { _program = glCreateProgram (); if (_shaders[VERTEX_SHADER] != 0) { glAttachShader (_program, _shaders[VERTEX_SHADER]); } if (_shaders[FRAGMENT_SHADER] != 0) { glAttachShader (_program, _shaders[FRAGMENT_SHADER]); } if (_shaders[GEOMETRY_SHADER] != 0) { glAttachShader (_program, _shaders[GEOMETRY_SHADER]); } //link and check whether the program links fine GLint status; glLinkProgram (_program); glGetProgramiv (_program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetProgramiv (_program, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *infoLog= new GLchar[infoLogLength]; glGetProgramInfoLog (_program, infoLogLength, NULL, infoLog); std::cerr << "Link log: " << infoLog << std::endl; delete [] infoLog; } glDeleteShader(_shaders[VERTEX_SHADER]); glDeleteShader(_shaders[FRAGMENT_SHADER]); glDeleteShader(_shaders[GEOMETRY_SHADER]); } void Shader::Use() { glUseProgram(_program); } void Shader::UnUse() { glUseProgram(0); } void Shader::AddAttribute(const std::string &attribute) { _attributeList[attribute]= glGetAttribLocation(_program, attribute.c_str()); } void Shader::AddUniform(const std::string &uniform) { _uniformLocationList[uniform] = glGetUniformLocation(_program, uniform.c_str()); } GLuint Shader::operator[](const std::string &attribute) { return _attributeList[attribute]; } GLuint Shader::operator()(const std::string &uniform) { return _uniformLocationList[uniform]; } void Shader::DeleteShaderProgram() { glDeleteProgram(_program); }
[ "everton.oliveira@pixeon.com" ]
everton.oliveira@pixeon.com
0ca84a324910185d9187590bbd571a544f05c132
663f36cfff3bfaf9ad64bba430e648b0dadc0f99
/dependencies/OIS/src/extras/LIRC/OISLIRCRingBuffer.h
eb896cfd6cf2060786be20d583b89b0b0d2beb6c
[ "Apache-2.0" ]
permissive
LiberatorUSA/GUCEF
b579a530ac40478e8d92d8c1688dce71634ec004
2f24399949bc2b2eb20b3f445100dd3e141fe6d5
refs/heads/master
2023-09-03T18:05:25.190918
2023-09-02T17:23:59
2023-09-02T17:23:59
24,012,676
9
15
Apache-2.0
2021-07-04T04:53:42
2014-09-14T03:30:46
C++
UTF-8
C++
false
false
7,776
h
#include "OISConfig.h" #ifdef OIS_LIRC_SUPPORT /* The zlib/libpng License Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. # ------------------------# # Original License follows: # ------------------------# * PortAudio Portable Real-Time Audio Library * Latest version at: http://www.audiomulch.com/portaudio/ * <platform> Implementation * Copyright (c) 1999-2000 <author(s)> * * 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. * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef OIS_LIRCRingBuffer_H #define OIS_LIRCRingBuffer_H #include "OISPrereqs.h" namespace OIS { struct LIRCEvent { //! high bit (0x80000000) will be on if button pushed, else it was released unsigned int button; }; /// <summary> /// Ring Buffer (fifo) used to store 16bit pcm data /// </summary> class LIRCRingBuffer { private: //! Number of bytes in FIFO. Power of 2. Set by RingBuffer_Init int bufferSize; //! Used for wrapping indices with extra bit to distinguish full/empty. int bigMask; // Used for fitting indices to buffer. int smallMask; // Buffer holding the actual event buffers LIRCEvent *buffer; //! Index of next writable byte. Set by RingBuffer_AdvanceWriteIndex. volatile int writeIndex; //! Index of next readable byte. Set by RingBuffer_AdvanceReadIndex. volatile int readIndex; public: LIRCRingBuffer( unsigned int numEntries ) { numEntries = RoundUpToNextPowerOf2( numEntries ); //2 bytes per short bufferSize = (int)numEntries; buffer = new LIRCEvent[numEntries]; Flush(); bigMask = (int)(numEntries*2)-1; smallMask = (int)(numEntries)-1; } ~LIRCRingBuffer() { delete buffer; } unsigned int RoundUpToNextPowerOf2( unsigned int n ) { int numBits = 0; if( ((n-1) & n) == 0) return n; //Already Power of two. while( n > 0 ) { n= n>>1; numBits++; } return (unsigned int)(1<<numBits); } int GetReadAvailable( ) { return ( (writeIndex - readIndex) & bigMask ); } int GetWriteAvailable( ) { return ( bufferSize - GetReadAvailable()); } int Write( LIRCEvent *data, int numEntries ) { int size1 = 0, size2 = 0, numWritten; int data1Ptr = 0, data2Ptr = 0; numWritten = GetWriteRegions( numEntries, data1Ptr, size1, data2Ptr, size2 ); if( size2 > 0 ) { //copy to two parts memcpy( &buffer[data1Ptr], data, sizeof(LIRCEvent) * size1 ); //Array.Copy( data, offsetPtr, buffer, data1Ptr, size1 ); memcpy( &buffer[data2Ptr], &data[size1], sizeof(LIRCEvent) * size2 ); //Array.Copy( data, offsetPtr + size1, buffer, data2Ptr, size2 ); } else { //Copy all continous memcpy( &buffer[data1Ptr], data, sizeof(LIRCEvent) * size1 ); //Array.Copy( data, offsetPtr, buffer, data1Ptr, size1 ); } AdvanceWriteIndex( numWritten ); return numWritten; } /// <summary> /// Reads requested number of entries into sent array. /// Returns number written /// </summary> int Read( LIRCEvent *data, int numEntries ) { int size1 = 0, size2 = 0, numRead, data1Ptr = 0, data2Ptr = 0; numRead = GetReadRegions( numEntries, data1Ptr, size1, data2Ptr, size2 ); if( size2 > 0 ) { memcpy( data, &buffer[data1Ptr], sizeof(LIRCEvent) * size1 ); //Array.Copy( buffer, data1Ptr, data, 0, size1 ); memcpy( &data[size1], &buffer[data2Ptr], sizeof(LIRCEvent) * size2 ); //Array.Copy( buffer, data2Ptr, data, size1, size2 ); } else memcpy( data, &buffer[data1Ptr], sizeof(LIRCEvent) * size1 ); //Array.Copy( buffer, data1Ptr, data, 0, size1 ); AdvanceReadIndex( numRead ); return numRead; } private: int GetWriteRegions( int numEntries, int &dataPtr1, int &sizePtr1, int &dataPtr2, int &sizePtr2 ) { int index; int available = GetWriteAvailable(); if( numEntries > available ) numEntries = available; //Check to see if write is not contiguous. index = writeIndex & smallMask; if( (index + numEntries) > bufferSize ) { //Write data in two blocks that wrap the buffer. int firstHalf = bufferSize - index; dataPtr1 = index;//&buffer[index]; sizePtr1 = firstHalf; dataPtr2 = 0;//&buffer[0]; sizePtr2 = numEntries - firstHalf; } else { dataPtr1 = index;//&buffer[index]; sizePtr1 = numEntries; dataPtr2 = 0; sizePtr2 = 0; } return numEntries; } int GetReadRegions( int numEntries, int &dataPtr1, int &sizePtr1, int &dataPtr2, int &sizePtr2 ) { int index; int available = GetReadAvailable( ); if( numEntries > available ) numEntries = available; // Check to see if read is not contiguous index = readIndex & smallMask; if( (index + numEntries) > bufferSize ) { // Write data in two blocks that wrap the buffer int firstHalf = bufferSize - index; dataPtr1 = index;//&buffer[index]; sizePtr1 = firstHalf; dataPtr2 = 0;//&buffer[0]; sizePtr2 = numEntries - firstHalf; } else { dataPtr1 = index;//&buffer[index]; sizePtr1 = numEntries; dataPtr2 = 0; sizePtr2 = 0; } return numEntries; } int AdvanceWriteIndex( int numEntries ) { return writeIndex = (writeIndex + numEntries) & bigMask; } int AdvanceReadIndex( int numEntries ) { return readIndex = (readIndex + numEntries) & bigMask; } void Flush( ) { writeIndex = readIndex = 0; } }; } #endif //#define OIS_LIRCRingBuffer_H #endif
[ "liberatorusa@9712d391-321d-0410-84f4-d6a0ebf28296" ]
liberatorusa@9712d391-321d-0410-84f4-d6a0ebf28296
52b534bc649748a2a262e28a811466f68beb5298
daf28dc6c26d812e0d0e36294390a3d33ac0afae
/src/Grudinsky/spectral_test_grudinsky.cpp
05cb869d47d95aeb96039dc9a4220e1a7aaf0bb9
[]
no_license
Ashes17b/NIST_tests
2dd8746cc367219305744f5aac2218a4d0d11700
dfe9281dfeea5fc19da1ffa35346e585aa050b6a
refs/heads/master
2020-05-25T17:01:18.487951
2019-06-08T17:12:54
2019-06-08T17:12:54
187,899,547
0
0
null
2019-06-08T16:55:57
2019-05-21T19:19:02
C++
UTF-8
C++
false
false
3,500
cpp
#include "../libraries/spectral_test_grudinsky.hpp" namespace spectral_test { void Spectral_test_grudinsky::read(std::string filename) { if (filename.empty()) std::cerr << "Filename is undefined" << std::endl; else std::cout << "Read from(Spectral_test Grudinsky) " << filename << std::endl; std::ifstream fin(filename, std::ios::binary); int n = get_size_file(filename); char * buf = new char[n]; fin.read(buf, n); n *= 8; numbers_of_bits = n; int npow = pow(2, largest_pow(n)); _buffer = new double [npow + 1]; for(int i = 0; i < npow / 8; i++) for(int j = 7; j >= 0; j--) _buffer[i * 8 + 7 - j] = 2 * ((buf[i] >> j) & 1) - 1; } double Spectral_test_grudinsky::run_test() { std::cout << "Started performing spectral_test Grudinsky" << std::endl; int npow = pow(2, largest_pow(numbers_of_bits)); double N0 = 0.95 * npow / 2; dittt(npow / 2); double T = sqrt(log(20) * npow); int N1 = 0; for(int i = 0; i < npow; i += 2) if(sqrt(pow(_buffer[i], 2) + pow(_buffer[i + 1], 2)) < T) N1++; double d = (N1 - N0) / sqrt(npow * 0.95 * 0.05 / 4); double p_value = erfc(fabs(d / sqrt(2))); delete [] _buffer; return p_value; } void Spectral_test_grudinsky::dittt(int size) { double wtemp, wr, wpr, wpi, wi, theta; double tempr, tempi; int N = size; int i = 0, j = 0, n = 0, k = 0, m = 0, isign = -1,istep,mmax; bytes data; data = &_buffer[0] - 1; n = N*2; j = 1; // do the bit-reversal for (i = 1; i < n; i += 2) { if (j > i) { std::swap(data[j], data[i]); std::swap(data[j+1], data[i+1]); } m = n >> 1; while (m >= 2 && j > m) { j -= m; m >>= 1; } j +=m; } mmax = 2; while (n > mmax) { istep = mmax << 1; theta = isign*(6.28318530717959/mmax); wtemp = sin(0.5*theta); wpr = -2.0*wtemp*wtemp; wpi = sin(theta); wr = 1.0; wi = 0.0; for (m = 1; m < mmax; m += 2) { for (i = m; i <= n; i += istep) { j = i + mmax; tempr = wr*data[j] - wi*data[j+1]; tempi = wr*data[j+1] + wi*data[j]; data[j] = data[i] - tempr; data[j+1] = data[i+1] - tempi; data[i] = data[i] + tempr; data[i+1] = data[i+1] + tempi; } wtemp = wr; wr += wtemp*wpr - wi*wpi; wi += wtemp*wpi + wi*wpr; } mmax = istep; } } std::size_t Spectral_test_grudinsky::get_size_file(std::string filename) const { std::ifstream f(filename, std::ios::binary | std::ios::in | std::ifstream::ate); return f.tellg(); } int Spectral_test_grudinsky::largest_pow(int n) { int i = 0; while(n != 1) { n /= 2; i++; } return i; } double Spectral_test_grudinsky::f(double x, double a) { return exp(-x) * pow(x, a - 1); } } //namespace spectral_test
[ "vadimlisai@gmail.com" ]
vadimlisai@gmail.com
ec39a3d27a32aaf22c50a3101eb7f42b728c1c9b
c8af3e63519bdba8ff56e46e69634aaa81922954
/数论/题目/集合中的质数/未命名3.cpp
f5573153dd2687ef8b8ea2fc8bf91c79136f8f01
[]
no_license
HexQwQ/Hp1
2fb8b4b0abeb1b63734d8366199b3f74833a77d2
414c96d1e901076ff27fe192b355bbdaab367130
refs/heads/master
2020-08-11T19:48:46.703445
2019-10-12T09:28:17
2019-10-12T09:28:17
214,617,458
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
#include<bits/stdc++.h> using namespace std; int n,prim[233]; bool book[233]; long long m, ans = 0; bool dfs(long long x,int f,int p){ if( x <= m/prim[p] ) ans += m/x/prim[p]*f; else return false; for(int i=p+1;i<=n;i++) { book[i] = true; bool flag = dfs(x*prim[p],f*(-1),i); book[i] = false; if( flag == false ) return true; } return true; } int main(int argc,char ** argv){ scanf("%d %lld",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&prim[i]); sort(prim+1,prim+1+n); for(int i=1;i<=n;i++) { book[i] = true; dfs(1,1,i); book[i] = false; } printf("%lld",ans); return 0; } /* 1 7 11 13 17 19 23 29 */
[ "56310759+HexQwQ@users.noreply.github.com" ]
56310759+HexQwQ@users.noreply.github.com
5d0a59567017329ca0dbe7efe04425e5054c8f0c
06f62d82a03116144ff4de343a99b579254aff56
/cpp/mindalpha/s3_sdk_filesys.cpp
a8797c74eb0b62911b193758bc9732f2e6e9d7a3
[ "Apache-2.0" ]
permissive
zyclove/MindAlpha
10aa7fd6d47261347850fd5e19399686aaeb99c6
69f599f89ba82688d692accfd9283444a2de7403
refs/heads/main
2023-07-04T06:34:32.599825
2021-07-27T05:37:23
2021-07-27T05:37:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,812
cpp
// // Copyright 2021 Mobvista // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mindalpha/s3_sdk_filesys.h" #include <iostream> #include <cstdlib> #include <fstream> #include <aws/core/Aws.h> #include <aws/core/auth/AWSCredentialsProvider.h> #include <aws/s3/S3Client.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/DefaultRetryStrategy.h> #include <aws/s3/model/ListObjectsRequest.h> #include <aws/s3/model/Object.h> #include <aws/s3/model/GetObjectRequest.h> #include <aws/s3/model/HeadObjectRequest.h> #include <aws/s3/model/HeadObjectResult.h> #include <aws/s3/model/PutObjectRequest.h> #include <aws/s3/model/CreateMultipartUploadRequest.h> #include <aws/s3/model/CreateMultipartUploadResult.h> #include <aws/s3/model/CompletedPart.h> #include <aws/s3/model/UploadPartRequest.h> #include <aws/s3/model/UploadPartResult.h> #include <aws/s3/model/CompleteMultipartUploadRequest.h> #include <aws/s3/model/CompleteMultipartUploadResult.h> #include <aws/s3/model/CompletedMultipartUpload.h> #include <aws/s3/model/AbortMultipartUploadRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/logging/ConsoleLogSystem.h> #include <aws/core/utils/logging/AWSLogging.h> #include "mindalpha/logging.h" namespace mindalpha { class AWSInitOption { public: AWSInitOption() { Aws::InitAPI(options); clientConfigPtr = std::make_shared<Aws::Client::ClientConfiguration>(); const char * ep = getenv("AWS_ENDPOINT"); if (ep) { std::cout << "Get aws endpoint from env: " << ep << std::endl; clientConfigPtr->endpointOverride = ep; } clientConfigPtr->scheme = Aws::Http::Scheme::HTTP; clientConfigPtr->connectTimeoutMs = 60000; clientConfigPtr->requestTimeoutMs = 60000; std::shared_ptr<Aws::Client::RetryStrategy> retry; retry.reset(new Aws::Client::DefaultRetryStrategy(10, 5)); clientConfigPtr->retryStrategy = retry; // assign to client_config Aws::Utils::Logging::InitializeAWSLogging( Aws::MakeShared<Aws::Utils::Logging::ConsoleLogSystem>("S3Logging", Aws::Utils::Logging::LogLevel::Warn)); } ~AWSInitOption() { clientConfigPtr.reset(); Aws::ShutdownAPI(options); } Aws::SDKOptions options; std::shared_ptr<Aws::Client::ClientConfiguration> clientConfigPtr; static AWSInitOption &GetInstance() { static AWSInitOption option; return option; } }; static const char * GetValidKey(const char *key, size_t len) { if (len == 0) { return key; } for (size_t i = 0; i < len - 1; ++i) { if (key[i] != '/') { return key + i; } } return key; } static Aws::S3::Model::ListObjectsOutcome ListS3Objects(const URI &path) { Aws::S3::S3Client s3_client(*AWSInitOption::GetInstance().clientConfigPtr); Aws::S3::Model::ListObjectsRequest objects_request; const char *prefix = GetValidKey(path.name.c_str(), path.name.size()); LOG(INFO) << "S3FileSystem::ListDirectory " << path.protocol << ", " << path.host << ", " << prefix; objects_request.WithBucket(path.host.c_str()).SetPrefix(prefix); auto list_objects_outcome = s3_client.ListObjects(objects_request); if (list_objects_outcome.IsSuccess()) { return std::move(list_objects_outcome); } else { LOG(ERROR) << "ListObjects error: " << list_objects_outcome.GetError().GetExceptionName() << " " << list_objects_outcome.GetError().GetMessage() << std::endl; return Aws::S3::Model::ListObjectsOutcome(); } } /*! * \brief get information about a path * \param path the path to the file * \return the information about the file */ FileInfo S3FileSystem::GetPathInfo(const URI &path) { auto list_objects_outcome = ListS3Objects(path); FileInfo info; info.path = path; const Aws::Vector<Aws::S3::Model::Object> &object_list = list_objects_outcome.GetResult().GetContents(); if (object_list.size() > 1) { info.type = kDirectory; info.size = 0UL; } else { info.type = kFile; auto const &s3_object = object_list.front(); info.size = s3_object.GetSize(); } return std::move(info); } /*! * \brief list files in a directory * \param path to the file * \param out_list the output information about the files */ void S3FileSystem::ListDirectory(const URI &path, std::vector<FileInfo> *out_list) { auto list_objects_outcome = ListS3Objects(path); const Aws::Vector<Aws::S3::Model::Object> &object_list = list_objects_outcome.GetResult().GetContents(); for (auto const &object : object_list) { auto const &key = object.GetKey(); out_list->emplace_back(); FileInfo &info = out_list->back(); info.path = path; if (key.front() != '/') { info.path.name = '/'; info.path.name += key.c_str(); } else { info.path.name = key.c_str(); } info.size = key.back() == '/' ? 0 : object.GetSize(); info.type = key.back() == '/' ? kDirectory : kFile; } } class ReadBuffer { public: ReadBuffer() : buf_(), pos_(), size_() {} void Init() { buf_.reserve(read_buf_size); } size_t LeftRoom() const { return size_ - pos_; } void Clear() { buf_.clear(); pos_ = 0; size_ = 0; } size_t FillBuffer(Stream *s); void UseBuffer(void *ptr, size_t len) { // return buf_[pos_] + len memcpy(ptr, &buf_[pos_], len); pos_ += len; } size_t Read(Stream *s, void *ptr, size_t len) { const size_t left = LeftRoom(); // current left room is enough for this read request if (left >= len) { UseBuffer(ptr, len); return len; } // not enough room. // 1. copy left root if (left > 0) { UseBuffer(ptr, left); } // 2. refill buffer until done size_t stillneed = len - left; while (stillneed > 0) { const size_t nread = FillBuffer(s); if (nread == 0) { // no more data return len - stillneed; } if (nread >= stillneed) { // finished reading UseBuffer((char *)ptr + len - stillneed, stillneed); return len; } else { UseBuffer((char *)ptr + len - stillneed, nread); stillneed -= nread; // continue loop } } return (len - stillneed); } private: std::string buf_; size_t pos_; // current used pos size_t size_; // valid size of current buffer // read buffer size for prefetch static const size_t read_buf_size = 1024UL * 1024UL * 8UL; }; class WriteBuffer { public: WriteBuffer(Aws::S3::S3Client &client) : client_(client) {} void Init(Aws::String &bucket, Aws::String &key) { buf_.reserve(write_buf_size); // Initiate upload part bucket_ = bucket; key_ = key; Aws::S3::Model::CreateMultipartUploadRequest request; request.WithBucket(bucket_).WithKey(key_); auto const createUploadOutcome = client_.CreateMultipartUpload(request); if (createUploadOutcome.IsSuccess()) { auto const &result = createUploadOutcome.GetResult(); upload_id_ = result.GetUploadId(); } else { LOG(ERROR) << "CreateMultipartUploadRequest error for file: " << key_ << ", " << createUploadOutcome.GetError().GetExceptionName() << " " << createUploadOutcome.GetError().GetMessage() << std::endl; throw std::runtime_error("CreateMultipartUpload error"); } } void Write(const void *ptr, size_t len) { // append to buffer buf_.append((const char *)ptr, len); if (buf_.length() >= write_buf_size) { DoUploadPart(); buf_.clear(); } } template<typename Request> void FillRequest(Request &request) { request.WithBucket(bucket_).WithKey(key_).WithContentLength(buf_.size()); request.SetContentType("binary/octet-stream"); auto s = Aws::MakeShared<Aws::StringStream>("WriteObjectStream", std::stringstream::in | std::stringstream::out | std::stringstream::binary); s->write(buf_.c_str(), buf_.size()); request.SetBody(s); } void DoPutObject() { Aws::S3::Model::PutObjectRequest request; FillRequest(request); auto const outcome = client_.PutObject(request); if (!outcome.IsSuccess()) { LOG(ERROR) << "PutObjectRequest error for file: " << key_ << ", " << outcome.GetError().GetExceptionName() << " " << outcome.GetError().GetMessage() << std::endl; throw std::runtime_error("PutObjectRequest error"); } } void DoUploadPart() { Aws::S3::Model::UploadPartRequest request; const int partNum = static_cast<int>(parts_.GetParts().size() + 1); FillRequest(request); request.WithPartNumber(partNum).WithUploadId(upload_id_).WithContentLength(buf_.size()); auto const outcome = client_.UploadPart(request); if (!outcome.IsSuccess()) { LOG(ERROR) << "UploadPart error for file: " << key_ << ", " << outcome.GetError().GetExceptionName() << " " << outcome.GetError().GetMessage() << std::endl; throw std::runtime_error("UploadPart error"); } Aws::S3::Model::CompletedPart part; part.SetETag(outcome.GetResult().GetETag()); part.SetPartNumber(partNum); parts_.AddParts(std::move(part)); } void Close() { if (!buf_.empty()) { if (parts_.GetParts().empty()) { // no previous part, directly put DoPutObject(); } else { // upload final part DoUploadPart(); } } if (!parts_.GetParts().empty()) { // complete part upload Aws::S3::Model::CompleteMultipartUploadRequest request; request.WithBucket(bucket_).WithKey(key_).WithUploadId(upload_id_).WithMultipartUpload(parts_); auto const complete_outcome = client_.CompleteMultipartUpload(request); if (!complete_outcome.IsSuccess()) { LOG(ERROR) << "CompleteMultipartUpload error for file: "<< key_ << ", " << complete_outcome.GetError().GetExceptionName() << " " << complete_outcome.GetError().GetMessage() << std::endl; throw std::runtime_error("CompleteMultipartUpload error"); } } else { // abort part upload Aws::S3::Model::AbortMultipartUploadRequest request; request.WithBucket(bucket_).WithKey(key_).WithUploadId(upload_id_); client_.AbortMultipartUpload(request); } } private: Aws::S3::S3Client &client_; std::string buf_; Aws::String bucket_; Aws::String key_; Aws::String upload_id_; Aws::S3::Model::CompletedMultipartUpload parts_; // default buffer size for caching write static const size_t write_buf_size = 1024UL * 1024UL * 5UL; }; class S3SDKStream : public SeekStream { public: S3SDKStream() : client_(*AWSInitOption::GetInstance().clientConfigPtr), pos_(), size_(), write_buf_(client_), is_write_(false) {} virtual ~S3SDKStream() { if (is_write_) { write_buf_.Close(); } } bool Open(const URI &path, bool read_only) { path_ = path; bucket_ = path.host.c_str(); key_ = GetValidKey(path.name.c_str(), path.name.size()); LOG(INFO) << "Try to open S3 stream: " << bucket_ << ":" << key_ << ", read_only: " << read_only << std::endl; if (path_.name.back() == '/') { LOG(ERROR) << "S3 open stream with a directory path: " << path.name << std::endl; throw std::runtime_error(path.name + " is not a valid file path"); } if (read_only) { Aws::S3::Model::HeadObjectRequest object_request; object_request.WithBucket(bucket_).WithKey(key_); auto const head_object_outcome = client_.HeadObject(object_request); if (head_object_outcome.IsSuccess()) { const int64_t length = head_object_outcome.GetResult().GetContentLength(); if (length < 0) { LOG(ERROR) << "Open read-only stream for object: " << key_ << " but with invalid length: " << length << std::endl; return false; } LOG(INFO) << "Opened read-only stream for object: " << key_ << " with total length: " << length << std::endl; size_ = length; read_buf_.Init(); // init read prefetch buffer return true; } else { LOG(ERROR) << "Read object failed with error: " << head_object_outcome.GetError().GetMessage(); throw std::runtime_error(std::string("Read object failed with error: ") + head_object_outcome.GetError().GetMessage()); } } else { is_write_ = true; write_buf_.Init(bucket_, key_); } return false; } virtual size_t Read(void *ptr, size_t size) override { // try prefetch const size_t rlen = read_buf_.Read(this, ptr, size); return rlen; } /** * For reading, aws sdk actually performs new http request for each * range, so there is no need to maintain a local stream. * Upper layer user should use proper buffer size to optimize performance. */ size_t ActualRead(void *ptr, size_t size) { if (pos_ == size_) { LOG(INFO) << "Read S3 object " << key_ << " reached end " << pos_ << std::endl; return 0UL; } if (pos_ + size > size_) { size = size_ - pos_; LOG(INFO) << "Read S3 object " << key_ << " with size " << size << " at position " << pos_ << " larger than total size: " << size_ << ", change size to " << size << std::endl; } // requesting range Aws::S3::Model::GetObjectRequest object_request; object_request.WithBucket(bucket_).WithKey(key_).WithRange(("bytes=" + std::to_string(pos_) + "-" + std::to_string(pos_ + size)).c_str()); auto get_object_outcome = client_.GetObject(object_request); if (get_object_outcome.IsSuccess()) { Aws::IOStream &input_stream = get_object_outcome.GetResult().GetBody(); input_stream.read((char *)ptr, size); pos_ += size; return size; } else { LOG(ERROR) << "GetObject error for file: " << key_ << ", " << get_object_outcome.GetError().GetExceptionName() << " " << get_object_outcome.GetError().GetMessage() << std::endl; throw std::runtime_error("GetObject error"); } } virtual void Seek(size_t pos) override { if (pos > size_) { LOG(ERROR) << "Try to seek position " << pos << " on object " << key_ << ", which is larger than total size: " << size_ << std::endl; throw std::runtime_error("Seek error"); } pos_ = pos; read_buf_.Clear(); // clear buffer } virtual size_t Tell(void) override { // since buffer might have some room, // we need to substract the unconsumed size in buffer. return pos_ - read_buf_.LeftRoom(); } virtual void Write(const void *ptr, size_t size) override { write_buf_.Write(ptr, size); } private: Aws::S3::S3Client client_; URI path_; Aws::String bucket_; Aws::String key_; // filename // use for read size_t pos_; size_t size_; ReadBuffer read_buf_; // use for write WriteBuffer write_buf_; bool is_write_; }; size_t ReadBuffer::FillBuffer(Stream *s) { Clear(); buf_.resize(read_buf_size); S3SDKStream * s3s = static_cast<S3SDKStream *>(s); size_ = s3s->ActualRead((void *)buf_.data(), read_buf_size); return size_; } /*! * \brief open a stream, will report error and exit if bad thing happens * NOTE: the Stream can continue to work even when filesystem was destructed * \param path path to file * \param uri the uri of the input * \param flag can be "w", "r", "a" * \param allow_null whether NULL can be returned, or directly report error * \return the created stream, can be NULL when allow_null == true and file do not exist */ Stream * S3FileSystem::Open(const URI &path, const char *const flag, bool allow_null) { S3SDKStream *s = new S3SDKStream; const size_t flen = strlen(flag); const bool read_only = std::find(flag, flag + flen + 1, 'w') == flag + flen + 1 ? true : false; s->Open(path, read_only); return s; } /*! * \brief open a seekable stream for read * \param path the path to the file * \param allow_null whether NULL can be returned, or directly report error * \return the created stream, can be NULL when allow_null == true and file do not exist */ SeekStream * S3FileSystem::OpenForRead(const URI &path, bool allow_null) { S3SDKStream *s = new S3SDKStream; s->Open(path, true); return s; } S3FileSystem::S3FileSystem() { } S3FileSystem *S3FileSystem::GetInstance(void) { static S3FileSystem instance; return &instance; } } // namespace mindalpha
[ "huaidong.xiong@mobvista.com" ]
huaidong.xiong@mobvista.com
23df45c4dee91c0e7061e61c0c5f1b8f5d4d30b0
e9131b2caef47532e0d502e82a5aa5373c0986f2
/Stack.cpp
29c8c9f8d9ea6eae0553e4950b4f368505cf9ecf
[]
no_license
jonchan1997/cs36300-spring2019-composition
ac3e4373b5ca164b061361725ef47d9b303c12bf
ceea4016e6f9b2dac6289612993364fdc6236457
refs/heads/master
2020-08-04T02:39:25.814059
2019-09-30T23:12:59
2019-09-30T23:12:59
211,974,380
0
0
null
null
null
null
UTF-8
C++
false
false
2,246
cpp
// $Id: Stack.cpp 827 2011-02-07 14:20:53Z hillj $ // Honor Pledge: // // I pledge that I have neither given nor received any help // on this assignment. #include "Stack.h" // // Stack // template <typename T> Stack <T>::Stack (void): Array<T>() { } // // Stack // template <typename T> Stack <T>::Stack (const Stack & stack): Array<T>() { T * copy_data = new T[stack.size()]; for(size_t i = 0; i < stack.size(); i++) { copy_data[i]=stack.top(); stack.pop(); } size_t r = stack.size()-1; for(size_t p = 0; p < stack.size(); p++) { this->push(copy_data[r]); r--; } delete [] copy_data; this->size_=stack.size(); } // // ~Stack // template <typename T> Stack <T>::~Stack (void) { delete [] this->data_; } // // push // template <typename T> void Stack <T>::push (T element) { this->resize(this->size() + 1); this->size_++; this->set((this->size() - 1), element); } // // pop // template <typename T> void Stack <T>::pop (void) { if(!this->is_empty()) { this->resize(this->size() - 1); this->size_ --; } else { throw empty_exception(""); } } // // operator = // template <typename T> const Stack <T> & Stack <T>::operator = (const Stack & rhs) { if(*this != rhs) { T * copy_data = new T[rhs.size()]; for(size_t i = 0; i < rhs.size(); i++) { copy_data[i]=rhs.top(); rhs.pop(); } size_t r = rhs.size()-1; for(size_t p = 0; p < rhs.size(); p++) { this->push(copy_data[r]); r--; } delete [] copy_data; this->size_=rhs.size(); } return *this; } // // clear // template <typename T> void Stack <T>::clear (void) { if(!(this->is_empty())) { size_t length = this->size(); for(size_t i = 0; i < length; i++) { this->pop(); } } else { throw empty_exception(""); } } // // top // template <typename T> T Stack <T>::top (void) const { if(!(this->is_empty())) { return (this->get(this->size() - 1)); } else { throw empty_exception(""); } }
[ "youngjon@iupui.edu" ]
youngjon@iupui.edu
c41c142679c7dce44fd5387f2a742443a60d4601
0b7a7ebe4abe8de84470792a6c76f6fca60859ba
/compileShit/cpl.cpp
12be3dbe0a8b0b690370211c5e09400a6eb3a1e4
[]
no_license
waxvapour/Bamboo
922368e2a06f944431298daac3359d36d9ccf60f
4d9fe50f261a467ff64222ec0efc40a9a47ca943
refs/heads/master
2023-02-23T16:18:00.086063
2021-01-28T12:49:31
2021-01-28T12:49:31
266,579,144
2
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include<iostream> using namespace std; // main function - // where the execution of program begins int main() { // prints hello world cout<<"Hello World"; return 0; }
[ "waxvapour@gmail.com" ]
waxvapour@gmail.com
dfa5503bdc4f6e6282f9722e7f850f5aac1209e5
89b7e4a17ae14a43433b512146364b3656827261
/testcases/CWE124_Buffer_Underwrite/s02/testcases.h
4c59ceccca21d01d14595df1a06cd085a1e6efb5
[]
no_license
tuyen1998/Juliet_test_Suite
7f50a3a39ecf0afbb2edfd9f444ee017d94f99ee
4f968ac0376304f4b1b369a615f25977be5430ac
refs/heads/master
2020-08-31T23:40:45.070918
2019-11-01T07:43:59
2019-11-01T07:43:59
218,817,337
0
1
null
null
null
null
UTF-8
C++
false
false
79,081
h
// NOTE - eventually this file will be automatically updated using a Perl script that understand // the naming of test case files, functions, and namespaces. #ifndef _TESTCASES_H #define _TESTCASES_H #ifdef __cplusplus extern "C" { #endif // declare C good and bad functions #ifndef OMITGOOD /* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-DECLARATIONS */ void CWE124_Buffer_Underwrite__CWE839_negative_44_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_15_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_07_good(); void CWE124_Buffer_Underwrite__CWE839_rand_21_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_15_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_03_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_44_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_11_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_45_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_52_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_52_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_10_good(); void CWE124_Buffer_Underwrite__CWE839_negative_52_good(); void CWE124_Buffer_Underwrite__CWE839_negative_08_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_04_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_15_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_17_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_15_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_42_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_22_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_21_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_05_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_03_good(); void CWE124_Buffer_Underwrite__CWE839_rand_07_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_16_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_18_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_67_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_09_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_52_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_44_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_41_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_42_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_17_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_06_good(); void CWE124_Buffer_Underwrite__CWE839_negative_14_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_64_good(); void CWE124_Buffer_Underwrite__CWE839_negative_31_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_17_good(); void CWE124_Buffer_Underwrite__CWE839_negative_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_10_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_63_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_07_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_05_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_07_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_32_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_51_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_68_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_65_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_53_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_31_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_68_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_32_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_51_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_41_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_64_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_54_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_02_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_51_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_14_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_12_good(); void CWE124_Buffer_Underwrite__CWE839_negative_07_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_02_good(); void CWE124_Buffer_Underwrite__CWE839_rand_11_good(); void CWE124_Buffer_Underwrite__CWE839_rand_14_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_13_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_03_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_68_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_51_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_03_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_17_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_31_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_09_good(); void CWE124_Buffer_Underwrite__CWE839_negative_51_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_10_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_05_good(); void CWE124_Buffer_Underwrite__CWE839_negative_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_09_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_42_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_64_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_18_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_52_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_06_good(); void CWE124_Buffer_Underwrite__CWE839_rand_41_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_41_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_32_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_02_good(); void CWE124_Buffer_Underwrite__CWE839_negative_68_good(); void CWE124_Buffer_Underwrite__CWE839_rand_32_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_32_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_34_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_32_good(); void CWE124_Buffer_Underwrite__CWE839_rand_64_good(); void CWE124_Buffer_Underwrite__CWE839_rand_06_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_08_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_01_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_42_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_03_good(); void CWE124_Buffer_Underwrite__CWE839_negative_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_12_good(); void CWE124_Buffer_Underwrite__CWE839_negative_13_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_14_good(); void CWE124_Buffer_Underwrite__CWE839_negative_02_good(); void CWE124_Buffer_Underwrite__CWE839_negative_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_64_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_14_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_34_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_21_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_61_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_65_good(); void CWE124_Buffer_Underwrite__CWE839_negative_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_45_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_44_good(); void CWE124_Buffer_Underwrite__CWE839_negative_04_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_42_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_53_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_09_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_14_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_42_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_08_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_07_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_52_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_66_good(); void CWE124_Buffer_Underwrite__CWE839_rand_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_31_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_06_good(); void CWE124_Buffer_Underwrite__CWE839_rand_65_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_31_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_68_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_05_good(); void CWE124_Buffer_Underwrite__CWE839_rand_31_good(); void CWE124_Buffer_Underwrite__CWE839_negative_63_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_51_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_22_good(); void CWE124_Buffer_Underwrite__CWE839_rand_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_08_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_18_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_64_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_05_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_63_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_52_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_18_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_12_good(); void CWE124_Buffer_Underwrite__CWE839_rand_53_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_22_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_04_good(); void CWE124_Buffer_Underwrite__CWE839_negative_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_53_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_65_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_44_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_45_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_22_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_08_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_63_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_34_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_66_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_51_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_64_good(); void CWE124_Buffer_Underwrite__CWE839_negative_18_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_64_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_61_good(); void CWE124_Buffer_Underwrite__CWE839_negative_03_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_10_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_22_good(); void CWE124_Buffer_Underwrite__CWE839_rand_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_12_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_63_good(); void CWE124_Buffer_Underwrite__CWE839_negative_17_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_04_good(); void CWE124_Buffer_Underwrite__CWE839_negative_05_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_67_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_64_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_07_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_14_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_52_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_63_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_44_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_61_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_05_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_14_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_31_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_11_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_18_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_21_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_16_good(); void CWE124_Buffer_Underwrite__CWE839_negative_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_32_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_31_good(); void CWE124_Buffer_Underwrite__CWE839_rand_18_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_08_good(); void CWE124_Buffer_Underwrite__CWE839_negative_42_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_18_good(); void CWE124_Buffer_Underwrite__CWE839_negative_32_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_14_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_09_good(); void CWE124_Buffer_Underwrite__CWE839_rand_08_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_12_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_65_good(); void CWE124_Buffer_Underwrite__CWE839_rand_04_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_66_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_53_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_68_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_10_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_07_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_14_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_21_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_07_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_06_good(); void CWE124_Buffer_Underwrite__CWE839_rand_52_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_06_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_08_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_61_good(); void CWE124_Buffer_Underwrite__CWE839_negative_11_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_67_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_21_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_21_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_08_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_44_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_15_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_45_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_03_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_41_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_63_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_45_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_31_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_01_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_61_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_06_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_41_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_17_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_05_good(); void CWE124_Buffer_Underwrite__CWE839_negative_16_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_67_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_51_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_31_good(); void CWE124_Buffer_Underwrite__CWE839_rand_42_good(); void CWE124_Buffer_Underwrite__CWE839_rand_17_good(); void CWE124_Buffer_Underwrite__CWE839_negative_67_good(); void CWE124_Buffer_Underwrite__CWE839_rand_45_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_67_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_10_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_67_good(); void CWE124_Buffer_Underwrite__CWE839_negative_41_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_17_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_68_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_04_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_52_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_05_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_18_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_67_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_44_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_22_good(); void CWE124_Buffer_Underwrite__CWE839_rand_22_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_41_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_53_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_06_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_31_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_16_good(); void CWE124_Buffer_Underwrite__CWE839_rand_51_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_22_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_07_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_21_good(); void CWE124_Buffer_Underwrite__CWE839_negative_06_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_63_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_67_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_53_good(); void CWE124_Buffer_Underwrite__CWE839_negative_01_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_65_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_17_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_09_good(); void CWE124_Buffer_Underwrite__CWE839_rand_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_44_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_53_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_05_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_32_good(); void CWE124_Buffer_Underwrite__CWE839_rand_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_42_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_10_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_04_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_68_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_06_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_51_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_03_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_41_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_22_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_17_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_09_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_02_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_52_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_64_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_54_good(); void CWE124_Buffer_Underwrite__CWE839_negative_12_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_10_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_18_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_61_good(); void CWE124_Buffer_Underwrite__CWE839_negative_22_good(); void CWE124_Buffer_Underwrite__CWE839_rand_10_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_42_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_04_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_04_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_67_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_10_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_03_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_67_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_02_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_54_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_31_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_53_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_13_good(); void CWE124_Buffer_Underwrite__CWE839_negative_53_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_68_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_32_good(); void CWE124_Buffer_Underwrite__CWE839_negative_64_good(); void CWE124_Buffer_Underwrite__CWE839_rand_63_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_01_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_21_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_04_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_11_good(); void CWE124_Buffer_Underwrite__CWE839_rand_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_66_good(); void CWE124_Buffer_Underwrite__CWE839_rand_68_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_18_good(); void CWE124_Buffer_Underwrite__CWE839_negative_65_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_44_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_17_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_65_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_04_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_51_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_42_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_13_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_65_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_54_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_68_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_63_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_10_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_04_good(); void CWE124_Buffer_Underwrite__CWE839_rand_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_06_good(); void CWE124_Buffer_Underwrite__CWE839_rand_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_32_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_65_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_03_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_63_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_01_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_41_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_17_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_21_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_53_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_54_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_14_good(); void CWE124_Buffer_Underwrite__CWE839_rand_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_51_good(); void CWE124_Buffer_Underwrite__CWE839_rand_03_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_22_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_14_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_15_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_16_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_13_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_07_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_42_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_41_good(); void CWE124_Buffer_Underwrite__CWE839_rand_34_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_13_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_13_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_34_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_18_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_03_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_63_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_22_good(); void CWE124_Buffer_Underwrite__CWE839_rand_67_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_65_good(); void CWE124_Buffer_Underwrite__malloc_char_cpy_08_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_52_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_66_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_01_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_08_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_11_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_15_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_32_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_05_good(); void CWE124_Buffer_Underwrite__CWE839_rand_16_good(); void CWE124_Buffer_Underwrite__CWE839_rand_44_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_68_good(); void CWE124_Buffer_Underwrite__CWE839_rand_05_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_54_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_02_good(); void CWE124_Buffer_Underwrite__CWE839_negative_21_good(); void CWE124_Buffer_Underwrite__malloc_char_memmove_21_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_65_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_53_good(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_64_good(); void CWE124_Buffer_Underwrite__CWE839_negative_10_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_11_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_44_good(); void CWE124_Buffer_Underwrite__malloc_char_loop_08_good(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_61_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_07_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_41_good(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_06_good(); /* END-AUTOGENERATED-C-GOOD-FUNCTION-DECLARATIONS */ #endif // OMITGOOD #ifndef OMITBAD /* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-DECLARATIONS */ void CWE124_Buffer_Underwrite__CWE839_negative_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_07_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_21_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_03_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_10_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_52_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_08_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_04_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_42_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_22_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_21_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_05_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_03_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_16_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_18_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_67_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_09_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_44_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_41_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_17_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_06_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_14_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_64_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_31_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_17_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_05_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_65_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_32_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_64_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_54_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_14_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_12_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_07_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_02_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_11_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_14_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_13_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_03_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_68_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_03_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_09_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_05_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_09_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_64_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_06_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_02_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_68_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_32_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_34_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_32_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_64_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_06_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_01_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_03_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_12_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_13_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_14_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_02_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_64_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_14_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_61_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_65_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_44_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_04_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_09_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_14_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_07_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_52_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_66_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_06_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_65_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_05_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_31_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_63_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_51_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_22_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_18_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_64_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_05_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_18_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_12_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_22_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_04_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_53_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_65_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_44_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_22_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_08_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_63_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_66_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_64_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_64_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_61_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_03_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_22_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_12_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_63_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_04_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_05_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_64_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_14_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_44_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_61_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_05_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_14_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_31_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_18_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_21_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_16_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_31_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_08_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_18_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_32_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_14_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_09_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_12_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_65_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_04_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_66_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_14_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_06_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_06_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_08_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_61_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_11_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_03_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_41_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_45_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_01_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_61_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_06_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_05_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_16_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_51_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_31_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_42_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_17_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_67_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_45_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_67_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_41_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_04_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_52_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_05_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_22_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_22_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_53_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_06_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_31_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_16_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_22_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_07_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_21_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_06_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_53_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_01_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_65_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_09_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_44_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_53_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_05_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_32_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_04_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_06_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_51_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_03_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_22_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_09_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_64_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_54_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_12_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_10_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_61_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_22_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_10_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_04_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_04_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_10_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_03_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_67_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_02_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_54_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_31_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_53_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_13_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_68_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_32_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_64_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_21_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_04_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_11_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_66_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_68_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_18_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_65_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_65_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_04_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_51_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_42_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_65_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_54_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_68_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_10_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_04_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_06_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_65_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_03_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_63_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_01_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_41_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_17_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_21_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_54_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_14_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_51_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_03_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_22_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_14_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_15_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_16_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_07_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_42_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_41_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_34_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_13_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_34_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_18_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_03_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_63_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_22_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_67_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_65_bad(); void CWE124_Buffer_Underwrite__malloc_char_cpy_08_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_52_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_66_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_01_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_15_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_32_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_05_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_16_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_44_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_68_bad(); void CWE124_Buffer_Underwrite__CWE839_rand_05_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_54_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_02_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_memmove_21_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_65_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_loop_53_bad(); void CWE124_Buffer_Underwrite__malloc_char_ncpy_64_bad(); void CWE124_Buffer_Underwrite__CWE839_negative_10_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_11_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_44_bad(); void CWE124_Buffer_Underwrite__malloc_char_loop_08_bad(); void CWE124_Buffer_Underwrite__malloc_char_memcpy_61_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_07_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_41_bad(); void CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_06_bad(); /* END-AUTOGENERATED-C-BAD-FUNCTION-DECLARATIONS */ #endif // OMITBAD #ifdef __cplusplus } // end extern "C" #endif #ifdef __cplusplus // declare C++ namespaces and good and bad functions #ifndef OMITGOOD /* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-DECLARATIONS */ namespace CWE124_Buffer_Underwrite__malloc_char_loop_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_81 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_81 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_72 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_73 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_73 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_83 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_81 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_74 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_74 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_83 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_43 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_72 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_43 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_33 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_84 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_82 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_83 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_73 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_84 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_rand_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_33 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_62 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_74 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_81 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_62 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_82 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_33 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_83 { void good();} namespace CWE124_Buffer_Underwrite__CWE839_negative_73 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_72 { void good();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_43 { void good();} /* END-AUTOGENERATED-CPP-GOOD-FUNCTION-DECLARATIONS */ #endif // OMITGOOD #ifndef OMITBAD /* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-DECLARATIONS */ namespace CWE124_Buffer_Underwrite__malloc_char_loop_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_81 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_72 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_73 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_74 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_83 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memmove_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_72 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_43 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_ncpy_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_84 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_82 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_83 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_cpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memcpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_84 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_rand_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_33 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_62 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_74 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_81 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_62 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_ncpy_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_cpy_82 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_33 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_loop_83 { void bad();} namespace CWE124_Buffer_Underwrite__CWE839_negative_73 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_wchar_t_memmove_72 { void bad();} namespace CWE124_Buffer_Underwrite__malloc_char_loop_43 { void bad();} /* END-AUTOGENERATED-CPP-BAD-FUNCTION-DECLARATIONS */ #endif // OMITBAD #endif // __cplusplus #endif // _TESTCASES_H
[ "35531872+tuyen1998@users.noreply.github.com" ]
35531872+tuyen1998@users.noreply.github.com
9564849eb1bb6555e761ed1d0fae47bece19060f
57c0bdd62e75990fc1821ab5cf568be478075c6d
/deprecated/SSKT/nodes_sskt_2/nodes_sskt_2.ino
14a610248e1be33cdb5a074db530e565222ba125
[ "MIT" ]
permissive
yang-sec/CAN-SessionKey
9c19702a8390a69a0787f6f33b9947d4287a6621
3435dcc33e5e9fbb262c6271ba5dc805f2a34599
refs/heads/master
2023-04-25T15:25:57.859281
2021-05-08T16:20:49
2021-05-08T16:20:49
288,497,465
4
0
null
null
null
null
UTF-8
C++
false
false
9,068
ino
//SKDC protocol, ECU nodes //Shanghao Shi //Protocol Implemention for ACSAC2020-Session key Distribution Make Practical for CAN and CAN-FD Message Authentication #include <SPI.h> #include "mcp_can.h" #include <SHA256.h> #include <GF256.h> /* PLEASE CHANGE TO SEE DIFFERENT SETUPS */ // Keep it the the same with the KS setup const int M=1; // Number of MSG IDs. Please fix M=1. const int N=2; // Number of normal ECUs with the max of 6. {2,3,4,5,6} are used in the paper. //Set CS pin const int SPI_CS_PIN = 9; MCP_CAN CAN(SPI_CS_PIN); SHA256 hash; int counter=0; uint8_t Pre_shared_key_x[16]= {0x2c,0xeb,0x89,0x11,0x5e,0x74,0xe6,0xd8,0xf6,0x8d,0xe2,0x33,0xad,0xb7,0x7b,0x4f}; uint8_t Pre_shared_key_y[16]= {0xce,0xda,0x31,0x94,0x8e,0x39,0xdd,0x10,0x4a,0xe5,0xe4,0xfb,0xcd,0x2e,0x64,0x27}; unsigned long EID[3]={0x001000, 0x002000, 0x003000}; unsigned long MID=0x000101; uint8_t flag; uint8_t epoch[8]={0,0,0,0,0,0,0,0}; uint8_t R[M][16]; uint8_t Session_key[M][16]; uint8_t List[N-1]={0xFC}; uint8_t Pre_computed_list[M][N][16]; void array_assignment(uint8_t *array_1, uint8_t *array_2, uint8_t array_len) { for(int i=0;i<array_len;i++) { array_1[i]=array_2[i]; } } uint8_t check_hmac(uint8_t new_hmac[8], unsigned long ID, uint8_t tmp_epoch[8], uint8_t R[16], uint8_t key[16]){ uint8_t tmp_hmac[8]; hash.resetHMAC(key, 16); hash.update(&ID, sizeof(ID)); hash.update(tmp_epoch, 8); hash.update(R, 16); hash.finalizeHMAC(key, 16, tmp_hmac, 8); // Serial.println("hmac:"); for(int i=0;i<8;i++) { // Serial.print(tmp_hmac[i]); // Serial.print("\t"); if(tmp_hmac[i]!=new_hmac[i]) { Serial.println("Secret MAC does not match"); return 1; break; } } Serial.println(); return 0; } //Precompute process //This part is done during CAN bus setup process, computation overhead can be significantly reduced //Details can be found in the paper void pre_compute() { uint8_t New_list[N]; array_assignment(New_list, List, N-1); for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { Serial.println("Pre_computed_list:"); for(int k=0;k<16;k++) { New_list[N-1]=Pre_shared_key_x[k]; Pre_computed_list[i][j][k]=0; for(int l=0;l<N;l++) { if(l!=j) { Pre_computed_list[i][j][k]=((Pre_computed_list[i][j][k]+GF256_Log[New_list[l]])%0xff+GF256_Log[GF256_Inv[New_list[j]^New_list[l]]])%0xff;//delete 0x01 } } Pre_computed_list[i][j][k]=GF256_Exp[Pre_computed_list[i][j][k]]; Serial.print(Pre_computed_list[i][j][k],HEX); Serial.print("\t"); } Serial.println(); } } } uint8_t recover_session_key( uint8_t Pre_computed_list[N][16], uint8_t Pre_shared_secret_y[16], uint8_t R[16], uint8_t points[N-1][16], unsigned long can_ID, uint8_t epoch[8], uint8_t MAC[8], uint8_t Session_key[16]) { uint8_t New_MAC[8]; for(int i=0;i<16;i++) { // Interpolation with pre-computed Lagrange coeffs Session_key[i]=0; for(int j=0;j<N;j++) { if(j!=(N-1)) { Session_key[i]=Session_key[i]^GF256_Exp[(GF256_Log[points[j][i]]+GF256_Log[Pre_computed_list[j][i]])%0xff]; } else { Session_key[i]=Session_key[i]^GF256_Exp[(GF256_Log[Pre_shared_secret_y[i]^R[i]]+GF256_Log[Pre_computed_list[j][i]])%0xff]; } } } // Check MAC. MAC of KDMSG: hash(session key|mid|epoch) hash.reset(); hash.update(Session_key, 16); hash.update(&can_ID, sizeof(can_ID)); hash.update(epoch, 8); hash.finalize(New_MAC,8); for(int b=0;b<8;b++) { if(New_MAC[b]!=MAC[b]) { // Serial.println("KDMSG MAC does not match"); return 1; } } return 0; } void send_message_back(uint8_t flag, uint8_t Session_key[M][16], uint8_t epoch[8], int e) { uint8_t MAC[8]; unsigned long re_ID = 0x010000 + EID[e]; hash.reset(); hash.update(&re_ID, 4); // Serial.print("send_message_back epoch: "); // for(int l=0;l<8;l++) // { // Serial.print(epoch[l]); // } hash.update(epoch, 8); // Serial.println(); if(flag==0) { for(int s=0; s<M; s++) { // Serial.println("Session key:"); // for(int l=0;l<16;l++) // { // Serial.print(Session_key[s][l],HEX); // Serial.print("\t"); // } // Serial.println(); hash.update(Session_key[s], 16); } hash.finalize(MAC,8); CAN.sendMsgBuf(re_ID, 1, 8, epoch); // delay(200); CAN.sendMsgBuf(re_ID, 1, 8, MAC); } else { hash.finalize(MAC,8); CAN.sendMsgBuf(re_ID, 1, 8, epoch); //delay(200); CAN.sendMsgBuf(re_ID, 1, 8, MAC); } } //uint8_t check_MAC(unsigned long can_ID, uint8_t epoch[8], uint8_t points[N-1][16], uint8_t MAC[8]){ // uint8_t New_MAC[8]; // hash.reset(); // hash.update(&can_ID, sizeof(can_ID)); // hash.update(epoch, 8); // for(int i=0;i<N-1; i++){ // hash.update(points[i], 16); // } // hash.finalize(New_MAC,8); // for(int i=0;i<8;i++){ // if(New_MAC[i]!=MAC[i]){ // return 1; // } // } // return 0; // } void setup() { Serial.begin(115200); while (CAN_OK != CAN.begin(CAN_500KBPS)) { // init can bus : baudrate = 500k Serial.println("CAN BUS Shield init fail"); Serial.println("Init CAN BUS Shield again"); delay(100); } //Initilize Masks and Filters //Different ECU nodes need different Masks and Filters initilization to receive different message CAN.init_Mask(0, 1, 0x1fffff00); CAN.init_Mask(1, 1, 0x1fffff00); CAN.init_Filt(0, 1, MID); // The MID for KDMSG CAN.init_Filt(1, 1, EID[0]+1); // For PRMSG CAN.init_Filt(2, 1, EID[1]+1); CAN.init_Filt(3, 1, EID[2]+1); Serial.println("CAN BUS Shield init ok!"); Serial.println(); epoch[7]=1; pre_compute(); // Serial.println("epoch"); // for(int i=0;i<8;i++){ // Serial.print(epoch[i]); // Serial.print("\t"); // } // Serial.println(); counter=0; } void loop() { uint8_t len = 8; uint8_t buf[8]; unsigned long canId; if (CAN_MSGAVAIL == CAN.checkReceive()) {// check if data coming CAN.readMsgBuf(&len, buf); // read data canId = CAN.getCanId(); // Serial.print("------- Get data from ID: 0x"); // Serial.println(canId, HEX); // for (int i = 0; i < len; i++) { // print the data // Serial.print(buf[i],HEX); // Serial.print("\t"); // } // Serial.println(); for(int m=0;m<M;m++) { if(counter==4*m+0) { uint8_t tmp_epoch[8]; array_assignment(tmp_epoch,buf,8); if(tmp_epoch[7]!=epoch[7]) { flag=1; } } else if(counter==4*m+1) { array_assignment(R[m],buf,8); } else if(counter==4*m+2) { array_assignment(&R[m][8],buf,8); } else if(counter==4*m+3) { uint8_t new_hmac[8]; array_assignment(new_hmac,buf,8); flag=check_hmac(new_hmac,canId,epoch,R[m],Pre_shared_key_x); // Serial.println("R:"); // for(int b=0;b<16;b++){ // Serial.print(R[m][b]); // Serial.print("\t"); // } // Serial.println(); } } // Serial.println("--------------------------------------------------------"); for(int j=0;j<M;j++) { uint8_t points[N-1][16]; uint8_t MAC[8]; if(counter==4*M-1+1+2*N*j) { uint8_t tmp_epoch[8]; array_assignment(tmp_epoch,buf,8); if(tmp_epoch[7]!=epoch[7]) { flag=1; } } for(int k=0;k<N-1;k++) { if(counter==4*M+1+2*k+2*N*j) { array_assignment(points[k],buf,8); } if(counter==4*M+2+2*k+2*N*j) { array_assignment(&points[k][8],buf,8); } } if(counter==4*M+2*N-1+2*N*j) { array_assignment(MAC,buf,8); flag=recover_session_key(Pre_computed_list[j], Pre_shared_key_y, R[j], points, canId, epoch, MAC, Session_key[j]); // Serial.println("counter:"); // Serial.println(counter); counter++; if(counter==4*M+2*N+2*N*(M-1)) { for(int repeat=0;repeat<7;repeat++) { send_message_back(flag,Session_key,epoch,0); delay(1); } counter=0; for(int m=0;m<M;m++) { Serial.print("Session key obtained:\t"); for(int b=0;b<16;b++) { Serial.print(Session_key[m][b], HEX); Serial.print("\t"); } Serial.println(); } } // Serial.println(flag); } } //END FILE
[ "yangshaw@umich.edu" ]
yangshaw@umich.edu
755f3f5aea9114bfbc59fa6052019be6c110149a
931f59b124ded93b002158a699474369f3ced983
/Application/Application/Main.cpp
d5ea988fd3455ee383c9b8380d99181dadfe3347
[]
no_license
CS340GroupFour/CabAndWeather
e0af8817d807a3ff2253fb6da2d59a8865e8a647
8be4194a53a98066052ab80bfbc7fc6cf6d8dc90
refs/heads/main
2023-05-10T14:02:02.004855
2021-05-26T01:57:58
2021-05-26T01:57:58
354,462,885
0
0
null
null
null
null
UTF-8
C++
false
false
4,790
cpp
#include "sortWeather.h" #include "sortCab.h" #include "cabAndWeather.h" #include "UserInterface.h" #include <string> #include <vector> #include <iostream> ostream & operator<< (ostream& out, const Cabs& c) { out << c.getDistance() << " " << c.getTime() << " " << c.getCabBrand() << " " << c.getCityDest() << "" << c.getCitySource() << " " << c.getPrice() << " " << c.getSurgeMultiplier() << " " << c.getIdentifier() << " " << c.getProdId() << " " << c.getCabType() << endl; return out; } ostream & operator<< (ostream& out, const Weather& w) { out << w.getTemperature() << " " << w.getLocation() << " " << w.getClouds() << " " << w.getPressure() << " " << w.getRain() << " " << w.getWtime() << " " << w.getHumidity() << " " << w.getWind() << endl; return out; } ostream & operator<< (ostream& out, const cabAndWeather& x) { out << " " << x.getDistance() << " " << x.getXtimes() << " " << x.getSourceLocation() << " " << x.getXcabBrand() << " " << x.getXcabType() << " " << x.getXrain() << " " << x.getXprice() << endl; return out; } void cabIter(vector<Cabs> const &a ){ cout << "Uber Price: " << endl; for(const auto & i : a){ cout << i << endl; } } void weatherIter(vector<Weather> const &a ){ cout << "Weather: " << endl; for(const auto & i : a){ cout << i << endl; } } void xcabWeatherIter(vector<cabAndWeather> const &a ){ cout << "Cabs And Weather " << endl; for(const auto & i : a){ cout << i << endl; } } void getCab(vector<Cabs>& cabRides, vector<Cabs>& onlyUber, vector<Cabs>& onlyLyft){ ifstream myfile1; myfile1.open("cab_rides.csv", ios::in); if(!myfile1.is_open()){ cout << "You're a failure"; } string line; int lineCount = 0; getline(myfile1, line); // ignore header line while (getline(myfile1, line) && !line.empty()) { sortCabComputation::sortCab(cabRides, onlyUber, onlyLyft, line, lineCount); } } void getWeather(vector<Weather>& weather, vector<Weather>& badWeather, vector<Weather>& goodWeather){ ifstream myfile2; myfile2.open("weather.csv", ios::in); if(!myfile2.is_open()){ cout << "You're a failure"; } string line1; int lineCount1 = 0; getline(myfile2, line1); // ignore header line while (getline(myfile2, line1) && !line1.empty()) { sortWeatherComputation::sortWeather(weather, badWeather, goodWeather, line1, lineCount1); } } void fusionCabWeather(vector<Cabs>& cabV, vector<Weather>& weatherV, vector<cabAndWeather>& cabXweather){ cabAndWeather collX; cabXweather.clear(); if(cabXweather.empty()) { for (int i = 0; i < cabV.size(); i++) { for (int j = 0; j < weatherV.size(); j++) { if (cabV[i].getTime() == weatherV[j].getWtime() && cabV[i].getCitySource() == weatherV[j].getLocation()) { collX.setDistance(cabV[i].getDistance()); collX.setXcabType(cabV[i].getCabType()); collX.setXcabBrand(cabV[i].getCabBrand()); collX.setXprice(cabV[i].getPrice()); collX.setXrain(weatherV[j].getRain()); collX.setXtimes(weatherV[j].getWtime()); collX.setSourceLocation(weatherV[j].getLocation()); cabXweather.push_back(collX); } } } } } int main() { std::vector<Cabs> cabRides; std::vector<Cabs> onlyUber; std::vector<Cabs> onlyLyft; std::vector<Weather> weather; std::vector<Weather> badWeather; std::vector<Weather> goodWeather; std::vector<cabAndWeather> xCabAndWeather; std::vector<cabAndWeather> cabBad; std::vector<cabAndWeather> cabGood; getCab(cabRides, onlyUber, onlyLyft); getWeather(weather, badWeather, goodWeather); //FIXME: Depends on user input - must fix based on case // fusionCabWeather(); char userOption; UserInterface ui(cabRides, onlyUber, onlyLyft, cabGood, cabBad); ui.WelcomeAndIntroduce(); userOption = ui.PrintMenu(ui.introOptions); ui.CallMainMenuFunction(userOption); /* fusionCabWeather(cabRides, badWeather, cabBad); fusionCabWeather(cabRides, goodWeather, cabGood); fusionCabWeather(cabRides, weather, xCabAndWeather); fusionCabWeather(onlyLyft, badWeather, cabBad); fusionCabWeather(onlyLyft, goodWeather, cabBad); fusionCabWeather(onlyLyft, weather, xCabAndWeather); fusionCabWeather(onlyUber, badWeather, cabGood); fusionCabWeather(onlyUber, goodWeather, cabGood); fusionCabWeather(onlyUber, weather, xCabAndWeather); */ //cabIter(cabRides); //weatherIter(weather); //xcabWeatherIter(xCabAndWeather); }
[ "noreply@github.com" ]
CS340GroupFour.noreply@github.com
1580a55432b9293e641e959107c7b439053c60bf
d79508660fa6ce1199a6a0c42c021f68d0a2fe1d
/Game/src/Box.h
98f299b9426a8a882fc20f37c98e5fe62e52eb29
[ "CC0-1.0" ]
permissive
DanielParra159/EngineAndGame
702ddd14bf15d4387046837e506b10eb837dda27
45af7439633054aa6c9a8e75dd0453f9ce297626
refs/heads/master
2020-04-04T16:40:34.796899
2017-11-25T21:52:56
2017-11-25T21:52:56
62,506,317
1
0
null
null
null
null
UTF-8
C++
false
false
832
h
#ifndef _GAME_BOX_H_ #define _GAME_BOX_H_ #include "Types.h" #include "Logic/IGameObject.h" namespace graphics { class Mesh; } namespace game { class Box : public logic::IGameObject { public: enum eBoxType { eWall, eCoin }; private: eBoxType mBoxType; public: Box() : IGameObject(){} virtual ~Box() {} virtual void Init(eBoxType aBoxType, BOOL aActive, const Vector3D<float32> aPosition, const Vector3D<float32> aBoxSize, const Vector3D<float32> aRotationOffset, const float32 lWallVertexData[], uint32 aSize); virtual void Update(); virtual void PrepareToRender(); virtual void Release(); private: void OnTriggerEnter(physics::Collider* aOther); }; // Box } // namespace game #endif // _GAME_BOX_H_
[ "dani.parra.90@gmail.com" ]
dani.parra.90@gmail.com
cf9a17af482d53f5d72aaec8f13afe812ec06bad
758184348fc9c09bd021dbf318bb6859640b06d4
/02/BetterFraming.cpp
7e1421f5aec532641560a704320a10718b279989
[]
no_license
limkokholefork/AcceleratedCPP
716c275c493dbf59ce4af467cf9fe5ba1cfa5104
735af96fed0c1baef6c84649f8d3ac426c82d3f9
refs/heads/master
2021-11-10T15:46:27.778544
2016-05-10T14:15:07
2016-05-10T14:15:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,853
cpp
// solution to 2-4 #include <iostream> #include <string> // say what standard-library names we use using std::cin; using std::cout; using std::endl; using std::string; int main() { // ask for the person's name cout << "Please enter your first name: "; // read the name string name; cin >> name; // build the message that we intend to write const string greeting = "Hello, " + name + "!"; // the number of blanks surrounding the greeting const int pad = 2; // the number of rows and the number of columns to write const int rows = pad * 2 + 3; const string::size_type cols = greeting.size() + pad * 2 + 2; // write a blank line to separate the output from the input cout << endl; // write 'rows' rows of input // invariant: we have written r rows so far for (int r = 0; r != rows; ++r) { string::size_type c = 0; // invariant: we have written c characters so far in the current rows while (c != cols) { // is it time to write the greeting? if (r == pad + 1 && c == pad + 1) { cout << greeting; c += greeting.size(); // are we on the border? } else if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) { cout << "*"; ++c; } else { string::size_type n; // Are we writing a lot of spaces? if (r != pad + 1) n = greeting.size() + 2 * pad; // or just one? else n = 1; cout << string(n, ' '); c += n; } } cout << endl; } return 0; }
[ "smshdwll@gmail.com" ]
smshdwll@gmail.com
01d6ce0a26b21fbca1d08c074faf23398aed2661
ccf2b344aac357dcdb7bf8e6be6b0791080d9d96
/externals/sfzCore/include/sfz/math/Matrix.hpp
7118172ed8ac2dc8bfbcc7d030590a21d9febc2b
[ "LicenseRef-scancode-khronos", "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
ambigeV/Linear-Genetic-Programming-Cuda
fa087fb5033db490299d9477459af749ce5d629a
8d078318d240993619c01126905a821bbf0a9d23
refs/heads/master
2020-04-28T00:43:07.226540
2017-02-19T09:15:29
2017-02-19T09:15:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,015
hpp
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #pragma once #include <cstdint> #include "sfz/Assert.hpp" #include "sfz/math/Vector.hpp" #include "sfz/CudaCompatibility.hpp" #include "sfz/SimdIntrinsics.hpp" namespace sfz { using std::int32_t; using std::uint32_t; // Matrix struct declaration // ------------------------------------------------------------------------------------------------ /// A mathematical Matrix POD class that imitates a built-in primitive. /// /// Uses row-major memory storage. Assumes vectors are column matrices, i.e. normal standard math /// syntax. When uploading to OpenGL it needs to be transposed as OpenGL uses column-major storage. /// OpenGL also assumes that vectors are column matrices, so only the storage layout is different. /// This should not be confused with Direct3D which often assumes that vectors are row matrices. /// When two indices are used the first one is always used to specify row (i.e. y-direction) and /// the second one is used to specify column (i.e. x-direction). /// /// The template is designed to be used with 32-bit floating points, other types may work, but no /// guarantees are given. /// /// Satisfies the conditions of std::is_pod, std::is_trivial and std::is_standard_layout if used /// with float. /// /// \param T the element type (float) /// \param H the height (i.e. the amount of rows) of the Matrix /// \param W the width (i.e. the amount of columns) of the Matrix template<typename T, uint32_t H, uint32_t W> struct Matrix final { Vector<T,W> rows[H]; SFZ_CUDA_CALL T* data() noexcept { return &rows[0][0]; } SFZ_CUDA_CALL const T* data() const noexcept { return &rows[0][0]; } Matrix() noexcept = default; Matrix(const Matrix<T,H,W>&) noexcept = default; Matrix<T,H,W>& operator= (const Matrix<T,H,W>&) noexcept = default; ~Matrix() noexcept = default; /// Constructs a matrix with the elements in an array (assumes array is in row-major order) SFZ_CUDA_CALL explicit Matrix(const T* arrayPtr) noexcept; SFZ_CUDA_CALL T& at(uint32_t y, uint32_t x) noexcept { return rows[y][x]; } SFZ_CUDA_CALL T at(uint32_t y, uint32_t x) const noexcept { return rows[y][x]; } SFZ_CUDA_CALL Vector<T,H> columnAt(uint32_t x) const noexcept; SFZ_CUDA_CALL void set(uint32_t y, uint32_t x, T value) noexcept { this->at(y, x) = value; } SFZ_CUDA_CALL void setColumn(uint32_t x, Vector<T,H> column) noexcept; }; template<typename T> struct Matrix<T,2,2> final { union { struct { Vector<T,2> rows[2]; }; struct { Vector<T,2> row0, row1; }; struct { T e00, e01, e10, e11; }; }; SFZ_CUDA_CALL T* data() noexcept { return &e00; } SFZ_CUDA_CALL const T* data() const noexcept { return &e00; } Matrix() noexcept = default; Matrix(const Matrix<T,2,2>&) noexcept = default; Matrix<T,2,2>& operator= (const Matrix<T,2,2>&) noexcept = default; ~Matrix() noexcept = default; /// Constructs a matrix with the elements in an array (assumes array is in row-major order) SFZ_CUDA_CALL explicit Matrix(const T* arrayPtr) noexcept; SFZ_CUDA_CALL Matrix(T e00, T e01, T e10, T e11) noexcept; SFZ_CUDA_CALL Matrix(Vector<T,2> row0, Vector<T,2> row1) noexcept; static SFZ_CUDA_CALL Matrix fill(T value) noexcept; static SFZ_CUDA_CALL Matrix identity() noexcept; static SFZ_CUDA_CALL Matrix scaling2(T scale) noexcept; static SFZ_CUDA_CALL Matrix scaling2(T x, T y) noexcept; static SFZ_CUDA_CALL Matrix scaling2(Vector<T,2> scale) noexcept; SFZ_CUDA_CALL T& at(uint32_t y, uint32_t x) noexcept { return rows[y][x]; } SFZ_CUDA_CALL T at(uint32_t y, uint32_t x) const noexcept { return rows[y][x]; } SFZ_CUDA_CALL Vector<T,2> columnAt(uint32_t x) const noexcept; SFZ_CUDA_CALL void set(uint32_t y, uint32_t x, T value) noexcept { this->at(y, x) = value; } SFZ_CUDA_CALL void setColumn(uint32_t x, Vector<T,2> column) noexcept; }; template<typename T> struct Matrix<T,3,3> final { union { struct { Vector<T,3> rows[3]; }; struct { Vector<T,3> row0, row1, row2; }; struct { T e00, e01, e02, e10, e11, e12, e20, e21, e22; }; }; SFZ_CUDA_CALL T* data() noexcept { return &e00; } SFZ_CUDA_CALL const T* data() const noexcept { return &e00; } Matrix() noexcept = default; Matrix(const Matrix<T,3,3>&) noexcept = default; Matrix<T,3,3>& operator= (const Matrix<T,3,3>&) noexcept = default; ~Matrix() noexcept = default; /// Constructs a matrix with the elements in an array (assumes array is in row-major order) SFZ_CUDA_CALL explicit Matrix(const T* arrayPtr) noexcept; SFZ_CUDA_CALL Matrix(T e00, T e01, T e02, T e10, T e11, T e12, T e20, T e21, T e22) noexcept; SFZ_CUDA_CALL Matrix(Vector<T,3> row0, Vector<T,3> row1, Vector<T,3> row2) noexcept; /// Constructs a 3x3 matrix by removing elements from the specified matrix SFZ_CUDA_CALL explicit Matrix(const Matrix<T,3,4>& matrix) noexcept; SFZ_CUDA_CALL explicit Matrix(const Matrix<T,4,4>& matrix) noexcept; static SFZ_CUDA_CALL Matrix fill(T value) noexcept; static SFZ_CUDA_CALL Matrix identity() noexcept; static SFZ_CUDA_CALL Matrix scaling3(T scale) noexcept; static SFZ_CUDA_CALL Matrix scaling3(T x, T y, T z) noexcept; static SFZ_CUDA_CALL Matrix scaling3(Vector<T,3> scale) noexcept; static SFZ_CUDA_CALL Matrix rotation3(Vector<T,3> axis, T angleRad) noexcept; SFZ_CUDA_CALL T& at(uint32_t y, uint32_t x) noexcept { return rows[y][x]; } SFZ_CUDA_CALL T at(uint32_t y, uint32_t x) const noexcept { return rows[y][x]; } SFZ_CUDA_CALL Vector<T,3> columnAt(uint32_t x) const noexcept; SFZ_CUDA_CALL void set(uint32_t y, uint32_t x, T value) noexcept { this->at(y, x) = value; } SFZ_CUDA_CALL void setColumn(uint32_t x, Vector<T,3> column) noexcept; }; template<typename T> struct alignas(16) Matrix<T,3,4> final { union { struct { Vector<T,4> rows[3]; }; struct { Vector<T,4> row0, row1, row2; }; struct { T e00, e01, e02, e03, e10, e11, e12, e13, e20, e21, e22, e23; }; }; SFZ_CUDA_CALL T* data() noexcept { return &e00; } SFZ_CUDA_CALL const T* data() const noexcept { return &e00; } Matrix() noexcept = default; Matrix(const Matrix<T,3,4>&) noexcept = default; Matrix<T,3,4>& operator= (const Matrix<T,3,4>&) noexcept = default; ~Matrix() noexcept = default; /// Constructs a matrix with the elements in an array (assumes array is in row-major order) SFZ_CUDA_CALL explicit Matrix(const T* arrayPtr) noexcept; SFZ_CUDA_CALL Matrix(T e00, T e01, T e02, T e03, T e10, T e11, T e12, T e13, T e20, T e21, T e22, T e23) noexcept; SFZ_CUDA_CALL Matrix(Vector<T,4> row0, Vector<T,4> row1, Vector<T,4> row2) noexcept; /// Constructs a 3x4 matrix by placing the specified matrix ontop a 3x4 identity-like matrix. SFZ_CUDA_CALL explicit Matrix(const Matrix<T,3,3>& matrix) noexcept; SFZ_CUDA_CALL explicit Matrix(const Matrix<T,4,4>& matrix) noexcept; static SFZ_CUDA_CALL Matrix fill(T value) noexcept; static SFZ_CUDA_CALL Matrix identity() noexcept; // Identity-like, identity does not exist for 3x4. static SFZ_CUDA_CALL Matrix scaling3(T scale) noexcept; static SFZ_CUDA_CALL Matrix scaling3(T x, T y, T z) noexcept; static SFZ_CUDA_CALL Matrix scaling3(Vector<T,3> scale) noexcept; static SFZ_CUDA_CALL Matrix rotation3(Vector<T,3> axis, T angleRad) noexcept; static SFZ_CUDA_CALL Matrix translation3(Vector<T,3> delta) noexcept; SFZ_CUDA_CALL T& at(uint32_t y, uint32_t x) noexcept { return rows[y][x]; } SFZ_CUDA_CALL T at(uint32_t y, uint32_t x) const noexcept { return rows[y][x]; } SFZ_CUDA_CALL Vector<T,3> columnAt(uint32_t x) const noexcept; SFZ_CUDA_CALL void set(uint32_t y, uint32_t x, T value) noexcept { this->at(y, x) = value; } SFZ_CUDA_CALL void setColumn(uint32_t x, Vector<T,3> column) noexcept; }; template<typename T> struct alignas(16) Matrix<T,4,4> final { union { struct { Vector<T,4> rows[4]; }; struct { Vector<T,4> row0, row1, row2, row3; }; struct { T e00, e01, e02, e03, e10, e11, e12, e13, e20, e21, e22, e23, e30, e31, e32, e33; }; }; SFZ_CUDA_CALL T* data() noexcept { return &e00; } SFZ_CUDA_CALL const T* data() const noexcept { return &e00; } Matrix() noexcept = default; Matrix(const Matrix<T,4,4>&) noexcept = default; Matrix<T,4,4>& operator= (const Matrix<T,4,4>&) noexcept = default; ~Matrix() noexcept = default; /// Constructs a matrix with the elements in an array (assumes array is in row-major order) SFZ_CUDA_CALL explicit Matrix(const T* arrayPtr) noexcept; SFZ_CUDA_CALL Matrix(T e00, T e01, T e02, T e03, T e10, T e11, T e12, T e13, T e20, T e21, T e22, T e23, T e30, T e31, T e32, T e33) noexcept; SFZ_CUDA_CALL Matrix(Vector<T,4> row0, Vector<T,4> row1, Vector<T,4> row2, Vector<T,4> row3) noexcept; /// Constructs a 4x4 matrix by placing the specified matrix ontop a 4x4 identity matrix. SFZ_CUDA_CALL explicit Matrix(const Matrix<T,3,3>& matrix) noexcept; SFZ_CUDA_CALL explicit Matrix(const Matrix<T,3,4>& matrix) noexcept; static SFZ_CUDA_CALL Matrix fill(T value) noexcept; static SFZ_CUDA_CALL Matrix identity() noexcept; static SFZ_CUDA_CALL Matrix scaling3(T scale) noexcept; // Note that the bottom right corner is 1 for 4x4 static SFZ_CUDA_CALL Matrix scaling3(T x, T y, T z) noexcept; // Note that the bottom right corner is 1 for 4x4 static SFZ_CUDA_CALL Matrix scaling3(Vector<T,3> scale) noexcept; // Note that the bottom right corner is 1 for 4x4 static SFZ_CUDA_CALL Matrix rotation3(Vector<T,3> axis, T angleRad) noexcept; static SFZ_CUDA_CALL Matrix translation3(Vector<T,3> delta) noexcept; SFZ_CUDA_CALL T& at(uint32_t y, uint32_t x) noexcept { return rows[y][x]; } SFZ_CUDA_CALL T at(uint32_t y, uint32_t x) const noexcept { return rows[y][x]; } SFZ_CUDA_CALL Vector<T,4> columnAt(uint32_t x) const noexcept; SFZ_CUDA_CALL void set(uint32_t y, uint32_t x, T value) noexcept { this->at(y, x) = value; } SFZ_CUDA_CALL void setColumn(uint32_t x, Vector<T,4> column) noexcept; }; using mat22 = Matrix<float,2,2>; using mat33 = Matrix<float,3,3>; using mat34 = Matrix<float,3,4>; using mat44 = Matrix<float,4,4>; using mat2 = mat22; using mat3 = mat33; using mat4 = mat44; static_assert(sizeof(mat22) == sizeof(float) * 2 * 2, "mat22 is padded"); static_assert(sizeof(mat33) == sizeof(float) * 3 * 3, "mat33 is padded"); static_assert(sizeof(mat34) == sizeof(float) * 3 * 4, "mat34 is padded"); static_assert(sizeof(mat44) == sizeof(float) * 4 * 4, "mat44 is padded"); // Matrix functions // ------------------------------------------------------------------------------------------------ /// Element-wise multiplication of two matrices template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> elemMult(const Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,W,H> transpose(const Matrix<T,H,W>& m) noexcept; template<typename T> SFZ_CUDA_CALL Vector<T,3> transformPoint(const Matrix<T,3,4>& m, const Vector<T,3>& p) noexcept; template<typename T> SFZ_CUDA_CALL Vector<T,3> transformPoint(const Matrix<T,4,4>& m, const Vector<T,3>& p) noexcept; template<typename T> SFZ_CUDA_CALL Vector<T,3> transformDir(const Matrix<T,3,4>& m, const Vector<T,3>& d) noexcept; template<typename T> SFZ_CUDA_CALL Vector<T,3> transformDir(const Matrix<T,4,4>& m, const Vector<T,3>& d) noexcept; template<typename T, uint32_t N> SFZ_CUDA_CALL T determinant(const Matrix<T,N,N>& m) noexcept; template<typename T, uint32_t N> SFZ_CUDA_CALL Matrix<T,N,N> inverse(const Matrix<T,N,N>& m) noexcept; // Operators (arithmetic & assignment) // ------------------------------------------------------------------------------------------------ template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W>& operator+= (Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W>& operator-= (Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W>& operator*= (Matrix<T,H,W>& lhs, T rhs) noexcept; template<typename T, uint32_t N> SFZ_CUDA_CALL Matrix<T,N,N>& operator*= (Matrix<T,N,N>& lhs, const Matrix<T,N,N>& rhs) noexcept; // Operators (arithmetic) // ------------------------------------------------------------------------------------------------ template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator+ (const Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator- (const Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator- (const Matrix<T,H,W>& matrix) noexcept; template<typename T, uint32_t H, uint32_t S, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator* (const Matrix<T,H,S>& lhs, const Matrix<T,S,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Vector<T,H> operator* (const Matrix<T,H,W>& lhs, const Vector<T,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator* (const Matrix<T,H,W>& lhs, T rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL Matrix<T,H,W> operator* (T lhs, const Matrix<T,H,W>& rhs) noexcept; // Operators (comparison) // ------------------------------------------------------------------------------------------------ template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL bool operator== (const Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; template<typename T, uint32_t H, uint32_t W> SFZ_CUDA_CALL bool operator!= (const Matrix<T,H,W>& lhs, const Matrix<T,H,W>& rhs) noexcept; } // namespace sfz #include "sfz/math/Matrix.inl"
[ "peter@hstroem.se" ]
peter@hstroem.se
da654647c16c6ba94eabe4ed28365db04dca849e
46895d63002f3ca7d2e37c9654aea5b145225c8b
/FYP - Comparison between two AI/FYP - Comparison between two AI/Track.cpp
83a785b1dc5aca20824fefe1ebc9eeb8d3e8e5bc
[]
no_license
ClionaHayden/FYP-AIComparision
b08c11340c4ec59bef9d8e83fc3e10fc56b7a472
039efa6ce65be9ab88995018d8fb9a0d50bedffd
refs/heads/main
2023-04-22T02:49:59.693256
2021-05-04T16:41:17
2021-05-04T16:41:17
310,625,184
0
0
null
null
null
null
UTF-8
C++
false
false
17,483
cpp
#include "Track.h" #define PI 3.14159265359 Track::Track() : m_drawBoundry{ false }, m_car{ Vector2f(100.0f, 450.0f), 50.0f }, m_ReinforcementCar{ Vector2f(150.0f, 450.0f), 50.0f }, m_inputTimer{ seconds(1) }, m_lap{ false }, m_lapNum{ 0 }, m_raycastTime(seconds(0.1)), m_colisionTimer(Time::Zero) { setup(); } Track::~Track() { } void Track::update(Time t_deltaTime) { m_colisionTimer += t_deltaTime; if (m_inputTimer > m_raycastTime) { raycast(); m_inputTimer = Time::Zero; } m_car.handleInput(m_inputs); m_car.update(t_deltaTime, m_checkpoints.at(m_car.getCpNum()).getPos()); m_inputTimer += t_deltaTime; if (s_gameState == GameState::LoadWeights) { //m_raycastTime = seconds(0.7); m_ReinforcementCar.handleInput(m_inputs); m_ReinforcementCar.update(t_deltaTime, m_checkpoints.at(m_car.getCpNum()).getPos()); pair<vector<float>, bool> eval = m_brain->Evaluate(m_inputs,false); if (!eval.second) { vector<float> outputs = eval.first; m_car.processOutputs(outputs); m_car.update(t_deltaTime, m_checkpoints.at(m_car.getCpNum()).getPos()); } eval = m_brain->Evaluate(m_ReinforcementInputs, true); if (!eval.second) { vector<float> outputs = eval.first; m_ReinforcementCar.processOutputs(outputs); m_ReinforcementCar.update(t_deltaTime,m_checkpoints.at(m_car.getCpNum()).getPos()); } } else if (s_gameState == GameState::Reinforcement) { pair<vector<float>, bool> eval = m_brain->Evaluate(m_inputs,false); vector<float> outputs = eval.first; m_car.processOutputs(outputs); m_car.update(t_deltaTime, m_checkpoints.at(m_car.getCpNum()).getPos()); m_brain->m_PastReinforcementscore = m_brain->m_Reinforcementscore; m_brain->m_Reinforcementscore = calculateReinforcmentScore(); if(m_brain->m_PastReinforcementscore > m_brain->m_Reinforcementscore) { m_brain->adjustWeights(outputs); m_car.reset(); for (Checkpoint c : m_checkpoints) { c.setPassed(false); } m_brain->m_Reinforcementscore = -100000; m_brain->m_PastReinforcementscore = -10000; } } checkCarCollision(); } void Track::render(RenderWindow& t_window) { t_window.draw(m_sprite); if (s_gameState == GameState::Reinforcement) { t_window.draw(m_instructionsText); } if (m_drawBoundry) { for (Boundry b : m_boundries) { b.draw(t_window); } for (Checkpoint c : m_checkpoints) { c.draw(t_window); } for (CircleShape c : m_colCirc) { t_window.draw(c); } for (CircleShape c : m_colCircReinforcment) { t_window.draw(c); } } m_car.render(t_window, m_drawBoundry); sf::VertexArray line(sf::LinesStrip, 2); line[0].position = m_car.getPos(); line[0].color = sf::Color::Black; line[1].position = m_checkpoints.at(m_car.getCpNum()).getPos(); line[1].color = sf::Color::Black; t_window.draw(line); if (s_gameState == GameState::LoadWeights) { m_ReinforcementCar.render(t_window, m_drawBoundry); } } void Track::handleInput(Event& e) { if (Keyboard::isKeyPressed(Keyboard::T)) { m_car.m_test = true; } if (m_inputTimer.asSeconds() > 0.1) { if (sf::Keyboard::B == e.key.code) { if (m_drawBoundry) { m_drawBoundry = false; } else { m_drawBoundry = true; } } m_inputTimer = sf::Time::Zero; } if (s_gameState == GameState::Reinforcement) { if (Keyboard::isKeyPressed(Keyboard::BackSpace)) { s_gameState = GameState::MainMenu; m_car.reset(); } } } void Track::setup() { setupText(); if (!m_tex.loadFromFile("ASSETS/track2.png")) { std::cout << "ERROR - Unable to laod track sprite" << std::endl; } m_sprite.setTexture(m_tex); m_car.changeColor(Color::Cyan); m_ReinforcementCar.changeColor(Color::Red); setupBoundries(); setupCheckpoints(); m_brain = make_shared<Brain>(); for (int i = 0; i < m_brain->numInputs; i++) { m_inputs.push_back(0); m_ReinforcementInputs.push_back(0); } for (int i = 0; i < 5; i++) { CircleShape c; c.setRadius(5); c.setFillColor(Color::Blue); c.setOrigin(c.getRadius(), c.getRadius()); m_colCirc.push_back(c); m_colCircReinforcment.push_back(c); } } void Track::setupText() { if (!m_font.loadFromFile("ASSETS/FONT/font.ttf")) cout << "Error loading font" << endl; m_instructionsText.setFont(m_font); m_instructionsText.setString("Instructions \nS - save weights \nBackspace - Return to Main Menu"); m_instructionsText.setFillColor(Color::White); m_instructionsText.setPosition(Vector2f(300.0f, 500.0f)); m_instructionsText.setCharacterSize(50); } float Track::calculateReinforcmentScore() { m_brain->m_PastReinforcementscore = m_brain->m_Reinforcementscore; float score = 0; score = lengthOfLine(m_checkpoints[m_car.getCpNum()].getPos(), m_car.getPos()) + 80; int nextcp = m_car.getCpNum() + 1; for (int i = m_car.getCpNum(); i < m_checkpoints.size(); i++) { score += lengthOfLine(m_checkpoints[i].getPos(), m_checkpoints[nextcp].getPos()); nextcp++; if (nextcp >= m_checkpoints.size()) break; } return (1000 - score) / 10000; } void Track::setupBoundries() { for (int i = 0; i < boundryData2::MAX_ENTRIES; i++) { Boundry temp(m_boundryData2.m_pos[i], m_boundryData2.m_size[i], m_boundryData2.m_rotation[i]); if (m_boundryData2.m_rotation[i] != 0.0f) { temp.setOrigin(Vector2f(m_boundryData2.m_size[i].x / 2.0f, m_boundryData2.m_size[i].y / 2.0f)); } m_boundries.push_back(temp); } } void Track::setupCheckpoints() { for (int i = 0; i < CheckpointData2::MAX_ENTRIES; i++) { Checkpoint temp(m_checkpointData2.m_pos[i], m_checkpointData2.m_size[i]); temp.setOrigin(Vector2f(m_checkpointData2.m_size[i].x / 2.0f, m_checkpointData2.m_size[i].y / 2.0f)); m_checkpoints.push_back(temp); } } void Track::checkCarCollision() { //-------------------- // Backprop Car //-------------------- for (Boundry b : m_boundries) { int inputNum = 0; for (int i = 0; i < m_car.getColLines().size(); i++) { // add inputs to neural network Vector2f c = m_car.getColLines().at(i); bool left = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, true); bool right = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x + b.getBounds().width, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, true); bool top = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y, inputNum, inputNum + 1, i, false, true); bool bottom = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y + b.getBounds().height, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, true); inputNum += 2; if (left/*m_car.getSprite().getGlobalBounds().intersects(b.getBounds())*/)//left { m_car.collidesBoundary(m_brain); m_car.push(Vector2f(-1, 0)); } if (right) { m_car.collidesBoundary(m_brain); m_car.push(Vector2f(1, 0)); } if (top) { m_car.collidesBoundary(m_brain); m_car.push(Vector2f(0, -1)); } if (bottom) { m_car.collidesBoundary(m_brain); m_car.push(Vector2f(0, 1)); } } } if (m_car.getBounds().intersects(m_checkpoints.at(m_car.getCpNum()).getBounds())/*rectCollision(m_car.getBounds(), m_checkpoints.at(m_car.getCpNum())->getBounds(), m_car.getPos(), m_checkpoints.at(m_car.getCpNum())->getPos())*/) { m_checkpoints.at(m_car.getCpNum()).setPassed(true); m_car.nextCP(); if (m_car.getCpNum() == m_checkpoints.size()) { for (Checkpoint c : m_checkpoints) { c.setPassed(false); } m_car.setCPNum(0); m_lapNum++; } if (m_lapNum == 3) { if (s_gameState == GameState::TrainingDataCollection) { cout << "Saving Data...." << endl; m_car.saveTrainingDataToFile(); cout << "Saved" << endl; s_gameState = GameState::Success; } } } //-------------------- // Reinforcement Car //-------------------- if (s_gameState == GameState::LoadWeights) { for (Boundry b : m_boundries) { int inputNum = 0; for (int i = 0; i < m_ReinforcementCar.getColLines().size(); i++) { // add inputs to neural network Vector2f c = m_ReinforcementCar.getColLines().at(i); bool left = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); bool right = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x + b.getBounds().width, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); bool top = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y, inputNum, inputNum + 1, i, false, false); bool bottom = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y + b.getBounds().height, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); inputNum += 2; if (left/*m_car.getSprite().getGlobalBounds().intersects(b.getBounds())*/)//left { m_ReinforcementCar.collidesBoundary(m_brain); m_ReinforcementCar.push(Vector2f(-1, 0)); } if (right) { m_ReinforcementCar.collidesBoundary(m_brain); m_ReinforcementCar.push(Vector2f(1, 0)); } if (top) { m_ReinforcementCar.collidesBoundary(m_brain); m_ReinforcementCar.push(Vector2f(0, -1)); } if (bottom) { m_ReinforcementCar.collidesBoundary(m_brain); m_ReinforcementCar.push(Vector2f(0, 1)); } } } } } void Track::raycast() { //-------------------- // Backprop Car //-------------------- int inputNum = 0; for (int i = 0; i < m_car.getRays().size(); i++) { m_car.collLineLengths[i] = 5.0f; bool left = false; bool right = false; bool top = false; bool bottom = false; Boundry bound; while (!left && !right && !top && !bottom) { m_car.collLineLengths[i] += 5.0f; m_car.updateColLines(); for (Boundry b : m_boundries) { Vector2f c = m_car.getRays().at(i); left = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false,true); right = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x + b.getBounds().width, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, true); top = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y, inputNum, inputNum + 1, i, false, true); bottom = lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y + b.getBounds().height, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, true); if (left || right || top || bottom) { if (m_car.collLineLengths[i] < 200.0f) { bound = b; break; } else { m_car.collLineLengths[i] = 200.0f; bound = b; break; } } } } Vector2f c = m_car.getRays().at(i); lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y, bound.getPos().x, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, true); lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, bound.getPos().x + bound.getBounds().width, bound.getPos().y, bound.getPos().x + bound.getBounds().width, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, true); lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y, bound.getPos().x + bound.getBounds().width, bound.getPos().y, inputNum, inputNum + 1, i, true, true); lineCollision(m_car.getPos().x, m_car.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y + bound.getBounds().height, bound.getPos().x + bound.getBounds().width, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, true); inputNum += 2; } //-------------------- // Reinforcement Car //-------------------- if (s_gameState == GameState::LoadWeights) { inputNum = 0; for (int i = 0; i < m_ReinforcementCar.getRays().size(); i++) { m_ReinforcementCar.collLineLengths[i] = 5.0f; bool left = false; bool right = false; bool top = false; bool bottom = false; Boundry bound; while (!left && !right && !top && !bottom) { m_ReinforcementCar.collLineLengths[i] += 5.0f; m_ReinforcementCar.updateColLines(); for (Boundry b : m_boundries) { Vector2f c = m_ReinforcementCar.getRays().at(i); left = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); right = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x + b.getBounds().width, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); top = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y, b.getPos().x + b.getBounds().width, b.getPos().y, inputNum, inputNum + 1, i, false, false); bottom = lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, b.getPos().x, b.getPos().y + b.getBounds().height, b.getPos().x + b.getBounds().width, b.getPos().y + b.getBounds().height, inputNum, inputNum + 1, i, false, false); if (left || right || top || bottom) { if (m_ReinforcementCar.collLineLengths[i] < 200.0f) { bound = b; break; } else { m_ReinforcementCar.collLineLengths[i] = 200.0f; bound = b; break; } } } } Vector2f c = m_ReinforcementCar.getRays().at(i); lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y, bound.getPos().x, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, false); lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, bound.getPos().x + bound.getBounds().width, bound.getPos().y, bound.getPos().x + bound.getBounds().width, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, false); lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y, bound.getPos().x + bound.getBounds().width, bound.getPos().y, inputNum, inputNum + 1, i, true, false); lineCollision(m_ReinforcementCar.getPos().x, m_ReinforcementCar.getPos().y, c.x, c.y, bound.getPos().x, bound.getPos().y + bound.getBounds().height, bound.getPos().x + bound.getBounds().width, bound.getPos().y + bound.getBounds().height, inputNum, inputNum + 1, i, true, false); inputNum += 2; } } } bool Track::lineCollision(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int t_inputNum1, int t_inputNum2, int t_circNum, bool t_addInput,bool t_backprop) { float uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); float uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) { if (t_addInput) { float intersectionX = x1 + (uA * (x2 - x1)); float intersectionY = y1 + (uA * (y2 - y1)); float input = lengthOfLine(Vector2f(x1, y1), Vector2f(intersectionX, intersectionY)); if (t_backprop) { m_colCirc.at(t_circNum).setPosition(intersectionX, intersectionY); m_inputs.at(t_inputNum1) = intersectionX; m_inputs.at(t_inputNum2) = intersectionY; m_inputs.at(10) = m_car.getPos().x; m_inputs.at(11) = m_car.getPos().y; m_inputs.at(12) = m_car.getSprite().getRotation(); } else { m_colCircReinforcment.at(t_circNum).setPosition(intersectionX, intersectionY); m_ReinforcementInputs.at(t_inputNum1) = intersectionX; m_ReinforcementInputs.at(t_inputNum2) = intersectionY; m_ReinforcementInputs.at(10) = m_ReinforcementCar.getPos().x; m_ReinforcementInputs.at(11) = m_ReinforcementCar.getPos().y; m_ReinforcementInputs.at(12) = m_ReinforcementCar.getSprite().getRotation(); } } return true; } return false; } float Track::lengthOfLine(Vector2f t_l1, Vector2f t_l2) { float sq = pow(t_l2.x - t_l1.x, 2) + pow(t_l2.y - t_l1.y, 2); return sqrt(sq); } bool Track::rectCollision(FloatRect t_rect1, FloatRect t_rect2, Vector2f t_pos1, Vector2f t_pos2) { if (t_pos1.x - (t_rect1.width / 2.0f) > t_pos2.x - (t_rect2.width / 2.0f) && t_pos1.x + (t_rect1.width / 2.0f) < t_pos2.x + (t_rect2.width / 2.0f) && t_pos1.y - (t_rect1.height / 2.0f) > t_pos2.y - (t_rect2.height / 2.0f) && t_pos1.y + (t_rect1.width / 2.0f) < t_pos2.y + (t_rect2.height / 2.0f)) return true; return false; }
[ "c00225401@itcarlow.ie" ]
c00225401@itcarlow.ie
a6b61c5189573ccbd7d2e4c6ec58a35099b6145c
ba4db75b9d1f08c6334bf7b621783759cd3209c7
/src_main/dx9sdk/Utilities/Source/Maya/DXMNodeAdapter.cpp
1080c0e5e7d9d39a618b1b90fa1c8bd6f74c72a6
[]
no_license
equalent/source-2007
a27326c6eb1e63899e3b77da57f23b79637060c0
d07be8d02519ff5c902e1eb6430e028e1b302c8b
refs/heads/master
2020-03-28T22:46:44.606988
2017-03-27T18:05:57
2017-03-27T18:05:57
149,257,460
2
0
null
2018-09-18T08:52:10
2018-09-18T08:52:09
null
UTF-8
C++
false
false
1,008
cpp
#include "pch.h" DXMNodeAdapter::DXMNodeAdapter() { Node= NULL; CallbackState= false; } DXMNodeAdapter::~DXMNodeAdapter() { } DXMNode* DXMNodeAdapter::GetNode() { return Node; } DXMGraph* DXMNodeAdapter::GetGraph() { return GetNode()->GetGraph(); } DXMGraphAdapter* DXMNodeAdapter::GetOwnerGraphAdapter() { return GetGraph()->FindAdapter(OwnerSignature()); } void DXMNodeAdapter::SetCallbackState(bool Activate) { CallbackState= Activate; } bool DXMNodeAdapter::GetCallbackState() { return CallbackState; } void DXMNodeAdapter::Initialize(DXMNode* node) { Node= node; SetCallbackState(node->GetCallbackState()); } void DXMNodeAdapter::Destroy() { SetCallbackState(false); GetOwnerGraphAdapter()->RemoveSyncRequest(this); } void DXMNodeAdapter::OnNameChange(const MString & prevName) { } /* void DXMNodeAdapter::OnAttributeChanged( MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug) { } */
[ "sean@csnxs.uk" ]
sean@csnxs.uk
d85f28baedebaa2b6c0ec55cd3a319a6b393b514
e61cce6a5bec4c31501c8627769518432db1ae3f
/Arduino/siramsis-nodemcu.ino
e71f9dbf8c1421e2188d55e1a19cb036d38393ce
[]
no_license
Syah4kram/siramsis.github.io
15e5efd2d42fda3cece3935fa09163d4fb93e6de
1bd8a77be317420f5e8255417be14c2907501e92
refs/heads/master
2023-06-03T05:00:21.167469
2021-06-21T10:40:07
2021-06-21T10:40:07
334,867,489
0
0
null
null
null
null
UTF-8
C++
false
false
3,237
ino
#include <ESP8266WiFi.h> #include <Wire.h> #include <WiFiClient.h> #include <ArduinoJson.h> const int ldrPin = A0; const int laserPin = 17; const int RELAY_PIN = 5; const int rainPin = 4; int valve_status = 0; int fog_status = 0; int rain = 0; int ldrStatus = 0; int fog_status_before = 0; int isFogTime = 0; int toSend = 0; String apiKey = "key apinya"; const char *ssid = "WiFi Name"; const char *pass = "password"; const char* server = "api.thingspeak.com"; WiFiClient client; void setup() { Serial.begin(115200); Serial.println("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); pinMode(ldrPin, INPUT); pinMode(rainPin,INPUT); pinMode(laserPin , OUTPUT); pinMode(RELAY_PIN, OUTPUT); digitalWrite(laserPin , HIGH); } void loop() { ldrStatus = analogRead(ldrPin); //int rain = digitalRead(rainPin); StaticJsonDocument<1000> doc; deserializeJson(doc, Serial); JsonObject root = doc.as<JsonObject>(); // get the root object auto error = deserializeJson(doc, Serial); if (error) { return; } Serial.println(); Serial.println("JSON received and parsed"); serializeJsonPretty(doc, Serial); Serial.println(); rain = doc["rain"]; if (ldrStatus < 860) { fog_status = 1; digitalWrite(RELAY_PIN, HIGH); } else { fog_status = 0; Serial.print(fog_status_before); Serial.print(fog_status); Serial.println(""); if(fog_status_before == 1){ if(isFogTime < 240){ Serial.println("MENGALIR"); digitalWrite(RELAY_PIN, LOW); valve_status = 1; isFogTime++; } else { Serial.println("TIDAK MENGALIR"); digitalWrite(RELAY_PIN, HIGH); fog_status = 0; valve_status = 0; } } } fog_status_before = fog_status; Serial.print("Hujan: "); Serial.print(rain); Serial.print(", Fog: "); Serial.print(fog_status); Serial.print(", Valve: "); Serial.print(valve_status); Serial.print(", LDR: "); Serial.print(ldrStatus); Serial.println(""); Serial.println(toSend); delay(5000); //180 if(toSend == 3){ if (client.connect(server, 80)) { String postStr = apiKey; postStr += "&field1="; postStr += String(rain); postStr += "&field2="; postStr += String(fog_status); postStr += "&field3="; postStr += String(valve_status); client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); Serial.print(". Send to Thingspeak."); } client.stop(); Serial.println(" Waiting..."); toSend = 0; } else { toSend++; } }
[ "noreply@github.com" ]
Syah4kram.noreply@github.com